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/mara/mybox/image/data/PixelsOperationFactory.java | released/MyBox/src/main/java/mara/mybox/image/data/PixelsOperationFactory.java | package mara.mybox.image.data;
import java.awt.Color;
import java.awt.image.BufferedImage;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.image.Image;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.FxTask;
import mara.mybox.image.data.PixelsOperation.ColorActionType;
import mara.mybox.image.data.PixelsOperation.OperationType;
import static mara.mybox.image.data.PixelsOperation.OperationType.Blend;
import static mara.mybox.image.data.PixelsOperation.OperationType.Color;
import mara.mybox.image.tools.ColorBlendTools;
import mara.mybox.image.tools.ColorConvertTools;
import mara.mybox.value.Colors;
/**
* @Author Mara
* @CreateDate 2019-2-13 14:44:03
* @License Apache License Version 2.0
*/
public class PixelsOperationFactory {
public static PixelsOperation createFX(Image image, ImageScope scope, OperationType operationType) {
return create(image != null ? SwingFXUtils.fromFXImage(image, null) : null,
scope, operationType);
}
public static PixelsOperation create(BufferedImage image, ImageScope scope, OperationType operationType) {
return create(image, scope, operationType, null);
}
public static PixelsOperation create(BufferedImage image, ImageScope scope,
OperationType operationType, ColorActionType colorActionType) {
switch (operationType) {
case ShowScope:
return new ShowScope(image, scope);
case SelectPixels:
return new SelectPixels(image, scope);
case ReplaceColor:
return new ReplaceColor(image, scope);
case Color:
return new ColorSet(image, scope);
case Blend:
return new BlendColor(image, scope);
case Sepia:
return new Sepia(image, scope);
case Thresholding:
return new Thresholding(image, scope);
case Opacity:
switch (colorActionType) {
case Increase:
return new IncreaseOpacity(image, scope);
case Decrease:
return new DecreaseOpacity(image, scope);
case Set:
default:
return new SetOpacity(image, scope);
}
case PreOpacity:
switch (colorActionType) {
case Increase:
return new IncreasePreOpacity(image, scope);
case Decrease:
return new DecreasePreOpacity(image, scope);
case Set:
default:
return new SetPreOpacity(image, scope);
}
case Brightness:
switch (colorActionType) {
case Increase:
return new IncreaseBrightness(image, scope);
case Decrease:
return new DecreaseBrightness(image, scope);
case Set:
default:
return new SetBrightness(image, scope);
}
case Saturation:
switch (colorActionType) {
case Increase:
return new IncreaseSaturation(image, scope);
case Decrease:
return new DecreaseSaturation(image, scope);
case Set:
default:
return new SetSaturation(image, scope);
}
case Hue:
switch (colorActionType) {
case Increase:
return new IncreaseHue(image, scope);
case Decrease:
return new DecreaseHue(image, scope);
case Set:
default:
return new SetHue(image, scope);
}
case Red:
switch (colorActionType) {
case Increase:
return new IncreaseRed(image, scope);
case Decrease:
return new DecreaseRed(image, scope);
case Filter:
return new FilterRed(image, scope);
case Invert:
return new InvertRed(image, scope);
case Set:
default:
return new SetRed(image, scope);
}
case Green:
switch (colorActionType) {
case Increase:
return new IncreaseGreen(image, scope);
case Decrease:
return new DecreaseGreen(image, scope);
case Filter:
return new FilterGreen(image, scope);
case Invert:
return new InvertGreen(image, scope);
case Set:
default:
return new SetGreen(image, scope);
}
case Blue:
switch (colorActionType) {
case Increase:
return new IncreaseBlue(image, scope);
case Decrease:
return new DecreaseBlue(image, scope);
case Filter:
return new FilterBlue(image, scope);
case Invert:
return new InvertBlue(image, scope);
case Set:
default:
return new SetBlue(image, scope);
}
case Yellow:
switch (colorActionType) {
case Increase:
return new IncreaseYellow(image, scope);
case Decrease:
return new DecreaseYellow(image, scope);
case Filter:
return new FilterYellow(image, scope);
case Invert:
return new InvertYellow(image, scope);
case Set:
default:
return new SetYellow(image, scope);
}
case Cyan:
switch (colorActionType) {
case Increase:
return new IncreaseCyan(image, scope);
case Decrease:
return new DecreaseCyan(image, scope);
case Filter:
return new FilterCyan(image, scope);
case Invert:
return new InvertCyan(image, scope);
case Set:
default:
return new SetCyan(image, scope);
}
case Magenta:
switch (colorActionType) {
case Increase:
return new IncreaseMagenta(image, scope);
case Decrease:
return new DecreaseMagenta(image, scope);
case Filter:
return new FilterMagenta(image, scope);
case Invert:
return new InvertMagenta(image, scope);
case Set:
default:
return new SetMagenta(image, scope);
}
case RGB:
switch (colorActionType) {
case Increase:
return new IncreaseRGB(image, scope);
case Decrease:
return new DecreaseRGB(image, scope);
case Invert:
return new InvertRGB(image, scope);
// case Set:
// default:
// return new SetRGB(image, scope);
}
default:
return null;
}
}
public static PixelsOperation createFX(Image image, ImageScope scope,
OperationType operationType, ColorActionType colorActionType) {
BufferedImage bufferedImage = SwingFXUtils.fromFXImage(image, null);
return create(bufferedImage, scope, operationType, colorActionType);
}
public static BufferedImage replaceColor(FxTask task, BufferedImage image,
Color oldColor, Color newColor, int distance) {
PixelsOperation pixelsOperation = replaceColorOperation(task, image, oldColor, newColor, distance);
if (pixelsOperation == null) {
return image;
}
return pixelsOperation.start();
}
public static PixelsOperation replaceColorOperation(FxTask task, BufferedImage image,
Color oldColor, Color newColor, double threshold) {
if (oldColor == null || threshold < 0) {
return null;
}
try {
ImageScope scope = new ImageScope();
scope.setShapeType(ImageScope.ShapeType.Whole);
scope.addColor(oldColor);
scope.setColorThreshold(threshold);
PixelsOperation pixelsOperation = PixelsOperationFactory.create(image,
scope, OperationType.ReplaceColor, ColorActionType.Set)
.setColorPara1(oldColor)
.setColorPara2(newColor)
.setTask(task);
return pixelsOperation;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
/*
subclass
*/
public static class ShowScope extends PixelsOperation {
private final float maskOpacity;
private final Color maskColor;
public ShowScope(BufferedImage image, ImageScope scope) {
this.operationType = OperationType.ShowScope;
this.image = image;
this.scope = scope;
maskOpacity = scope.getMaskOpacity();
maskColor = scope.getMaskColor();
}
@Override
protected boolean inScope(int x, int y, Color color) {
return !super.inScope(x, y, color);
}
@Override
protected Color skipTransparent(BufferedImage target, int x, int y) {
try {
Color color = ColorBlendTools.blendColor(Colors.TRANSPARENT, maskOpacity, maskColor, true);
target.setRGB(x, y, color.getRGB());
return color;
} catch (Exception e) {
return null;
}
}
@Override
protected Color operateColor(Color color) {
return ColorBlendTools.blendColor(color, maskOpacity, maskColor, true);
}
}
public static class SelectPixels extends PixelsOperation {
public SelectPixels(BufferedImage image, ImageScope scope) {
this.operationType = OperationType.SelectPixels;
this.image = image;
this.scope = scope;
}
@Override
protected Color skipTransparent(BufferedImage target, int x, int y) {
try {
target.setRGB(x, y, colorPara1.getRGB());
return colorPara1;
} catch (Exception e) {
return null;
}
}
@Override
protected boolean inScope(int x, int y, Color color) {
return !super.inScope(x, y, color);
}
@Override
protected Color operateColor(Color color) {
return colorPara1;
}
}
public static class Sepia extends PixelsOperation {
public Sepia(BufferedImage image, ImageScope scope) {
this.operationType = OperationType.Sepia;
this.image = image;
this.scope = scope;
}
@Override
protected Color operateColor(Color color) {
return ColorConvertTools.pixel2Sepia(color, intPara1);
}
}
public static class Thresholding extends PixelsOperation {
public Thresholding(BufferedImage image, ImageScope scope) {
this.operationType = OperationType.Thresholding;
this.image = image;
this.scope = scope;
}
@Override
protected Color operateColor(Color color) {
return ColorConvertTools.thresholdingColor(color, intPara1, intPara2, intPara3);
}
}
public static class ReplaceColor extends PixelsOperation {
private float paraHue, paraSaturation, paraBrightness,
colorHue, colorSaturation, colorBrightness;
private boolean directReplace;
public ReplaceColor(BufferedImage image, ImageScope scope) {
this.operationType = OperationType.ReplaceColor;
this.colorActionType = ColorActionType.Set;
this.image = image;
this.scope = scope;
boolPara1 = boolPara2 = boolPara3 = true;
directReplace = false;
}
@Override
public BufferedImage start() {
directReplace = (boolPara1 && boolPara2 && boolPara3)
|| (!boolPara1 && !boolPara2 && !boolPara3);
if (!directReplace) {
float[] hsb = ColorConvertTools.color2hsb(colorPara2);
paraHue = hsb[0];
paraSaturation = hsb[1];
paraBrightness = hsb[2];
}
return super.start();
}
@Override
protected Color operateColor(Color color) {
if (directReplace) {
return colorPara2;
}
float[] hsb = ColorConvertTools.color2hsb(color);
colorHue = boolPara1 ? paraHue : hsb[0];
colorSaturation = boolPara2 ? paraSaturation : hsb[1];
colorBrightness = boolPara3 ? paraBrightness : hsb[2];
return ColorConvertTools.hsb2rgb(colorHue, colorSaturation, colorBrightness);
}
}
public static class ColorSet extends PixelsOperation {
private float paraHue, paraSaturation, paraBrightness,
colorHue, colorSaturation, colorBrightness;
private boolean directReplace;
public ColorSet(BufferedImage image, ImageScope scope) {
this.operationType = OperationType.Color;
this.colorActionType = ColorActionType.Set;
this.image = image;
this.scope = scope;
boolPara1 = boolPara2 = boolPara3 = true;
directReplace = false;
}
@Override
public BufferedImage start() {
directReplace = (boolPara1 && boolPara2 && boolPara3)
|| (!boolPara1 && !boolPara2 && !boolPara3);
if (!directReplace) {
float[] hsb = ColorConvertTools.color2hsb(colorPara1);
paraHue = hsb[0];
paraSaturation = hsb[1];
paraBrightness = hsb[2];
}
return super.start();
}
@Override
protected Color operateColor(Color color) {
if (directReplace) {
return colorPara1;
}
float[] hsb = ColorConvertTools.color2hsb(color);
colorHue = boolPara1 ? paraHue : hsb[0];
colorSaturation = boolPara2 ? paraSaturation : hsb[1];
colorBrightness = boolPara3 ? paraBrightness : hsb[2];
return ColorConvertTools.hsb2rgb(colorHue, colorSaturation, colorBrightness);
}
}
public static class BlendColor extends PixelsOperation {
protected PixelsBlend blender;
public BlendColor(BufferedImage image, ImageScope scope) {
this.operationType = OperationType.Blend;
this.colorActionType = ColorActionType.Set;
this.image = image;
this.scope = scope;
}
public BlendColor setBlender(PixelsBlend blender) {
this.blender = blender;
return this;
}
@Override
protected Color operateColor(Color color) {
if (blender == null) {
return color;
}
return blender.blend(colorPara1, color);
}
}
public static class SetOpacity extends PixelsOperation {
public SetOpacity(BufferedImage image, ImageScope scope) {
this.operationType = OperationType.Opacity;
this.colorActionType = ColorActionType.Set;
this.image = image;
this.scope = scope;
}
@Override
protected Color operateColor(Color color) {
return new Color(color.getRed(), color.getGreen(), color.getBlue(),
Math.min(Math.max(intPara1, 0), 255));
}
}
public static class IncreaseOpacity extends PixelsOperation {
public IncreaseOpacity(BufferedImage image, ImageScope scope) {
this.operationType = OperationType.Opacity;
this.colorActionType = ColorActionType.Increase;
this.image = image;
this.scope = scope;
}
@Override
protected Color operateColor(Color color) {
return new Color(color.getRed(), color.getGreen(), color.getBlue(),
Math.min(Math.max(color.getAlpha() + intPara1, 0), 255));
}
}
public static class DecreaseOpacity extends PixelsOperation {
public DecreaseOpacity(BufferedImage image, ImageScope scope) {
this.operationType = OperationType.Opacity;
this.colorActionType = ColorActionType.Decrease;
this.image = image;
this.scope = scope;
}
@Override
protected Color operateColor(Color color) {
return new Color(color.getRed(), color.getGreen(), color.getBlue(),
Math.min(Math.max(color.getAlpha() - intPara1, 0), 255));
}
}
public static class SetPreOpacity extends PixelsOperation {
protected Color bkColor;
public SetPreOpacity(BufferedImage image, ImageScope scope) {
this.operationType = OperationType.PreOpacity;
this.colorActionType = ColorActionType.Set;
this.image = image;
this.scope = scope;
bkColor = ColorConvertTools.alphaColor();
}
@Override
protected Color operateColor(Color color) {
int opacity = Math.min(Math.max(intPara1, 0), 255);
float f = opacity / 255.0f;
return ColorBlendTools.blendColor(color, f, bkColor);
}
}
public static class IncreasePreOpacity extends PixelsOperation {
protected Color bkColor;
public IncreasePreOpacity(BufferedImage image, ImageScope scope) {
this.operationType = OperationType.PreOpacity;
this.colorActionType = ColorActionType.Increase;
this.image = image;
this.scope = scope;
bkColor = ColorConvertTools.alphaColor();
}
@Override
protected Color operateColor(Color color) {
int opacity = Math.min(Math.max(color.getAlpha() + intPara1, 0), 255);
float f = opacity / 255.0f;
return ColorBlendTools.blendColor(color, f, bkColor);
}
}
public static class DecreasePreOpacity extends PixelsOperation {
protected Color bkColor;
public DecreasePreOpacity(BufferedImage image, ImageScope scope) {
this.operationType = OperationType.PreOpacity;
this.colorActionType = ColorActionType.Decrease;
this.image = image;
this.scope = scope;
bkColor = ColorConvertTools.alphaColor();
}
@Override
protected Color operateColor(Color color) {
int opacity = Math.min(Math.max(color.getAlpha() - intPara1, 0), 255);
float f = opacity / 255.0f;
return ColorBlendTools.blendColor(color, f, bkColor);
}
}
public static class SetBrightness extends PixelsOperation {
public SetBrightness(BufferedImage image, ImageScope scope) {
this.operationType = OperationType.Brightness;
this.colorActionType = ColorActionType.Set;
this.image = image;
this.scope = scope;
}
@Override
protected Color operateColor(Color color) {
float[] hsb;
hsb = ColorConvertTools.color2hsb(color);
float f = floatPara1;
f = Math.min(Math.max(f, 0.0f), 1.0f);
return ColorConvertTools.hsb2rgb(hsb[0], hsb[1], f);
}
}
public static class IncreaseBrightness extends PixelsOperation {
public IncreaseBrightness(BufferedImage image, ImageScope scope) {
this.operationType = OperationType.Brightness;
this.colorActionType = ColorActionType.Increase;
this.image = image;
this.scope = scope;
}
@Override
protected Color operateColor(Color color) {
float[] hsb;
hsb = ColorConvertTools.color2hsb(color);
float f = hsb[2] * (1.0f + floatPara1);
f = Math.min(Math.max(f, 0.0f), 1.0f);
return ColorConvertTools.hsb2rgb(hsb[0], hsb[1], f);
}
}
public static class DecreaseBrightness extends PixelsOperation {
public DecreaseBrightness(BufferedImage image, ImageScope scope) {
this.operationType = OperationType.Brightness;
this.colorActionType = ColorActionType.Decrease;
this.image = image;
this.scope = scope;
}
@Override
protected Color operateColor(Color color) {
float[] hsb;
hsb = ColorConvertTools.color2hsb(color);
float f = hsb[2] * (1.0f - floatPara1);
f = Math.min(Math.max(f, 0.0f), 1.0f);
return ColorConvertTools.hsb2rgb(hsb[0], hsb[1], f);
}
}
public static class SetSaturation extends PixelsOperation {
public SetSaturation(BufferedImage image, ImageScope scope) {
this.operationType = OperationType.Saturation;
this.colorActionType = ColorActionType.Set;
this.image = image;
this.scope = scope;
}
@Override
protected Color operateColor(Color color) {
float[] hsb;
hsb = ColorConvertTools.color2hsb(color);
float f = floatPara1;
f = Math.min(Math.max(f, 0.0f), 1.0f);
return ColorConvertTools.hsb2rgb(hsb[0], f, hsb[2]);
}
}
public static class IncreaseSaturation extends PixelsOperation {
public IncreaseSaturation(BufferedImage image, ImageScope scope) {
this.operationType = OperationType.Saturation;
this.colorActionType = ColorActionType.Increase;
this.image = image;
this.scope = scope;
}
@Override
protected Color operateColor(Color color) {
float[] hsb;
hsb = ColorConvertTools.color2hsb(color);
float f = hsb[1] * (1.0f + floatPara1);
f = Math.min(Math.max(f, 0.0f), 1.0f);
return ColorConvertTools.hsb2rgb(hsb[0], f, hsb[2]);
}
}
public static class DecreaseSaturation extends PixelsOperation {
public DecreaseSaturation(BufferedImage image, ImageScope scope) {
this.operationType = OperationType.Saturation;
this.colorActionType = ColorActionType.Decrease;
this.image = image;
this.scope = scope;
}
@Override
protected Color operateColor(Color color) {
float[] hsb;
hsb = ColorConvertTools.color2hsb(color);
float f = hsb[1] * (1.0f - floatPara1);
f = Math.min(Math.max(f, 0.0f), 1.0f);
return ColorConvertTools.hsb2rgb(hsb[0], f, hsb[2]);
}
}
public static class SetHue extends PixelsOperation {
public SetHue(BufferedImage image, ImageScope scope) {
this.operationType = OperationType.Hue;
this.colorActionType = ColorActionType.Set;
this.image = image;
this.scope = scope;
}
@Override
protected Color operateColor(Color color) {
float[] hsb;
hsb = ColorConvertTools.color2hsb(color);
float f = floatPara1;
if (f > 1.0f) {
f = f - 1.0f;
}
if (f < 0.0f) {
f = f + 1.0f;
}
f = Math.min(Math.max(f, 0.0f), 1.0f);
return ColorConvertTools.hsb2rgb(f, hsb[1], hsb[2]);
}
}
public static class IncreaseHue extends PixelsOperation {
public IncreaseHue(BufferedImage image, ImageScope scope) {
this.operationType = OperationType.Hue;
this.colorActionType = ColorActionType.Increase;
this.image = image;
this.scope = scope;
}
@Override
protected Color operateColor(Color color) {
float[] hsb;
hsb = ColorConvertTools.color2hsb(color);
float f = hsb[0] + floatPara1;
if (f > 1.0f) {
f = f - 1.0f;
}
if (f < 0.0f) {
f = f + 1.0f;
}
f = Math.min(Math.max(f, 0.0f), 1.0f);
return ColorConvertTools.hsb2rgb(f, hsb[1], hsb[2]);
}
}
public static class DecreaseHue extends PixelsOperation {
public DecreaseHue(BufferedImage image, ImageScope scope) {
this.operationType = OperationType.Hue;
this.colorActionType = ColorActionType.Decrease;
this.image = image;
this.scope = scope;
}
@Override
protected Color operateColor(Color color) {
float[] hsb;
hsb = ColorConvertTools.color2hsb(color);
float f = hsb[0] - floatPara1;
if (f > 1.0f) {
f = f - 1.0f;
}
if (f < 0.0f) {
f = f + 1.0f;
}
f = Math.min(Math.max(f, 0.0f), 1.0f);
return ColorConvertTools.hsb2rgb(f, hsb[1], hsb[2]);
}
}
public static class SetRed extends PixelsOperation {
public SetRed(BufferedImage image, ImageScope scope) {
this.operationType = OperationType.Red;
this.colorActionType = ColorActionType.Set;
this.image = image;
this.scope = scope;
}
@Override
protected Color operateColor(Color color) {
return new Color(Math.min(Math.max(intPara1, 0), 255),
color.getGreen(), color.getBlue(), color.getAlpha());
}
}
public static class IncreaseRed extends PixelsOperation {
public IncreaseRed(BufferedImage image, ImageScope scope) {
this.operationType = OperationType.Red;
this.colorActionType = ColorActionType.Increase;
this.image = image;
this.scope = scope;
}
@Override
protected Color operateColor(Color color) {
return new Color(Math.min(Math.max(color.getRed() + intPara1, 0), 255),
color.getGreen(), color.getBlue(), color.getAlpha());
}
}
public static class DecreaseRed extends PixelsOperation {
public DecreaseRed(BufferedImage image, ImageScope scope) {
this.operationType = OperationType.Red;
this.colorActionType = ColorActionType.Decrease;
this.image = image;
this.scope = scope;
}
@Override
protected Color operateColor(Color color) {
return new Color(Math.min(Math.max(color.getRed() - intPara1, 0), 255),
color.getGreen(), color.getBlue(), color.getAlpha());
}
}
public static class FilterRed extends PixelsOperation {
public FilterRed(BufferedImage image, ImageScope scope) {
this.operationType = OperationType.Red;
this.colorActionType = ColorActionType.Filter;
this.image = image;
this.scope = scope;
}
@Override
protected Color operateColor(Color color) {
return new Color(color.getRed(), 0, 0, color.getAlpha());
}
}
public static class InvertRed extends PixelsOperation {
public InvertRed(BufferedImage image, ImageScope scope) {
this.operationType = OperationType.Red;
this.colorActionType = ColorActionType.Invert;
this.image = image;
this.scope = scope;
}
@Override
protected Color operateColor(Color color) {
return new Color(255 - color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha());
}
}
public static class SetGreen extends PixelsOperation {
public SetGreen(BufferedImage image, ImageScope scope) {
this.operationType = OperationType.Green;
this.colorActionType = ColorActionType.Set;
this.image = image;
this.scope = scope;
}
@Override
protected Color operateColor(Color color) {
return new Color(color.getRed(), Math.min(Math.max(intPara1, 0), 255),
color.getBlue(), color.getAlpha());
}
}
public static class IncreaseGreen extends PixelsOperation {
public IncreaseGreen(BufferedImage image, ImageScope scope) {
this.operationType = OperationType.Green;
this.colorActionType = ColorActionType.Increase;
this.image = image;
this.scope = scope;
}
@Override
protected Color operateColor(Color color) {
return new Color(color.getRed(), Math.min(Math.max(color.getGreen() + intPara1, 0), 255),
color.getBlue(), color.getAlpha());
}
}
public static class DecreaseGreen extends PixelsOperation {
public DecreaseGreen(BufferedImage image, ImageScope scope) {
this.operationType = OperationType.Green;
this.colorActionType = ColorActionType.Decrease;
this.image = image;
this.scope = scope;
}
@Override
protected Color operateColor(Color color) {
return new Color(color.getRed(), Math.min(Math.max(color.getGreen() - intPara1, 0), 255),
color.getBlue(), color.getAlpha());
}
}
public static class FilterGreen extends PixelsOperation {
public FilterGreen(BufferedImage image, ImageScope scope) {
this.operationType = OperationType.Green;
this.colorActionType = ColorActionType.Filter;
this.image = image;
this.scope = scope;
}
@Override
protected Color operateColor(Color color) {
return new Color(0, color.getGreen(), 0, color.getAlpha());
}
}
public static class InvertGreen extends PixelsOperation {
public InvertGreen(BufferedImage image, ImageScope scope) {
this.operationType = OperationType.Green;
this.colorActionType = ColorActionType.Invert;
this.image = image;
this.scope = scope;
}
@Override
protected Color operateColor(Color color) {
return new Color(color.getRed(), 255 - color.getGreen(), color.getBlue(), color.getAlpha());
}
}
public static class SetBlue extends PixelsOperation {
public SetBlue(BufferedImage image, ImageScope scope) {
this.operationType = OperationType.Blue;
this.colorActionType = ColorActionType.Set;
this.image = image;
this.scope = scope;
}
@Override
protected Color operateColor(Color color) {
return new Color(color.getRed(), color.getGreen(),
Math.min(Math.max(intPara1, 0), 255), color.getAlpha());
}
}
public static class IncreaseBlue extends PixelsOperation {
public IncreaseBlue(BufferedImage image, ImageScope scope) {
this.operationType = OperationType.Blue;
this.colorActionType = ColorActionType.Increase;
this.image = image;
this.scope = scope;
}
@Override
protected Color operateColor(Color color) {
return new Color(color.getRed(), color.getGreen(),
Math.min(Math.max(color.getBlue() + intPara1, 0), 255), color.getAlpha());
| 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/image/data/ImageScope.java | released/MyBox/src/main/java/mara/mybox/image/data/ImageScope.java | package mara.mybox.image.data;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.image.Image;
import javax.imageio.ImageIO;
import mara.mybox.color.ColorMatch;
import mara.mybox.color.ColorMatch.MatchAlgorithm;
import mara.mybox.data.DoubleCircle;
import mara.mybox.data.DoubleEllipse;
import mara.mybox.data.DoublePolygon;
import mara.mybox.data.DoubleRectangle;
import mara.mybox.data.IntPoint;
import mara.mybox.fxml.FxTask;
import mara.mybox.image.tools.ImageScopeTools;
import mara.mybox.value.Colors;
/**
* @Author Mara
* @CreateDate 2018-8-1 16:22:41
* @License Apache License Version 2.0
*/
public class ImageScope {
public static String ValueSeparator = ",";
protected String background, name, shapeData, colorData, outlineName;
protected ShapeType shapeType;
protected List<Color> colors;
protected List<IntPoint> points;
protected DoubleRectangle rectangle;
protected DoubleCircle circle;
protected DoubleEllipse ellipse;
protected DoublePolygon polygon;
protected ColorMatch colorMatch;
protected boolean shapeExcluded, colorExcluded;
protected Image image, clip;
protected Color maskColor;
protected float maskOpacity;
protected BufferedImage outlineSource, outline;
public static enum ShapeType {
Whole, Matting4, Matting8, Rectangle, Circle, Ellipse, Polygon, Outline
}
public ImageScope() {
init();
}
public final void init() {
shapeType = ShapeType.Whole;
colorMatch = new ColorMatch();
maskColor = Colors.TRANSPARENT;
maskOpacity = 0.5f;
shapeExcluded = false;
resetParameters();
}
public final void resetParameters() {
rectangle = null;
circle = null;
ellipse = null;
polygon = null;
shapeData = null;
colorData = null;
outlineName = null;
outlineSource = null;
outline = null;
points = new ArrayList<>();
clearColors();
}
public ImageScope cloneValues() {
return ImageScopeTools.cloneAll(this);
}
public boolean isWhole() {
return (shapeType == null || shapeType == ShapeType.Whole)
&& (colors == null || colors.isEmpty());
}
public void decode(FxTask task) {
if (colorData != null) {
ImageScopeTools.decodeColorData(this);
}
if (shapeData != null) {
ImageScopeTools.decodeShapeData(this);
}
if (outlineName != null) {
decodeOutline(task);
}
}
public BufferedImage decodeOutline(FxTask task) {
outlineSource = null;
outline = null;
try {
if (outlineName.startsWith("img/") || outlineName.startsWith("buttons/")) {
outlineSource = SwingFXUtils.fromFXImage(new Image(outlineName), null);
} else {
File file = new File(outlineName);
if (file.exists()) {
outlineSource = ImageIO.read(file);
}
}
} catch (Exception e) {
}
return outlineSource;
}
public void encode(FxTask task) {
ImageScopeTools.encodeColorData(this);
ImageScopeTools.encodeShapeData(this);
ImageScopeTools.encodeOutline(task, this);
}
public void addPoint(IntPoint point) {
if (point == null) {
return;
}
if (points == null) {
points = new ArrayList<>();
}
if (!points.contains(point)) {
points.add(point);
}
}
public void addPoint(int x, int y) {
if (x < 0 || y < 0) {
return;
}
IntPoint point = new IntPoint(x, y);
addPoint(point);
}
public void setPoint(int index, int x, int y) {
if (x < 0 || y < 0 || points == null || index < 0 || index >= points.size()) {
return;
}
IntPoint point = new IntPoint(x, y);
points.set(index, point);
}
public void deletePoint(int index) {
if (points == null || index < 0 || index >= points.size()) {
return;
}
points.remove(index);
}
public void clearPoints() {
points = new ArrayList<>();
}
/*
color match
*/
protected boolean isMatchColor(Color color1, Color color2) {
boolean match = colorMatch.isMatch(color1, color2);
return colorExcluded ? !match : match;
}
public boolean isMatchColors(Color color) {
return colorMatch.isMatchColors(colors, color, colorExcluded);
}
public boolean addColor(Color color) {
if (color == null) {
return false;
}
if (colors == null) {
colors = new ArrayList<>();
}
if (!colors.contains(color)) {
colors.add(color);
return true;
} else {
return false;
}
}
public void clearColors() {
colors = null;
}
/**
*
* @param x the x of the pixel
* @param y the y of the pixel
* @param color the color of the pixel
* @return whether in image scope
*/
public boolean inScope(int x, int y, Color color) {
return inShape(x, y) && isMatchColors(color);
}
public boolean inShape(int x, int y) {
return true;
}
/*
Static methods
*/
public static ImageScope create() {
return new ImageScope();
}
public static boolean valid(ImageScope data) {
return data != null
&& data.getColorMatch() != null
&& data.getShapeType() != null;
}
public static ShapeType shapeType(String type) {
try {
return ShapeType.valueOf(type);
} catch (Exception e) {
return ShapeType.Whole;
}
}
public static MatchAlgorithm matchAlgorithm(String a) {
try {
return MatchAlgorithm.valueOf(a);
} catch (Exception e) {
return ColorMatch.DefaultAlgorithm;
}
}
/*
customized get/set
*/
public ShapeType getShapeType() {
if (shapeType == null) {
shapeType = ShapeType.Whole;
}
return shapeType;
}
public ImageScope setShapeType(ShapeType shapeType) {
this.shapeType = shapeType != null ? shapeType : ShapeType.Whole;
return this;
}
public ImageScope setShapeType(String shapeType) {
this.shapeType = shapeType(shapeType);
return this;
}
public double getColorThreshold() {
return colorMatch.getThreshold();
}
public void setColorThreshold(double threshold) {
colorMatch.setThreshold(threshold);
}
public MatchAlgorithm getColorAlgorithm() {
return colorMatch.getAlgorithm();
}
public void setColorAlgorithm(MatchAlgorithm algorithm) {
colorMatch.setAlgorithm(algorithm);
}
public void setColorAlgorithm(String algorithm) {
colorMatch.setAlgorithm(matchAlgorithm(algorithm));
}
public boolean setColorWeights(String weights) {
return colorMatch.setColorWeights(weights);
}
public String getColorWeights() {
return colorMatch.getColorWeights();
}
/*
get/set
*/
public DoubleRectangle getRectangle() {
return rectangle;
}
public ImageScope setRectangle(DoubleRectangle rectangle) {
this.rectangle = rectangle;
return this;
}
public DoubleCircle getCircle() {
return circle;
}
public void setCircle(DoubleCircle circle) {
this.circle = circle;
}
public Image getImage() {
return image;
}
public ImageScope setImage(Image image) {
this.image = image;
return this;
}
public ColorMatch getColorMatch() {
return colorMatch;
}
public List<Color> getColors() {
return colors;
}
public ImageScope setColors(List<Color> colors) {
this.colors = colors;
return this;
}
public boolean isColorExcluded() {
return colorExcluded;
}
public ImageScope setColorExcluded(boolean colorExcluded) {
this.colorExcluded = colorExcluded;
return this;
}
public float getMaskOpacity() {
return maskOpacity;
}
public ImageScope setMaskOpacity(float maskOpacity) {
this.maskOpacity = maskOpacity;
return this;
}
public Color getMaskColor() {
return maskColor;
}
public ImageScope setMaskColor(Color maskColor) {
this.maskColor = maskColor;
return this;
}
public String getBackground() {
return background;
}
public boolean isShapeExcluded() {
return shapeExcluded;
}
public ImageScope setShapeExcluded(boolean shapeExcluded) {
this.shapeExcluded = shapeExcluded;
return this;
}
public List<IntPoint> getPoints() {
return points;
}
public void setPoints(List<IntPoint> points) {
this.points = points;
}
public DoubleEllipse getEllipse() {
return ellipse;
}
public void setEllipse(DoubleEllipse ellipse) {
this.ellipse = ellipse;
}
public DoublePolygon getPolygon() {
return polygon;
}
public void setPolygon(DoublePolygon polygon) {
this.polygon = polygon;
}
public void setBackground(String background) {
this.background = background;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public BufferedImage getOutline() {
return outline;
}
public ImageScope setOutline(BufferedImage outline) {
this.outline = outline;
return this;
}
public BufferedImage getOutlineSource() {
return outlineSource;
}
public ImageScope setOutlineSource(BufferedImage outlineSource) {
this.outlineSource = outlineSource;
return this;
}
public Image getClip() {
return clip;
}
public void setClip(Image clip) {
this.clip = clip;
}
public String getShapeData() {
return shapeData;
}
public void setShapeData(String shapeData) {
this.shapeData = shapeData;
}
public String getColorData() {
return colorData;
}
public void setColorData(String colorData) {
this.colorData = colorData;
}
public String getOutlineName() {
return outlineName;
}
public void setOutlineName(String outlineName) {
this.outlineName = outlineName;
}
}
| 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/dev/Test.java | released/MyBox/src/main/java/mara/mybox/dev/Test.java | package mara.mybox.dev;
import java.awt.Rectangle;
import java.awt.geom.Rectangle2D;
import javafx.geometry.Bounds;
/**
* @Author Mara
* @CreateDate 2023-8-7
* @License Apache License Version 2.0
*/
public class Test {
/* https://github.com/Mararsh/MyBox/issues/1816
Following are results of checking these values in Java20:
javafx.scene.shape.Rectangle: Rectangle[x=0.0, y=0.0, width=5.0, height=6.0, fill=0x000000ff]
default isPickOnBounds: false
rect.contains (rect.getX(), rect.getY()): true rect.contains (rect.getWidth(), rect.getHeight()):false
rect.getBoundsInLocal():
bind.getMinX: 0.0 bind.getMinY: 0.0 bind.getMaxX: 5.0 bind.getMaxY: 6.0 bind.getMaxX: 5.0 bind.getWidth: 5.0 bind.getHeight: 6.0
bind.contains (bind.getMinX(), bind.getMinY()): true bind.contains (bind.getMaxX(), bind.getMaxY()):true bind.contains (bind.getWidth(), bind.getHeight()):true
---------------------
javafx.scene.shape.Rectangle: Rectangle[x=0.0, y=0.0, width=5.0, height=6.0, fill=0x000000ff]
isPickOnBounds: true
rect.contains (rect.getX(), rect.getY()): true rect.contains (rect.getWidth(), rect.getHeight()):true
rect.getBoundsInLocal():
bind.getMinX: 0.0 bind.getMinY: 0.0 bind.getMaxX: 5.0 bind.getMaxY: 6.0 bind.getMaxX: 5.0 bind.getWidth: 5.0 bind.getHeight: 6.0
bind.contains (bind.getMinX(), bind.getMinY()): true bind.contains (bind.getMaxX(), bind.getMaxY()):true bind.contains (bind.getWidth(), bind.getHeight()):true
---------------------
java.awt.geom.Rectangle2D.Double: java.awt.geom.Rectangle2D$Double[x=0.0,y=0.0,w=5.0,h=6.0]
rect2d.getMinX: 0.0 rect2d.getMinY: 0.0 rect2d.getMaxX: 5.0 rect2d.getMaxY: 6.0 rect2d.getMaxX: 5.0 rect2d.getWidth: 5.0 rect2d.getHeight: 6.0
rect2d.contains (rect.getX(), rect2d.getY()): true rect2d.contains (rect.getWidth(), rect2d.getHeight()):false
rect2d.getBounds():
bind2d.getMinX: 0.0 bind2d.getMinY: 0.0 bind2d.getMaxX: 5.0 bind2d.getMaxY: 6.0 bind2d.getMaxX: 5.0 bind2d.getWidth: 5.0 bind2d.getHeight: 6.0
bind2d.contains (bind2d.getMinX(), bind2d.getMinY()): true bind2d.contains (bind2d.getMaxX(), bind2d.getMaxY()):false bind2d.contains (bind2d.getWidth(), bind2d.getHeight()):false
*/
public static void rectangleBounds() {
javafx.scene.shape.Rectangle rect = new javafx.scene.shape.Rectangle(0, 0, 5, 6);
MyBoxLog.console("javafx.scene.shape.Rectangle: " + rect.toString());
MyBoxLog.console("default isPickOnBounds: " + rect.isPickOnBounds());
MyBoxLog.console("rect.contains (rect.getX(), rect.getY()): " + rect.contains(rect.getX(), rect.getY())
+ " rect.contains (rect.getWidth(), rect.getHeight()):" + rect.contains(rect.getWidth(), rect.getHeight()));
Bounds bind = rect.getBoundsInLocal();
MyBoxLog.console("rect.getBoundsInLocal(): ");
MyBoxLog.console("bind.getMinX: " + bind.getMinX()
+ " bind.getMinY: " + bind.getMinY()
+ " bind.getMaxX: " + bind.getMaxX()
+ " bind.getMaxY: " + bind.getMaxY()
+ " bind.getMaxX: " + bind.getMaxX()
+ " bind.getWidth: " + bind.getWidth()
+ " bind.getHeight: " + bind.getHeight());
MyBoxLog.console("bind.contains (bind.getMinX(), bind.getMinY()): " + bind.contains(bind.getMinX(), bind.getMinY())
+ " bind.contains (bind.getMaxX(), bind.getMaxY()):" + bind.contains(bind.getMaxX(), bind.getMaxY())
+ " bind.contains (bind.getWidth(), bind.getHeight()):" + bind.contains(bind.getWidth(), bind.getHeight()));
MyBoxLog.console("---------------------");
rect.setPickOnBounds(!rect.isPickOnBounds());
MyBoxLog.console("javafx.scene.shape.Rectangle: " + rect.toString());
MyBoxLog.console("isPickOnBounds: " + rect.isPickOnBounds());
MyBoxLog.console("rect.contains (rect.getX(), rect.getY()): " + rect.contains(rect.getX(), rect.getY())
+ " rect.contains (rect.getWidth(), rect.getHeight()):" + rect.contains(rect.getWidth(), rect.getHeight()));
bind = rect.getBoundsInLocal();
MyBoxLog.console("rect.getBoundsInLocal(): ");
MyBoxLog.console("bind.getMinX: " + bind.getMinX()
+ " bind.getMinY: " + bind.getMinY()
+ " bind.getMaxX: " + bind.getMaxX()
+ " bind.getMaxY: " + bind.getMaxY()
+ " bind.getMaxX: " + bind.getMaxX()
+ " bind.getWidth: " + bind.getWidth()
+ " bind.getHeight: " + bind.getHeight());
MyBoxLog.console("bind.contains (bind.getMinX(), bind.getMinY()): " + bind.contains(bind.getMinX(), bind.getMinY())
+ " bind.contains (bind.getMaxX(), bind.getMaxY()):" + bind.contains(bind.getMaxX(), bind.getMaxY())
+ " bind.contains (bind.getWidth(), bind.getHeight()):" + bind.contains(bind.getWidth(), bind.getHeight()));
MyBoxLog.console("---------------------");
Rectangle2D.Double rect2d = new Rectangle2D.Double(0, 0, 5, 6);
MyBoxLog.console("java.awt.geom.Rectangle2D.Double: " + rect2d.toString());
MyBoxLog.console("rect2d.getMinX: " + rect2d.getMinX()
+ " rect2d.getMinY: " + rect2d.getMinY()
+ " rect2d.getMaxX: " + rect2d.getMaxX()
+ " rect2d.getMaxY: " + rect2d.getMaxY()
+ " rect2d.getMaxX: " + rect2d.getMaxX()
+ " rect2d.getWidth: " + rect2d.getWidth()
+ " rect2d.getHeight: " + rect2d.getHeight());
MyBoxLog.console("rect2d.contains (rect.getX(), rect2d.getY()): " + rect2d.contains(rect2d.getX(), rect2d.getY())
+ " rect2d.contains (rect.getWidth(), rect2d.getHeight()):" + rect2d.contains(rect2d.getWidth(), rect2d.getHeight()));
Rectangle bind2d = rect2d.getBounds();
MyBoxLog.console("rect2d.getBounds(): ");
MyBoxLog.console("bind2d.getMinX: " + bind2d.getMinX()
+ " bind2d.getMinY: " + bind2d.getMinY()
+ " bind2d.getMaxX: " + bind2d.getMaxX()
+ " bind2d.getMaxY: " + bind2d.getMaxY()
+ " bind2d.getMaxX: " + bind2d.getMaxX()
+ " bind2d.getWidth: " + bind2d.getWidth()
+ " bind2d.getHeight: " + bind2d.getHeight());
MyBoxLog.console("bind2d.contains (bind2d.getMinX(), bind2d.getMinY()): " + bind2d.contains(bind2d.getMinX(), bind2d.getMinY())
+ " bind2d.contains (bind2d.getMaxX(), bind2d.getMaxY()):" + bind2d.contains(bind2d.getMaxX(), bind2d.getMaxY())
+ " bind2d.contains (bind2d.getWidth(), bind2d.getHeight()):" + bind2d.contains(bind2d.getWidth(), bind2d.getHeight()));
}
}
| 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/dev/MyBoxLog.java | released/MyBox/src/main/java/mara/mybox/dev/MyBoxLog.java | package mara.mybox.dev;
import java.util.Date;
import javafx.application.Platform;
import mara.mybox.controller.MyBoxLogViewerController;
import mara.mybox.db.data.BaseData;
import mara.mybox.db.data.ColumnDefinition;
import mara.mybox.db.table.TableMyBoxLog;
import mara.mybox.tools.DateTools;
import mara.mybox.value.AppVariables;
import mara.mybox.value.Languages;
/**
* @Author Mara
* @CreateDate 2020-11-24
* @License Apache License Version 2.0
*/
public class MyBoxLog extends BaseData {
protected long mblid, count;
protected Date time;
protected LogType logType;
protected String fileName, className, methodName, log, comments, callers, typeName;
protected int line;
public static MyBoxLog LastMyBoxLog;
public static long LastRecordTime;
public static int MinInterval = 1; // ms
public static enum LogType {
Console, Error, Debug, Info, Macro
}
public MyBoxLog() {
mblid = -1;
time = new Date();
logType = LogType.Console;
}
@Override
public boolean valid() {
return valid(this);
}
@Override
public boolean setValue(String column, Object value) {
return setValue(this, column, value);
}
@Override
public Object getValue(String column) {
return getValue(this, column);
}
public boolean equalTo(MyBoxLog myMyboxLog) {
return myMyboxLog != null && logType == myMyboxLog.getLogType()
&& log != null && log.equals(myMyboxLog.getLog())
&& fileName != null && fileName.equals(myMyboxLog.getFileName())
&& className != null && className.equals(myMyboxLog.getClassName())
&& methodName != null && methodName.equals(myMyboxLog.getMethodName())
&& callers != null && callers.equals(myMyboxLog.getCallers())
&& line == myMyboxLog.getLine();
}
/*
static methods;
*/
public static MyBoxLog create() {
return new MyBoxLog();
}
public static boolean setValue(MyBoxLog data, String column, Object value) {
if (data == null || column == null) {
return false;
}
try {
switch (column) {
case "mblid":
data.setMblid(value == null ? -1 : (long) value);
return true;
case "time":
data.setTime(value == null ? null : (Date) value);
return true;
case "log_type":
data.setLogType(logType((short) value));
return true;
case "file_name":
data.setFileName(value == null ? null : (String) value);
return true;
case "class_name":
data.setClassName(value == null ? null : (String) value);
return true;
case "method_name":
data.setMethodName(value == null ? null : (String) value);
return true;
case "line":
data.setLine((int) value);
return true;
case "log":
data.setLog(value == null ? null : (String) value);
return true;
case "comments":
data.setComments(value == null ? null : (String) value);
return true;
case "callers":
data.setCallers(value == null ? null : (String) value);
return true;
}
} catch (Exception e) {
MyBoxLog.debug(e);
}
return false;
}
public static Object getValue(MyBoxLog data, String column) {
if (data == null || column == null) {
return null;
}
switch (column) {
case "mblid":
return data.getMblid();
case "time":
return data.getTime();
case "log_type":
return logType(data.getLogType());
case "file_name":
return data.getFileName();
case "class_name":
return data.getClassName();
case "method_name":
return data.getMethodName();
case "line":
return data.getLine();
case "log":
return data.getLog();
case "comments":
return data.getComments();
case "callers":
return data.getCallers();
}
return null;
}
public static boolean valid(MyBoxLog data) {
return data != null
&& data.getTime() != null && data.getLog() != null && data.getLogType() != null;
}
public static String displayColumn(MyBoxLog data, ColumnDefinition column, Object value) {
if (data == null || column == null || value == null) {
return null;
}
if ("log_type".equals(column.getColumnName())) {
return Languages.message(data.getLogType().name());
}
return column.formatValue(value);
}
public static short logType(LogType logType) {
if (logType == null) {
return (short) LogType.Info.ordinal();
}
return (short) logType.ordinal();
}
public static LogType logType(short logType) {
try {
return LogType.values()[logType];
} catch (Exception e) {
return LogType.Info;
}
}
public static MyBoxLog console(Object log) {
return log(LogType.Console, log, null);
}
public static MyBoxLog console(Object log, String comments) {
return log(LogType.Console, log, comments);
}
public static MyBoxLog debug(Object log) {
return log(LogType.Debug, log, null);
}
public static MyBoxLog debug(Object log, String comments) {
return log(LogType.Debug, log, comments);
}
public static MyBoxLog error(Object log) {
return log(LogType.Error, log, null);
}
public static MyBoxLog error(Object log, String comments) {
return log(LogType.Error, log, comments);
}
public static MyBoxLog info(Object log) {
return log(LogType.Info, log, null);
}
public static MyBoxLog info(Object log, String comments) {
return log(LogType.Info, log, comments);
}
public static boolean isFlooding() {
return new Date().getTime() - LastRecordTime < MinInterval;
}
private static MyBoxLog log(LogType type, Object log, String comments) {
try {
if (type == null) {
return null;
}
// if (isFlooding()) {
// return null;
// }
String logString = log == null ? "null" : log.toString();
if (logString.contains("java.sql.SQLException: No suitable driver found")
|| logString.contains("java.sql.SQLNonTransientConnectionException")) {
if (AppVariables.ignoreDbUnavailable) {
return null;
}
AppVariables.ignoreDbUnavailable = true; // Record only once
}
StackTraceElement[] stacks = new Throwable().getStackTrace();
if (stacks.length <= 2) {
return null;
}
StackTraceElement stack = stacks[2];
boolean isMylog = stack.getClassName().contains("MyBoxLog");
String callers = null;
for (int i = 3; i < stacks.length; ++i) {
StackTraceElement s = stacks[i];
if (s.getClassName().startsWith("mara.mybox")) {
if (callers != null) {
callers += "\n";
} else {
callers = "";
}
callers += s.getFileName() + " " + s.getClassName()
+ " " + s.getMethodName() + " " + s.getLineNumber();
if (s.getClassName().contains("MyBoxLog")) {
isMylog = true;
}
}
}
MyBoxLog myboxLog = MyBoxLog.create()
.setLogType(type)
.setLog(logString)
.setComments(comments)
.setFileName(stack.getFileName())
.setClassName(stack.getClassName())
.setMethodName(stack.getMethodName())
.setLine(stack.getLineNumber())
.setCallers(callers);
String logText = println(myboxLog,
type == LogType.Error
|| (AppVariables.detailedDebugLogs && type == LogType.Debug));
System.out.print(logText);
if (LastMyBoxLog != null && LastMyBoxLog.equalTo(myboxLog)) {
return myboxLog;
}
if (logString.contains("java.sql.SQLNonTransientConnectionException")) {
type = LogType.Debug;
}
if (AppVariables.popErrorLogs && type == LogType.Error) {
Platform.runLater(() -> {
MyBoxLogViewerController controller = MyBoxLogViewerController.oneOpen();
if (controller != null) {
controller.addLog(myboxLog);
}
});
}
boolean notSave = isMylog || type == LogType.Console
|| (type == LogType.Debug && !AppVariables.saveDebugLogs);
if (!notSave) {
new TableMyBoxLog().writeData(myboxLog);
}
if (type == LogType.Error && AppVariables.autoTestingController != null) {
AppVariables.autoTestingController.errorHappened();
}
LastMyBoxLog = myboxLog;
LastRecordTime = new Date().getTime();
return myboxLog;
} catch (Exception e) {
return null;
}
}
public static String print(MyBoxLog log, boolean printCallers) {
return print(log, " ", printCallers);
}
public static String println(MyBoxLog log, boolean printCallers) {
return println(log, " ", printCallers);
}
public static String println(MyBoxLog log, String separator, boolean printCallers) {
return print(log, separator, printCallers) + "\n";
}
public static String print(MyBoxLog log, String separator, boolean printCallers) {
if (log == null) {
return "";
}
String s = DateTools.datetimeToString(log.getTime())
+ (log.getLogType() != null && log.getLogType() != LogType.Console ? separator + log.getLogType() : "")
+ (log.getFileName() != null ? separator + log.getFileName() : "")
+ (log.getClassName() != null ? separator + log.getClassName() : "")
+ (log.getMethodName() != null ? separator + log.getMethodName() : "")
+ (log.getLine() >= 0 ? separator + log.getLine() : "")
+ (log.getLog() != null ? separator + log.getLog() : "null")
+ (log.getComments() != null ? separator + log.getComments() : "");
if (printCallers && log.getCallers() != null && !log.getCallers().isBlank()) {
String[] array = log.getCallers().split("\n");
for (String a : array) {
s += "\n\t\t\t\t" + a;
}
}
return s;
}
/*
set/get
*/
public Date getTime() {
return time;
}
public MyBoxLog setTime(Date time) {
this.time = time;
return this;
}
public String getLog() {
return log;
}
public MyBoxLog setLog(String log) {
this.log = log;
return this;
}
public LogType getLogType() {
return logType;
}
public MyBoxLog setLogType(LogType logType) {
this.logType = logType;
return this;
}
public String getClassName() {
return className;
}
public MyBoxLog setClassName(String className) {
this.className = className;
return this;
}
public String getMethodName() {
return methodName;
}
public MyBoxLog setMethodName(String methodName) {
this.methodName = methodName;
return this;
}
public long getMblid() {
return mblid;
}
public MyBoxLog setMblid(long mblid) {
this.mblid = mblid;
return this;
}
public String getComments() {
return comments;
}
public MyBoxLog setComments(String comments) {
this.comments = comments;
return this;
}
public int getLine() {
return line;
}
public MyBoxLog setLine(int line) {
this.line = line;
return this;
}
public String getFileName() {
return fileName;
}
public MyBoxLog setFileName(String fileName) {
this.fileName = fileName;
return this;
}
public String getCallers() {
return callers;
}
public MyBoxLog setCallers(String callers) {
this.callers = callers;
return this;
}
public String getTypeName() {
if (logType != null) {
typeName = Languages.message(logType.name());
}
return typeName;
}
public void setTypeName(String typeName) {
this.typeName = typeName;
}
}
| 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/dev/BaseMacro.java | released/MyBox/src/main/java/mara/mybox/dev/BaseMacro.java | package mara.mybox.dev;
import java.io.File;
import java.util.LinkedHashMap;
import mara.mybox.controller.BaseTaskController;
import mara.mybox.fxml.FxTask;
import mara.mybox.tools.StringTools;
import mara.mybox.value.AppValues;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2025-8-29
* @License Apache License Version 2.0
*/
public class BaseMacro {
public static final String ParameterPrefix = "MacroPara_";
protected String script;
protected LinkedHashMap<String, String> arguments; // values defined in macro
protected LinkedHashMap<String, Object> parameters; // values referred when run
protected BaseTaskController controller;
protected boolean defaultOpenResult, ok;
protected FxTask<Void> task;
/*
build macro
*/
public BaseMacro() {
init();
}
public BaseMacro(boolean openResult) {
init();
this.defaultOpenResult = openResult;
}
public final void init() {
script = null;
arguments = null;
reset();
}
public void reset() {
parameters = null;
controller = null;
task = null;
ok = false;
defaultOpenResult = false;
}
public void copyTo(BaseMacro macro) {
if (macro == null) {
return;
}
macro.setScript(script);
macro.setArguments(arguments);
macro.setParameters(parameters);
macro.setController(controller);
macro.setTask(task);
macro.setOk(ok);
macro.setDefaultOpenResult(defaultOpenResult);
}
public void copyFrom(BaseMacro macro) {
if (macro == null) {
return;
}
script = macro.getScript();
arguments = macro.getArguments();
parameters = macro.getParameters();
controller = macro.getController();
task = macro.getTask();
ok = macro.isOk();
defaultOpenResult = macro.isDefaultOpenResult();
}
public void info() {
if (arguments == null) {
return;
}
MyBoxLog.console(arguments);
}
public BaseMacro make(String inScript) {
try {
parseString(inScript);
String func = pickFunction();
if (func == null) {
return null;
}
func = func.toLowerCase();
switch (func) {
case "image":
ImageMacro imageMacro = new ImageMacro();
imageMacro.copyFrom(this);
return imageMacro;
case "pdf":
PdfMacro pdfMacro = new PdfMacro();
pdfMacro.copyFrom(this);
return pdfMacro;
}
} catch (Exception e) {
MyBoxLog.error(e);
}
return null;
}
// helped with deepseek
public boolean parseString(String inScript) {
try {
script = inScript;
if (script == null || script.isBlank()) {
return false;
}
boolean inDoubleQuotes = false;
boolean inSingleQuotes = false;
StringBuilder currentToken = new StringBuilder();
for (int i = 0; i < script.length(); i++) {
char c = script.charAt(i);
if (c == '"' && !inSingleQuotes) {
inDoubleQuotes = !inDoubleQuotes;
currentToken.append(c);
continue;
} else if (c == '\'' && !inDoubleQuotes) {
inSingleQuotes = !inSingleQuotes;
currentToken.append(c);
continue;
}
if (c == ' ' && !inDoubleQuotes && !inSingleQuotes) {
if (currentToken.length() > 0) {
processToken(currentToken.toString());
currentToken.setLength(0);
}
continue;
}
currentToken.append(c);
}
if (currentToken.length() > 0) {
processToken(currentToken.toString());
}
return true;
} catch (Exception e) {
MyBoxLog.error(e);
return false;
}
}
private void processToken(String token) {
if (token.contains("=")) {
int equalsIndex = token.indexOf('=');
String key = token.substring(0, equalsIndex);
String value = token.substring(equalsIndex + 1);
value = removeQuotes(value);
writeArgument(key, value);
} else {
String value = removeQuotes(token);
writeArgument(ParameterPrefix + (arguments != null ? arguments.size() + 1 : 1), value);
}
}
private static String removeQuotes(String str) {
if ((str.startsWith("\"") && str.endsWith("\""))
|| (str.startsWith("'") && str.endsWith("'"))) {
return str.substring(1, str.length() - 1);
}
return str;
}
public boolean parseArray(String[] args) {
try {
if (args == null) {
return false;
}
for (String arg : args) {
processToken(arg);
if (script == null) {
script = arg;
} else {
script += " " + arg;
}
}
return true;
} catch (Exception e) {
MyBoxLog.error(e);
return false;
}
}
/*
arguments: values defined in macro
*/
// key is case-insensitive
public void writeArgument(String key, String value) {
if (key == null) {
return;
}
if (arguments == null) {
arguments = new LinkedHashMap<>();
}
arguments.put(key.toLowerCase(), value);
}
// key is case-insensitive
public String readArgument(String key) {
if (key == null || arguments == null) {
return null;
}
return arguments.get(key.toLowerCase());
}
public int readIntArgument(String key) {
try {
return Integer.parseInt(readArgument(key));
} catch (Exception e) {
return AppValues.InvalidInteger;
}
}
public short readShortArgument(String key) {
try {
return Short.parseShort(readArgument(key));
} catch (Exception e) {
return AppValues.InvalidShort;
}
}
public boolean readBooleanArgument(String key) {
try {
return StringTools.isTrue(readArgument(key));
} catch (Exception e) {
return false;
}
}
/*
parameters: values referred when run
*/
// key is case-insensitive
public void writeParameter(String key, Object value) {
if (key == null) {
return;
}
if (parameters == null) {
parameters = new LinkedHashMap<>();
}
if (value != null) {
parameters.put(key.toLowerCase(), value);
} else {
parameters.remove(key);
}
}
// key is case-insensitive
public Object readParameter(String key) {
if (key == null || parameters == null) {
return null;
}
return parameters.get(key.toLowerCase());
}
public String pickFunction() {
try {
String func = readArgument(ParameterPrefix + "1");
writeParameter("function", func);
return func;
} catch (Exception e) {
return null;
}
}
public String pickOperation() {
try {
String op = defaultOperation();
String v = readArgument(ParameterPrefix + "2");
if (v != null) {
op = v;
}
writeParameter("operation", op);
return op;
} catch (Exception e) {
return null;
}
}
public File pickInputFile() {
try {
File file = defaultInputFile();
String v = readArgument("inputFile");
if (v != null) {
File fv = new File(v);
if (fv.exists()) {
file = fv;
}
}
writeParameter("inputFile", file);
return file;
} catch (Exception e) {
return null;
}
}
public File pickOutputFile() {
try {
File file = defaultOutputFile();
String v = readArgument("outputFile");
if (v != null) {
file = new File(v);
}
writeParameter("outputFile", file);
return file;
} catch (Exception e) {
return null;
}
}
public boolean pickOpenResult() {
try {
boolean bv = defaultOpenResult;
String v = readArgument("openResult");
if (v != null) {
bv = StringTools.isTrue(v);
}
writeParameter("openResult", bv);
return bv;
} catch (Exception e) {
return false;
}
}
public String defaultOperation() {
return null;
}
public File defaultInputFile() {
return null;
}
public File defaultOutputFile() {
return null;
}
public String getFunction() {
try {
return (String) readParameter("function");
} catch (Exception e) {
return null;
}
}
public String getOperation() {
try {
return (String) readParameter("operation");
} catch (Exception e) {
return null;
}
}
public File getInputFile() {
try {
return (File) readParameter("inputFile");
} catch (Exception e) {
return null;
}
}
public File getOutputFile() {
try {
return (File) readParameter("outputFile");
} catch (Exception e) {
return null;
}
}
public boolean isOpenResult() {
try {
return (boolean) readParameter("openResult");
} catch (Exception e) {
}
return defaultOpenResult;
}
/*
run
*/
public boolean checkParameters() {
try {
parameters = null;
String function = pickFunction();
if (function == null) {
displayError(message("Invalid" + ": function"));
return false;
}
String operation = pickOperation();
if (operation == null) {
displayError(message("Invalid" + ": operation"));
return false;
}
pickInputFile();
pickOutputFile();
if (!checkMoreParameters()) {
return false;
}
pickOpenResult();
String command = "";
for (String key : parameters.keySet()) {
if ("inputFile".equalsIgnoreCase(key) || "outputFile".equalsIgnoreCase(key)) {
continue;
}
Object v = readParameter(key);
if (v == null) {
continue;
}
String s = v.toString();
if (s.contains(" ")) {
s = "\"" + s + "\"";
}
if (!command.isBlank()) {
command += " ";
}
command += key + "=" + s;
}
File inputFile = getInputFile();
if (inputFile != null) {
command += " inputFile=\"" + inputFile.getAbsolutePath() + "\"";
}
File outputFile = getOutputFile();
if (outputFile != null) {
command += " outputFile=\"" + outputFile.getAbsolutePath() + "\"";
}
displayInfo(message("Parameters") + ": " + command);
return true;
} catch (Exception e) {
displayError(e.toString());
return false;
}
}
public boolean checkMoreParameters() {
return true;
}
public boolean run() {
return false;
}
public void displayResult() {
displayEnd();
if (isOpenResult()) {
openResult();
}
}
public void displayEnd() {
try {
if (ok) {
displayInfo(message("Completed"));
} else {
displayInfo(message("Failed"));
}
File outputFile = getOutputFile();
if (outputFile != null && outputFile.exists()) {
displayInfo(message("FileGenerated") + ": " + outputFile);
}
} catch (Exception e) {
displayError(e.toString());
}
}
public void openResult() {
}
public void displayError(String info) {
display(info, true);
}
public void displayInfo(String info) {
display(info, false);
}
public void display(String info, boolean isError) {
if (controller != null) {
controller.showLogs(info);
} else if (task != null) {
task.setInfo(info);
} else if (isError) {
MyBoxLog.error(info);
} else {
MyBoxLog.console(info);
}
}
/*
static
*/
public static BaseMacro create() {
return new BaseMacro();
}
public static BaseMacro create(String inScript, boolean openResult) {
BaseMacro macro = new BaseMacro(openResult);
return macro.make(inScript);
}
public static BaseMacro create(String[] args) {
BaseMacro macro = new BaseMacro();
macro.parseArray(args);
return macro.make(macro.getScript());
}
/*
get/set
*/
public LinkedHashMap<String, String> getArguments() {
return arguments;
}
public BaseMacro setArguments(LinkedHashMap<String, String> arguments) {
this.arguments = arguments;
return this;
}
public LinkedHashMap<String, Object> getParameters() {
return parameters;
}
public BaseMacro setParameters(LinkedHashMap<String, Object> parameters) {
this.parameters = parameters;
return this;
}
public String getScript() {
return script;
}
public BaseMacro setScript(String script) {
this.script = script;
return this;
}
public boolean isDefaultOpenResult() {
return defaultOpenResult;
}
public BaseMacro setDefaultOpenResult(boolean defaultOpenResult) {
this.defaultOpenResult = defaultOpenResult;
return this;
}
public BaseTaskController getController() {
return controller;
}
public BaseMacro setController(BaseTaskController controller) {
this.controller = controller;
return this;
}
public boolean isOk() {
return ok;
}
public BaseMacro setOk(boolean ok) {
this.ok = ok;
return this;
}
public FxTask<Void> getTask() {
return task;
}
public BaseMacro setTask(FxTask<Void> task) {
this.task = task;
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/dev/PdfMacro.java | released/MyBox/src/main/java/mara/mybox/dev/PdfMacro.java | package mara.mybox.dev;
/**
* @Author Mara
* @CreateDate 2025-8-29
* @License Apache License Version 2.0
*/
public class PdfMacro extends BaseMacro {
@Override
public boolean run() {
try {
} 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/dev/DevTools.java | released/MyBox/src/main/java/mara/mybox/dev/DevTools.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package mara.mybox.dev;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import mara.mybox.db.table.TableStringValues;
/**
*
* @author mara
*/
public class DevTools {
public static List<Integer> installedVersion(Connection conn) {
List<Integer> versions = new ArrayList<>();
try {
List<String> installed = TableStringValues.read(conn, "InstalledVersions");
for (String v : installed) {
versions.add(myboxVersion(v));
}
} catch (Exception e) {
// MyBoxLog.debug(e);
}
return versions;
}
public static int lastVersion(Connection conn) {
try {
List<Integer> versions = installedVersion(conn);
if (!versions.isEmpty()) {
Collections.sort(versions);
return versions.get(versions.size() - 1);
}
} catch (Exception e) {
// MyBoxLog.debug(e);
}
return 0;
}
public static int myboxVersion(String string) {
try {
String[] vs = string.split("\\.");
switch (vs.length) {
case 1:
return Integer.parseInt(vs[0]) * 1000000;
case 2:
return Integer.parseInt(vs[0]) * 1000000 + Integer.parseInt(vs[1]) * 1000;
case 3:
return Integer.parseInt(vs[0]) * 1000000 + Integer.parseInt(vs[1]) * 1000 + Integer.parseInt(vs[2]);
}
} catch (Exception e) {
// MyBoxLog.debug(e);
}
return 0;
}
public static String myboxVersion(int i) {
try {
int v1 = i / 1000000;
int ii = i % 1000000;
int v2 = ii / 1000;
int v3 = ii % 1000;
if (v3 == 0) {
return v1 + "." + v2;
} else {
return v1 + "." + v2 + "." + v3;
}
} catch (Exception e) {
// MyBoxLog.debug(e);
}
return i + "";
}
public static String getFileName() {
StackTraceElement[] stacks = new Throwable().getStackTrace();
return stacks[1].getFileName();
}
public static String getMethodName() {
StackTraceElement[] stacks = new Throwable().getStackTrace();
return stacks[1].getMethodName();
}
public static String getClassName() {
StackTraceElement[] stacks = new Throwable().getStackTrace();
return stacks[1].getClassName();
}
public static int getLineNumber() {
StackTraceElement[] stacks = new Throwable().getStackTrace();
return stacks[1].getLineNumber();
}
}
| 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/dev/TestCase.java | released/MyBox/src/main/java/mara/mybox/dev/TestCase.java | package mara.mybox.dev;
import java.util.ArrayList;
import java.util.List;
import mara.mybox.controller.BaseController;
import mara.mybox.value.AppValues;
import mara.mybox.value.Fxmls;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2022-1-5
* @License Apache License Version 2.0
*/
public class TestCase {
protected int id;
protected String object, version, fxml;
protected Operation operation;
protected Type type;
protected Stage stage;
protected Status Status;
protected BaseController controller;
public static enum Type {
Function, UserInterface, Bundary, Data, API, IO, Exception, Performance, Robustness,
Usability, Compatibility, Security, Document
}
public static enum Operation {
Handle, OpenInterface, ClickButton, OpenFile, Edit
}
public static enum Stage {
Alpha, Unit, Integration, Verification, Beta
}
public static enum Status {
NotTested, Testing, Success, Fail
}
public TestCase() {
init();
}
public TestCase(int id, String object, String fxml) {
init();
this.id = id;
this.object = object;
this.fxml = fxml;
}
private void init() {
type = Type.UserInterface;
operation = Operation.OpenInterface;
version = AppValues.AppVersion;
stage = Stage.Alpha;
Status = Status.NotTested;
}
/*
static
*/
public static List<TestCase> testCases() {
List<TestCase> cases = new ArrayList<>();
try {
int index = 1;
cases.add(new TestCase(index++, message("TextTree"), Fxmls.DataTreeFxml).setType(Type.Data));
cases.add(new TestCase(index++, message("HtmlTree"), Fxmls.DataTreeFxml).setType(Type.Data));
cases.add(new TestCase(index++, message("PdfView"), Fxmls.PdfViewFxml));
cases.add(new TestCase(index++, message("PdfConvertImagesBatch"), Fxmls.PdfConvertImagesBatchFxml));
cases.add(new TestCase(index++, message("PdfImagesConvertBatch"), Fxmls.PdfImagesConvertBatchFxml));
cases.add(new TestCase(index++, message("PdfCompressImagesBatch"), Fxmls.PdfCompressImagesBatchFxml));
cases.add(new TestCase(index++, message("PdfConvertHtmlsBatch"), Fxmls.PdfConvertHtmlsBatchFxml));
cases.add(new TestCase(index++, message("PdfExtractImagesBatch"), Fxmls.PdfExtractImagesBatchFxml));
cases.add(new TestCase(index++, message("PdfExtractTextsBatch"), Fxmls.PdfExtractTextsBatchFxml));
cases.add(new TestCase(index++, message("PdfOCRBatch"), Fxmls.PdfOCRBatchFxml));
cases.add(new TestCase(index++, message("PdfSplitBatch"), Fxmls.PdfSplitBatchFxml));
cases.add(new TestCase(index++, message("MergePdf"), Fxmls.PdfMergeFxml));
cases.add(new TestCase(index++, message("PDFAttributes"), Fxmls.PdfAttributesFxml));
cases.add(new TestCase(index++, message("PDFAttributesBatch"), Fxmls.PdfAttributesBatchFxml));
cases.add(new TestCase(index++, message("MarkdownEditer"), Fxmls.MarkdownEditorFxml));
cases.add(new TestCase(index++, message("MarkdownToHtml"), Fxmls.MarkdownToHtmlFxml));
cases.add(new TestCase(index++, message("MarkdownToText"), Fxmls.MarkdownToTextFxml));
cases.add(new TestCase(index++, message("MarkdownToPdf"), Fxmls.MarkdownToPdfFxml));
cases.add(new TestCase(index++, message("HtmlEditor"), Fxmls.HtmlEditorFxml));
cases.add(new TestCase(index++, message("WebFind"), Fxmls.HtmlFindFxml));
cases.add(new TestCase(index++, message("WebElements"), Fxmls.HtmlElementsFxml));
cases.add(new TestCase(index++, message("HtmlSnap"), Fxmls.HtmlSnapFxml));
cases.add(new TestCase(index++, message("HtmlExtractTables"), Fxmls.HtmlExtractTablesFxml));
cases.add(new TestCase(index++, message("HtmlToMarkdown"), Fxmls.HtmlToMarkdownFxml));
cases.add(new TestCase(index++, message("HtmlToText"), Fxmls.HtmlToTextFxml));
cases.add(new TestCase(index++, message("HtmlToPdf"), Fxmls.HtmlToPdfFxml));
cases.add(new TestCase(index++, message("HtmlSetCharset"), Fxmls.HtmlSetCharsetFxml));
cases.add(new TestCase(index++, message("HtmlSetStyle"), Fxmls.HtmlSetStyleFxml));
cases.add(new TestCase(index++, message("HtmlMergeAsHtml"), Fxmls.HtmlMergeAsHtmlFxml));
cases.add(new TestCase(index++, message("HtmlMergeAsMarkdown"), Fxmls.HtmlMergeAsMarkdownFxml));
cases.add(new TestCase(index++, message("HtmlMergeAsPDF"), Fxmls.HtmlMergeAsPDFFxml));
cases.add(new TestCase(index++, message("HtmlMergeAsText"), Fxmls.HtmlMergeAsTextFxml));
cases.add(new TestCase(index++, message("HtmlFrameset"), Fxmls.HtmlFramesetFxml));
cases.add(new TestCase(index++, message("TextEditer"), Fxmls.TextEditorFxml));
cases.add(new TestCase(index++, message("TextConvertSplit"), Fxmls.TextFilesConvertFxml));
cases.add(new TestCase(index++, message("TextFilesMerge"), Fxmls.TextFilesMergeFxml));
cases.add(new TestCase(index++, message("TextReplaceBatch"), Fxmls.TextReplaceBatchFxml));
cases.add(new TestCase(index++, message("TextFilterBatch"), Fxmls.TextFilterBatchFxml));
cases.add(new TestCase(index++, message("TextToHtml"), Fxmls.TextToHtmlFxml));
cases.add(new TestCase(index++, message("TextToPdf"), Fxmls.TextToPdfFxml));
cases.add(new TestCase(index++, message("WordView"), Fxmls.WordViewFxml));
cases.add(new TestCase(index++, message("WordToHtml"), Fxmls.WordToHtmlFxml));
cases.add(new TestCase(index++, message("WordToPdf"), Fxmls.WordToPdfFxml));
cases.add(new TestCase(index++, message("PptView"), Fxmls.PptViewFxml));
cases.add(new TestCase(index++, message("PptToImages"), Fxmls.PptToImagesFxml));
cases.add(new TestCase(index++, message("PptToPdf"), Fxmls.PptToPdfFxml));
cases.add(new TestCase(index++, message("PptExtract"), Fxmls.PptExtractFxml));
cases.add(new TestCase(index++, message("PptSplit"), Fxmls.PptSplitFxml));
cases.add(new TestCase(index++, message("PptxMerge"), Fxmls.PptxMergeFxml));
cases.add(new TestCase(index++, message("ExtractTextsFromMS"), Fxmls.ExtractTextsFromMSFxml));
cases.add(new TestCase(index++, message("BytesEditer"), Fxmls.BytesEditorFxml));
cases.add(new TestCase(index++, message("TextInMyBoxClipboard"), Fxmls.TextInMyBoxClipboardFxml));
cases.add(new TestCase(index++, message("TextInSystemClipboard"), Fxmls.TextInSystemClipboardFxml));
cases.add(new TestCase(index++, message("ImagesBrowser"), Fxmls.ImagesBrowserFxml));
cases.add(new TestCase(index++, message("ImageAnalyse"), Fxmls.ImageAnalyseFxml));
cases.add(new TestCase(index++, message("ImagesPlay"), Fxmls.ImagesPlayFxml));
cases.add(new TestCase(index++, message("ImageEditor"), Fxmls.ImageEditorFxml));
cases.add(new TestCase(index++, message("ImageBatch") + "-" + message("Size"), Fxmls.ImageSizeBatchFxml));
cases.add(new TestCase(index++, message("ImageBatch") + "-" + message("Crop"), Fxmls.ImageCropBatchFxml));
cases.add(new TestCase(index++, message("ImageBatch") + "-" + message("Paste"), Fxmls.ImagePasteBatchFxml));
cases.add(new TestCase(index++, message("ImageBatch") + "-" + message("AdjustColor"), Fxmls.ImageAdjustColorBatchFxml));
cases.add(new TestCase(index++, message("ImageBatch") + "-" + message("ReplaceColor"), Fxmls.ImageReplaceColorBatchFxml));
cases.add(new TestCase(index++, message("ImageBatch") + "-" + message("ReduceColors"), Fxmls.ImageReduceColorsBatchFxml));
cases.add(new TestCase(index++, message("ImageBatch") + "-" + message("EdgeDetection"), Fxmls.ImageEdgeBatchFxml));
cases.add(new TestCase(index++, message("ImageBatch") + "-" + message("Sharpen"), Fxmls.ImageSharpenBatchFxml));
cases.add(new TestCase(index++, message("ImageBatch") + "-" + message("Smooth"), Fxmls.ImageSmoothBatchFxml));
cases.add(new TestCase(index++, message("ImageBatch") + "-" + message("Text"), Fxmls.ImageTextBatchFxml));
cases.add(new TestCase(index++, message("ImageBatch") + "-" + message("Round"), Fxmls.ImageRoundBatchFxml));
cases.add(new TestCase(index++, message("ImageBatch") + "-" + message("Shadow"), Fxmls.ImageShadowBatchFxml));
cases.add(new TestCase(index++, message("ImageBatch") + "-" + message("Mirror"), Fxmls.ImageMirrorBatchFxml));
cases.add(new TestCase(index++, message("ImageBatch") + "-" + message("Shear"), Fxmls.ImageShearBatchFxml));
cases.add(new TestCase(index++, message("ImageBatch") + "-" + message("Rotate"), Fxmls.ImageRotateBatchFxml));
cases.add(new TestCase(index++, message("ImageBatch") + "-" + message("Margins"), Fxmls.ImageMarginsBatchFxml));
cases.add(new TestCase(index++, message("ImagesSplice"), Fxmls.ImagesSpliceFxml));
cases.add(new TestCase(index++, message("ImageAlphaAdd"), Fxmls.ImageAlphaAddBatchFxml));
cases.add(new TestCase(index++, message("ImageSplit"), Fxmls.ImageSplitFxml));
cases.add(new TestCase(index++, message("ImageSample"), Fxmls.ImageSampleFxml));
cases.add(new TestCase(index++, message("ImageAlphaExtract"), Fxmls.ImageAlphaExtractBatchFxml));
cases.add(new TestCase(index++, message("ImageConverterBatch"), Fxmls.ImageConverterBatchFxml));
cases.add(new TestCase(index++, message("ImageOCR"), Fxmls.ImageOCRFxml));
cases.add(new TestCase(index++, message("ImageOCRBatch"), Fxmls.ImageOCRBatchFxml));
cases.add(new TestCase(index++, message("ManageColors"), Fxmls.ColorsManageFxml));
cases.add(new TestCase(index++, message("QueryColor"), Fxmls.ColorQueryFxml));
cases.add(new TestCase(index++, message("ImageScope"), Fxmls.DataTreeFxml).setType(Type.Data));
cases.add(new TestCase(index++, message("DrawChromaticityDiagram"), Fxmls.ChromaticityDiagramFxml));
cases.add(new TestCase(index++, message("IccProfileEditor"), Fxmls.IccProfileEditorFxml));
cases.add(new TestCase(index++, message("RGBColorSpaces"), Fxmls.RGBColorSpacesFxml));
cases.add(new TestCase(index++, message("LinearRGB2XYZMatrix"), Fxmls.RGB2XYZConversionMatrixFxml));
cases.add(new TestCase(index++, message("LinearRGB2RGBMatrix"), Fxmls.RGB2RGBConversionMatrixFxml));
cases.add(new TestCase(index++, message("Illuminants"), Fxmls.IlluminantsFxml));
cases.add(new TestCase(index++, message("ChromaticAdaptationMatrix"), Fxmls.ChromaticAdaptationMatrixFxml));
cases.add(new TestCase(index++, message("ImagesInMyBoxClipboard"), Fxmls.ImageInMyBoxClipboardFxml));
cases.add(new TestCase(index++, message("ImagesInSystemClipboard"), Fxmls.ImageInSystemClipboardFxml));
cases.add(new TestCase(index++, message("ConvolutionKernelManager"), Fxmls.ConvolutionKernelManagerFxml));
cases.add(new TestCase(index++, message("PixelsCalculator"), Fxmls.PixelsCalculatorFxml));
cases.add(new TestCase(index++, message("ImageBase64"), Fxmls.ImageBase64Fxml));
cases.add(new TestCase(index++, message("DataManufacture"), Fxmls.Data2DManufactureFxml));
cases.add(new TestCase(index++, message("ManageData"), Fxmls.Data2DManageFxml));
cases.add(new TestCase(index++, message("CsvConvert"), Fxmls.DataFileCSVConvertFxml));
cases.add(new TestCase(index++, message("CsvMerge"), Fxmls.DataFileCSVMergeFxml));
cases.add(new TestCase(index++, message("ExcelConvert"), Fxmls.DataFileExcelConvertFxml));
cases.add(new TestCase(index++, message("ExcelMerge"), Fxmls.DataFileExcelMergeFxml));
cases.add(new TestCase(index++, message("TextDataConvert"), Fxmls.DataFileTextConvertFxml));
cases.add(new TestCase(index++, message("TextDataMerge"), Fxmls.DataFileTextMergeFxml));
cases.add(new TestCase(index++, message("DataInSystemClipboard"), Fxmls.DataInMyBoxClipboardFxml));
cases.add(new TestCase(index++, message("DataInMyBoxClipboard"), Fxmls.DataInSystemClipboardFxml));
cases.add(new TestCase(index++, message("MatricesManage"), Fxmls.MatricesManageFxml));
cases.add(new TestCase(index++, message("MatrixUnaryCalculation"), Fxmls.MatrixUnaryCalculationFxml));
cases.add(new TestCase(index++, message("MatricesBinaryCalculation"), Fxmls.MatricesBinaryCalculationFxml));
cases.add(new TestCase(index++, message("DatabaseTable"), Fxmls.DataTablesFxml));
cases.add(new TestCase(index++, message("RowExpression"), Fxmls.DataTreeFxml).setType(Type.Data));
cases.add(new TestCase(index++, message("DataColumn"), Fxmls.DataTreeFxml).setType(Type.Data));
cases.add(new TestCase(index++, message("DatabaseSQL"), Fxmls.DataTreeFxml).setType(Type.Data));
cases.add(new TestCase(index++, message("MathFunction"), Fxmls.DataTreeFxml).setType(Type.Data));
cases.add(new TestCase(index++, message("JShell"), Fxmls.DataTreeFxml).setType(Type.Data));
cases.add(new TestCase(index++, message("JEXL"), Fxmls.DataTreeFxml).setType(Type.Data));
cases.add(new TestCase(index++, message("JavaScript"), Fxmls.DataTreeFxml).setType(Type.Data));
cases.add(new TestCase(index++, message("GeographyCode"), Fxmls.GeographyCodeFxml).setType(Type.Data));
cases.add(new TestCase(index++, message("ConvertCoordinate"), Fxmls.ConvertCoordinateFxml));
cases.add(new TestCase(index++, message("BarcodeCreator"), Fxmls.BarcodeCreatorFxml));
cases.add(new TestCase(index++, message("BarcodeDecoder"), Fxmls.BarcodeDecoderFxml));
cases.add(new TestCase(index++, message("MessageDigest"), Fxmls.MessageDigestFxml));
cases.add(new TestCase(index++, message("Base64Conversion"), Fxmls.Base64Fxml));
cases.add(new TestCase(index++, message("TTC2TTF"), Fxmls.FileTTC2TTFFxml));
cases.add(new TestCase(index++, message("FilesArrangement"), Fxmls.FilesArrangementFxml));
cases.add(new TestCase(index++, message("DirectorySynchronize"), Fxmls.DirectorySynchronizeFxml));
cases.add(new TestCase(index++, message("FileCut"), Fxmls.FileCutFxml));
cases.add(new TestCase(index++, message("FilesMerge"), Fxmls.FilesMergeFxml));
cases.add(new TestCase(index++, message("FilesFind"), Fxmls.FilesFindFxml));
cases.add(new TestCase(index++, message("FilesRedundancy"), Fxmls.FilesRedundancyFxml));
cases.add(new TestCase(index++, message("FilesCompare"), Fxmls.FilesCompareFxml));
cases.add(new TestCase(index++, message("FilesRename"), Fxmls.FilesRenameFxml));
cases.add(new TestCase(index++, message("FilesCopy"), Fxmls.FilesCopyFxml));
cases.add(new TestCase(index++, message("FilesMove"), Fxmls.FilesMoveFxml));
cases.add(new TestCase(index++, message("DeleteJavaIOTemporaryPathFiles"), Fxmls.FilesDeleteJavaTempFxml));
cases.add(new TestCase(index++, message("DeleteEmptyDirectories"), Fxmls.FilesDeleteEmptyDirFxml));
cases.add(new TestCase(index++, message("FilesDelete"), Fxmls.FilesDeleteFxml));
cases.add(new TestCase(index++, message("DeleteNestedDirectories"), Fxmls.FilesDeleteNestedDirFxml));
cases.add(new TestCase(index++, message("FileDecompressUnarchive"), Fxmls.FileDecompressUnarchiveFxml));
cases.add(new TestCase(index++, message("FilesDecompressUnarchiveBatch"), Fxmls.FilesDecompressUnarchiveBatchFxml));
cases.add(new TestCase(index++, message("FilesArchiveCompress"), Fxmls.FilesArchiveCompressFxml));
cases.add(new TestCase(index++, message("FilesCompressBatch"), Fxmls.FilesCompressBatchFxml));
cases.add(new TestCase(index++, message("MediaPlayer"), Fxmls.MediaPlayerFxml));
cases.add(new TestCase(index++, message("ManageMediaLists"), Fxmls.MediaListFxml));
cases.add(new TestCase(index++, message("FFmpegScreenRecorder"), Fxmls.FFmpegScreenRecorderFxml));
cases.add(new TestCase(index++, message("FFmpegConvertMediaStreams"), Fxmls.FFmpegConvertMediaStreamsFxml));
cases.add(new TestCase(index++, message("FFmpegConvertMediaFiles"), Fxmls.FFmpegConvertMediaFilesFxml));
cases.add(new TestCase(index++, message("FFmpegMergeImagesInformation"), Fxmls.FFmpegMergeImagesFxml));
cases.add(new TestCase(index++, message("FFmpegMergeImagesFiles"), Fxmls.FFmpegMergeImageFilesFxml));
cases.add(new TestCase(index++, message("FFmpegProbeMediaInformation"), Fxmls.FFmpegProbeMediaInformationFxml));
cases.add(new TestCase(index++, message("FFmpegInformation"), Fxmls.FFmpegInformationFxml));
cases.add(new TestCase(index++, message("AlarmClock"), Fxmls.AlarmClockFxml));
cases.add(new TestCase(index++, message("GameElimniation"), Fxmls.GameElimniationFxml));
cases.add(new TestCase(index++, message("GameMine"), Fxmls.GameMineFxml));
cases.add(new TestCase(index++, message("WebBrowser"), Fxmls.WebBrowserFxml));
cases.add(new TestCase(index++, message("WebFavorite"), Fxmls.DataTreeFxml).setType(Type.Data));
cases.add(new TestCase(index++, message("WebHistories"), Fxmls.WebHistoriesFxml));
cases.add(new TestCase(index++, message("QueryNetworkAddress"), Fxmls.NetworkQueryAddressFxml));
cases.add(new TestCase(index++, message("QueryDNSBatch"), Fxmls.NetworkQueryDNSBatchFxml));
cases.add(new TestCase(index++, message("ConvertUrl"), Fxmls.NetworkConvertUrlFxml));
cases.add(new TestCase(index++, message("DownloadHtmls"), Fxmls.DownloadFirstLevelLinksFxml));
cases.add(new TestCase(index++, message("SecurityCertificates"), Fxmls.SecurityCertificatesFxml));
cases.add(new TestCase(index++, message("Settings"), Fxmls.SettingsFxml));
cases.add(new TestCase(index++, message("MyBoxProperties"), Fxmls.MyBoxPropertiesFxml));
cases.add(new TestCase(index++, message("MyBoxLogs"), Fxmls.MyBoxLogsFxml));
cases.add(new TestCase(index++, message("MacroCommands"), Fxmls.DataTreeFxml).setType(Type.Data));
cases.add(new TestCase(index++, message("RunSystemCommand"), Fxmls.RunSystemCommandFxml));
cases.add(new TestCase(index++, message("ManageLanguages"), Fxmls.MyBoxLanguagesFxml));
cases.add(new TestCase(index++, message("MakeIcons"), Fxmls.MyBoxIconsFxml));
cases.add(new TestCase(index++, message("AutoTesting"), Fxmls.AutoTestingCasesFxml));
cases.add(new TestCase(index++, message("MessageAuthor"), Fxmls.MessageAuthorFxml));
cases.add(new TestCase(index++, message("Shortcuts"), Fxmls.ShortcutsFxml));
cases.add(new TestCase(index++, message("FunctionsList"), Fxmls.FunctionsListFxml));
} catch (Exception e) {
MyBoxLog.error(e.toString());
}
return cases;
}
/*
get/set
*/
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Operation getOperation() {
return operation;
}
public String getOperationName() {
return message(operation.name());
}
public void setOperation(Operation operation) {
this.operation = operation;
}
public String getObject() {
return object;
}
public void setObject(String object) {
this.object = object;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public Type getType() {
return type;
}
public String getTypeName() {
return message(type.name());
}
public TestCase setType(Type type) {
this.type = type;
return this;
}
public Stage getStage() {
return stage;
}
public void setStage(Stage stage) {
this.stage = stage;
}
public Status getStatus() {
return Status;
}
public String getStatusName() {
return message(Status.name());
}
public void setStatus(Status Status) {
this.Status = Status;
}
public BaseController getController() {
return controller;
}
public void setController(BaseController controller) {
this.controller = controller;
}
public String getFxml() {
return fxml;
}
public void setFxml(String fxml) {
this.fxml = fxml;
}
}
| 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/dev/ImageMacro.java | released/MyBox/src/main/java/mara/mybox/dev/ImageMacro.java | package mara.mybox.dev;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javafx.embed.swing.SwingFXUtils;
import javax.imageio.ImageIO;
import mara.mybox.color.ColorMatch;
import mara.mybox.color.ColorMatch.MatchAlgorithm;
import mara.mybox.controller.ImageEditorController;
import mara.mybox.db.data.ConvolutionKernel;
import mara.mybox.fxml.FxFileTools;
import mara.mybox.fxml.image.FxColorTools;
import mara.mybox.image.data.ImageConvolution;
import mara.mybox.image.data.ImageScope;
import mara.mybox.image.data.PixelsOperation;
import mara.mybox.image.data.PixelsOperationFactory;
import mara.mybox.image.file.ImageFileWriters;
import mara.mybox.tools.FileTmpTools;
import mara.mybox.tools.StringTools;
import mara.mybox.value.Languages;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2025-8-29
* @License Apache License Version 2.0
*/
public class ImageMacro extends BaseMacro {
protected BufferedImage sourceImage;
protected BufferedImage resultImage;
protected PixelsOperation pixelsOperation;
protected ImageConvolution convolution;
protected ConvolutionKernel kernel;
@Override
public void reset() {
super.reset();
sourceImage = null;
resultImage = null;
pixelsOperation = null;
}
@Override
public String defaultOperation() {
return "edit";
}
@Override
public File defaultInputFile() {
return FxFileTools.getInternalFile("/img/MyBox.png", "image", "MyBox.png");
}
@Override
public File defaultOutputFile() {
return FileTmpTools.tmpFile("macro", "jpg");
}
/*
parameters
*/
@Override
public boolean checkMoreParameters() {
try {
File inputFile = getInputFile();
if (inputFile == null || !inputFile.exists()) {
displayError(message("Invalid" + ": inputFile") + (inputFile != null ? ("\n" + inputFile.getAbsolutePath()) : ""));
return false;
}
String operation = getOperation();
switch (operation.toLowerCase()) {
case "edit":
ok = checkEdit();
break;
case "replace":
ok = checkReplace();
break;
case "sharp":
ok = checkSharp();
break;
}
if (!ok) {
return false;
}
sourceImage = ImageIO.read(inputFile);
return sourceImage != null;
} catch (Exception e) {
displayError(e.toString());
return false;
}
}
public boolean checkEdit() {
try {
File inputFile = getInputFile();
writeParameter("outputFile", inputFile);
return true;
} catch (Exception e) {
displayError(e.toString());
return false;
}
}
public boolean checkReplace() {
try {
ImageScope scope = new ImageScope();
ColorMatch colorMatch = scope.getColorMatch();
pixelsOperation = PixelsOperationFactory.create(sourceImage, scope,
PixelsOperation.OperationType.ReplaceColor,
PixelsOperation.ColorActionType.Set);
Color color;
try {
color = FxColorTools.cssToAwt(readArgument("color"));
writeParameter("color", color);
List<java.awt.Color> colors = new ArrayList();
colors.add(color);
scope.setColors(colors);
pixelsOperation.setColorPara1(color);
} catch (Exception e) {
displayError(message("Invalid" + ": color"));
return false;
}
try {
Color newColor = FxColorTools.cssToAwt(readArgument("newColor"));
writeParameter("newColor", newColor);
pixelsOperation.setColorPara2(newColor);
} catch (Exception e) {
displayError(message("Invalid" + ": newColor"));
return false;
}
boolean invert = false, trans = false;
String invertv = readArgument("invert");
if (invertv != null) {
invert = StringTools.isTrue(invertv);
}
writeParameter("invert", invert);
scope.setColorExcluded(invert);
String transv = readArgument("trans");
if (transv != null) {
trans = StringTools.isTrue(transv);
}
writeParameter("trans", trans);
pixelsOperation.setSkipTransparent(color.getRGB() != 0 && !trans);
MatchAlgorithm a = null;
String aname = readArgument("algorithm");
if (aname == null) {
a = ColorMatch.DefaultAlgorithm;
} else {
for (MatchAlgorithm ma : MatchAlgorithm.values()) {
if (Languages.matchIgnoreCase(ma.name(), aname)) {
a = ma;
break;
}
}
}
if (a == null) {
displayError(message("Invalid" + ": algorithm"));
return false;
}
writeParameter("algorithm", a);
colorMatch.setAlgorithm(a);
double threshold = ColorMatch.suggestedThreshold(a);
try {
String v = readArgument("threshold");
if (v != null) {
threshold = Double.parseDouble(v);
}
} catch (Exception e) {
displayError(message("Invalid" + ": threshold"));
return false;
}
writeParameter("threshold", threshold);
colorMatch.setThreshold(threshold);
if (ColorMatch.supportWeights(a)) {
double hueWeight = 1d, brightnessWeight = 1d, saturationWeight = 1d;
try {
String v = readArgument("hueWeight");
if (v != null) {
hueWeight = Double.parseDouble(v);
}
} catch (Exception e) {
displayError(message("Invalid" + ": hueWeight"));
return false;
}
writeParameter("hueWeight", hueWeight);
colorMatch.setHueWeight(hueWeight);
try {
String v = readArgument("brightnessWeight");
if (v != null) {
brightnessWeight = Double.parseDouble(v);
}
} catch (Exception e) {
displayError(message("Invalid" + ": brightnessWeight"));
return false;
}
writeParameter("brightnessWeight", brightnessWeight);
colorMatch.setBrightnessWeight(brightnessWeight);
try {
String v = readArgument("saturationWeight");
if (v != null) {
saturationWeight = Double.parseDouble(v);
}
} catch (Exception e) {
displayError(message("Invalid" + ": saturationWeight"));
return false;
}
writeParameter("saturationWeight", saturationWeight);
colorMatch.setSaturationWeight(saturationWeight);
}
boolean hue = true, brightness = false, saturation = false;
String huev = readArgument("hue");
if (huev != null) {
hue = StringTools.isTrue(huev);
}
writeParameter("hue", hue);
String brightnessv = readArgument("brightness");
if (brightnessv != null) {
brightness = StringTools.isTrue(brightnessv);
}
writeParameter("brightness", brightness);
String saturationv = readArgument("saturation");
if (saturationv != null) {
saturation = StringTools.isTrue(saturationv);
}
writeParameter("saturation", saturation);
pixelsOperation.setBoolPara1(hue)
.setBoolPara2(brightness)
.setBoolPara3(saturation);
return true;
} catch (Exception e) {
displayError(e.toString());
return false;
}
}
public boolean checkSharp() {
try {
String a = readArgument("algorithm");
if (a == null || "mask".equalsIgnoreCase(a)) {
short intensity = 2;
String v = readArgument("intensity");
if (v != null) {
try {
intensity = Short.parseShort(v);
} catch (Exception e) {
displayError(message("Invalid" + ": intensity"));
return false;
}
}
a = "mask";
writeParameter("intensity", intensity);
kernel = ConvolutionKernel.makeUnsharpMasking(intensity);
} else if ("eight".equalsIgnoreCase(a)) {
a = "eight";
kernel = ConvolutionKernel.MakeSharpenEightNeighborLaplace();
} else if ("four".equalsIgnoreCase(a)) {
a = "four";
kernel = ConvolutionKernel.MakeSharpenFourNeighborLaplace();
} else {
displayError(message("Invalid" + ": algorithm"));
return false;
}
writeParameter("algorithm", a);
String edge = readArgument("edge");
if (edge == null || "copy".equalsIgnoreCase(edge)) {
edge = "copy";
kernel.setEdge(ConvolutionKernel.Edge_Op.COPY);
} else if ("zero".equalsIgnoreCase(edge)) {
edge = "zero";
kernel.setEdge(ConvolutionKernel.Edge_Op.FILL_ZERO);
} else {
displayError(message("Invalid" + ": edge"));
return false;
}
writeParameter("edge", edge);
String color = readArgument("color");
if (color == null || "keep".equalsIgnoreCase(color)) {
color = "keep";
kernel.setColor(ConvolutionKernel.Color.Keep);
} else if ("grey".equalsIgnoreCase(color) || "gray".equalsIgnoreCase(color)) {
color = "grey";
kernel.setColor(ConvolutionKernel.Color.Grey);
} else if ("bw".equalsIgnoreCase(color) || "blackwhite".equalsIgnoreCase(color)) {
color = "blackwhite";
kernel.setColor(ConvolutionKernel.Color.BlackWhite);
} else {
displayError(message("Invalid" + ": color=" + color));
return false;
}
writeParameter("color", color);
return true;
} catch (Exception e) {
displayError(e.toString());
return false;
}
}
/*
run
*/
@Override
public boolean run() {
try {
ok = false;
resultImage = null;
String operation = getOperation();
switch (operation.toLowerCase()) {
case "edit":
ok = true;
break;
case "replace":
ok = runReplace();
break;
case "sharp":
ok = runSharp();
break;
}
File outputFile = getOutputFile();
if (resultImage != null && outputFile != null) {
ImageFileWriters.writeImageFile(task, resultImage, outputFile);
}
} catch (Exception e) {
displayError(e.toString());
}
return ok;
}
public boolean runReplace() {
try {
pixelsOperation.setImage(sourceImage).setTask(task);
resultImage = pixelsOperation.start();
return true;
} catch (Exception e) {
displayError(e.toString());
return false;
}
}
public boolean runSharp() {
try {
convolution = ImageConvolution.create();
convolution.setImage(sourceImage).setKernel(kernel).setTask(task);
resultImage = convolution.start();
return resultImage != null;
} catch (Exception e) {
displayError(e.toString());
return false;
}
}
@Override
public void openResult() {
try {
File outputFile = getOutputFile();
if (outputFile != null && outputFile.exists()) {
ImageEditorController.openFile(outputFile);
} else if (resultImage != null) {
displayInfo(message("ImageGenerated"));
ImageEditorController.openImage(SwingFXUtils.toFXImage(resultImage, null));
}
} catch (Exception e) {
displayError(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/fxml/SquareRootCoordinate.java | released/MyBox/src/main/java/mara/mybox/fxml/SquareRootCoordinate.java | package mara.mybox.fxml;
import javafx.util.StringConverter;
import mara.mybox.tools.StringTools;
/**
* @Author Mara
* @CreateDate 2020-05-16
* @License Apache License Version 2.0
*/
public class SquareRootCoordinate extends StringConverter<Number> {
@Override
public String toString(Number value) {
double d = value.doubleValue();
return StringTools.format(d * d);
}
@Override
public Number fromString(String string) {
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/fxml/AlarmClockTask.java | released/MyBox/src/main/java/mara/mybox/fxml/AlarmClockTask.java | package mara.mybox.fxml;
import java.util.Date;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
import javafx.application.Platform;
import mara.mybox.controller.AlarmClockRunController;
import mara.mybox.db.data.AlarmClock;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.tools.DateTools;
import mara.mybox.value.AppVariables;
import mara.mybox.value.Fxmls;
/**
* @Author Mara
* @CreateDate 2018-7-16
* @License Apache License Version 2.0
*/
public class AlarmClockTask extends TimerTask {
protected AlarmClock alarm;
protected TimeUnit timeUnit = TimeUnit.SECONDS;
protected long delay, period;
public AlarmClockTask(AlarmClock alarmClock) {
this.alarm = alarmClock;
// AlarmClock.calculateNextTime(alarmClock);
// delay = alarmClock.getNextTime() - new Date().getTime();
// period = AlarmClock.period(alarmClock);
}
@Override
public void run() {
try {
// MyBoxLog.debug("call");
if (!canTriggerAlarm(alarm)) {
MyBoxLog.debug("Can not tigger alarm due to not satisfied");
return;
}
Platform.runLater(new Runnable() {
@Override
public void run() {
try {
AlarmClockRunController controller = (AlarmClockRunController) WindowTools.openStage(Fxmls.AlarmClockRunFxml);
controller.runAlarm(alarm);
if (AppVariables.AlarmClockController != null
&& AppVariables.AlarmClockController.getAlertClockTableController() != null) {
AppVariables.AlarmClockController.getAlertClockTableController().refreshAction();
}
} catch (Exception e) {
MyBoxLog.error(e.toString());
}
}
});
// if (alarm.getAlarmType() == NotRepeat) {
// ScheduledFuture future = ScheduledTasks.get(alarm.getKey());
// if (future != null) {
// future.cancel(true);
// ScheduledTasks.remove(alarm.getKey());
// }
// alarm.setIsActive(false);
// AlarmClock.writeAlarmClock(alarm);
// } else {
// alarm.setLastTime(new Date().getTime());
// alarm.setNextTime(-1);
// AlarmClock.calculateNextTime(alarm);
// AlarmClock.writeAlarmClock(alarm);
// }
} catch (Exception e) {
MyBoxLog.error(e.toString());
}
}
public static boolean canTriggerAlarm(AlarmClock alarm) {
long now = new Date().getTime();
switch (alarm.getAlarmType()) {
case NotRepeat:
case EveryDay:
case EverySomeDays:
case EverySomeHours:
case EverySomeMinutes:
case EverySomeSeconds:
return true;
case Weekend:
return DateTools.isWeekend(now);
case WorkingDays:
return !DateTools.isWeekend(now);
default:
return false;
}
}
/*
get/set
*/
public AlarmClock getAlarm() {
return alarm;
}
public void setAlarm(AlarmClock alarm) {
this.alarm = alarm;
}
public TimeUnit getTimeUnit() {
return timeUnit;
}
public void setTimeUnit(TimeUnit timeUnit) {
this.timeUnit = timeUnit;
}
public long getDelay() {
return delay;
}
public void setDelay(long delay) {
this.delay = delay;
}
public long getPeriod() {
return period;
}
public void setPeriod(long period) {
this.period = period;
}
}
| 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/fxml/WebViewTools.java | released/MyBox/src/main/java/mara/mybox/fxml/WebViewTools.java | package mara.mybox.fxml;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import javafx.geometry.Orientation;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.control.ScrollBar;
import javafx.scene.shape.Rectangle;
import javafx.scene.web.HTMLEditor;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.tools.DateTools;
import mara.mybox.tools.StringTools;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
* @Author Mara
* @CreateDate 2021-7-29
* @License Apache License Version 2.0
*/
public class WebViewTools {
public static String userAgent() {
return new WebView().getEngine().getUserAgent();
}
public static String getHtml(WebView webView) {
if (webView == null) {
return "";
}
return getHtml(webView.getEngine());
}
public static String getHtml(WebEngine engine) {
try {
if (engine == null) {
return "";
}
Object c = engine.executeScript("document.documentElement.outerHTML");
if (c == null) {
return "";
}
return (String) c;
} catch (Exception e) {
MyBoxLog.error(e.toString());
return "";
}
}
public static void selectAll(WebEngine webEngine) {
try {
String js = "window.getSelection().removeAllRanges(); "
+ "var selection = window.getSelection();\n"
+ "var range = document.createRange();\n"
+ "range.selectNode(document.documentElement);\n"
+ "selection.addRange(range);";
webEngine.executeScript(js);
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
public static void selectNone(WebEngine webEngine) {
try {
String js = "window.getSelection().removeAllRanges(); ";
webEngine.executeScript(js);
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
public static void selectNode(WebEngine webEngine, String id) {
try {
String js = "window.getSelection().removeAllRanges(); "
+ "var selection = window.getSelection();\n"
+ "var range = document.createRange();\n"
+ "range.selectNode(document.getElementById('" + id + "'));\n"
+ "selection.addRange(range);";
webEngine.executeScript(js);
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
public static void selectElement(WebView webView, Element element) {
try {
if (webView == null || element == null) {
return;
}
String id = element.getAttribute("id");
String newid = DateTools.nowFileString();
element.setAttribute("id", newid);
selectNode(webView.getEngine(), newid);
if (id != null) {
element.setAttribute("id", id);
} else {
element.removeAttribute("id");
}
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
public static String selectedText(WebEngine webEngine) {
try {
Object ret = webEngine.executeScript("window.getSelection().toString();");
if (ret == null) {
return null;
}
return ((String) ret);
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
public static String selectedHtml(WebEngine webEngine) {
try {
String js = " var selectionObj = window.getSelection();\n"
+ " var rangeObj = selectionObj.getRangeAt(0);\n"
+ " var docFragment = rangeObj.cloneContents();\n"
+ " var div = document.createElement(\"div\");\n"
+ " div.appendChild(docFragment);\n"
+ " div.innerHTML;";
Object ret = webEngine.executeScript(js);
if (ret == null) {
return null;
}
return ((String) ret);
} catch (Exception e) {
// MyBoxLog.debug(e);
return null;
}
}
// https://blog.csdn.net/weixin_29251337/article/details/117888001
public static void addStyle(WebEngine webEngine, String style, String styleid) {
try {
if (webEngine == null || styleid == null || styleid.isBlank()
|| style == null || style.isBlank()) {
return;
}
removeNode(webEngine, styleid);
String js = "var node = document.createElement(\"style\");\n"
+ "node.id = \"" + styleid + "\";\n"
+ "node.type = \"text/css\";\n"
+ "node.innerHTML = \"" + StringTools.replaceLineBreak(style) + "\";\n"
+ "document.body.appendChild(node);";
webEngine.executeScript(js);
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
public static void removeNode(WebEngine webEngine, String id) {
try {
if (webEngine == null || id == null || id.isBlank()) {
return;
}
String js = "var node = document.getElementById(\"" + id + "\");\n"
+ "if ( node != null ) node.parentNode.removeChild(node);";
webEngine.executeScript(js);
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
public static HTMLEditor editor(WebView webView) {
if (webView == null) {
return null;
}
Parent p = webView.getParent();
while (p != null) {
if (p instanceof HTMLEditor) {
return (HTMLEditor) p;
}
p = p.getParent();
}
return null;
}
public static WebView webview(Parent node) {
if (node == null) {
return null;
}
for (Node child : node.getChildrenUnmodifiable()) {
if (child instanceof WebView) {
return (WebView) child;
}
if (child instanceof Parent) {
WebView w = webview((Parent) child);
if (w != null) {
return w;
}
}
}
return null;
}
public static String getFrame(WebEngine engine, int index) {
try {
if (engine == null || index < 0) {
return "";
}
Object c = engine.executeScript("window.frames[" + index + "].document.documentElement.outerHTML");
if (c == null) {
return "";
}
return (String) c;
} catch (Exception e) {
MyBoxLog.error(e.toString());
return "";
}
}
public static String getFrame(WebEngine engine, String frameName) {
try {
if (engine == null || frameName == null) {
return "";
}
Object c = engine.executeScript("window.frames." + frameName + ".document.documentElement.outerHTML");
if (c == null) {
return "";
}
return (String) c;
} catch (Exception e) {
MyBoxLog.error(e.toString());
return "";
}
}
public static Document getFrameDocument(WebEngine engine, String frameName) {
try {
if (engine == null) {
return null;
}
Object c = engine.executeScript("window.frames." + frameName + ".document");
if (c == null) {
return null;
}
return (Document) c;
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
public static int frameIndex(WebEngine webEngine, String frameName) {
try {
if (frameName == null) {
return -1;
}
Object c = webEngine.executeScript("function checkFrameIndex(frameName) { "
+ " for (i=0; i<window.frames.length; i++) { "
+ " if ( window.frames[i].name == frameName ) return i ;"
+ " };"
+ " return -1; "
+ "};"
+ "checkFrameIndex(\"" + frameName + "\");");
if (c == null) {
return -1;
}
return ((int) c);
} catch (Exception e) {
MyBoxLog.error(e.toString());
return -1;
}
}
public static Map<String, String> readCookie(WebEngine webEngine) {
try {
String s = (String) webEngine.executeScript("document.cookie;");
String[] vs = s.split(";");
Map<String, String> m = new HashMap<>();
for (String v : vs) {
String[] vv = v.split("=");
if (vv.length < 2) {
continue;
}
m.put(vv[0].trim(), vv[1].trim());
}
return m;
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
// https://stackoverflow.com/questions/31264847/how-to-set-remember-scrollbar-thumb-position-in-javafx-8-webview?r=SearchResults
public static ScrollBar getVScrollBar(WebView webView) {
try {
Set<Node> scrolls = webView.lookupAll(".scroll-bar");
for (Node scrollNode : scrolls) {
if (ScrollBar.class.isInstance(scrollNode)) {
ScrollBar scroll = (ScrollBar) scrollNode;
if (scroll.getOrientation() == Orientation.VERTICAL) {
return scroll;
}
}
}
} catch (Exception e) {
}
return null;
}
// https://bbs.csdn.net/topics/310020841
public static int px(WebEngine webEngine, String s) {
try {
String js = "function stringPX(s){"
+ " var span = document.createElement(\"span\");\n"
+ " span.innerHTML = s;\n"
+ " document.body.appendChild(span);\n"
+ " var width = span.offsetWidth;\n"
+ " document.body.removeChild(span); "
+ " return width; "
+ "}"
+ "stringPX(\"" + s + "\");";
Object c = webEngine.executeScript(js);
if (c == null) {
return -1;
}
return ((int) c);
} catch (Exception e) {
MyBoxLog.debug(e);
return -1;
}
}
public static Rectangle tagRect(WebEngine webEngine, String tag, int index) {
try {
Rectangle rect = new Rectangle();
String js = "var rect = document.getElementsByTagName('" + tag + "')[" + index + "].getBoundingClientRect();"
+ "rect.x + ' ' + rect.y + ' ' + rect.width + ' ' + rect.height ";
Object c = webEngine.executeScript(js);
if (c == null) {
return null;
}
String[] values = ((String) c).split("\\s+");
rect.setX(Double.parseDouble(values[0]));
rect.setY(Double.parseDouble(values[1]));
rect.setWidth(Double.parseDouble(values[2]));
rect.setHeight(Double.parseDouble(values[3]));
return rect;
} catch (Exception e) {
MyBoxLog.debug(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/fxml/FxSingletonTask.java | released/MyBox/src/main/java/mara/mybox/fxml/FxSingletonTask.java | package mara.mybox.fxml;
import mara.mybox.controller.BaseController;
/**
* @Author Mara
* @CreateDate 2019-12-18
* @License Apache License Version 2.0
*/
public class FxSingletonTask<Void> extends FxTask<Void> {
public FxSingletonTask(BaseController controller) {
this.controller = controller;
}
@Override
protected void taskQuit() {
if (controller != null && controller.getTask() == self) {
controller.setTask(null);
}
super.taskQuit();
}
}
| 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/fxml/ValidationTools.java | released/MyBox/src/main/java/mara/mybox/fxml/ValidationTools.java | package mara.mybox.fxml;
import java.io.File;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TextField;
import mara.mybox.value.UserConfig;
/**
* @Author Mara
* @CreateDate 2021-8-5
* @License Apache License Version 2.0
*/
public class ValidationTools {
public static void setEditorStyle(final ComboBox box, final String style) {
box.getEditor().setStyle(style);
// Platform.runLater(new Runnable() {
// @Override
// public void run() {
// box.getEditor().setStyle(style);
// }
// });
}
public static void setEditorNormal(final ComboBox box) {
setEditorStyle(box, null);
}
public static void setEditorBadStyle(final ComboBox box) {
setEditorStyle(box, UserConfig.badStyle());
}
public static void setEditorWarnStyle(final ComboBox box) {
setEditorStyle(box, UserConfig.warnStyle());
}
public static int positiveValue(final TextField input) {
return positiveValue(input, Integer.MAX_VALUE);
}
public static int positiveValue(final TextField input, final int max) {
try {
int v = Integer.parseInt(input.getText());
if (v > 0 && v <= max) {
input.setStyle(null);
return v;
} else {
input.setStyle(UserConfig.badStyle());
return -1;
}
} catch (Exception e) {
input.setStyle(UserConfig.badStyle());
return -1;
}
}
public static void setNonnegativeValidation(final TextField input) {
setNonnegativeValidation(input, Integer.MAX_VALUE);
}
public static void setNonnegativeValidation(final TextField input, final int max) {
input.textProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
try {
int v = Integer.parseInt(newValue);
if (v >= 0 && v <= max) {
input.setStyle(null);
} else {
input.setStyle(UserConfig.badStyle());
}
} catch (Exception e) {
input.setStyle(UserConfig.badStyle());
}
}
});
}
public static void setFloatValidation(final TextField input) {
input.textProperty().addListener((ObservableValue<? extends String> observable, String oldValue, String newValue) -> {
try {
float v = Float.parseFloat(newValue);
input.setStyle(null);
} catch (Exception e) {
input.setStyle(UserConfig.badStyle());
}
});
}
public static void setPositiveValidation(final TextField input) {
setPositiveValidation(input, Integer.MAX_VALUE);
}
public static void setPositiveValidation(final TextField input, final int max) {
input.textProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
try {
int v = Integer.parseInt(newValue);
if (v > 0 && v <= max) {
input.setStyle(null);
} else {
input.setStyle(UserConfig.badStyle());
}
} catch (Exception e) {
input.setStyle(UserConfig.badStyle());
}
}
});
}
public static void setFileValidation(final TextField input, String key) {
if (input == null) {
return;
}
input.setStyle(UserConfig.badStyle());
input.textProperty().addListener((ObservableValue<? extends String> observable, String oldValue, String newValue) -> {
String v = input.getText();
if (v == null || v.isEmpty()) {
input.setStyle(UserConfig.badStyle());
return;
}
final File file = new File(newValue);
if (!file.exists() || !file.isFile()) {
input.setStyle(UserConfig.badStyle());
return;
}
input.setStyle(null);
UserConfig.setString(key, file.getParent());
});
}
public static void setPathValidation(final TextField input) {
if (input == null) {
return;
}
input.textProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
final File file = new File(newValue);
if (!file.isDirectory()) {
input.setStyle(UserConfig.badStyle());
return;
}
input.setStyle(null);
}
});
}
public static void setPathExistedValidation(final TextField input) {
if (input == null) {
return;
}
input.textProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
final File file = new File(newValue);
if (!file.exists() || !file.isDirectory()) {
input.setStyle(UserConfig.badStyle());
return;
}
input.setStyle(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/fxml/TextClipboardTools.java | released/MyBox/src/main/java/mara/mybox/fxml/TextClipboardTools.java | package mara.mybox.fxml;
import java.io.File;
import java.sql.Connection;
import javafx.application.Platform;
import javafx.scene.control.TextInputControl;
import javafx.scene.input.Clipboard;
import javafx.scene.input.ClipboardContent;
import mara.mybox.controller.BaseController;
import mara.mybox.controller.TextInMyBoxClipboardController;
import mara.mybox.controller.TextInSystemClipboardController;
import mara.mybox.db.DerbyBase;
import mara.mybox.db.table.TableTextClipboard;
import mara.mybox.dev.MyBoxLog;
import static mara.mybox.fxml.TextClipboardMonitor.DefaultInterval;
import mara.mybox.tools.TextFileTools;
import static mara.mybox.value.AppVariables.TextClipMonitor;
import static mara.mybox.value.Languages.message;
import mara.mybox.value.UserConfig;
/**
* @Author Mara
* @CreateDate 2021-8-1
* @License Apache License Version 2.0
*/
public class TextClipboardTools {
/*
monitor
*/
public static void stopTextClipboardMonitor() {
if (TextClipMonitor != null) {
TextClipMonitor.stop();
TextClipMonitor = null;
}
}
public static void startTextClipboardMonitor() {
startTextClipboardMonitor(getMonitorInterval());
}
public static void startTextClipboardMonitor(int interval) {
if (TextClipMonitor != null) {
TextClipMonitor.cancel();
TextClipMonitor = null;
}
TextClipMonitor = new TextClipboardMonitor().start(interval);
}
public static int getMonitorInterval() {
int v = UserConfig.getInt("TextClipboardMonitorInterval", DefaultInterval);
if (v <= 0) {
v = DefaultInterval;
}
return v;
}
public static int setMonitorInterval(int v) {
if (v <= 0) {
v = DefaultInterval;
}
UserConfig.setInt("TextClipboardMonitorInterval", v);
return v;
}
public static boolean isMonitoring() {
return TextClipMonitor != null;
}
public static boolean isCopy() {
return UserConfig.getBoolean("CopyTextInSystemClipboard", false);
}
public static boolean isMonitoringCopy() {
return isMonitoring() && isCopy();
}
public static void setCopy(boolean value) {
UserConfig.setBoolean("CopyTextInSystemClipboard", value);
}
public static boolean isStartWhenBoot() {
return UserConfig.getBoolean("StartTextClipboardMonitorWhenBoot", false);
}
public static void setStartWhenBoot(boolean value) {
UserConfig.setBoolean("StartTextClipboardMonitorWhenBoot", value);
}
/*
System Clipboard
*/
public static boolean systemClipboardHasString() {
return Clipboard.getSystemClipboard().hasString();
}
public static String getSystemClipboardString() {
return Clipboard.getSystemClipboard().getString();
}
public static boolean stringToSystemClipboard(String string) {
try {
if (string == null || string.isBlank()) {
return false;
}
ClipboardContent cc = new ClipboardContent();
cc.putString(string);
Clipboard.getSystemClipboard().setContent(cc);
TextInSystemClipboardController.updateSystemClipboardStatus();
return true;
} catch (Exception e) {
MyBoxLog.error(e.toString());
return false;
}
}
public static void copyToSystemClipboard(BaseController controller, TextInputControl textInput) {
if (controller == null || textInput == null) {
return;
}
String text = textInput.getSelectedText();
if (text == null || text.isEmpty()) {
text = textInput.getText();
}
copyToSystemClipboard(controller, text);
}
public static void copyToSystemClipboard(BaseController controller, String text) {
Platform.runLater(new Runnable() {
@Override
public void run() {
if (text == null || text.isEmpty()) {
if (controller != null) {
controller.popError(message("NoData"));
}
return;
}
if (stringToSystemClipboard(text)) {
if (controller == null) {
return;
}
int len = text.length();
String info = "\n" + message("CharactersNumber") + ":" + len
+ "\n----------------------\n"
+ (len > 100 ? text.substring(0, 100) + "\n......" : text);
if (TextClipboardTools.isMonitoringCopy()) {
controller.popInformation(message("CopiedInClipBoards") + info);
} else {
controller.popInformation(message("CopiedInSystemClipBoard") + info);
}
} else {
if (controller != null) {
controller.popFailed();
}
}
}
});
}
public static void copyFileToSystemClipboard(BaseController controller, File file) {
Platform.runLater(new Runnable() {
@Override
public void run() {
if (file == null || !file.exists()) {
controller.popError(message("NoData"));
return;
}
copyToSystemClipboard(controller, TextFileTools.readTexts(null, file));
}
});
}
/*
MyBox Clipboard
*/
public static void copyToMyBoxClipboard(BaseController controller, TextInputControl textInput) {
if (controller == null || textInput == null) {
return;
}
String text = textInput.getSelectedText();
if (text == null || text.isEmpty()) {
text = textInput.getText();
}
copyToMyBoxClipboard(controller, text);
}
public static void copyToMyBoxClipboard(BaseController controller, String text) {
if (controller == null) {
return;
}
Platform.runLater(new Runnable() {
@Override
public void run() {
if (text == null || text.isEmpty()) {
controller.popError(message("NoData"));
return;
}
if (stringToMyBoxClipboard(text)) {
String info = text.length() > 200 ? text.substring(0, 200) + "\n......" : text;
controller.popInformation(message("CopiedInMyBoxClipBoard") + "\n----------------------\n" + info);
} else {
controller.popFailed();
}
}
});
}
public static boolean stringToMyBoxClipboard(String string) {
if (string == null || string.isBlank()) {
return false;
}
return stringToMyBoxClipboard(null, null, string);
}
public static boolean stringToMyBoxClipboard(TableTextClipboard inTable, Connection inConn, String string) {
try {
if (string == null || string.isBlank()) {
return false;
}
new Thread() {
@Override
public void run() {
try {
TableTextClipboard table = inTable;
if (table == null) {
table = new TableTextClipboard();
}
Connection conn = inConn;
if (conn == null || conn.isClosed()) {
conn = DerbyBase.getConnection();
}
table.save(conn, string);
conn.commit();
TextInMyBoxClipboardController.updateMyBoxClipboard();
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
}.start();
return true;
} catch (Exception e) {
MyBoxLog.error(e.toString());
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/fxml/FxBackgroundTask.java | released/MyBox/src/main/java/mara/mybox/fxml/FxBackgroundTask.java | package mara.mybox.fxml;
import mara.mybox.controller.BaseController;
/**
* @Author Mara
* @CreateDate 2019-12-18
* @License Apache License Version 2.0
*/
public class FxBackgroundTask<Void> extends FxTask<Void> {
public FxBackgroundTask(BaseController controller) {
this.controller = controller;
}
@Override
protected void taskQuit() {
if (controller != null && controller.getBackgroundTask() == self) {
controller.setBackgroundTask(null);
}
super.taskQuit();
}
}
| 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/fxml/ImageClipboardTools.java | released/MyBox/src/main/java/mara/mybox/fxml/ImageClipboardTools.java | package mara.mybox.fxml;
import javafx.scene.image.Image;
import javafx.scene.input.Clipboard;
import javafx.scene.input.ClipboardContent;
import mara.mybox.image.data.ImageAttributes;
import mara.mybox.controller.BaseController;
import mara.mybox.controller.ImageInMyBoxClipboardController;
import mara.mybox.db.data.ImageClipboard;
import static mara.mybox.fxml.ImageClipboardMonitor.DefaultInterval;
import static mara.mybox.value.AppVariables.ImageClipMonitor;
import static mara.mybox.value.Languages.message;
import mara.mybox.value.UserConfig;
/**
* @Author Mara
* @CreateDate 2021-8-2
* @License Apache License Version 2.0
*/
public class ImageClipboardTools {
/*
monitor
*/
public static void stopImageClipboardMonitor() {
if (ImageClipMonitor != null) {
ImageClipMonitor.stop();
ImageClipMonitor = null;
}
}
public static void startImageClipboardMonitor(int interval, ImageAttributes attributes, String filePrefix) {
if (ImageClipMonitor != null) {
ImageClipMonitor.stop();
ImageClipMonitor = null;
}
ImageClipMonitor = new ImageClipboardMonitor().start(interval, attributes, filePrefix);
}
public static int getMonitorInterval() {
int v = UserConfig.getInt("ImageClipboardMonitorInterval", DefaultInterval);
if (v <= 0) {
v = DefaultInterval;
}
return v;
}
public static int setMonitorInterval(int v) {
if (v <= 0) {
v = DefaultInterval;
}
UserConfig.setInt("ImageClipboardMonitorInterval", v);
return v;
}
public static boolean isMonitoring() {
return ImageClipMonitor != null;
}
public static int getWidth() {
return UserConfig.getInt("ImageClipboardMonitorWidth", -1);
}
public static int setWidth(int v) {
UserConfig.setInt("ImageClipboardMonitorWidth", v);
return v;
}
public static boolean isCopy() {
return UserConfig.getBoolean("CopyImageInSystemClipboard", false);
}
public static boolean isMonitoringCopy() {
return isMonitoring() && isCopy();
}
public static void setCopy(boolean value) {
UserConfig.setBoolean("CopyImageInSystemClipboard", value);
}
public static boolean isSave() {
return UserConfig.getBoolean("SaveImageInSystemClipboard", false);
}
public static void setSave(boolean value) {
UserConfig.setBoolean("SaveImageInSystemClipboard", value);
}
/*
Image in System Clipboard
*/
public static void copyToSystemClipboard(BaseController controller, Image image) {
if (controller == null || image == null) {
return;
}
ClipboardContent cc = new ClipboardContent();
cc.putImage(image);
Clipboard.getSystemClipboard().setContent(cc);
if (isMonitoringCopy()) {
controller.popInformation(message("CopiedInClipBoards"));
ImageInMyBoxClipboardController.updateClipboards();
} else {
controller.popInformation(message("CopiedInSystemClipBoard"));
}
}
public static Image fetchImageInClipboard(boolean clear) {
Clipboard clipboard = Clipboard.getSystemClipboard();
if (!clipboard.hasImage()) {
return null;
}
Image image = clipboard.getImage();
if (clear) {
clipboard.clear();
}
return image;
}
/*
Image in MyBox Clipboard
*/
public static void copyToMyBoxClipboard(BaseController controller, Image image, ImageClipboard.ImageSource source) {
if (controller == null || image == null) {
return;
}
if (ImageClipboard.add(null, image, source) != null) {
controller.popInformation(message("CopiedInMyBoxClipBoard"));
} else {
controller.popFailed();
}
}
}
| 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/fxml/FxFileTools.java | released/MyBox/src/main/java/mara/mybox/fxml/FxFileTools.java | package mara.mybox.fxml;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import javafx.stage.FileChooser;
import mara.mybox.controller.BaseController_Files;
import mara.mybox.db.data.VisitHistoryTools;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.tools.FileTmpTools;
import mara.mybox.value.AppVariables;
import mara.mybox.value.UserConfig;
/**
* @Author Mara
* @CreateDate 2021-8-1
* @License Apache License Version 2.0
*/
public class FxFileTools {
public static File getInternalFile(String resourceFile, String subPath, String userFile) {
return getInternalFile(resourceFile, subPath, userFile, false);
}
// Solution from https://stackoverflow.com/questions/941754/how-to-get-a-path-to-a-resource-in-a-java-jar-file
public static File getInternalFile(String resourceFile, String subPath, String userFile, boolean deleteExisted) {
if (resourceFile == null || userFile == null) {
return null;
}
try {
File path = new File(AppVariables.MyboxDataPath + File.separator + subPath + File.separator);
if (!path.exists()) {
path.mkdirs();
}
File file = new File(AppVariables.MyboxDataPath + File.separator + subPath + File.separator + userFile);
if (file.exists() && !deleteExisted) {
return file;
}
File tmpFile = getInternalFile(resourceFile);
if (tmpFile == null) {
return null;
}
if (file.exists()) {
file.delete();
}
mara.mybox.tools.FileTools.override(tmpFile, file);
return file;
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
public static File getInternalFile(String resourceFile) {
if (resourceFile == null) {
return null;
}
File file = FileTmpTools.getTempFile();
try (final InputStream input = FxFileTools.class.getResourceAsStream(resourceFile);
final OutputStream out = new FileOutputStream(file)) {
int read;
byte[] bytes = new byte[1024];
while ((read = input.read(bytes)) > 0) {
out.write(bytes, 0, read);
}
file.deleteOnExit();
return file;
} catch (Exception e) {
// MyBoxLog.error(e.toString());
return null;
}
}
public static File selectFile(BaseController_Files controller) {
return selectFile(controller,
UserConfig.getPath(controller.getBaseName() + "SourcePath"),
controller.getSourceExtensionFilter());
}
public static File selectFile(BaseController_Files controller, int fileType) {
return selectFile(controller,
UserConfig.getPath(VisitHistoryTools.getPathKey(fileType)),
VisitHistoryTools.getExtensionFilter(fileType));
}
public static File selectFile(BaseController_Files controller, File path, List<FileChooser.ExtensionFilter> filter) {
try {
FileChooser fileChooser = new FileChooser();
if (path.exists()) {
fileChooser.setInitialDirectory(path);
}
fileChooser.getExtensionFilters().addAll(filter);
File file = fileChooser.showOpenDialog(controller.getMyStage());
if (file == null || !file.exists()) {
return null;
}
controller.recordFileOpened(file);
return file;
} catch (Exception e) {
return null;
}
}
public static List<String> getResourceFiles(String path) {
List<String> files = new ArrayList<>();
try {
if (!path.endsWith("/")) {
path += "/";
}
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
URL dirURL = classLoader.getResource(path);
if (dirURL == null) {
File filePath = new File(path);
if (!filePath.exists()) {
MyBoxLog.error(path);
return files;
}
File[] list = filePath.listFiles();
if (list != null) {
for (File file : list) {
if (file.isFile()) {
files.add(file.getName());
}
}
}
return files;
}
if (dirURL.getProtocol().equals("jar")) {
String jarPath = dirURL.getPath().substring(5, dirURL.getPath().indexOf("!"));
try (final JarFile jar = new JarFile(URLDecoder.decode(jarPath, "UTF-8"))) {
Enumeration<JarEntry> entries = jar.entries();
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
String name = entry.getName();
if (entry.isDirectory() || !name.startsWith(path)) {
continue;
}
name = name.substring(path.length());
if (!name.contains("/")) {
files.add(name);
}
}
}
} else if (dirURL.getProtocol().equals("file")) {
File[] list = new File(dirURL.getPath()).listFiles();
if (list != null) {
for (File file : list) {
if (file.isFile()) {
files.add(file.getName());
}
}
}
}
} catch (Exception e) {
MyBoxLog.console(e);
}
return files;
}
}
| 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/fxml/BaseTask.java | released/MyBox/src/main/java/mara/mybox/fxml/BaseTask.java | package mara.mybox.fxml;
import java.util.Date;
import javafx.application.Platform;
import javafx.concurrent.Task;
import mara.mybox.tools.DateTools;
/**
* @Author Mara
* @CreateDate 2019-12-18
* @License Apache License Version 2.0
*/
public class BaseTask<P> extends Task<P> {
protected BaseTask self;
protected Date startTime, endTime;
protected long cost;
protected boolean ok, quit;
protected String error;
public BaseTask() {
error = null;
startTime = new Date();
ok = quit = false;
self = this;
}
public static BaseTask create() {
BaseTask task = new BaseTask();
return task;
}
@Override
protected P call() {
ok = false;
if (!initValues()) {
return null;
}
try {
ok = handle();
} catch (Exception e) {
error = e.toString();
ok = false;
}
return null;
}
protected boolean initValues() {
startTime = new Date();
return true;
}
protected boolean handle() {
return true;
}
@Override
protected void succeeded() {
super.succeeded();
taskQuit();
Platform.runLater(() -> {
if (isCancelled()) {
return;
}
if (ok) {
whenSucceeded();
} else {
whenFailed();
}
finalAction();
});
Platform.requestNextPulse();
}
protected void whenSucceeded() {
}
protected void whenFailed() {
}
protected void whenCanceled() {
}
@Override
protected void failed() {
super.failed();
taskQuit();
Platform.runLater(() -> {
whenFailed();
finalAction();
});
Platform.requestNextPulse();
}
@Override
protected void cancelled() {
super.cancelled();
taskQuit();
Platform.runLater(() -> {
whenCanceled();
finalAction();
});
Platform.requestNextPulse();
}
protected void taskQuit() {
endTime = new Date();
if (startTime != null) {
cost = endTime.getTime() - startTime.getTime();
}
self = null;
quit = true;
}
protected void finalAction() {
}
public String duration() {
return DateTools.datetimeMsDuration(new Date().getTime() - startTime.getTime());
}
public boolean isWorking() {
return !quit && !isCancelled() && !isDone();
}
/*
get/set
*/
public Date getStartTime() {
return startTime;
}
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
public Date getEndTime() {
return endTime;
}
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
public long getCost() {
return cost;
}
public void setCost(long cost) {
this.cost = cost;
}
public boolean isOk() {
return ok;
}
public void setOk(boolean ok) {
this.ok = ok;
}
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
public BaseTask getSelf() {
return self;
}
public void setSelf(BaseTask self) {
this.self = self;
}
public boolean isQuit() {
return quit;
}
public void setQuit(boolean quit) {
this.quit = quit;
}
}
| 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/fxml/PopTools.java | released/MyBox/src/main/java/mara/mybox/fxml/PopTools.java | package mara.mybox.fxml;
import mara.mybox.fxml.menu.MenuTools;
import java.awt.Desktop;
import java.io.File;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonBar.ButtonData;
import javafx.scene.control.ButtonType;
import javafx.scene.control.CheckBox;
import javafx.scene.control.CheckMenuItem;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.Hyperlink;
import javafx.scene.control.Label;
import javafx.scene.control.MenuItem;
import javafx.scene.control.RadioMenuItem;
import javafx.scene.control.Separator;
import javafx.scene.control.SeparatorMenuItem;
import javafx.scene.control.TableView;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.control.TextInputControl;
import javafx.scene.control.TextInputDialog;
import javafx.scene.control.ToggleGroup;
import javafx.scene.control.Tooltip;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Pane;
import javafx.scene.layout.Region;
import javafx.stage.Popup;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import jdk.jshell.JShell;
import jdk.jshell.SourceCodeAnalysis;
import mara.mybox.controller.BaseController;
import mara.mybox.controller.BaseController_Attributes;
import mara.mybox.controller.BaseLogsController;
import mara.mybox.controller.ControlWebView;
import mara.mybox.controller.HtmlStyleInputController;
import mara.mybox.controller.MenuController;
import mara.mybox.data2d.Data2D;
import static mara.mybox.db.data.ColumnDefinition.ColumnType.Color;
import static mara.mybox.db.data.ColumnDefinition.ColumnType.Date;
import static mara.mybox.db.data.ColumnDefinition.ColumnType.Datetime;
import static mara.mybox.db.data.ColumnDefinition.ColumnType.Double;
import static mara.mybox.db.data.ColumnDefinition.ColumnType.Enumeration;
import static mara.mybox.db.data.ColumnDefinition.ColumnType.EnumerationEditable;
import static mara.mybox.db.data.ColumnDefinition.ColumnType.Era;
import static mara.mybox.db.data.ColumnDefinition.ColumnType.File;
import static mara.mybox.db.data.ColumnDefinition.ColumnType.Float;
import static mara.mybox.db.data.ColumnDefinition.ColumnType.Image;
import static mara.mybox.db.data.ColumnDefinition.ColumnType.Latitude;
import static mara.mybox.db.data.ColumnDefinition.ColumnType.Long;
import static mara.mybox.db.data.ColumnDefinition.ColumnType.Longitude;
import static mara.mybox.db.data.ColumnDefinition.ColumnType.Short;
import static mara.mybox.db.data.ColumnDefinition.ColumnType.String;
import mara.mybox.db.data.Data2DColumn;
import mara.mybox.db.table.BaseTableTools;
import mara.mybox.db.table.TableStringValues;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.style.HtmlStyles;
import mara.mybox.fxml.style.NodeStyleTools;
import static mara.mybox.fxml.style.NodeStyleTools.attributeTextStyle;
import mara.mybox.fxml.style.StyleTools;
import mara.mybox.tools.DateTools;
import mara.mybox.tools.StringTools;
import mara.mybox.tools.SystemTools;
import mara.mybox.value.AppVariables;
import mara.mybox.value.Languages;
import static mara.mybox.value.Languages.message;
import mara.mybox.value.TimeFormats;
import mara.mybox.value.UserConfig;
/**
* @Author Mara
* @CreateDate 2021-8-1
* @License Apache License Version 2.0
*/
public class PopTools {
/*
common
*/
public static void browseURI(BaseController controller, URI uri) {
if (uri == null) {
return;
}
if (SystemTools.isLinux()) {
// On my CentOS 7, system hangs when both Desktop.isDesktopSupported() and
// desktop.isSupported(Desktop.Action.BROWSE) are true.
// https://stackoverflow.com/questions/27879854/desktop-getdesktop-browse-hangs
// Below workaround for Linux because "Desktop.getDesktop().browse()" doesn't work on some Linux implementations
try {
if (Runtime.getRuntime().exec(new String[]{"which", "xdg-open"}).getInputStream().read() > 0) {
Runtime.getRuntime().exec(new String[]{"xdg-open", uri.toString()});
return;
}
} catch (Exception e) {
MyBoxLog.debug(e);
}
} else if (SystemTools.isMac()) {
// https://stackoverflow.com/questions/5226212/how-to-open-the-default-webbrowser-using-java/28807079#28807079
try {
Runtime.getRuntime().exec(new String[]{"open", uri.toString()});
return;
} catch (Exception e) {
MyBoxLog.debug(e);
}
} else if (Desktop.isDesktopSupported()) {
// https://stackoverflow.com/questions/23176624/javafx-freeze-on-desktop-openfile-desktop-browseuri?r=SearchResults
try {
Desktop.getDesktop().browse(uri);
return;
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
if (!uri.getScheme().equals("file") || new File(uri.getPath()).isFile()) {
ControllerTools.openTarget(uri.toString());
} else {
alertError(controller, message("DesktopNotSupportBrowse"));
}
}
public static Alert alert(BaseController controller, Alert.AlertType type, String information) {
try {
Alert alert = new Alert(type);
if (controller != null) {
alert.setTitle(controller.getTitle());
}
alert.setHeaderText(null);
alert.setContentText(information);
alert.getDialogPane().setMinWidth(Region.USE_PREF_SIZE);
alert.getDialogPane().setMinHeight(Region.USE_PREF_SIZE);
alert.getDialogPane().applyCss();
// https://stackoverflow.com/questions/38799220/javafx-how-to-bring-dialog-alert-to-the-front-of-the-screen?r=SearchResults
Stage stage = (Stage) alert.getDialogPane().getScene().getWindow();
stage.setAlwaysOnTop(true);
stage.toFront();
stage.sizeToScene();
alert.showAndWait();
return alert;
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
public static Alert alertInformation(BaseController controller, String information) {
return alert(controller, Alert.AlertType.INFORMATION, information);
}
public static Alert alertWarning(BaseController controller, String information) {
return alert(controller, Alert.AlertType.WARNING, information);
}
public static Alert alertError(BaseController controller, String information) {
return alert(controller, Alert.AlertType.ERROR, information);
}
public static String askValue(String title, String header, String name, String initValue) {
return askValue(title, header, name, initValue, 400);
}
public static String askValue(String title, String header, String name, String initValue, int minWidth) {
TextInputDialog dialog = new TextInputDialog();
dialog.setTitle(title);
dialog.setHeaderText(header);
dialog.setContentText(name);
dialog.getEditor().setText(initValue);
dialog.getEditor().setPrefWidth(initValue == null ? minWidth : Math.min(minWidth, initValue.length() * AppVariables.sceneFontSize));
dialog.getEditor().selectEnd();
Stage stage = (Stage) dialog.getDialogPane().getScene().getWindow();
stage.setAlwaysOnTop(true);
stage.toFront();
stage.getScene().getRoot().requestFocus();
Optional<String> result = dialog.showAndWait();
if (result == null || !result.isPresent()) {
return null;
}
String value = result.get();
return value;
}
public static boolean askSure(String title, String sureString) {
return askSure(title, null, sureString);
}
// https://openjfx.io/javadoc/17/javafx.controls/javafx/scene/control/Dialog.html
public static boolean askSure(String title, String header, String sureString) {
Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
alert.setTitle(title);
if (header != null) {
alert.setHeaderText(header);
}
alert.setContentText(sureString);
alert.getDialogPane().setMinHeight(Region.USE_PREF_SIZE);
ButtonType buttonSure = new ButtonType(message("Sure"));
ButtonType buttonCancel = new ButtonType(message("Cancel"), ButtonData.CANCEL_CLOSE);
alert.getButtonTypes().setAll(buttonSure, buttonCancel);
Stage stage = (Stage) alert.getDialogPane().getScene().getWindow();
stage.setAlwaysOnTop(true);
stage.toFront();
Optional<ButtonType> result = alert.showAndWait();
return result != null && result.isPresent() && result.get() == buttonSure;
}
public static Popup makePopWindow(BaseController parent, String fxml) {
try {
BaseController controller = WindowTools.loadFxml(fxml);
if (controller == null) {
return null;
}
Popup popup = new Popup();
popup.setAutoHide(true);
popup.getContent().add(controller.getMyScene().getRoot());
popup.setUserData(controller);
popup.setOnHiding((WindowEvent event) -> {
WindowTools.closeWindow(popup);
});
controller.setParent(parent, BaseController_Attributes.StageType.Popup);
controller.setMyWindow(popup);
if (parent != null) {
parent.closePopup();
parent.setPopup(popup);
}
return popup;
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
public static void showError(BaseController controller, String error) {
if (controller == null) {
MyBoxLog.error(error);
} else if (controller instanceof BaseLogsController) {
((BaseLogsController) controller).updateLogs(error, true, true);
} else if (controller.getTask() != null) {
controller.getTask().setError(error);
} else {
Platform.runLater(() -> {
controller.alertError(error);
// MyBoxLog.debug(error);
});
}
}
/*
style
*/
public static ContextMenu popHtmlStyle(Event event, ControlWebView controller) {
try {
if (event == null || controller == null) {
return null;
}
List<MenuItem> items = new ArrayList<>();
String baseName = controller.getBaseName();
MenuItem menu = new MenuItem(message("HtmlStyle"));
menu.setStyle(attributeTextStyle());
items.add(menu);
items.add(new SeparatorMenuItem());
ToggleGroup sgroup = new ToggleGroup();
String prefix = UserConfig.getBoolean(baseName + "ShareHtmlStyle", true) ? "AllInterface" : baseName;
String currentStyle = UserConfig.getString(prefix + "HtmlStyle", null);
RadioMenuItem rmenu = new RadioMenuItem(message("None"));
rmenu.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
controller.setStyle(null);
}
});
rmenu.setSelected(currentStyle == null);
rmenu.setToggleGroup(sgroup);
items.add(rmenu);
boolean predefinedValue = false;
for (HtmlStyles.HtmlStyle style : HtmlStyles.HtmlStyle.values()) {
rmenu = new RadioMenuItem(message(style.name()));
String styleValue = HtmlStyles.styleValue(style);
rmenu.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
controller.setStyle(styleValue);
}
});
boolean isCurrent = currentStyle != null && currentStyle.equals(styleValue);
rmenu.setSelected(isCurrent);
rmenu.setToggleGroup(sgroup);
items.add(rmenu);
if (isCurrent) {
predefinedValue = true;
}
}
rmenu = new RadioMenuItem(message("Input") + "...");
rmenu.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
HtmlStyleInputController inputController = HtmlStyleInputController.open(controller,
message("Style"), UserConfig.getString(prefix + "HtmlStyle", null));
inputController.getNotify().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
String value = inputController.getInputString();
if (value == null || value.isBlank()) {
value = null;
}
controller.setStyle(value);
inputController.closeStage();
}
});
}
});
rmenu.setSelected(currentStyle != null && !predefinedValue);
rmenu.setToggleGroup(sgroup);
items.add(rmenu);
items.add(new SeparatorMenuItem());
items.add(MenuTools.popCheckMenu(baseName + "HtmlStyles"));
controller.popEventMenu(event, items);
return controller.getPopMenu();
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
public static ContextMenu popWindowStyles(BaseController parent, String baseStyle, Event event) {
try {
List<MenuItem> items = new ArrayList<>();
String baseName = parent.getBaseName();
MenuItem menu = new MenuItem(message("WindowStyle"));
menu.setStyle(attributeTextStyle());
items.add(menu);
items.add(new SeparatorMenuItem());
Map<String, String> styles = new LinkedHashMap<>();
styles.put("None", "");
styles.put("Transparent", "; -fx-text-fill: black; -fx-background-color: transparent;");
styles.put("Console", "; -fx-text-fill: #CCFF99; -fx-background-color: black;");
styles.put("Blackboard", "; -fx-text-fill: white; -fx-background-color: #336633;");
styles.put("Ago", "; -fx-text-fill: white; -fx-background-color: darkblue;");
styles.put("Book", "; -fx-text-fill: black; -fx-background-color: #F6F1EB;");
ToggleGroup sgroup = new ToggleGroup();
String prefix = UserConfig.getBoolean(baseName + "ShareWindowStyle", true) ? "AllInterface" : baseName;
String currentStyle = UserConfig.getString(prefix + "WindowStyle", "");
for (String name : styles.keySet()) {
RadioMenuItem rmenu = new RadioMenuItem(message(name));
String style = styles.get(name);
rmenu.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
UserConfig.setString(prefix + "WindowStyle", style);
parent.getThisPane().setStyle(baseStyle + style);
setMenuLabelsStyle(parent.getThisPane(), baseStyle + style);
}
});
rmenu.setSelected(currentStyle != null && currentStyle.equals(style));
rmenu.setToggleGroup(sgroup);
items.add(rmenu);
}
items.add(new SeparatorMenuItem());
CheckMenuItem checkMenu = new CheckMenuItem(message("ShareAllInterface"));
checkMenu.setSelected(UserConfig.getBoolean(baseName + "ShareWindowStyle", true));
checkMenu.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
UserConfig.setBoolean(baseName + "ShareWindowStyle", checkMenu.isSelected());
}
});
items.add(checkMenu);
items.add(MenuTools.popCheckMenu(baseName + "WindowStyles"));
parent.popEventMenu(event, items);
return parent.getPopMenu();
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
public static void setMenuLabelsStyle(Node node, String style) {
if (node instanceof Label) {
node.setStyle(style);
} else if (node instanceof Parent && !(node instanceof TableView)) {
for (Node child : ((Parent) node).getChildrenUnmodifiable()) {
setMenuLabelsStyle(child, style);
}
}
}
public static void setWindowStyle(Pane pane, String baseName, String baseStyle) {
String prefix = UserConfig.getBoolean(baseName + "ShareWindowStyle", true) ? "AllInterface" : baseName;
String style = UserConfig.getString(prefix + "WindowStyle", "");
pane.setStyle(baseStyle + style);
setMenuLabelsStyle(pane, baseStyle + style);
}
/*
common parts
*/
public static MenuController valuesMenu(BaseController parent, TextInputControl input,
String valueName, String title, Event event) {
return valuesMenu(parent, input, valueName, title, event, null, false);
}
public static MenuController valuesMenu(BaseController parent, TextInputControl input,
String valueName, String title, Event event, boolean alwaysClear) {
return valuesMenu(parent, input, valueName, title, event, null, alwaysClear);
}
public static MenuController valuesMenu(BaseController parent, TextInputControl input,
String valueName, String title, Event event, List<Node> exTopButtons, boolean alwaysClear) {
try {
MenuController controller = MenuController.open(parent, input, event, valueName, alwaysClear);
if (title != null) {
controller.setTitleLabel(title);
}
List<Node> topButtons = new ArrayList<>();
if (input instanceof TextArea) {
Button newLineButton = new Button();
newLineButton.setGraphic(StyleTools.getIconImageView("iconTurnOver.png"));
NodeStyleTools.setTooltip(newLineButton, new Tooltip(message("Newline")));
newLineButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
input.replaceText(input.getSelection(), "\n");
controller.getThisPane().requestFocus();
input.requestFocus();
}
});
topButtons.add(newLineButton);
}
Button clearButton = new Button(message("ClearInputArea"));
clearButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
input.clear();
controller.getThisPane().requestFocus();
input.requestFocus();
}
});
topButtons.add(clearButton);
if (exTopButtons != null) {
topButtons.addAll(exTopButtons);
}
controller.addFlowPane(topButtons);
controller.addNode(new Separator());
return controller;
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
public static void addButtonsPane(MenuController controller, List<String> values) {
addButtonsPane(controller, values, -1);
}
public static void addButtonsPane(MenuController controller, List<String> values, int index) {
try {
List<Node> buttons = new ArrayList<>();
for (String value : values) {
Button button = makeMenuButton(controller, value, value);
if (button != null) {
buttons.add(button);
}
}
controller.addFlowPane(buttons);
} catch (Exception e) {
MyBoxLog.error(e.toString());
}
}
public static Button makeMenuButton(MenuController controller, String name, String value) {
try {
if (controller == null || value == null) {
return null;
}
if (name == null) {
name = value;
}
TextInputControl input = (TextInputControl) controller.getNode();
Button button = new Button(name.length() > 200 ? name.substring(0, 200) + " ..." : name);
button.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
if (controller.isClearAndSet()) {
input.setText(value);
} else {
input.replaceText(input.getSelection(), value);
}
if (controller.isCloseAfterPaste()) {
controller.close();
} else {
controller.getThisPane().requestFocus();
}
input.requestFocus();
input.deselect();
}
});
return button;
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
/*
pop values
*/
public static void popListValues(BaseController parent, TextInputControl input,
String valueName, String title, List<String> values, Event event) {
try {
MenuController controller = valuesMenu(parent, input, valueName, title, event);
addButtonsPane(controller, values);
} catch (Exception e) {
MyBoxLog.error(e.toString());
}
}
public static void popMappedValues(BaseController parent, TextInputControl input,
String valueName, LinkedHashMap<String, String> values, Event event) {
try {
MenuController controller = valuesMenu(parent, input, valueName, valueName, event);
List<Node> nodes = new ArrayList<>();
for (String value : values.keySet()) {
String msg = values.get(value);
Button button = makeMenuButton(controller,
value + (msg != null && !msg.isBlank() ? " " + msg : ""),
value);
if (button != null) {
nodes.add(button);
}
}
controller.addFlowPane(nodes);
} catch (Exception e) {
MyBoxLog.error(e.toString());
}
}
/*
saved values
*/
public static void popSavedValues(BaseController parent, TextInputControl input, Event event,
String valueName, boolean alwaysClear) {
try {
List<Node> setButtons = new ArrayList<>();
Button clearValuesButton = new Button(message("ClearValues"));
clearValuesButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent aevent) {
TableStringValues.clear(valueName);
parent.closePopup();
popSavedValues(parent, input, aevent, valueName, alwaysClear);
}
});
setButtons.add(clearValuesButton);
int max = UserConfig.getInt(valueName + "MaxSaved", 20);
Button maxButton = new Button(message("MaxSaved"));
maxButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent aevent) {
String value = PopTools.askValue(parent.getTitle(), null, message("MaxSaved"), max + "");
if (value == null) {
return;
}
try {
int v = Integer.parseInt(value);
UserConfig.setInt(valueName + "MaxSaved", v);
} catch (Exception e) {
MyBoxLog.error(e);
}
}
});
setButtons.add(maxButton);
MenuController controller = valuesMenu(parent, input, valueName, null,
event, setButtons, alwaysClear);
controller.addNode(new Label(message("PopValuesComments")));
List<String> values = TableStringValues.max(valueName, max);
List<Node> buttons = new ArrayList<>();
for (String value : values) {
Button button = makeMenuButton(controller, value, value);
button.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent aevent) {
if (aevent.getButton() == MouseButton.SECONDARY) {
TableStringValues.delete(valueName, value);
controller.close();
popSavedValues(parent, input, event, valueName, alwaysClear);
}
}
});
buttons.add(button);
}
controller.addFlowPane(buttons);
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
public static void popSavedValues(BaseController parent, TextInputControl input, Event event,
String valueName) {
popSavedValues(parent, input, event, valueName, false);
}
/*
examples
*/
public static ContextMenu popDatetimeExamples(BaseController parent, ContextMenu inPopMenu,
TextField input, MouseEvent mouseEvent) {
try {
List<String> values = new ArrayList<>();
Date d = new Date();
values.add(DateTools.datetimeToString(d, TimeFormats.Datetime));
values.add(DateTools.datetimeToString(d, TimeFormats.DatetimeMs));
values.add(DateTools.datetimeToString(d, TimeFormats.Date));
values.add(DateTools.datetimeToString(d, TimeFormats.Month));
values.add(DateTools.datetimeToString(d, TimeFormats.Year));
values.add(DateTools.datetimeToString(d, TimeFormats.TimeMs));
values.add(DateTools.datetimeToString(d, TimeFormats.DatetimeZone));
values.add(DateTools.datetimeToString(d, TimeFormats.DatetimeC));
values.add(DateTools.datetimeToString(d, TimeFormats.DatetimeMsC));
values.add(DateTools.datetimeToString(d, TimeFormats.DateC));
values.add(DateTools.datetimeToString(d, TimeFormats.MonthC));
values.add(DateTools.datetimeToString(d, TimeFormats.DatetimeZoneC));
values.add(DateTools.datetimeToString(d, TimeFormats.DatetimeE));
values.add(DateTools.datetimeToString(d, TimeFormats.DatetimeMsE));
values.add(DateTools.datetimeToString(d, TimeFormats.DateE));
values.add(DateTools.datetimeToString(d, TimeFormats.MonthE));
values.add(DateTools.datetimeToString(d, TimeFormats.DatetimeZoneE));
values.addAll(Arrays.asList(
"2020-07-15T36:55:09", "2020-07-10T10:10:10.532 +0800"
));
return popDateMenu(parent, inPopMenu, input, mouseEvent, values);
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
public static ContextMenu popDateExamples(BaseController parent, ContextMenu inPopMenu,
TextField input, MouseEvent mouseEvent) {
try {
List<String> values = new ArrayList<>();
Date d = new Date();
values.add(DateTools.datetimeToString(d, TimeFormats.Date));
values.add(DateTools.datetimeToString(d, TimeFormats.Month));
values.add(DateTools.datetimeToString(d, TimeFormats.Year));
values.add(DateTools.datetimeToString(d, TimeFormats.DateC));
values.add(DateTools.datetimeToString(d, TimeFormats.MonthC));
values.add(DateTools.datetimeToString(d, TimeFormats.DateE));
values.add(DateTools.datetimeToString(d, TimeFormats.MonthE));
return popDateMenu(parent, inPopMenu, input, mouseEvent, values);
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
public static void popEraExamples(BaseController parent, TextField input, MouseEvent mouseEvent) {
try {
List<String> values = new ArrayList<>();
Date d = new Date();
values.add(DateTools.datetimeToString(d, TimeFormats.Datetime + " G", Locale.ENGLISH, null));
values.add(DateTools.datetimeToString(d, TimeFormats.DatetimeMs + " G", Locale.ENGLISH, null));
values.add(DateTools.datetimeToString(d, TimeFormats.Date + " G", Locale.ENGLISH, null));
values.add(DateTools.datetimeToString(d, TimeFormats.Month + " G", Locale.ENGLISH, null));
values.add(DateTools.datetimeToString(d, "G" + TimeFormats.DateA, Locale.ENGLISH, null));
Date bc = DateTools.encodeDate("770-3-9 12:56:33.498 BC");
values.add(DateTools.datetimeToString(bc, TimeFormats.DatetimeA + " G", Locale.ENGLISH, null));
values.add(DateTools.datetimeToString(bc, TimeFormats.Date + " G", Locale.ENGLISH, null));
values.add(DateTools.datetimeToString(bc, "G" + TimeFormats.MonthA, Locale.ENGLISH, null));
values.add(DateTools.datetimeToString(bc, "G" + TimeFormats.YearA, Locale.ENGLISH, null));
if (Languages.isChinese()) {
values.add(DateTools.datetimeToString(d, TimeFormats.Datetime + " G", Locale.CHINESE, null));
values.add(DateTools.datetimeToString(d, TimeFormats.DatetimeMs + " G", Locale.CHINESE, null));
values.add(DateTools.datetimeToString(d, TimeFormats.Date + " G", Locale.CHINESE, null));
values.add(DateTools.datetimeToString(d, TimeFormats.Month + " G", Locale.CHINESE, null));
values.add(DateTools.datetimeToString(d, "G" + TimeFormats.DateA, Locale.CHINESE, null));
values.add(DateTools.datetimeToString(bc, TimeFormats.DatetimeA + " G", Locale.CHINESE, null));
values.add(DateTools.datetimeToString(bc, TimeFormats.DateA + " G", Locale.CHINESE, null));
values.add(DateTools.datetimeToString(bc, "G" + TimeFormats.MonthA, Locale.CHINESE, null));
values.add(DateTools.datetimeToString(bc, "G" + TimeFormats.YearA, Locale.CHINESE, null));
}
values.add(DateTools.datetimeToString(d, TimeFormats.DatetimeMsC + " G", Locale.ENGLISH, null));
values.add(DateTools.datetimeToString(d, TimeFormats.DateC + " G", Locale.ENGLISH, null));
values.add(DateTools.datetimeToString(d, "G" + TimeFormats.MonthC, Locale.ENGLISH, null));
values.add(DateTools.datetimeToString(d, TimeFormats.DatetimeMsB + " G", Locale.ENGLISH, null));
values.add(DateTools.datetimeToString(d, TimeFormats.DateB + " G", Locale.ENGLISH, null));
values.add(DateTools.datetimeToString(d, "G" + TimeFormats.DatetimeB, Locale.ENGLISH, null));
values.add(DateTools.datetimeToString(d, "G" + TimeFormats.MonthB, Locale.ENGLISH, null));
| 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/fxml/TextClipboardMonitor.java | released/MyBox/src/main/java/mara/mybox/fxml/TextClipboardMonitor.java | package mara.mybox.fxml;
import java.sql.Connection;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import javafx.application.Platform;
import javafx.scene.input.Clipboard;
import mara.mybox.controller.TextInMyBoxClipboardController;
import mara.mybox.controller.TextInSystemClipboardController;
import mara.mybox.db.table.TableTextClipboard;
import mara.mybox.dev.MyBoxLog;
/**
* @Author Mara
* @CreateDate 2021-8-3
* @License Apache License Version 2.0
*/
public class TextClipboardMonitor extends Timer {
public final static int DefaultInterval = 200;
protected Date startTime = null;
protected int number;
protected final TableTextClipboard tableTextClipboard = new TableTextClipboard();
protected String lastString = "";
protected Connection conn = null;
protected TextInSystemClipboardController controller;
public TextClipboardMonitor start(int inInterval) {
int interval = TextClipboardTools.setMonitorInterval(inInterval);
startTime = new Date();
number = 0;
schedule(new MonitorTask(), 0, interval);
Platform.runLater(() -> {
TextInSystemClipboardController.updateSystemClipboardStatus();
TextInMyBoxClipboardController.updateMyBoxClipboardStatus();
});
MyBoxLog.debug("Text Clipboard Monitor started. Interval:" + interval);
return this;
}
public void stop() {
cancel();
Platform.runLater(() -> {
TextInSystemClipboardController.updateSystemClipboardStatus();
TextInMyBoxClipboardController.updateMyBoxClipboardStatus();
});
MyBoxLog.debug("Text Clipboard Monitor stopped.");
}
class MonitorTask extends TimerTask {
@Override
public void run() {
Platform.runLater(new Runnable() {
@Override
public synchronized void run() {
try {
controller = TextInSystemClipboardController.running();
if (!TextClipboardTools.isCopy() && controller == null) {
TextClipboardTools.stopTextClipboardMonitor();
return;
}
Clipboard clipboard = Clipboard.getSystemClipboard();
if (!clipboard.hasString()) {
return;
}
String clip = clipboard.getString();
if (clip == null || clip.isEmpty() || clip.equals(lastString)) {
return;
}
lastString = clip;
number++;
if (TextClipboardTools.isCopy()) {
TextClipboardTools.stringToMyBoxClipboard(tableTextClipboard, conn, lastString);
}
if (controller != null) {
controller.loadClip(clip);
}
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
});
}
}
/*
get/set
*/
public Date getStartTime() {
return startTime;
}
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public String getLastString() {
return lastString;
}
public void setLastString(String lastString) {
this.lastString = lastString;
}
public Connection getConn() {
return conn;
}
public void setConn(Connection conn) {
this.conn = conn;
}
public TextInSystemClipboardController getController() {
return controller;
}
public void setController(TextInSystemClipboardController controller) {
this.controller = 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/fxml/DownloadTask.java | released/MyBox/src/main/java/mara/mybox/fxml/DownloadTask.java | package mara.mybox.fxml;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Date;
import java.util.Map;
import mara.mybox.data.DownloadItem;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.tools.FileDeleteTools;
import mara.mybox.tools.FileNameTools;
import mara.mybox.tools.HtmlReadTools;
import mara.mybox.tools.NetworkTools;
import mara.mybox.tools.UrlTools;
import mara.mybox.value.AppValues;
import mara.mybox.value.Languages;
/**
* @Author Mara
* @CreateDate 2019-12-18
* @License Apache License Version 2.0
*/
public class DownloadTask<Void> extends FxTask<Void> {
protected String address;
protected URL url;
protected HttpURLConnection connection;
protected File targetPath, targetFile, tmpFile;
protected long totalSize, currentSize;
protected boolean readHead = false;
protected Map<String, String> head;
protected int responseCode;
public static DownloadTask create() {
DownloadTask task = new DownloadTask();
return task;
}
@Override
protected boolean initValues() {
if (address == null) {
error = Languages.message("InvalidData");
return false;
}
startTime = new Date();
currentSize = 0;
try {
url = UrlTools.url(address);
return url != null;
} catch (Exception e) {
error = e.toString();
return false;
}
}
@Override
protected boolean handle() {
if (readHead) {
readHead();
} else {
download();
}
return true;
}
protected HttpURLConnection getConnection() {
try {
return NetworkTools.httpConnection(url);
} catch (Exception e) {
error = e.toString();
MyBoxLog.debug(error);
return null;
}
}
protected void readHead() {
try {
connection = getConnection();
head = HtmlReadTools.requestHead(connection);
connection.disconnect();
connection = null;
} catch (Exception e) {
error = e.toString();
MyBoxLog.debug(error);
}
}
protected boolean download() {
try {
String filename = url.getFile().substring(url.getFile().lastIndexOf('/'));
targetFile = new File(targetPath.getAbsolutePath() + File.separator
+ FileNameTools.filter(filename.trim()));
connection = getConnection();
connection.setRequestMethod("GET");
responseCode = connection.getResponseCode();
totalSize = connection.getContentLength();
error = connection.getResponseMessage();
connection.disconnect();
progress();
if (responseCode >= 400) {
return false;
}
error = null;
connection = getConnection();
// connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
connection.connect();
tmpFile = new File(targetFile.getAbsolutePath() + ".downloading");
progress();
try (BufferedInputStream inStream = new BufferedInputStream(connection.getInputStream());
RandomAccessFile tmpFileStream = new RandomAccessFile(tmpFile, "rw")) {
currentSize = tmpFile.length();
if (currentSize > 0) {
inStream.skip(currentSize);
tmpFileStream.seek(currentSize);
}
progress();
byte[] buf = new byte[AppValues.IOBufferLength];
int len;
while ((len = inStream.read(buf)) > 0) {
if (isCancelled()) {
break;
}
tmpFileStream.write(buf, 0, len);
currentSize += len;
progress();
}
}
connection.disconnect();
responseCode = 0;
Files.copy(Paths.get(tmpFile.getAbsolutePath()), Paths.get(targetFile.getAbsolutePath()),
StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES);
FileDeleteTools.delete(tmpFile);
return targetFile.exists();
} catch (Exception e) {
error = e.toString();
MyBoxLog.debug(error);
return false;
}
}
protected void progress() {
}
@Override
protected void taskQuit() {
super.taskQuit();
progress();
}
protected void assign(DownloadItem item) {
item.setTask(this);
}
/*
get/set
*/
public String getAddress() {
return address;
}
public DownloadTask setAddress(String address) {
this.address = address;
return this;
}
public URL getUrl() {
return url;
}
public DownloadTask setUrl(URL url) {
this.url = url;
return this;
}
public File getTargetPath() {
return targetPath;
}
public DownloadTask setTargetPath(File targetPath) {
this.targetPath = targetPath;
return this;
}
public Map<String, String> getHead() {
return head;
}
public DownloadTask setHead(Map<String, String> head) {
this.head = head;
return this;
}
public int getResponseCode() {
return responseCode;
}
public DownloadTask setResponseCode(int responseCode) {
this.responseCode = responseCode;
return this;
}
public File getTmpFile() {
return tmpFile;
}
public DownloadTask setTmpFile(File tmpFile) {
this.tmpFile = tmpFile;
return this;
}
public long getTotalSize() {
return totalSize;
}
public DownloadTask setTotalSize(long totalSize) {
this.totalSize = totalSize;
return this;
}
public long getCurrentSize() {
return currentSize;
}
public DownloadTask setCurrentSize(long currentSize) {
this.currentSize = currentSize;
return this;
}
public boolean isReadHead() {
return readHead;
}
public DownloadTask setReadHead(boolean readHead) {
this.readHead = readHead;
return this;
}
public File getTargetFile() {
return targetFile;
}
public DownloadTask setTargetFile(File targetFile) {
this.targetFile = targetFile;
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/fxml/FxTask.java | released/MyBox/src/main/java/mara/mybox/fxml/FxTask.java | package mara.mybox.fxml;
import javafx.scene.Node;
import mara.mybox.controller.BaseController;
import mara.mybox.controller.LoadingController;
import mara.mybox.dev.MyBoxLog;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2019-12-18
* @License Apache License Version 2.0
*/
public class FxTask<Void> extends BaseTask<Void> {
protected BaseController controller;
protected LoadingController loading;
protected Node disableNode;
public FxTask() {
}
public FxTask(BaseController controller) {
this.controller = controller;
}
@Override
protected boolean initValues() {
if (!super.initValues()) {
return false;
}
if (disableNode != null) {
disableNode.setDisable(true);
}
return true;
}
public void setInfo(String info) {
if (info == null || info.isBlank()) {
return;
}
if (loading != null) {
loading.setInfo(info);
} else if (controller != null) {
controller.displayInfo(info);
} else {
MyBoxLog.console(info);
}
}
@Override
public void setError(String error) {
this.error = error;
if (error == null || error.isBlank()) {
return;
}
if (loading != null) {
loading.setInfo(error);
} else if (controller != null) {
controller.displayError(error);
} else {
MyBoxLog.error(error);
}
}
public String getInfo() {
if (loading == null) {
return null;
}
return loading.getInfo();
}
@Override
protected void whenSucceeded() {
if (isCancelled()) {
setInfo(message("Cancelled"));
return;
}
if (controller != null) {
controller.displayInfo(message("Successful"));
}
}
@Override
protected void whenCanceled() {
setInfo(message("Cancelled"));
}
@Override
protected void whenFailed() {
if (isCancelled()) {
setInfo(message("Cancelled"));
return;
}
if (controller != null) {
MyBoxLog.console(controller.getClass());
if (error != null) {
MyBoxLog.debug(controller.getTitle() + ": " + error);
if (error.equals(message("Failed"))) {
controller.displayError(error);
} else {
if (error.contains("java.sql.SQLDataException: 22003 : [0] DOUBLE")) {
error = error + "\n\n" + message("DataOverflow");
}
controller.alertError(error);
}
} else {
controller.popFailed();
}
}
}
@Override
protected void finalAction() {
super.finalAction();
controller = null;
loading = null;
if (disableNode != null) {
disableNode.setDisable(false);
}
}
/*
get/set
*/
public BaseController getController() {
return controller;
}
public void setController(BaseController controller) {
this.controller = controller;
}
public LoadingController getLoading() {
return loading;
}
public void setLoading(LoadingController loading) {
this.loading = loading;
}
public Node getDisableNode() {
return disableNode;
}
public void setDisableNode(Node disableNode) {
this.disableNode = disableNode;
}
}
| 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/fxml/ConditionNode.java | released/MyBox/src/main/java/mara/mybox/fxml/ConditionNode.java | package mara.mybox.fxml;
import javafx.scene.text.Text;
import mara.mybox.data.GeographyCode;
/**
* @Author Mara
* @CreateDate 2020-04-18
* @License Apache License Version 2.0
*/
public class ConditionNode extends Text {
private GeographyCode code;
private String title, condition;
public ConditionNode() {
}
public ConditionNode(String text) {
setText(text);
}
public static ConditionNode create(String text) {
ConditionNode item = new ConditionNode(text);
return item;
}
public GeographyCode getCode() {
return code;
}
/*
customized get/set
*/
/*
get/set
*/
public ConditionNode setCode(GeographyCode code) {
this.code = code;
return this;
}
public String getTitle() {
return title;
}
public ConditionNode setTitle(String title) {
this.title = title;
return this;
}
public String getCondition() {
return condition;
}
public ConditionNode setCondition(String condition) {
this.condition = condition;
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/fxml/ImageClipboardMonitor.java | released/MyBox/src/main/java/mara/mybox/fxml/ImageClipboardMonitor.java | package mara.mybox.fxml;
import java.awt.image.BufferedImage;
import java.io.File;
import java.sql.Connection;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import javafx.application.Platform;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.image.Image;
import javafx.scene.input.Clipboard;
import mara.mybox.image.data.ImageAttributes;
import mara.mybox.image.tools.ImageConvertTools;
import mara.mybox.image.tools.ScaleTools;
import mara.mybox.controller.ImageInMyBoxClipboardController;
import mara.mybox.controller.ImageInSystemClipboardController;
import mara.mybox.db.DerbyBase;
import mara.mybox.db.data.ImageClipboard;
import mara.mybox.db.data.ImageClipboard.ImageSource;
import mara.mybox.db.table.TableImageClipboard;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.image.FxImageTools;
import mara.mybox.image.file.ImageFileWriters;
import mara.mybox.tools.DateTools;
import mara.mybox.tools.FileTools;
import mara.mybox.tools.IntTools;
import static mara.mybox.value.Languages.message;
import org.apache.commons.io.FileUtils;
/**
* @Author Mara
* @CreateDate 2021-8-3
* @License Apache License Version 2.0
*/
public class ImageClipboardMonitor extends Timer {
public final static int DefaultInterval = 1000;
protected ImageAttributes attributes;
protected Date startTime = null;
protected int recordNumber, savedNumber, copiedNumber;
protected TableImageClipboard tableImageClipboard;
private String filePrefix;
private Image lastImage = null;
public ImageClipboardMonitor start(int inInterval, ImageAttributes attributes, String filePrefix) {
int interval = ImageClipboardTools.setMonitorInterval(inInterval);
this.attributes = attributes;
this.filePrefix = filePrefix;
startTime = new Date();
recordNumber = 0;
savedNumber = 0;
copiedNumber = 0;
lastImage = null;
schedule(new MonitorTask(), 0, interval);
Platform.runLater(() -> {
ImageInSystemClipboardController.updateSystemClipboardStatus();
ImageInMyBoxClipboardController.updateClipboardsStatus();
});
MyBoxLog.debug("Image Clipboard Monitor started. Interval:" + interval);
return this;
}
public void stop() {
cancel();
Platform.runLater(() -> {
ImageInSystemClipboardController.updateSystemClipboardStatus();
ImageInMyBoxClipboardController.updateClipboardsStatus();
});
MyBoxLog.debug("Image Clipboard Monitor stopped.");
clearTmpClips();
attributes = null;
lastImage = null;
tableImageClipboard = null;
startTime = null;
filePrefix = null;
}
class MonitorTask extends TimerTask {
private Image clip;
@Override
public void run() {
Platform.runLater(new Runnable() {
@Override
public synchronized void run() {
try {
clearTmpClips();
ImageInSystemClipboardController controller = ImageInSystemClipboardController.running();
if (controller == null && !ImageClipboardTools.isCopy()
&& (!ImageClipboardTools.isSave() || filePrefix == null || attributes == null)) {
ImageClipboardTools.stopImageClipboardMonitor();
return;
}
Clipboard clipboard = Clipboard.getSystemClipboard();
if (!clipboard.hasImage()) {
return;
}
clip = clipboard.getImage();
if (clip == null || FxImageTools.sameImage(null, lastImage, clip)) {
return;
}
lastImage = clip;
recordNumber++;
if (controller != null) {
controller.loadClip(clip);
}
if (ImageClipboardTools.isCopy()) {
copyToMyBoxClipboard(clip);
}
if (ImageClipboardTools.isSave()) {
if (filePrefix == null || attributes == null) {
if (controller != null) {
controller.filesInfo(message("ImageNotSaveDueInvalidPath"));
}
} else {
saveImage(clip);
}
}
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
});
}
}
public static void clearTmpClips() {
try {
System.gc();
File path = FileTools.javaIOTmpPath();
File[] files = path.listFiles();
if (files == null) {
return;
}
for (File file : files) {
try {
if (file.isFile() && file.getName().endsWith(".TMP")) {
FileUtils.deleteQuietly(file);
}
} catch (Exception e) {
}
}
} catch (Exception e) {
// MyBoxLog.debug(e);
}
}
public void saveImage(Image image) {
if (image == null || filePrefix == null || attributes == null) {
return;
}
new Thread() {
@Override
public void run() {
File file = new File(filePrefix + DateTools.nowFileString() + "-"
+ IntTools.random(1000) + "." + attributes.getImageFormat());
while (file.exists()) {
file = new File(filePrefix + DateTools.nowFileString() + "-"
+ IntTools.random(1000) + "." + attributes.getImageFormat());
}
String fname = file.getAbsolutePath();
ImageInSystemClipboardController controller = ImageInSystemClipboardController.running();
if (controller != null) {
Platform.runLater(() -> {
controller.filesInfo(message("Saving") + " " + fname);
});
}
BufferedImage bufferedImage = SwingFXUtils.fromFXImage(image, null);
int width = ImageClipboardTools.getWidth();
if (width > 0) {
bufferedImage = ScaleTools.scaleImageWidthKeep(bufferedImage, width);
}
BufferedImage converted = ImageConvertTools.convertColorSpace(null, bufferedImage, attributes);
ImageFileWriters.writeImageFile(null, converted, attributes, fname);
savedNumber++;
if (controller != null) {
Platform.runLater(() -> {
controller.updateNumbers();
controller.filesInfo("");
});
}
}
}.start();
}
public void copyToMyBoxClipboard(Image image) {
if (image == null) {
return;
}
new Thread() {
@Override
public void run() {
try (Connection conn = DerbyBase.getConnection()) {
int width = ImageClipboardTools.getWidth();
BufferedImage bufferedImage = SwingFXUtils.fromFXImage(image, null);
if (width > 0) {
bufferedImage = ScaleTools.scaleImageWidthKeep(bufferedImage, width);
}
if (bufferedImage == null) {
return;
}
if (tableImageClipboard == null) {
tableImageClipboard = new TableImageClipboard();
}
tableImageClipboard.insertData(conn,
ImageClipboard.create(null, bufferedImage, ImageSource.SystemClipBoard));
conn.commit();
ImageInMyBoxClipboardController.updateClipboards();
copiedNumber++;
ImageInSystemClipboardController controller = ImageInSystemClipboardController.running();
if (controller != null) {
Platform.runLater(() -> {
controller.updateNumbers();
});
}
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
}.start();
}
/*
get/set
*/
public Date getStartTime() {
return startTime;
}
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
public int getNumber() {
return recordNumber;
}
public void setNumber(int number) {
this.recordNumber = number;
}
public TableImageClipboard getTableImageClipboard() {
return tableImageClipboard;
}
public void setTableImageClipboard(TableImageClipboard tableImageClipboard) {
this.tableImageClipboard = tableImageClipboard;
}
public String getFilePrefix() {
return filePrefix;
}
public void setFilePrefix(String filePrefix) {
this.filePrefix = filePrefix;
}
public Image getLastImage() {
return lastImage;
}
public void setLastImage(Image lastImage) {
this.lastImage = lastImage;
}
public ImageAttributes getAttributes() {
return attributes;
}
public void setAttributes(ImageAttributes attributes) {
this.attributes = attributes;
}
public int getRecordNumber() {
return recordNumber;
}
public void setRecordNumber(int recordNumber) {
this.recordNumber = recordNumber;
}
public int getSavedNumber() {
return savedNumber;
}
public void setSavedNumber(int savedNumber) {
this.savedNumber = savedNumber;
}
public int getCopiedNumber() {
return copiedNumber;
}
public void setCopiedNumber(int copiedNumber) {
this.copiedNumber = copiedNumber;
}
}
| 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/fxml/ControllerTools.java | released/MyBox/src/main/java/mara/mybox/fxml/ControllerTools.java | package mara.mybox.fxml;
import java.io.File;
import java.util.Arrays;
import javafx.stage.Stage;
import mara.mybox.controller.BaseController;
import mara.mybox.controller.ControlDataJavascript;
import mara.mybox.controller.Data2DManufactureController;
import mara.mybox.controller.FileDecompressUnarchiveController;
import mara.mybox.controller.HtmlPopController;
import mara.mybox.controller.ImageEditorController;
import mara.mybox.controller.ImagePopController;
import mara.mybox.controller.JsonEditorController;
import mara.mybox.controller.MarkdownEditorController;
import mara.mybox.controller.MarkdownPopController;
import mara.mybox.controller.MediaPlayerController;
import mara.mybox.controller.PdfViewController;
import mara.mybox.controller.PptViewController;
import mara.mybox.controller.SvgEditorController;
import mara.mybox.controller.TextEditorController;
import mara.mybox.controller.TextPopController;
import mara.mybox.controller.WebBrowserController;
import mara.mybox.controller.WordViewController;
import mara.mybox.controller.XmlEditorController;
import static mara.mybox.fxml.WindowTools.replaceStage;
import mara.mybox.tools.CompressTools;
import mara.mybox.tools.FileNameTools;
import mara.mybox.value.FileExtensions;
import mara.mybox.value.Fxmls;
/**
* @Author Mara
* @CreateDate 2021-8-1
* @License Apache License Version 2.0
*/
public class ControllerTools {
public static BaseController openMyBox(Stage stage) {
return replaceStage(stage, Fxmls.MyboxFxml);
}
public static BaseController openTarget(String filename) {
return openTarget(filename, true);
}
public static BaseController openTarget(String filename, boolean mustOpen) {
if (filename == null) {
return null;
}
if (filename.startsWith("http") || filename.startsWith("ftp")) {
return WebBrowserController.openAddress(filename, true);
}
File file = new File(filename);
if (!file.exists()) {
return null;
}
if (file.isDirectory()) {
PopTools.browseURI(null, file.toURI());
return null;
}
String suffix = FileNameTools.ext(file.getName()).toLowerCase();
if (FileExtensions.SupportedImages.contains(suffix)) {
return ImageEditorController.openFile(file);
} else if ("html".equals(suffix) || "htm".equals(suffix)) {
return WebBrowserController.openFile(file);
} else if ("md".equals(suffix)) {
return MarkdownEditorController.open(file);
} else if ("pdf".equals(suffix)) {
return PdfViewController.open(file);
} else if ("csv".equals(suffix)) {
return Data2DManufactureController.openCSVFile(file, null, true, ",");
} else if ("xlsx".equals(suffix) || "xls".equals(suffix)) {
return Data2DManufactureController.openExcelFile(file, null, true);
} else if ("ppt".equals(suffix) || "pptx".equals(suffix)) {
return PptViewController.openFile(file);
} else if ("doc".equals(suffix) || "docx".equals(suffix)) {
return WordViewController.openFile(file);
} else if ("json".equals(suffix)) {
return JsonEditorController.open(file);
} else if ("xml".equals(suffix)) {
return XmlEditorController.open(file);
} else if ("svg".equals(suffix)) {
return SvgEditorController.open(file);
} else if ("js".equals(suffix)) {
return ControlDataJavascript.openFile(null, file);
} else if (Arrays.asList(FileExtensions.TextFileSuffix).contains(suffix)) {
return TextEditorController.open(file);
} else if (CompressTools.compressFormats().contains(suffix) || CompressTools.archiveFormats().contains(suffix)) {
return FileDecompressUnarchiveController.open(file);
} else if (Arrays.asList(FileExtensions.MediaPlayerSupports).contains(suffix)) {
return MediaPlayerController.open(file);
} else if (mustOpen) {
PopTools.browseURI(null, file.toURI());
}
return null;
}
public static BaseController popTarget(BaseController parent, String filename, boolean mustOpen) {
if (filename == null) {
return null;
}
if (filename.startsWith("http") || filename.startsWith("ftp")) {
return HtmlPopController.openAddress(parent, filename);
}
File file = new File(filename);
if (!file.exists()) {
return null;
}
if (file.isDirectory()) {
PopTools.browseURI(parent, file.toURI());
return null;
}
if (file.length() > 1024 * 1024) {
return openTarget(filename, true);
}
String suffix = FileNameTools.ext(file.getName()).toLowerCase();
if (FileExtensions.SupportedImages.contains(suffix)) {
return ImagePopController.openFile(parent, filename);
} else if ("html".equals(suffix) || "htm".equals(suffix)) {
return HtmlPopController.openAddress(parent, filename);
} else if ("md".equals(suffix)) {
return MarkdownPopController.openFile(parent, filename);
} else if (Arrays.asList(FileExtensions.TextFileSuffix).contains(suffix)) {
return TextPopController.openFile(parent, filename);
} else if (mustOpen) {
return openTarget(filename, mustOpen);
} else {
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/fxml/WindowTools.java | released/MyBox/src/main/java/mara/mybox/fxml/WindowTools.java | package mara.mybox.fxml;
import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import java.util.concurrent.ScheduledFuture;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.stage.Modality;
import javafx.stage.Popup;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import javafx.stage.Window;
import javafx.stage.WindowEvent;
import mara.mybox.controller.BaseController;
import mara.mybox.controller.BaseController_Attributes.StageType;
import mara.mybox.controller.BaseTaskController;
import mara.mybox.controller.ClearExpiredDataController;
import mara.mybox.controller.WindowsListController;
import mara.mybox.db.DerbyBase;
import mara.mybox.db.DerbyBase.DerbyStatus;
import mara.mybox.db.table.TableUserConf;
import mara.mybox.dev.MyBoxLog;
import static mara.mybox.value.AppValues.AppIcon;
import mara.mybox.value.AppVariables;
import mara.mybox.value.UserConfig;
/**
* @Author Mara
* @CreateDate 2019-1-27 21:48:55
* @License Apache License Version 2.0
*/
public class WindowTools {
/*
* make stage
*/
public static BaseController initScene(Stage stage, String newFxml, StageStyle stageStyle) {
return initScene(stage, newFxml, AppVariables.CurrentBundle, stageStyle);
}
public static BaseController initScene(Stage stage, String newFxml, ResourceBundle bundle, StageStyle stageStyle) {
try {
if (stage == null) {
return null;
}
FXMLLoader fxmlLoader = new FXMLLoader(WindowTools.class.getResource(newFxml), bundle);
return initController(fxmlLoader, stage, stageStyle);
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
public static BaseController initController(FXMLLoader fxmlLoader, Stage stage, StageStyle stageStyle) {
try {
if (fxmlLoader == null) {
return null;
}
Scene scene = new Scene(fxmlLoader.load());
BaseController controller = (BaseController) fxmlLoader.getController();
return initController(controller, scene, stage, stageStyle);
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
// this works for top level pane which is not part of other node
public static BaseController initController(BaseController controller, Scene scene, Stage stage, StageStyle stageStyle) {
try {
if (controller == null || scene == null || stage == null) {
return null;
}
controller.setMyScene(scene);
controller.setMyStage(stage);
controller.setMyWindow(stage);
scene.getStylesheets().add(WindowTools.class.getResource(UserConfig.getStyle()).toExternalForm());
stage.setUserData(controller);
stage.getIcons().add(AppIcon);
stage.setTitle(controller.getBaseTitle());
if (stageStyle != null) {
stage.initStyle(stageStyle);
}
// External request to close
stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
@Override
public void handle(WindowEvent event) {
if (!controller.leavingScene()) {
event.consume();
} else {
WindowTools.closeWindow(stage);
}
}
});
stage.setOnHiding(new EventHandler<WindowEvent>() {
@Override
public void handle(WindowEvent event) {
if (controller != null) {
controller.leaveScene();
}
WindowTools.closeWindow(stage); // Close anyway
}
});
stage.focusedProperty().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> ob, Boolean ov, Boolean nv) {
if (!nv && controller != null) {
controller.closePopup();
}
}
});
stage.setScene(scene);
stage.show();
if (controller != null) {
controller.afterSceneLoaded();
}
WindowsListController.refresh();
Platform.setImplicitExit(AppVariables.ScheduledTasks == null || AppVariables.ScheduledTasks.isEmpty());
return controller;
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
public static BaseController initController(FXMLLoader fxmlLoader) {
return initController(fxmlLoader, newStage(), null);
}
public static BaseController loadFxml(String fxml) {
try {
if (fxml == null) {
return null;
}
return loadURL(WindowTools.class.getResource(fxml));
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
public static BaseController loadFile(File file) {
try {
if (file == null || !file.exists()) {
return null;
}
return loadURL(file.toURI().toURL());
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
// the pane may be part of other node
public static BaseController loadURL(URL url) {
try {
if (url == null) {
return null;
}
FXMLLoader fxmlLoader = new FXMLLoader(url, AppVariables.CurrentBundle);
Pane pane = fxmlLoader.load();
try {
pane.getStylesheets().add(WindowTools.class.getResource(UserConfig.getStyle()).toExternalForm());
} catch (Exception e) {
}
Scene scene = new Scene(pane);
BaseController controller = (BaseController) fxmlLoader.getController();
controller.setMyScene(scene); // the final scene may be changed
controller.refreshStyle();
return controller;
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
public static FXMLLoader newFxml(String fxml) {
try {
return new FXMLLoader(WindowTools.class.getResource(fxml), AppVariables.CurrentBundle);
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
public static Stage newStage() {
try {
Stage newStage = new Stage();
newStage.initModality(Modality.NONE);
newStage.initStyle(StageStyle.DECORATED);
newStage.initOwner(null);
return newStage;
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
/*
* open stage
*/
public static BaseController openStage(String fxml) {
return initController(newFxml(fxml), newStage(), null);
}
public static BaseController replaceStage(Window parent, String fxml) {
try {
Stage newStage = new Stage(); // new stage should be opened instead of keeping old stage, to clean resources
newStage.initModality(Modality.NONE);
newStage.initStyle(StageStyle.DECORATED);
newStage.initOwner(null);
BaseController controller = initScene(newStage, fxml, StageStyle.DECORATED);
if (controller != null) {
closeWindow(parent);
}
return controller;
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
public static BaseController openStage(Window parent, String fxml, ResourceBundle bundle,
boolean isOwned, Modality modality, StageStyle stageStyle) {
try {
Stage stage = new Stage();
stage.initModality(modality);
if (isOwned && parent != null) {
if (parent instanceof Popup) {
stage.initOwner(((Popup) parent).getOwnerWindow());
} else {
stage.initOwner(parent);
}
} else {
stage.initOwner(null);
}
return initScene(stage, fxml, bundle, stageStyle);
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
public static BaseController openStage(Window parent, String newFxml) {
return openStage(parent, newFxml, AppVariables.CurrentBundle, false, Modality.NONE, null);
}
public static BaseController openStage(String fxml, ResourceBundle bundle) {
return openStage(null, fxml, bundle, false, Modality.NONE, null);
}
/*
* sub stage
*/
public static BaseController childStage(BaseController parent, String newFxml) {
try {
if (parent == null) {
return openStage(newFxml);
}
BaseController c = openStage(parent.getMyWindow(), newFxml,
AppVariables.CurrentBundle, true, Modality.WINDOW_MODAL, null);
if (c == null) {
return null;
}
c.setParent(parent, StageType.Child);
return c;
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
public static BaseController popupStage(BaseController parent, String newFxml) {
try {
if (parent == null) {
return null;
}
BaseController c = openStage(parent.getMyWindow(), newFxml,
AppVariables.CurrentBundle, true, Modality.WINDOW_MODAL, null);
if (c == null) {
return null;
}
c.setParent(parent, StageType.Popup);
return c;
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
public static BaseController referredTopStage(BaseController parent, String newFxml) {
try {
BaseController c = openStage(newFxml);
if (c == null) {
return null;
}
c.setParent(parent, StageType.RefferredTop);
return c;
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
public static BaseController forkStage(BaseController parent, String newFxml) {
try {
BaseController c = openStage(newFxml);
if (c == null) {
return null;
}
c.setParent(parent, StageType.Fork);
return c;
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
public static BaseController referredStage(BaseController parent, String newFxml) {
try {
BaseController c = openStage(newFxml);
if (c == null) {
return null;
}
c.setParent(parent, StageType.Referred);
return c;
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
public static BaseController topStage(BaseController parent, String newFxml) {
try {
BaseController c = parent != null
? openStage(parent.getMyWindow(), newFxml)
: openStage(newFxml);
if (c == null) {
return null;
}
c.setParent(parent, StageType.Top);
return c;
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
/*
* handle stage
*/
public static void reloadAll() {
try {
List<Window> windows = new ArrayList<>();
windows.addAll(Window.getWindows());
for (Window window : windows) {
if (!window.isShowing()) {
continue;
}
Object object = window.getUserData();
if (object != null && object instanceof BaseController) {
try {
BaseController controller = (BaseController) object;
controller.reload();
} catch (Exception e) {
}
}
}
} catch (Exception e) {
MyBoxLog.error(e.toString());
}
}
public static void refreshInterfaceAll() {
try {
List<Window> windows = new ArrayList<>();
windows.addAll(Window.getWindows());
for (Window window : windows) {
if (!window.isShowing()) {
continue;
}
Object object = window.getUserData();
if (object != null && object instanceof BaseController) {
try {
BaseController controller = (BaseController) object;
controller.refreshInterface();
} catch (Exception e) {
}
}
}
} catch (Exception e) {
MyBoxLog.error(e.toString());
}
}
public static void styleAll(String style) {
try {
List<Window> windows = new ArrayList<>();
windows.addAll(Window.getWindows());
for (Window window : windows) {
if (!window.isShowing()) {
continue;
}
Object object = window.getUserData();
if (object != null && object instanceof BaseController) {
try {
BaseController controller = (BaseController) object;
controller.setInterfaceStyle(style);
} catch (Exception e) {
}
}
}
} catch (Exception e) {
MyBoxLog.error(e.toString());
}
}
public static boolean resetWindows() {
if (!TableUserConf.deletePrefix("Interface_")) {
return false;
}
List<String> keys = new ArrayList<>();
keys.addAll(AppVariables.UserConfigValues.keySet());
for (String key : keys) {
if (key.startsWith("Interface_")) {
AppVariables.UserConfigValues.remove(key);
}
}
return true;
}
public static void closeWindow(Window window) {
try {
if (window == null) {
return;
}
Object object = window.getUserData();
if (object != null) {
try {
if (object instanceof BaseController) {
((BaseController) object).leaveScene();
}
} catch (Exception e) {
}
window.setUserData(null);
}
window.hide();
WindowsListController.refresh();
checkExit();
} catch (Exception e) {
// MyBoxLog.error(e.toString());
}
}
public static void checkExit() {
try {
List<Window> windows = new ArrayList<>();
windows.addAll(Window.getWindows());
for (Window window : windows) {
if (window != null && window.isShowing()) {
return;
}
}
appExit();
} catch (Exception e) {
// MyBoxLog.error(e.toString());
}
}
public static synchronized void appExit() {
if (AppVariables.handlingExit) {
return;
}
if (UserConfig.getBoolean("ClearExpiredDataBeforeExit", true)) {
AppVariables.handlingExit = true;
Platform.runLater(new Runnable() {
@Override
public void run() {
ClearExpiredDataController.open(true);
}
});
} else {
handleExit();
}
}
public static synchronized void handleExit() {
try {
if (AppVariables.handlingExit) {
return;
}
AppVariables.handlingExit = true;
if (Window.getWindows() != null) {
List<Window> windows = new ArrayList<>();
windows.addAll(Window.getWindows());
for (Window window : windows) {
closeWindow(window);
}
}
ImageClipboardTools.stopImageClipboardMonitor();
TextClipboardTools.stopTextClipboardMonitor();
if (AppVariables.ScheduledTasks != null && !AppVariables.ScheduledTasks.isEmpty()) {
if (UserConfig.getBoolean("StopAlarmsWhenExit")) {
for (String key : AppVariables.ScheduledTasks.keySet()) {
ScheduledFuture future = AppVariables.ScheduledTasks.get(key);
future.cancel(true);
}
AppVariables.ScheduledTasks = null;
if (AppVariables.ExecutorService != null) {
AppVariables.ExecutorService.shutdownNow();
AppVariables.ExecutorService = null;
}
}
} else {
if (AppVariables.ScheduledTasks != null) {
AppVariables.ScheduledTasks = null;
}
if (AppVariables.ExecutorService != null) {
AppVariables.ExecutorService.shutdownNow();
AppVariables.ExecutorService = null;
}
}
if (AppVariables.ExitTimer != null) {
AppVariables.ExitTimer.cancel();
AppVariables.ExitTimer = null;
}
if (AppVariables.ScheduledTasks == null || AppVariables.ScheduledTasks.isEmpty()) {
doExit();
return;
}
} catch (Exception e) {
}
AppVariables.handlingExit = false;
}
public static synchronized void doExit() {
MyBoxLog.info("Exit now. Bye!");
if (DerbyBase.status == DerbyStatus.Embedded) {
MyBoxLog.info("Shut down Derby...");
DerbyBase.shutdownEmbeddedDerby();
}
// AppVariables.handlingExit = false;
Platform.setImplicitExit(true);
System.gc();
Platform.exit(); // Some thread may still be alive after this
System.exit(0); // Go
Runtime.getRuntime().halt(0);
}
public static void taskInfo(FxTask task, String info) {
if (task != null) {
task.setInfo(info);
}
MyBoxLog.console(info);
}
public static void taskError(FxTask task, String error) {
if (task != null) {
task.setError(error);
}
MyBoxLog.error(error);
}
public static void recordInfo(BaseTaskController taskController, String info) {
if (taskController != null) {
taskController.updateLogs(info);
}
MyBoxLog.console(info);
}
public static void recordError(BaseTaskController taskController, String error) {
if (taskController != null) {
taskController.showLogs(error);
}
MyBoxLog.error(error);
}
public static void closeAllPopup() {
try {
List<Window> windows = new ArrayList<>();
windows.addAll(Window.getWindows());
for (Window window : windows) {
if (window instanceof Popup) {
window.hide();
}
}
} catch (Exception e) {
}
}
public static BaseController getController(Window window) {
if (window == null) {
return null;
}
Object object = window.getUserData();
if (object != null) {
try {
if (object instanceof BaseController) {
return (BaseController) object;
}
} catch (Exception e) {
}
}
return null;
}
public static BaseController find(String interfaceName) {
try {
if (interfaceName == null || interfaceName.isBlank()) {
return null;
}
List<Window> windows = new ArrayList<>();
windows.addAll(Window.getWindows());
for (Window window : windows) {
Object object = window.getUserData();
if (object != null && object instanceof BaseController) {
try {
BaseController controller = (BaseController) object;
if (interfaceName.equals(controller.getInterfaceName())) {
return controller;
}
} catch (Exception e) {
}
}
}
} catch (Exception e) {
}
return null;
}
public static boolean isRunning(BaseController controller) {
return controller != null
&& controller.getMyStage() != null
&& controller.getMyStage().isShowing();
}
}
| 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/fxml/NodeTools.java | released/MyBox/src/main/java/mara/mybox/fxml/NodeTools.java | package mara.mybox.fxml;
import java.awt.Toolkit;
import java.net.URL;
import javafx.collections.ObservableList;
import javafx.event.Event;
import javafx.geometry.Bounds;
import javafx.geometry.Rectangle2D;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.SnapshotParameters;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Control;
import javafx.scene.control.RadioButton;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.SplitPane;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.control.TextField;
import javafx.scene.control.TextInputControl;
import javafx.scene.control.TitledPane;
import javafx.scene.control.Toggle;
import javafx.scene.control.ToggleGroup;
import javafx.scene.image.Image;
import javafx.scene.image.WritableImage;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.web.WebView;
import javafx.stage.Screen;
import javafx.stage.Stage;
import mara.mybox.dev.MyBoxLog;
/**
* @Author Mara
* @CreateDate 2018-6-11 11:19:42
* @License Apache License Version 2.0
*/
public class NodeTools {
public static String getFxmlName(URL url) {
if (url == null) {
return null;
}
try {
String fullPath = url.getPath();
if (!fullPath.endsWith(".fxml")) {
return null;
}
String fname;
int pos = fullPath.lastIndexOf('/');
if (pos < 0) {
fname = fullPath;
} else {
fname = fullPath.substring(pos + 1);
}
return fname.substring(0, fname.length() - 5);
} catch (Exception e) {
return null;
}
}
public static String getFxmlFile(URL url) {
return "/fxml/" + getFxmlName(url) + ".fxml";
}
public static Node findNode(Pane pane, String nodeId) {
try {
Node node = pane.lookup("#" + nodeId);
return node;
} catch (Exception e) {
return null;
}
}
public static void children(int level, Node node) {
try {
if (node == null) {
return;
}
MyBoxLog.debug(" ".repeat(level) + node.getClass() + " " + node.getId() + " " + node.getStyle());
if (node instanceof SplitPane) {
for (Node child : ((SplitPane) node).getItems()) {
children(level + 1, child);
}
} else if (node instanceof ScrollPane) {
children(level + 1, ((ScrollPane) node).getContent());
} else if (node instanceof TitledPane) {
children(level + 1, ((TitledPane) node).getContent());
} else if (node instanceof StackPane) {
for (Node child : ((StackPane) node).getChildren()) {
children(level + 1, child);
}
} else if (node instanceof TabPane) {
for (Tab tab : ((TabPane) node).getTabs()) {
children(level + 1, tab.getContent());
}
} else if (node instanceof Parent) {
for (Node child : ((Parent) node).getChildrenUnmodifiable()) {
children(level + 1, child);
}
}
} catch (Exception e) {
MyBoxLog.error(e.toString());
}
}
public static Node parent(int level, Node node) {
if (node == null) {
return node;
}
MyBoxLog.console(" ".repeat(level) + node.getClass() + " id:" + node.getId() + " style:" + node.getStyle());
Node parent = node.getParent();
if (parent == null) {
return node;
}
return parent(level + 1, parent);
}
public static Node root(Node node) {
if (node == null) {
return node;
}
MyBoxLog.console(node.getClass() + " id:" + node.getId() + " style:" + node.getStyle());
Node parent = node.getParent();
if (parent == null) {
MyBoxLog.console(parent == null);
return node;
}
return root(parent);
}
public static boolean setRadioFirstSelected(ToggleGroup group) {
if (group == null) {
return false;
}
ObservableList<Toggle> buttons = group.getToggles();
for (Toggle button : buttons) {
RadioButton radioButton = (RadioButton) button;
radioButton.setSelected(true);
return true;
}
return false;
}
public static boolean setRadioSelected(ToggleGroup group, String text) {
if (group == null || text == null) {
return false;
}
ObservableList<Toggle> buttons = group.getToggles();
for (Toggle button : buttons) {
RadioButton radioButton = (RadioButton) button;
if (text.equals(radioButton.getText())) {
button.setSelected(true);
return true;
}
}
return false;
}
public static String getSelectedText(ToggleGroup group) {
if (group == null) {
return null;
}
Toggle button = group.getSelectedToggle();
if (button == null || !(button instanceof RadioButton)) {
return null;
}
return ((RadioButton) button).getText();
}
public static boolean setItemSelected(ComboBox<String> box, String text) {
if (box == null || text == null) {
return false;
}
ObservableList<String> items = box.getItems();
for (String item : items) {
if (text.equals(item)) {
box.getSelectionModel().select(item);
return true;
}
}
return false;
}
public static int getInputInt(TextField input) {
try {
return Integer.parseInt(input.getText());
} catch (Exception e) {
throw new IllegalArgumentException(
"InvalidData");
}
}
public static Object textInputFocus(Scene scene) {
if (scene == null) {
return null;
}
return isTextInput(scene.getFocusOwner());
}
public static Object isTextInput(Object node) {
if (node == null) {
return null;
}
if (node instanceof TextInputControl) {
return node;
}
if (node instanceof ComboBox) {
ComboBox cb = (ComboBox) node;
return cb.isEditable() ? node : null;
}
if (node instanceof WebView) {
return WebViewTools.editor((WebView) node);
}
return null;
}
public static Rectangle2D getScreen() {
return Screen.getPrimary().getVisualBounds();
}
// https://stackoverflow.com/questions/38599588/javafx-stage-setmaximized-only-works-once-on-mac-osx-10-9-5
public static void setMaximized(Stage stage, boolean max) {
stage.setMaximized(max);
if (max) {
Rectangle2D primaryScreenBounds = getScreen();
stage.setX(primaryScreenBounds.getMinX());
stage.setY(primaryScreenBounds.getMinY());
stage.setWidth(primaryScreenBounds.getWidth());
stage.setHeight(primaryScreenBounds.getHeight());
}
}
public static double getWidth(Control control) {
return control.getBoundsInParent().getWidth();
}
public static double getHeight(Control control) {
return control.getBoundsInParent().getHeight();
}
public static void setScrollPane(ScrollPane scrollPane, double xOffset, double yOffset) {
final Bounds visibleBounds = scrollPane.getViewportBounds();
double scrollWidth = scrollPane.getContent().getBoundsInLocal().getWidth() - visibleBounds.getWidth();
double scrollHeight = scrollPane.getContent().getBoundsInLocal().getHeight() - visibleBounds.getHeight();
scrollPane.setHvalue(scrollPane.getHvalue() + xOffset / scrollWidth);
scrollPane.setVvalue(scrollPane.getVvalue() + yOffset / scrollHeight);
}
// https://stackoverflow.com/questions/11552176/generating-a-mouseevent-in-javafx/11567122?r=SearchResults#11567122
public static void fireMouseClicked(Node node) {
try {
Event.fireEvent(node, new MouseEvent(MouseEvent.MOUSE_CLICKED,
node.getLayoutX(), node.getLayoutY(), node.getLayoutX(), node.getLayoutY(),
MouseButton.PRIMARY, 1,
true, true, true, true, true, true, true, true, true, true, null));
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
public static double screenDpi() {
return Screen.getPrimary().getDpi();
}
public static double screenResolution() {
return Toolkit.getDefaultToolkit().getScreenResolution();
}
public static double dpiScale() {
return dpiScale(screenResolution());
}
public static double dpiScale(double dpi) {
try {
return dpi / screenDpi();
} catch (Exception e) {
return 1;
}
}
public static Image snap(Node node) {
return snap(node, dpiScale());
}
public static Image snap(Node node, double scale) {
try {
if (node == null) {
return null;
}
final SnapshotParameters snapPara = new SnapshotParameters();
snapPara.setFill(Color.TRANSPARENT);
snapPara.setTransform(javafx.scene.transform.Transform.scale(scale, scale));
WritableImage snapshot = node.snapshot(snapPara, null);
return snapshot;
} catch (Exception e) {
MyBoxLog.debug(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/fxml/ConditionTreeView.java | released/MyBox/src/main/java/mara/mybox/fxml/ConditionTreeView.java | package mara.mybox.fxml;
import java.util.ArrayList;
import java.util.List;
import javafx.scene.Node;
import javafx.scene.control.CheckBox;
import javafx.scene.control.CheckBoxTreeItem;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.control.cell.CheckBoxTreeCell;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.style.NodeStyleTools;
/**
* @Author Mara
* @CreateDate 2020-04-19
* @License Apache License Version 2.0
*/
public class ConditionTreeView extends TreeView {
protected String finalConditions, finalTitle;
protected List<String> selectedTitles, selectedConditions, expandedNodes;
public ConditionTreeView() {
finalConditions = null;
finalTitle = "";
selectedTitles = new ArrayList();
selectedConditions = new ArrayList();
expandedNodes = new ArrayList();
setCellFactory(p -> new CheckBoxTreeCell<ConditionNode>() {
@Override
public void updateItem(ConditionNode item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null) {
setText(null);
setGraphic(null);
return;
}
setText(item.getText());
Node node = getGraphic();
if (node != null && node instanceof CheckBox) {
CheckBox checkBox = (CheckBox) node;
if (item.getCondition() != null && !item.getCondition().isBlank()) {
NodeStyleTools.setTooltip(checkBox, item.getTitle() + "\n" + item.getCondition());
} else {
NodeStyleTools.removeTooltip(checkBox);
}
}
}
});
}
public void checkSelection() {
try {
finalConditions = null;
finalTitle = "";
selectedTitles.clear();
if (getRoot() == null) {
return;
}
checkSelection(getRoot());
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
public void checkSelection(TreeItem<ConditionNode> item) {
try {
if (item == null || !(item instanceof CheckBoxTreeItem)) {
return;
}
CheckBoxTreeItem<ConditionNode> citem = (CheckBoxTreeItem<ConditionNode>) item;
ConditionNode node = item.getValue();
if (!citem.isLeaf() && citem.isIndeterminate()) {
for (TreeItem<ConditionNode> child : item.getChildren()) {
checkSelection(child);
}
} else if (citem.isSelected()) {
if (finalConditions == null || finalConditions.isBlank()) {
if (node.getCondition() == null || node.getCondition().isBlank()) {
finalConditions = "";
} else {
finalConditions = " ( " + node.getCondition() + ") ";
}
} else {
if (node.getCondition() != null && !node.getCondition().isBlank()) {
finalConditions += " OR ( " + node.getCondition() + " ) ";
}
}
if (finalTitle == null || finalTitle.isBlank()) {
finalTitle = "\"" + node.getTitle() + "\"";
} else {
finalTitle += " + \"" + node.getTitle() + "\"";
}
if (!selectedTitles.contains(node.getTitle())) {
selectedTitles.add(node.getTitle());
}
}
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
public void setSelection() {
TreeItem<ConditionNode> root = getRoot();
if (selectedTitles == null || selectedTitles.isEmpty()
|| root == null) {
selectNone();
}
setSelection(root);
}
public void setSelection(TreeItem<ConditionNode> item) {
try {
if (item == null || !(item instanceof CheckBoxTreeItem)) {
return;
}
CheckBoxTreeItem<ConditionNode> citem = (CheckBoxTreeItem<ConditionNode>) item;
ConditionNode node = item.getValue();
if (selectedTitles.contains(node.getTitle())) {
citem.setSelected(true);
return;
} else if (item.isLeaf()) {
return;
}
for (TreeItem<ConditionNode> child : item.getChildren()) {
setSelection(child);
}
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
public void selectAll() {
TreeItem<ConditionNode> root = getRoot();
if (root == null) {
return;
}
CheckBoxTreeItem<ConditionNode> rootCheck = (CheckBoxTreeItem<ConditionNode>) getRoot();
rootCheck.setSelected(true);
}
public void selectNone() {
TreeItem<ConditionNode> root = getRoot();
if (root == null) {
return;
}
CheckBoxTreeItem<ConditionNode> rootCheck = (CheckBoxTreeItem<ConditionNode>) root;
rootCheck.setSelected(false);
}
public void select(List<String> titles) {
selectedTitles = titles;
setSelection();
}
public void select(String title) {
if (title == null) {
selectNone();
return;
}
selectedTitles = new ArrayList();
selectedTitles.add(title);
setSelection();
}
public void checkExpanded() {
try {
expandedNodes.clear();
if (getRoot() == null) {
return;
}
checkExpanded(getRoot());
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
public void checkExpanded(TreeItem<ConditionNode> item) {
try {
if (item == null || item.isLeaf() || !(item instanceof CheckBoxTreeItem)) {
return;
}
CheckBoxTreeItem<ConditionNode> citem = (CheckBoxTreeItem<ConditionNode>) item;
ConditionNode node = item.getValue();
if (citem.isExpanded() && !expandedNodes.contains(node.getTitle())) {
expandedNodes.add(node.getTitle());
}
for (TreeItem<ConditionNode> child : item.getChildren()) {
checkExpanded(child);
}
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
public void check() {
checkExpanded();
checkSelection();
}
public void expandAll() {
try {
if (getRoot() == null) {
return;
}
expandNode(getRoot());
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
public void expandNode(TreeItem<ConditionNode> item) {
try {
if (item == null || item.isLeaf()) {
return;
}
item.setExpanded(true);
for (TreeItem<ConditionNode> child : item.getChildren()) {
expandNode(child);
}
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
public void expandNone() {
try {
if (getRoot() == null) {
return;
}
expandNone(getRoot());
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
public void expandNone(TreeItem<ConditionNode> item) {
try {
if (item == null || item.isLeaf()) {
return;
}
item.setExpanded(true);
for (TreeItem<ConditionNode> child : item.getChildren()) {
expandNode(child);
}
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
/*
get/set
*/
public String getFinalConditions() {
return finalConditions;
}
public void setFinalConditions(String finalConditions) {
this.finalConditions = finalConditions;
}
public String getFinalTitle() {
return finalTitle;
}
public void setFinalTitle(String finalTitle) {
this.finalTitle = finalTitle;
}
public List<String> getSelectedTitles() {
return selectedTitles;
}
public void setSelectedTitles(List<String> selectedTitles) {
this.selectedTitles = selectedTitles;
}
public List<String> getSelectedConditions() {
return selectedConditions;
}
public void setSelectedConditions(List<String> selectedConditions) {
this.selectedConditions = selectedConditions;
}
public List<String> getExpandedNodes() {
return expandedNodes;
}
public void setExpandedNodes(List<String> expandedNodes) {
this.expandedNodes = expandedNodes;
}
}
| 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/fxml/LocateTools.java | released/MyBox/src/main/java/mara/mybox/fxml/LocateTools.java | package mara.mybox.fxml;
import java.awt.Point;
import javafx.event.Event;
import javafx.geometry.Bounds;
import javafx.geometry.Point2D;
import javafx.geometry.Rectangle2D;
import javafx.scene.Node;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Region;
import javafx.scene.robot.Robot;
import javafx.stage.PopupWindow;
import javafx.stage.Stage;
import mara.mybox.tools.SystemTools;
/**
* @Author Mara
* @CreateDate 2021-8-5
* @License Apache License Version 2.0
*/
public class LocateTools {
public static final int PopOffsetY = 30;
public static Point2D coordinate(Event event) {
double x, y;
try {
Point2D everntCoord = getScreenCoordinate(event);
x = everntCoord.getX();
y = everntCoord.getY() + PopOffsetY;
} catch (Exception e) {
javafx.scene.robot.Robot r = new javafx.scene.robot.Robot();
x = r.getMouseX();
y = r.getMouseY() + PopOffsetY;
}
return new Point2D(x, y);
}
public static Point2D getScreenCoordinate(Event event) {
try {
Node node = (Node) (event.getTarget());
return node.localToScreen(0, 0);
} catch (Exception e) {
// MyBoxLog.error(e);
return null;
}
}
public static Point2D center(Node node) {
double x, y;
try {
Point2D p = node.localToScreen(0, 0);
x = p.getX();
y = p.getY() + LocateTools.PopOffsetY;
} catch (Exception e) {
javafx.scene.robot.Robot r = new javafx.scene.robot.Robot();
x = r.getMouseX();
y = r.getMouseY() + PopOffsetY;
}
return new Point2D(x, y);
}
public static double getScreenX(Node node) {
Point2D localToScreen = node.localToScreen(0, 0);
return localToScreen.getX();
}
public static double getScreenY(Node node) {
Point2D localToScreen = node.localToScreen(0, 0);
return localToScreen.getY();
}
public static void locateRight(Stage stage) {
Rectangle2D screen = NodeTools.getScreen();
stage.setX(screen.getWidth() - stage.getWidth());
}
public static void locateUp(Node node, PopupWindow window) {
Bounds bounds = node.localToScreen(node.getBoundsInLocal());
window.show(node, bounds.getMinX() + 2, bounds.getMinY() - 50);
}
public static void locateCenter(Stage stage, Node node) {
if (stage == null || node == null) {
return;
}
Rectangle2D screen = NodeTools.getScreen();
Bounds bounds = node.localToScreen(node.getBoundsInLocal());
double centerX = bounds.getMinX() - stage.getWidth() / 2;
centerX = Math.min(screen.getWidth(), Math.max(0, centerX));
stage.setX(centerX);
double centerY = bounds.getMinY() - stage.getHeight() / 2;
centerY = Math.min(screen.getHeight(), Math.max(0, centerY));
stage.setY(centerY);
}
public static void locateCenter(Node node, PopupWindow window) {
Bounds bounds = node.localToScreen(node.getBoundsInLocal());
window.show(node, bounds.getMinX() + bounds.getWidth() / 2, bounds.getMinY() + bounds.getHeight() / 2);
}
public static void locateRightTop(Node node, PopupWindow window) {
Bounds bounds = node.localToScreen(node.getBoundsInLocal());
window.show(node, bounds.getMaxX() - window.getWidth() - 20, bounds.getMinY() + 50);
}
public static void aboveCenter(Node node, Node refer) {
if (node == null || refer == null) {
return;
}
Bounds regionBounds = node.getBoundsInLocal();
Bounds referBounds = refer.getBoundsInLocal();
double xOffset = referBounds.getWidth() - regionBounds.getWidth();
node.setLayoutX(referBounds.getMinX() + xOffset / 2);
node.setLayoutY(referBounds.getMinY() - 10);
}
public static void belowCenter(Node node, Node refer) {
if (node == null || refer == null) {
return;
}
Bounds regionBounds = node.getBoundsInLocal();
Bounds referBounds = refer.getBoundsInLocal();
double xOffset = referBounds.getWidth() - regionBounds.getWidth();
node.setLayoutX(referBounds.getMinX() + xOffset / 2);
node.setLayoutY(referBounds.getMaxY() + 10);
}
public static void center(Node node, Node refer) {
if (node == null || refer == null) {
return;
}
Bounds regionBounds = node.getBoundsInLocal();
Bounds referBounds = refer.getBoundsInLocal();
double xOffset = referBounds.getWidth() - regionBounds.getWidth();
double yOffset = referBounds.getHeight() - regionBounds.getHeight();
node.setLayoutX(referBounds.getMinX() + xOffset / 2);
node.setLayoutY(referBounds.getMinY() + yOffset / 2);
}
public static void locateBelow(Node node, PopupWindow window) {
Bounds bounds = node.localToScreen(node.getBoundsInLocal());
window.show(node, bounds.getMinX() + 2, bounds.getMinY() + bounds.getHeight());
}
public static void locateMouse(MouseEvent event, PopupWindow window) {
window.show((Node) event.getSource(), event.getScreenX(), event.getScreenY());
}
public static void locateEvent(Event event, PopupWindow window) {
if (window == null || event == null) {
return;
}
Point2D everntCoord = coordinate(event);
window.show((Node) event.getSource(), everntCoord.getX(), everntCoord.getY());
}
public static void locateMouse(Node owner, PopupWindow window) {
Point point = SystemTools.getMousePoint();
window.show(owner, point.getX(), point.getY());
}
public static void moveXCenter(Node pNnode, Node node) {
if (node == null || pNnode == null) {
return;
}
double xOffset = pNnode.getBoundsInLocal().getWidth() - node.getBoundsInLocal().getWidth();
if (xOffset > 0) {
node.setLayoutX(xOffset / 2);
} else {
node.setLayoutX(0);
}
}
public static void moveXCenter(Node node) {
if (node == null) {
return;
}
double xOffset = node.getBoundsInLocal().getWidth() - node.getBoundsInLocal().getWidth();
if (xOffset > 0) {
node.setLayoutX(xOffset / 2);
} else {
node.setLayoutX(0);
}
}
public static void moveYCenter(Node pNnode, Node node) {
if (node == null || pNnode == null) {
return;
}
double yOffset = pNnode.getBoundsInLocal().getHeight() - node.getBoundsInLocal().getHeight();
if (yOffset > 0) {
node.setLayoutY(yOffset / 2);
} else {
node.setLayoutY(0);
}
}
public static void moveYCenter(Node node) {
if (node == null) {
return;
}
double yOffset = node.getBoundsInLocal().getHeight() - node.getBoundsInLocal().getHeight();
if (yOffset > 0) {
node.setLayoutY(yOffset / 2);
} else {
node.setLayoutY(0);
}
}
public static void mouseCenter() {
Rectangle2D screen = NodeTools.getScreen();
try {
Robot robot = new Robot();
robot.mouseMove((int) screen.getWidth() / 2, (int) screen.getHeight() / 2);
} catch (Exception e) {
}
}
public static void mouseCenter(Stage stage) {
try {
Robot robot = new Robot();
robot.mouseMove((int) (stage.getX() + stage.getWidth() / 2), (int) (stage.getY() + stage.getHeight() / 2));
} catch (Exception e) {
}
}
public static void moveCenter(Node pNnode, Node node) {
moveXCenter(pNnode, node);
moveYCenter(pNnode, node);
}
public static void moveCenter(Node node) {
moveXCenter(node);
moveYCenter(node);
}
public static void fitSize(Node pNnode, Region region, int margin) {
try {
if (pNnode == null || region == null) {
return;
}
Bounds bounds = pNnode.getBoundsInLocal();
region.setPrefSize(bounds.getWidth() - 2 * margin, bounds.getHeight() - 2 * margin);
LocateTools.moveCenter(pNnode, region);
} 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/fxml/HelpTools.java | released/MyBox/src/main/java/mara/mybox/fxml/HelpTools.java | package mara.mybox.fxml;
import java.io.File;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.MenuItem;
import javafx.scene.control.SeparatorMenuItem;
import mara.mybox.controller.BaseController;
import mara.mybox.controller.ColorQueryController;
import mara.mybox.controller.WebBrowserController;
import mara.mybox.data.ImageItem;
import mara.mybox.data.StringTable;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.menu.MenuTools;
import mara.mybox.fxml.style.HtmlStyles;
import mara.mybox.tools.FileTmpTools;
import mara.mybox.tools.HtmlWriteTools;
import mara.mybox.tools.MarkdownTools;
import mara.mybox.tools.TextFileTools;
import static mara.mybox.value.AppValues.JavaVersion;
import mara.mybox.value.AppVariables;
import mara.mybox.value.InternalImages;
import mara.mybox.value.Languages;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2022-8-8
* @License Apache License Version 2.0
*/
public class HelpTools {
public static void readMe(BaseController controller) {
try {
File htmlFile = makeReadMe(Languages.embedFileLang());
if (htmlFile == null) {
return;
}
PopTools.browseURI(controller, htmlFile.toURI());
SoundTools.miao5();
} catch (Exception e) {
MyBoxLog.error(e);
}
}
public static File makeReadMe(String fileLang) {
try {
File htmlFile = new File(AppVariables.MyboxDataPath + "/doc/readme_" + fileLang + ".html");
File mdFile = FxFileTools.getInternalFile("/doc/" + fileLang + "/README.md",
"doc", "README-" + fileLang + ".md", true);
String html = MarkdownTools.md2html(null,
MarkdownTools.htmlOptions(), mdFile, HtmlStyles.DefaultStyle);
if (html == null) {
return null;
}
html = html.replaceAll("href=\"", "target=_blank href=\"");
TextFileTools.writeFile(htmlFile, html);
return htmlFile;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public static File aboutColor() {
try {
StringTable table = new StringTable(null, message("ResourcesAboutColor"));
table.newLinkRow(message("ICCWebsite"), "http://www.color.org");
table.newLinkRow(message("ICCProfileTags"), "https://sno.phy.queensu.ca/~phil/exiftool/TagNames/ICC_Profile.html");
table.newLinkRow(message("IccProfilesECI"), "http://www.eci.org/en/downloads");
table.newLinkRow(message("IccProfilesAdobe"), "https://supportdownloads.adobe.com/detail.jsp?ftpID=3680");
table.newLinkRow(message("ColorSpace"), "http://brucelindbloom.com/index.html?WorkingSpaceInfo.html#Specifications");
table.newLinkRow(message("StandardsRGB"), "https://www.w3.org/Graphics/Color/sRGB.html");
table.newLinkRow(message("RGBXYZMatrices"), "http://brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html");
table.newLinkRow(message("ColorCalculator"), "http://www.easyrgb.com/en/math.php");
table.newLinkRow("", "http://brucelindbloom.com/index.html?ColorCalculator.html");
table.newLinkRow("", "http://davengrace.com/cgi-bin/cspace.pl");
table.newLinkRow(message("ColorData"), "https://www.rit.edu/science/pocs/useful-data");
table.newLinkRow("", "http://www.thefullwiki.org/Standard_illuminant");
table.newLinkRow(message("ColorTopics"), "https://www.codeproject.com/Articles/1202772/Color-Topics-for-Programmers");
table.newLinkRow("", "https://www.w3.org/TR/css-color-4/#lab-to-rgb");
table.newLinkRow(message("ChromaticAdaptation"), "http://brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html");
table.newLinkRow(message("ChromaticityDiagram"), "http://demonstrations.wolfram.com/CIEChromaticityDiagram/");
table.newLinkRow(message("ArtHuesWheel"), "https://blog.csdn.net/weixin_44938037/article/details/90599711");
table.newLinkRow("", "https://stackoverflow.com/questions/4945457/conversion-between-rgb-and-ryb-color-spaces");
table.newLinkRow("", "https://math.stackexchange.com/questions/305395/ryb-and-rgb-color-space-conversion");
table.newLinkRow("", "http://bahamas10.github.io/ryb/about.html");
table.newLinkRow("", "https://redyellowblue.org/ryb-color-model/");
File htmFile = HtmlWriteTools.writeHtml(table.html());
return htmFile;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public static File aboutDataAnalysis() {
try {
StringTable table = new StringTable(null, message("AboutDataAnalysis"));
table.newLinkRow(message("Dataset"), "http://archive.ics.uci.edu/ml/datasets.php");
table.newLinkRow("", "https://www4.stat.ncsu.edu/~boos/var.select/");
table.newLinkRow("", "http://lib.stat.cmu.edu/datasets/");
table.newLinkRow("", "http://yann.lecun.com/exdb/mnist/");
table.newLinkRow("", "https://docs.microsoft.com/en-us/azure/open-datasets/");
table.newLinkRow("", "https://github.com/tomsharp/SVR/tree/master/data");
table.newLinkRow("", "https://github.com/krishnaik06/simple-Linear-Regression");
table.newLinkRow("", "https://github.com/susanli2016/Machine-Learning-with-Python/tree/master/data");
table.newLinkRow("", "https://www.datarepository.movebank.org");
table.newLinkRow("", "https://github.com/CSSEGISandData/COVID-19");
table.newLinkRow("", "https://data.stats.gov.cn/index.htm");
table.newLinkRow("Apache-Math", "https://commons.apache.org/proper/commons-math/");
table.newLinkRow("", "https://commons.apache.org/proper/commons-math/apidocs/index.html");
table.newLinkRow(message("Study"), "https://github.com/InfolabAI/DeepLearning");
table.newLinkRow("", "https://www.deeplearningbook.org/");
table.newLinkRow("", "https://github.com/zsdonghao/deep-learning-book");
table.newLinkRow("", "https://github.com/hadrienj/deepLearningBook-Notes");
table.newLinkRow("", "https://github.com/janishar/mit-deep-learning-book-pdf");
table.newLinkRow("", "https://clauswilke.com/dataviz/");
table.newLinkRow("", "https://www.kancloud.cn/apachecn/dataviz-zh/1944809");
table.newLinkRow("", "https://www.bilibili.com/video/BV1Ua4y1e7YG");
table.newLinkRow("", "https://www.bilibili.com/video/BV1i7411d7aP");
table.newLinkRow("", "https://github.com/fengdu78/Coursera-ML-AndrewNg-Notes");
table.newLinkRow(message("Tools"), "https://scikit-learn.org/stable/");
table.newLinkRow("", "https://www.mathworks.com/help/index.html");
table.newLinkRow(message("Example"), "https://www.xycoon.com/simple_linear_regression.htm");
table.newLinkRow("", "https://www.scribbr.com/statistics/simple-linear-regression/");
table.newLinkRow("", "http://www.datasetsanalysis.com/regressions/simple-linear-regression.html");
File htmFile = HtmlWriteTools.writeHtml(table.html());
return htmFile;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public static File aboutCoordinateSystem() {
try {
StringTable table = new StringTable(null, message("AboutCoordinateSystem"));
table.newLinkRow(message("ChinaCommonGeospatialInformationServices"), "https://www.tianditu.gov.cn/");
table.newLinkRow("", "https://www.tianditu.gov.cn/world_coronavirusmap/");
table.newLinkRow(message("ChineseCoordinateSystems"), "https://politics.stackexchange.com/questions/40991/why-must-chinese-maps-be-obfuscated");
table.newLinkRow("", "https://zhuanlan.zhihu.com/p/62243160");
table.newLinkRow("", "https://blog.csdn.net/qq_36377037/article/details/86479796");
table.newLinkRow("", "https://www.zhihu.com/question/31204062?sort=created");
table.newLinkRow("", "https://blog.csdn.net/ssxueyi/article/details/102622156");
table.newLinkRow(message("EPSGCodes"), "http://epsg.io/4490");
table.newLinkRow("", "http://epsg.io/4479");
table.newLinkRow("", "http://epsg.io/4326");
table.newLinkRow("", "http://epsg.io/3857");
table.newLinkRow(message("TrackingData"), "https://www.microsoft.com/en-us/download/details.aspx?id=52367");
table.newLinkRow("", "https://www.datarepository.movebank.org/discover");
table.newLinkRow("", "https://sumo.dlr.de/docs/Data/Scenarios/TAPASCologne.html");
table.newLinkRow("", "https://blog.csdn.net/souvenir001/article/details/52180335");
table.newLinkRow("", "https://www.cnblogs.com/genghenggao/p/9625511.html");
table.newLinkRow(message("TianDiTuAPI"), "http://lbs.tianditu.gov.cn/api/js4.0/guide.html");
table.newLinkRow(message("TianDiTuKey"), "https://console.tianditu.gov.cn/api/key");
table.newLinkRow(message("GaoDeAPI"), "https://lbs.amap.com/api/javascript-api/summary");
table.newLinkRow(message("GaoDeKey"), "https://console.amap.com/dev/index");
File htmFile = HtmlWriteTools.writeHtml(table.html());
return htmFile;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public static File aboutMedia() {
try {
StringTable table = new StringTable(null, message("AboutMedia"));
table.newLinkRow(message("FFmpegDocuments"), "http://ffmpeg.org/documentation.html");
table.newLinkRow(message("FFmpeg wiki"), "https://trac.ffmpeg.org");
table.newLinkRow(message("H264VideoEncodingGuide"), "http://trac.ffmpeg.org/wiki/Encode/H.264");
table.newLinkRow(message("AACEncodingGuide"), "https://trac.ffmpeg.org/wiki/Encode/AAC");
table.newLinkRow(message("UnderstandingRateControlModes"), "https://slhck.info/video/2017/03/01/rate-control.html");
table.newLinkRow(message("CRFGuide"), "https://slhck.info/video/2017/02/24/crf-guide.html");
table.newLinkRow(message("CapturingDesktopScreenRecording"), "http://trac.ffmpeg.org/wiki/Capture/Desktop");
File htmFile = HtmlWriteTools.writeHtml(table.html());
return htmFile;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public static File aboutMacro() {
try {
String lang = Languages.embedFileLang();
File file = FxFileTools.getInternalFile("/doc/" + lang + "/mybox_about_macro_" + lang + ".html",
"doc", "mybox_about_macro_" + lang + ".html");
return file;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public static File aboutData2D() {
try {
String lang = Languages.embedFileLang();
File file = FxFileTools.getInternalFile("/doc/" + lang + "/mybox_about_data2d_" + lang + ".html",
"doc", "mybox_about_data2d_" + lang + ".html");
return file;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public static File aboutGroupingRows() {
try {
String lang = Languages.embedFileLang();
File file = FxFileTools.getInternalFile("/doc/" + lang + "/mybox_about_grouping_" + lang + ".html",
"doc", "mybox_about_grouping_" + lang + ".html");
return file;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public static File aboutRowExpression() {
try {
String lang = Languages.embedFileLang();
File file = FxFileTools.getInternalFile("/doc/" + lang + "/mybox_about_row_expression_" + lang + ".html",
"doc", "mybox_about_row_expression_" + lang + ".html");
return file;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public static File aboutTreeInformation() {
try {
String lang = Languages.embedFileLang();
File file = FxFileTools.getInternalFile("/doc/" + lang + "/mybox_about_tree_" + lang + ".html",
"doc", "mybox_about_tree_" + lang + ".html");
return file;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public static File aboutImageScope() {
try {
String lang = Languages.embedFileLang();
File file = FxFileTools.getInternalFile("/doc/" + lang + "/mybox_about_image_scope_" + lang + ".html",
"doc", "mybox_about_image_scope_" + lang + ".html");
return file;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public static void imageStories(BaseController controller) {
FxTask task = new FxTask<Void>(controller) {
private File htmFile;
@Override
protected boolean handle() {
htmFile = imageStories(this, false, AppVariables.CurrentLangName);
return htmFile != null && htmFile.exists();
}
@Override
protected void whenSucceeded() {
controller.browse(htmFile);
}
};
controller.start(task);
}
public static File imageStories(FxTask task, boolean isRemote, String lang) {
try {
StringTable table = new StringTable(null, message(lang, "StoriesOfImages"));
List<ImageItem> imageItems = InternalImages.all(lang);
for (ImageItem item : imageItems) {
String comments = item.getComments();
File file = item.getFile();
if (comments == null || comments.isBlank()
|| file == null || !file.exists()) {
continue;
}
task.setInfo(file.getAbsolutePath());
table.newNameValueRow(
"<Img src='" + (isRemote
? "https://mara-mybox.sourceforge.io/images/" + file.getName()
: file.toURI().toString())
+ "' width=" + item.getWidth() + ">",
comments);
}
String html = HtmlWriteTools.html(table.getTitle(), "utf-8",
HtmlStyles.styleValue("Table"), table.body());
File file = new File(FileTmpTools.generatePath("html")
+ "/MyBox-StoriesOfImages-" + lang + ".html");
return TextFileTools.writeFile(file, html);
} catch (Exception e) {
task.setError(e.toString());
return null;
}
}
public static File usefulLinks(String lang) {
try {
StringTable table = new StringTable(null, message(lang, "Links"));
table.newLinkRow(message(lang, "DecimalFormat"), decimalFormatLink());
table.newLinkRow(message(lang, "DateFormat"), simpleDateFormatLink());
table.newLinkRow(message(lang, "Charset"), charsetLink());
table.newLinkRow(message(lang, "Color"), colorLink());
table.newLinkRow("URI", uriLink());
table.newLinkRow("URL", urlLink());
table.newLinkRow("Full list of Math functions", javaMathLink());
table.newLinkRow("Learning the Java Language", javaLink());
table.newLinkRow("Java Development Kit (JDK) APIs", javaAPILink());
table.newLinkRow(message(lang, "JavafxCssGuide"), javaFxCssLink());
table.newLinkRow(message(lang, "DerbyReferenceManual"), derbyLink());
table.newLinkRow(message(lang, "SqlIdentifier"), sqlLink());
table.newLinkRow(message(lang, "HtmlTutorial") + " - " + message(lang, "Chinese"), htmlZhLink());
table.newLinkRow(message(lang, "HtmlTutorial") + " - " + message(lang, "English"), htmlEnLink());
table.newLinkRow(message(lang, "JavaScriptTutorial") + " - " + message(lang, "Chinese"), javaScriptZhLink());
table.newLinkRow(message(lang, "JavaScriptTutorial") + " - " + message(lang, "English"), javaScriptEnLink());
table.newLinkRow("JavaScript language specification", javaScriptSpecification());
table.newLinkRow("Nashorn User's Guide", nashornLink());
table.newLinkRow(message(lang, "CssTutorial") + " - " + message(lang, "Chinese"), cssZhLink());
table.newLinkRow(message(lang, "CssTutorial") + " - " + message(lang, "English"), cssEnLink());
table.newLinkRow(message(lang, "CssReference"), cssSpecificationLink());
table.newLinkRow("RenderingHints", renderingHintsLink());
table.newLinkRow(message(lang, "JsonTutorial") + " - " + message(lang, "Chinese"), jsonZhLink());
table.newLinkRow(message(lang, "JsonTutorial") + " - " + message(lang, "English"), jsonEnLink());
table.newLinkRow(message(lang, "JsonSpecification"), jsonSpecification());
table.newLinkRow(message(lang, "XmlTutorial") + " - " + message(lang, "Chinese"), xmlZhLink());
table.newLinkRow(message(lang, "XmlTutorial") + " - " + message(lang, "English"), xmlEnLink());
table.newLinkRow(message(lang, "DomSpecification"), domSpecification());
table.newLinkRow(message(lang, "SvgTutorial") + " - " + message(lang, "Chinese"), svgZhLink());
table.newLinkRow(message(lang, "SvgTutorial") + " - " + message(lang, "English"), svgEnLink());
table.newLinkRow(message(lang, "SvgSpecification"), svgSpecification());
table.newLinkRow("SVGPath in JavaFX", javafxSVGPathLink());
table.newLinkRow("Shape 2D in JavaFX", javafxShape2DLink());
table.newLinkRow("Shape 2D in Java", javaShape2DLink());
String html = HtmlWriteTools.html(message(lang, "Links"), HtmlStyles.DefaultStyle, table.div());
File file = new File(FileTmpTools.generatePath("html")
+ "/mybox_useful_link_" + lang + ".html");
return TextFileTools.writeFile(file, html);
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public static File makeInterfaceTips(String lang) {
try {
StringBuilder s = new StringBuilder();
s.append("<BODY>\n");
s.append("<H1>").append(message(lang, "DocumentTools")).append("</H1>\n");
s.append(" <H3>").append(message(lang, "PdfView")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "PdfViewTips"))).append("\n");
s.append(" <H3>").append(message(lang, "MarkdownEditer")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "MarkdownEditerTips"))).append("\n");
s.append(" <H3>").append(message(lang, "HtmlEditor")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "HtmlFormatTips"))).append("\n");
s.append(" <H3>").append(message(lang, "HtmlSnap")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "HtmlSnapComments"))).append("\n");
s.append(" <H3>").append(message(lang, "JsonEditor")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "JsonEditorTips"))).append("\n");
s.append(" <H3>").append(message(lang, "XmlEditor")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "XmlEditorTips"))).append("\n");
s.append(" <H3>").append(message(lang, "TextEditer")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "TextEditerTips"))).append("\n");
s.append(" <H3>").append(message(lang, "Charset")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "EncodeComments"))).append("\n");
s.append(" <H3>").append("BOM").append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "BOMcomments"))).append("\n");
s.append(" <H3>").append(message(lang, "FindReplace")).append(" - ").append(message(lang, "Texts")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "FindReplaceTextsTips"))).append("\n");
s.append(" <H3>").append(message(lang, "FindReplace")).append(" - ").append(message(lang, "Bytes")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "FindReplaceBytesTips"))).append("\n");
s.append(" <H3>").append(message(lang, "FilterLines")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "FilterTypesComments"))).append("\n");
s.append(" <H3>").append(message(lang, "TextFindBatch")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "TextFindBatchTips"))).append("\n");
s.append(" <H3>").append(message(lang, "TextReplaceBatch")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "TextReplaceBatchTips"))).append("\n");
s.append(" <H3>").append(message(lang, "TextToHtml")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "PasteTextAsHtml"))).append("\n");
s.append(" <H3>").append(message(lang, "BytesFindBatch")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "BytesFindBatchTips"))).append("\n");
s.append(" <H3>").append(message(lang, "TextInMyBoxClipboard")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "TextClipboardUseComments"))).append("</BR>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "TextInMyBoxClipboardTips"))).append("\n");
s.append(" <H3>").append(message(lang, "WordView")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "WordViewTips"))).append("\n");
s.append("\n");
s.append("<H1>").append(message(lang, "ImageTools")).append("</H1>\n");
s.append(" <H3>").append(message(lang, "EditImage")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "ImageEditTips"))).append("\n");
s.append(" <H3>").append(message(lang, "SVGEditor")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "SVGEditorTips"))).append("\n");
s.append(" <H3>").append(message(lang, "ImageQuantization")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "ImageQuantizationComments"))).append("\n");
s.append(" <H3>").append(message(lang, "Dithering")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "DitherComments"))).append("\n");
s.append(" <H3>").append(message(lang, "ColorMatching")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "ColorMatchComments"))).append("\n");
s.append(" <H3>").append(message(lang, "PremultipliedAlpha")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "PremultipliedAlphaTips"))).append("\n");
s.append(" <H3>").append(message(lang, "Thresholding")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "ImageThresholdingComments"))).append("\n");
s.append(" <H3>").append(message(lang, "Contrast")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "ImageContrastComments"))).append("\n");
s.append(" <H3>").append(message(lang, "Shear")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "ImageShearComments"))).append("\n");
s.append(" <H3>").append(message(lang, "ImageRepeatTile")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "ImageRepeatTips"))).append("\n");
s.append(" <H3>").append(message(lang, "ImageSample")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "ImageSampleTips"))).append("\n");
s.append(" <H3>").append(message(lang, "ImageSplit")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "ImageSplitTips"))).append("\n");
s.append(" <H3>").append(message(lang, "ImagesEditor")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "ImagesEditorTips"))).append("\n");
s.append(" <H3>").append(message(lang, "ImagesPlay")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "ImagesPlayTips"))).append("\n");
s.append(" <H3>").append(message(lang, "ImageOCR")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "ImageOCRComments"))).append("</BR>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "OCRPreprocessComment"))).append("\n");
s.append(" <H3>").append(message(lang, "ImageAlphaExtract")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "ImageAlphaExtractTips"))).append("\n");
s.append(" <H3>").append(message(lang, "ImageToSvg")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "SvgFromImageComments"))).append("\n");
s.append(" <H3>").append(message(lang, "ImagesInSystemClipboard")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "RecordImagesTips"))).append("\n");
s.append(" <H3>").append(message(lang, "ManageColors")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "ColorsManageTips"))).append("\n");
s.append(" <H3>").append(message(lang, "DrawChromaticityDiagram")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "ChromaticityDiagramTips"))).append("\n");
s.append(" <H3>").append(message(lang, "IccProfileEditor")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "IccProfileTips"))).append("\n");
s.append("\n");
s.append("<H1>").append(message(lang, "NetworkTools")).append("</H1>\n");
s.append(" <H3>").append(message(lang, "DownloadHtmls")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "DownloadFirstLevelLinksComments"))).append("\n");
s.append(" <H3>").append(message(lang, "ConvertUrl")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "ConvertUrlTips"))).append("\n");
s.append(" <H3>").append(message(lang, "QueryDNSBatch")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "QueryDNSBatchTips"))).append("\n");
s.append(" <H3>").append(message(lang, "WeiboSnap")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "WeiboAddressComments"))).append("\n");
s.append("\n");
s.append("<H1>").append(message(lang, "DataTools")).append("</H1>\n");
s.append(" <H3>").append(message(lang, "Column")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "ColumnComments"))).append("\n");
s.append(" <H3>").append(message(lang, "ManageData")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "DataManageTips"))).append("\n");
s.append(" <H3>").append(message(lang, "DatabaseTable")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "DataTableTips"))).append("\n");
s.append(" <H3>").append(message(lang, "SqlIdentifier")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "SqlIdentifierComments"))).append("\n");
s.append(" <H3>").append(message(lang, "XYChart")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "DataChartXYTips"))).append("\n");
s.append(" <H3>").append(message(lang, "PieChart")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "DataChartPieTips"))).append("\n");
s.append(" <H3>").append(message(lang, "BoxWhiskerChart")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "BoxWhiskerChartTips"))).append("\n");
s.append(" <H3>").append(message(lang, "ComparisonBarsChart")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "ComparisonBarsChartTips"))).append("\n");
s.append(" <H3>").append(message(lang, "SelfComparisonBarsChart")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "SelfComparisonBarsChartTips"))).append("\n");
s.append(" <H3>").append(message(lang, "XYZChart")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "WebglComments"))).append("\n");
s.append(" <H3>").append(message(lang, "SetStyles")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "SetStylesTips"))).append("\n");
s.append(" <H3>").append(message(lang, "SimpleLinearRegression")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "SimpleLinearRegressionTips"))).append("\n");
s.append(" <H3>").append(message(lang, "SimpleLinearRegressionCombination")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "SimpleLinearRegressionCombinationTips"))).append("\n");
s.append(" <H3>").append(message(lang, "MultipleLinearRegression")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "MultipleLinearRegressionTips"))).append("\n");
s.append(" <H3>").append(message(lang, "MultipleLinearRegressionCombination")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "MultipleLinearRegressionCombinationTips"))).append("\n");
s.append(" <H3>").append(message(lang, "Matrix")).append("</H3>\n");
s.append(" <H4>").append(message(lang, "Plus")).append("</H4>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "MatricesPlusComments"))).append("\n");
s.append(" <H4>").append(message(lang, "Minus")).append("</H4>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "MatricesMinusComments"))).append("\n");
s.append(" <H4>").append(message(lang, "Multiply")).append("</H4>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "MatricesMultiplyComments"))).append("\n");
s.append(" <H4>").append(message(lang, "HadamardProduct")).append("</H4>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "HadamardProductComments"))).append("\n");
s.append(" <H4>").append(message(lang, "KroneckerProduct")).append("</H4>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "KroneckerProductComments"))).append("\n");
s.append(" <H4>").append(message(lang, "VerticalMerge")).append("</H4>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "VerticalMergeComments"))).append("\n");
s.append(" <H4>").append(message(lang, "HorizontalMerge")).append("</H4>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "HorizontalMergeComments"))).append("\n");
s.append("\n");
s.append(" <H3>").append(message(lang, "JavaScript")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "JavaScriptTips"))).append("\n");
s.append(" <H3>").append(message(lang, "JShell")).append("</H3>\n");
s.append(HtmlWriteTools.codeToHtml(message(lang, "JShellTips"))).append("\n");
| 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/fxml/RecentVisitMenu.java | released/MyBox/src/main/java/mara/mybox/fxml/RecentVisitMenu.java | package mara.mybox.fxml;
import mara.mybox.fxml.menu.MenuTools;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javafx.event.ActionEvent;
import javafx.event.Event;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuItem;
import javafx.scene.control.SeparatorMenuItem;
import javafx.stage.FileChooser;
import mara.mybox.controller.BaseController;
import mara.mybox.controller.BaseController_Files;
import mara.mybox.db.data.VisitHistory;
import mara.mybox.db.data.VisitHistoryTools;
import mara.mybox.dev.MyBoxLog;
import static mara.mybox.fxml.style.NodeStyleTools.attributeTextStyle;
import mara.mybox.tools.StringTools;
import mara.mybox.value.AppVariables;
import static mara.mybox.value.Languages.message;
import mara.mybox.value.UserConfig;
/**
* @Author Mara
* @License Apache License Version 2.0
*/
public abstract class RecentVisitMenu {
protected BaseController controller;
protected Event event;
protected List<String> examples;
protected int SourceFileType, SourcePathType, AddFileType, AddPathType, TargetFileType, TargetPathType;
protected List<FileChooser.ExtensionFilter> sourceExtensionFilter;
protected String baseName, defaultPath;
protected boolean onlyPath;
public RecentVisitMenu() {
}
public RecentVisitMenu(BaseController_Files controller, Event event, boolean onlyPath) {
this.controller = (BaseController) controller;
this.event = event;
this.baseName = controller.getBaseName();
this.onlyPath = onlyPath;
SourceFileType = controller.getSourceFileType();
SourcePathType = controller.getSourcePathType();
AddFileType = controller.getAddFileType();
AddPathType = controller.getAddPathType();
TargetFileType = controller.getTargetFileType();
TargetPathType = controller.getTargetPathType();
if (AddFileType <= 0) {
AddFileType = SourceFileType;
}
}
public RecentVisitMenu setFileType(int fileType) {
SourceFileType = fileType;
SourcePathType = fileType;
TargetFileType = fileType;
TargetPathType = fileType;
AddFileType = fileType;
AddPathType = fileType;
return this;
}
public void pop() {
try {
if (controller == null || event == null) {
return;
}
List<MenuItem> items = menu();
controller.popEventMenu(event, items);
} catch (Exception e) {
MyBoxLog.error(e.toString());
}
}
public List<MenuItem> menu() {
try {
List<MenuItem> items = MenuTools.initMenu(message("SelectFile"));
MenuItem menu = new MenuItem(message("Select..."));
menu.setOnAction((ActionEvent event1) -> {
handleSelect();
});
items.add(menu);
items.add(new SeparatorMenuItem());
if (onlyPath) {
List<String> paths = paths();
if (paths != null && !paths.isEmpty()) {
menu = new MenuItem(message("RecentAccessedDirectories"));
menu.setStyle(attributeTextStyle());
items.add(menu);
for (String path : paths) {
menu = new MenuItem(StringTools.menuSuffix(path));
menu.setOnAction((ActionEvent event1) -> {
handlePath(path);
});
items.add(menu);
}
items.add(new SeparatorMenuItem());
}
} else {
List<VisitHistory> written = recentWrittenFiles();
if (written != null && !written.isEmpty()) {
List<String> files = new ArrayList<>();
for (VisitHistory h : written) {
String fname = h.getResourceValue();
if (!files.contains(fname)) {
files.add(fname);
}
}
if (!files.isEmpty()) {
Menu wmenu = new Menu(message("RecentWrittenFiles"));
items.add(wmenu);
for (String fname : files) {
menu = new MenuItem(StringTools.menuSuffix(fname));
menu.setOnAction((ActionEvent event1) -> {
handleFile(fname);
});
wmenu.getItems().add(menu);
}
}
}
List<String> paths = paths();
if (paths != null && !paths.isEmpty()) {
Menu pmenu = new Menu(message("RecentAccessedDirectories"));
items.add(pmenu);
for (String path : paths) {
menu = new MenuItem(StringTools.menuSuffix(path));
menu.setOnAction((ActionEvent event1) -> {
handlePath(path);
});
pmenu.getItems().add(menu);
}
}
List<VisitHistory> opened = recentOpenedFiles();
if (opened != null && !opened.isEmpty()) {
List<String> files = new ArrayList<>();
for (VisitHistory h : opened) {
String fname = h.getResourceValue();
if (!files.contains(fname)) {
files.add(fname);
}
}
if (!files.isEmpty()) {
items.add(new SeparatorMenuItem());
menu = new MenuItem(message("RecentOpenedFiles"));
menu.setStyle(attributeTextStyle());
items.add(menu);
for (String fname : files) {
menu = new MenuItem(StringTools.menuSuffix(fname));
menu.setOnAction((ActionEvent event1) -> {
handleFile(fname);
});
items.add(menu);
}
}
}
if (examples != null && !examples.isEmpty()) {
items.add(new SeparatorMenuItem());
menu = new MenuItem(message("Examples"));
menu.setStyle(attributeTextStyle());
items.add(menu);
for (String example : examples) {
menu = new MenuItem(StringTools.menuSuffix(example));
menu.setOnAction((ActionEvent event1) -> {
handleFile(example);
});
items.add(menu);
}
}
items.add(new SeparatorMenuItem());
}
items.add(MenuTools.popCheckMenu("RecentVisit"));
return items;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public abstract void handleSelect();
public List<VisitHistory> recentFiles() {
return recentOpenedFiles();
}
public List<VisitHistory> recentPaths() {
return recentSourcePathsBesidesFiles();
}
public void handleFile(String fname) {
}
public void handlePath(String fname) {
handleSourcePath(fname);
}
public List<String> paths() {
List<VisitHistory> his = recentPaths();
List<String> paths = new ArrayList<>();
if (his != null) {
for (VisitHistory h : his) {
String pathname = h.getResourceValue();
if (!paths.contains(pathname)) {
paths.add(pathname);
}
}
}
if (defaultPath != null && !paths.contains(defaultPath)) {
paths.add(defaultPath);
}
File lastPath = UserConfig.getPath("LastPath");
if (lastPath != null) {
String lastPathString = lastPath.getAbsolutePath();
if (!paths.contains(lastPathString)) {
paths.add(lastPathString);
}
}
return paths;
}
public List<VisitHistory> recentOpenedFiles() {
int fileNumber = AppVariables.fileRecentNumber;
if (fileNumber == 0) {
fileNumber = 1;
}
return VisitHistoryTools.getRecentFileRead(SourceFileType, fileNumber);
}
public List<VisitHistory> recentWrittenFiles() {
int fileNumber = AppVariables.fileRecentNumber;
if (fileNumber == 0) {
fileNumber = 1;
}
return VisitHistoryTools.getRecentFileWrite(SourceFileType, fileNumber);
}
public List<VisitHistory> recentAddFiles() {
int fileNumber = AppVariables.fileRecentNumber;
if (fileNumber == 0) {
fileNumber = 1;
}
return VisitHistoryTools.getRecentFileRead(AddFileType, fileNumber);
}
public List<VisitHistory> recentSourcePathsBesidesFiles() {
int pathNumber = AppVariables.fileRecentNumber;
if (pathNumber == 0) {
pathNumber = 1;
}
return VisitHistoryTools.getRecentPathRead(SourcePathType, pathNumber);
}
public List<VisitHistory> recentTargetPathsBesidesFiles() {
int pathNumber = AppVariables.fileRecentNumber;
if (pathNumber == 0) {
pathNumber = 1;
}
return VisitHistoryTools.getRecentPathWrite(TargetPathType, pathNumber);
}
public List<VisitHistory> recentSourcePaths() {
return VisitHistoryTools.getRecentPathRead(SourcePathType);
}
public List<VisitHistory> recentTargetPaths() {
return VisitHistoryTools.getRecentPathWrite(TargetPathType);
}
public void handleSourcePath(String fname) {
File file = new File(fname);
if (!file.exists()) {
handleSelect();
return;
}
UserConfig.setString(baseName + "SourcePath", fname);
handleSelect();
}
public void handleTargetPath(String fname) {
File file = new File(fname);
if (!file.exists()) {
handleSelect();
return;
}
UserConfig.setString(baseName + "TargetPath", fname);
handleSelect();
}
/*
get/set
*/
public List<String> getExamples() {
return examples;
}
public RecentVisitMenu setExamples(List<String> examples) {
this.examples = examples;
return this;
}
public int getSourceFileType() {
return SourceFileType;
}
public RecentVisitMenu setSourceFileType(int SourceFileType) {
this.SourceFileType = SourceFileType;
return this;
}
public int getSourcePathType() {
return SourcePathType;
}
public RecentVisitMenu setSourcePathType(int SourcePathType) {
this.SourcePathType = SourcePathType;
return this;
}
public int getAddFileType() {
return AddFileType;
}
public RecentVisitMenu setAddFileType(int AddFileType) {
this.AddFileType = AddFileType;
return this;
}
public int getAddPathType() {
return AddPathType;
}
public RecentVisitMenu setAddPathType(int AddPathType) {
this.AddPathType = AddPathType;
return this;
}
public int getTargetPathType() {
return TargetPathType;
}
public RecentVisitMenu setTargetPathType(int TargetPathType) {
this.TargetPathType = TargetPathType;
return this;
}
public List<FileChooser.ExtensionFilter> getSourceExtensionFilter() {
return sourceExtensionFilter;
}
public RecentVisitMenu setSourceExtensionFilter(List<FileChooser.ExtensionFilter> sourceExtensionFilter) {
this.sourceExtensionFilter = sourceExtensionFilter;
return this;
}
public String getDefaultPath() {
return defaultPath;
}
public RecentVisitMenu setDefaultPath(String defaultPath) {
this.defaultPath = defaultPath;
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/fxml/SoundTools.java | released/MyBox/src/main/java/mara/mybox/fxml/SoundTools.java | package mara.mybox.fxml;
import java.io.File;
import java.util.Arrays;
import javafx.scene.media.AudioClip;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Mixer;
import mara.mybox.dev.MyBoxLog;
/**
* @Author Mara
* @CreateDate 2018-7-12
* @License Apache License Version 2.0
*/
public class SoundTools {
public static void audioSystem() {
Mixer.Info[] infos = AudioSystem.getMixerInfo();
for (Mixer.Info info : infos) {
MyBoxLog.debug(info.getName() + " " + info.getVendor() + " " + info.getVersion() + " " + info.getDescription());
}
AudioFileFormat.Type[] formats = AudioSystem.getAudioFileTypes();
MyBoxLog.debug(Arrays.asList(formats).toString());
}
public static void miao6() {
playClip("/sound/guaiMiao6.mp3", "guaiMiao6.mp3");
}
public static void GuaiAO() {
playClip("/sound/GuaiAO.mp3", "GuaiAO.mp3");
}
public static void mp3(File file) {
playClip(file);
}
public static void miao5() {
playClip("/sound/guaiMiao5.mp3", "guaiMiao5.mp3");
}
public static void miao3() {
playClip("/sound/guaiMiao3.mp3", "guaiMiao3.mp3");
}
public static void miao2() {
playClip("/sound/guaiMiao2.mp3", "guaiMiao2.mp3");
}
public static void miao7() {
playClip("/sound/guaiMiao7.mp3", "guaiMiao7.mp3");
}
public static void BenWu() {
playClip("/sound/BenWu.mp3", "BenWu.mp3");
}
public static void BenWu2() {
playClip("/sound/BenWu2.mp3", "BenWu2.mp3");
}
public static void playSound(final String file, final String userFile) {
File miao = FxFileTools.getInternalFile(file, "sound", userFile);
play(miao, 1, 1);
}
public static void playClip(final String file, final String userFile) {
File sound = FxFileTools.getInternalFile(file, "sound", userFile);
playClip(sound);
}
public static void playClip(File file) {
FxTask miaoTask = new FxTask<Void>() {
@Override
protected boolean handle() {
try {
AudioClip plonkSound = new AudioClip(file.toURI().toString());
plonkSound.play();
} catch (Exception e) {
}
return true;
}
};
Thread thread = new Thread(miaoTask);
thread.setDaemon(false);
thread.start();
}
public static MediaPlayer play(File file, double volumn, int cycle) {
return play(file.toURI().toString(), volumn, cycle);
}
public static MediaPlayer play(String address, double volumn, int cycle) {
MediaPlayer mp = new MediaPlayer(new Media(address));
mp.setVolume(volumn);
mp.setCycleCount(cycle);
mp.setAutoPlay(true);
return mp;
}
public static void audio(File file) {
audio(file, 1, 1);
}
public static void audio(File file, double volumn, int cycle) {
AudioClip clip = new AudioClip(file.toURI().toString());
clip.setVolume(volumn);
clip.setCycleCount(cycle);
clip.play();
}
public static AudioClip clip(File file, double volumn) {
AudioClip clip = new AudioClip(file.toURI().toString());
clip.setVolume(volumn);
return clip;
}
}
| 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/fxml/image/ShapeTools.java | released/MyBox/src/main/java/mara/mybox/fxml/image/ShapeTools.java | package mara.mybox.fxml.image;
import java.awt.image.BufferedImage;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.image.Image;
import mara.mybox.image.data.ImageMosaic;
import mara.mybox.image.data.PixelsBlend;
import mara.mybox.data.DoublePolylines;
import mara.mybox.data.DoubleShape;
import mara.mybox.data.ShapeStyle;
import mara.mybox.fxml.FxTask;
/**
* @Author Mara
* @CreateDate 2018-11-13 12:38:14
* @License Apache License Version 2.0
*/
public class ShapeTools {
public static Image drawShape(FxTask task, Image image, DoubleShape shape, ShapeStyle style, PixelsBlend blender) {
if (shape == null) {
return image;
}
BufferedImage source = SwingFXUtils.fromFXImage(image, null);
BufferedImage target = mara.mybox.image.tools.ShapeTools.drawShape(task, source, shape, style, blender);
if (target == null || (task != null && !task.isWorking())) {
return null;
}
Image newImage = SwingFXUtils.toFXImage(target, null);
return newImage;
}
public static Image drawErase(FxTask task, Image image, DoublePolylines penData, ShapeStyle style) {
if (penData == null || style == null) {
return image;
}
BufferedImage source = SwingFXUtils.fromFXImage(image, null);
BufferedImage target = mara.mybox.image.tools.ShapeTools.drawErase(task, source, penData, style);
if (target == null || (task != null && !task.isWorking())) {
return null;
}
Image newImage = SwingFXUtils.toFXImage(target, null);
return newImage;
}
public static Image drawMosaic(FxTask task, Image image, DoublePolylines penData,
ImageMosaic.MosaicType mosaicType, int strokeWidth, int intensity) {
if (penData == null || mosaicType == null || strokeWidth < 1) {
return image;
}
BufferedImage source = SwingFXUtils.fromFXImage(image, null);
BufferedImage target = mara.mybox.image.tools.ShapeTools.drawMosaic(task, source, penData, mosaicType, strokeWidth, intensity);
if (target == null || (task != null && !task.isWorking())) {
return null;
}
Image newImage = SwingFXUtils.toFXImage(target, null);
return newImage;
}
}
| 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/fxml/image/FxImageTools.java | released/MyBox/src/main/java/mara/mybox/fxml/image/FxImageTools.java | package mara.mybox.fxml.image;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Map;
import java.util.Random;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.Group;
import javafx.scene.SnapshotParameters;
import javafx.scene.effect.Blend;
import javafx.scene.effect.BlendMode;
import javafx.scene.effect.DropShadow;
import javafx.scene.effect.ImageInput;
import javafx.scene.image.Image;
import javafx.scene.image.PixelReader;
import javafx.scene.image.PixelWriter;
import javafx.scene.image.WritableImage;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import mara.mybox.image.tools.AlphaTools;
import mara.mybox.image.tools.BufferedImageTools;
import mara.mybox.image.tools.ColorConvertTools;
import mara.mybox.image.data.PixelsBlend;
import mara.mybox.image.data.PixelsOperationFactory;
import mara.mybox.data.DoubleShape;
import mara.mybox.dev.MyBoxLog;
import static mara.mybox.fxml.image.FxColorTools.toAwtColor;
import mara.mybox.fxml.FxTask;
import mara.mybox.image.file.ImageFileReaders;
import mara.mybox.image.file.ImageFileWriters;
import mara.mybox.tools.FileTmpTools;
/**
* @Author Mara
* @CreateDate 2018-6-11 11:19:42
* @License Apache License Version 2.0
*/
public class FxImageTools {
public class ManufactureType {
public static final int Brighter = 0;
public static final int Darker = 1;
public static final int Gray = 2;
public static final int Invert = 3;
public static final int Saturate = 4;
public static final int Desaturate = 5;
}
public static Image createImage(int width, int height, Color color) {
WritableImage newImage = new WritableImage(width, height);
PixelWriter pixelWriter = newImage.getPixelWriter();
for (int y = 0; y < newImage.getHeight(); y++) {
for (int x = 0; x < newImage.getWidth(); x++) {
pixelWriter.setColor(x, y, color);
}
}
return newImage;
}
public static Image readImage(FxTask task, File file) {
BufferedImage bufferedImage = ImageFileReaders.readImage(task, file);
if (bufferedImage == null) {
return null;
}
return SwingFXUtils.toFXImage(bufferedImage, null);
}
public static File writeImage(FxTask task, Image image) {
if (image == null) {
return null;
}
BufferedImage bufferedImage = SwingFXUtils.fromFXImage(image, null);
if (bufferedImage == null) {
return null;
}
File tmpFile = FileTmpTools.getTempFile(".png");
if (ImageFileWriters.writeImageFile(task, bufferedImage, "png", tmpFile.getAbsolutePath())
&& tmpFile.exists()) {
return tmpFile;
} else {
return null;
}
}
public static byte[] bytes(FxTask task, Image image, String format) {
return BufferedImageTools.bytes(task, SwingFXUtils.fromFXImage(image, null), format);
}
public static String base64(FxTask task, File file, String format) {
try {
BufferedImage bufferedImage = ImageFileReaders.readImage(task, file);
if (bufferedImage == null) {
return null;
}
return BufferedImageTools.base64(task, bufferedImage, format);
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
public static String base64(FxTask task, Image image, String format) {
try {
if (image == null || format == null) {
return null;
}
return BufferedImageTools.base64(task, SwingFXUtils.fromFXImage(image, null), format);
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
public static Image clone(FxTask task, Image srcImage) {
if (srcImage == null) {
return srcImage;
}
double w = srcImage.getWidth();
double h = srcImage.getHeight();
PixelReader pixelReader = srcImage.getPixelReader();
WritableImage newImage = new WritableImage((int) w, (int) h);
PixelWriter pixelWriter = newImage.getPixelWriter();
for (int y = 0; y < h; y++) {
for (int x = 0; x < w; x++) {
pixelWriter.setColor(x, y, pixelReader.getColor(x, y));
}
}
return newImage;
}
// This way may be more quicker than comparing digests
public static boolean sameImage(FxTask task, Image imageA, Image imageB) {
try {
if (imageA == null || imageB == null
|| imageA.getWidth() != imageB.getWidth()
|| imageA.getHeight() != imageB.getHeight()) {
return false;
}
int width = (int) imageA.getWidth(), height = (int) imageA.getHeight();
PixelReader readA = imageA.getPixelReader();
PixelReader readB = imageB.getPixelReader();
for (int y = 0; y < height / 2; y++) {
if (task != null && !task.isWorking()) {
return false;
}
for (int x = 0; x < width / 2; x++) {
if (task != null && !task.isWorking()) {
return false;
}
if (!readA.getColor(x, y).equals(readB.getColor(x, y))) {
return false;
}
}
for (int x = width - 1; x >= width / 2; x--) {
if (task != null && !task.isWorking()) {
return false;
}
if (!readA.getColor(x, y).equals(readB.getColor(x, y))) {
return false;
}
}
}
for (int y = height - 1; y >= height / 2; y--) {
if (task != null && !task.isWorking()) {
return false;
}
for (int x = 0; x < width / 2; x++) {
if (task != null && !task.isWorking()) {
return false;
}
if (!readA.getColor(x, y).equals(readB.getColor(x, y))) {
return false;
}
}
for (int x = width - 1; x >= width / 2; x--) {
if (task != null && !task.isWorking()) {
return false;
}
if (!readA.getColor(x, y).equals(readB.getColor(x, y))) {
return false;
}
}
}
return true;
} catch (Exception e) {
return false;
}
}
// https://stackoverflow.com/questions/19548363/image-saved-in-javafx-as-jpg-is-pink-toned
public static BufferedImage toBufferedImage(Image image) {
if (image == null) {
return null;
}
BufferedImage source = SwingFXUtils.fromFXImage(image, null);
return source;
}
public static BufferedImage checkAlpha(FxTask task, Image image, String format) {
BufferedImage source = SwingFXUtils.fromFXImage(image, null);
BufferedImage target = AlphaTools.checkAlpha(task, source, format);
return target;
}
public static Image clearAlpha(FxTask task, Image image) {
BufferedImage source = SwingFXUtils.fromFXImage(image, null);
BufferedImage target = AlphaTools.removeAlpha(task, source);
Image newImage = SwingFXUtils.toFXImage(target, null);
return newImage;
}
// This way may fail for big image
public static Image addTextFx(Image image, String textString,
Font font, Color color, int x, int y, float transparent, int shadow) {
try {
Group group = new Group();
Text text = new Text(x, y, textString);
text.setFill(color);
text.setFont(font);
if (shadow > 0) {
DropShadow dropShadow = new DropShadow();
dropShadow.setOffsetX(shadow);
dropShadow.setOffsetY(shadow);
text.setEffect(dropShadow);
}
group.getChildren().add(text);
Blend blend = new Blend(BlendMode.SRC_OVER);
blend.setBottomInput(new ImageInput(image));
blend.setOpacity(1.0 - transparent);
group.setEffect(blend);
SnapshotParameters parameters = new SnapshotParameters();
parameters.setFill(Color.TRANSPARENT);
WritableImage newImage = group.snapshot(parameters, null);
return newImage;
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
public static Image setRound(FxTask task, Image image, int roundX, int roundY, Color bgColor) {
if (image == null || roundX <= 0 || roundY <= 0) {
return image;
}
BufferedImage source = SwingFXUtils.fromFXImage(image, null);
BufferedImage target = BufferedImageTools.setRound(task, source, roundX, roundY, toAwtColor(bgColor));
Image newImage = SwingFXUtils.toFXImage(target, null);
return newImage;
}
public static Image addShadow(FxTask task, Image image, int offsetX, int offsetY, Color color, boolean isBlur) {
if (image == null || color == null) {
return image;
}
BufferedImage source = SwingFXUtils.fromFXImage(image, null);
BufferedImage target = BufferedImageTools.addShadow(task, source, offsetX, offsetY, toAwtColor(color), isBlur);
Image newImage = SwingFXUtils.toFXImage(target, null);
return newImage;
}
public static Image blend(FxTask task, Image foreImage, Image backImage,
int x, int y, PixelsBlend blender) {
if (foreImage == null || backImage == null || blender == null) {
return null;
}
BufferedImage source1 = SwingFXUtils.fromFXImage(foreImage, null);
BufferedImage source2 = SwingFXUtils.fromFXImage(backImage, null);
BufferedImage target = PixelsBlend.blend(task, source1, source2, x, y, blender);
if (target == null) {
target = source1;
}
Image newImage = SwingFXUtils.toFXImage(target, null);
return newImage;
}
public static Image makeMosaic(FxTask task, Image image, DoubleShape shape, int size,
boolean isMosaic, boolean isExcluded) {
if (!shape.isValid()) {
return image;
}
int w = (int) image.getWidth();
int h = (int) image.getHeight();
PixelReader pixelReader = image.getPixelReader();
WritableImage newImage = new WritableImage(w, h);
PixelWriter pixelWriter = newImage.getPixelWriter();
for (int y = 0; y < h; y++) {
if (task != null && !task.isWorking()) {
return null;
}
for (int x = 0; x < w; x++) {
if (task != null && !task.isWorking()) {
return null;
}
if (isExcluded) {
if (DoubleShape.contains(shape, x, y)) {
pixelWriter.setColor(x, y, pixelReader.getColor(x, y));
} else {
if (isMosaic) {
int mx = Math.max(0, Math.min(w - 1, x - x % size));
int my = Math.max(0, Math.min(h - 1, y - y % size));
pixelWriter.setColor(x, y, pixelReader.getColor(mx, my));
} else {
int fx = Math.max(0, Math.min(w - 1, x - new Random().nextInt(size)));
int fy = Math.max(0, Math.min(h - 1, y - new Random().nextInt(size)));
pixelWriter.setColor(x, y, pixelReader.getColor(fx, fy));
}
}
} else {
if (DoubleShape.contains(shape, x, y)) {
if (isMosaic) {
int mx = Math.max(0, Math.min(w - 1, x - x % size));
int my = Math.max(0, Math.min(h - 1, y - y % size));
pixelWriter.setColor(x, y, pixelReader.getColor(mx, my));
} else {
int fx = Math.max(0, Math.min(w - 1, x - new Random().nextInt(size)));
int fy = Math.max(0, Math.min(h - 1, y - new Random().nextInt(size)));
pixelWriter.setColor(x, y, pixelReader.getColor(fx, fy));
}
} else {
pixelWriter.setColor(x, y, pixelReader.getColor(x, y));
}
}
}
}
return newImage;
}
public static Image replaceColor(FxTask task, Image image, Color oldColor, Color newColor, int distance) {
if (image == null || oldColor == null || newColor == null || distance < 0) {
return image;
}
BufferedImage source = SwingFXUtils.fromFXImage(image, null);
BufferedImage target = PixelsOperationFactory.replaceColor(task, source,
ColorConvertTools.converColor(oldColor), ColorConvertTools.converColor(newColor), distance);
Image newImage = SwingFXUtils.toFXImage(target, null);
return newImage;
}
public static Image applyRenderHints(Image image, Map<RenderingHints.Key, Object> hints) {
if (image == null || hints == null) {
return image;
}
BufferedImage source = SwingFXUtils.fromFXImage(image, null);
BufferedImage target = BufferedImageTools.applyRenderHints(source, hints);
Image newImage = SwingFXUtils.toFXImage(target, null);
return newImage;
}
}
| 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/fxml/image/TransformTools.java | released/MyBox/src/main/java/mara/mybox/fxml/image/TransformTools.java | package mara.mybox.fxml.image;
import java.awt.image.BufferedImage;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.image.Image;
import javafx.scene.image.PixelReader;
import javafx.scene.image.PixelWriter;
import javafx.scene.image.WritableImage;
import javafx.scene.paint.Color;
import mara.mybox.fxml.FxTask;
/**
* @Author Mara
* @CreateDate 2018-11-13 12:38:14
* @License Apache License Version 2.0
*/
public class TransformTools {
public static Image horizontalImage(FxTask task, Image image) {
int width = (int) image.getWidth();
int height = (int) image.getHeight();
PixelReader pixelReader = image.getPixelReader();
WritableImage newImage = new WritableImage(width, height);
PixelWriter pixelWriter = newImage.getPixelWriter();
for (int j = 0; j < height; ++j) {
if (task != null && !task.isWorking()) {
return null;
}
int l = 0;
int r = width - 1;
while (l <= r) {
if (task != null && !task.isWorking()) {
return null;
}
Color cl = pixelReader.getColor(l, j);
Color cr = pixelReader.getColor(r, j);
pixelWriter.setColor(l, j, cr);
pixelWriter.setColor(r, j, cl);
l++;
r--;
}
}
return newImage;
}
public static Image verticalImage(FxTask task, Image image) {
int width = (int) image.getWidth();
int height = (int) image.getHeight();
PixelReader pixelReader = image.getPixelReader();
WritableImage newImage = new WritableImage(width, height);
PixelWriter pixelWriter = newImage.getPixelWriter();
for (int i = 0; i < width; ++i) {
if (task != null && !task.isWorking()) {
return null;
}
int t = 0;
int b = height - 1;
while (t <= b) {
if (task != null && !task.isWorking()) {
return null;
}
Color ct = pixelReader.getColor(i, t);
Color cb = pixelReader.getColor(i, b);
pixelWriter.setColor(i, t, cb);
pixelWriter.setColor(i, b, ct);
t++;
b--;
}
}
return newImage;
}
public static Image rotateImage(FxTask task, Image image, int angle, boolean cutMargins) {
BufferedImage source = SwingFXUtils.fromFXImage(image, null);
BufferedImage target = mara.mybox.image.tools.TransformTools.rotateImage(task, source, angle, cutMargins);
if (target == null || (task != null && !task.isWorking())) {
return null;
}
Image newImage = SwingFXUtils.toFXImage(target, null);
return newImage;
}
public static Image shearImage(FxTask task, Image image, float shearX, float shearY, boolean cutMargins) {
BufferedImage source = SwingFXUtils.fromFXImage(image, null);
BufferedImage target = mara.mybox.image.tools.TransformTools.shearImage(task, source, shearX, shearY, cutMargins);
if (target == null || (task != null && !task.isWorking())) {
return null;
}
Image newImage = SwingFXUtils.toFXImage(target, null);
return newImage;
}
}
| 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/fxml/image/ImageDemos.java | released/MyBox/src/main/java/mara/mybox/fxml/image/ImageDemos.java | package mara.mybox.fxml.image;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Arrays;
import java.util.List;
import mara.mybox.image.tools.BufferedImageTools;
import mara.mybox.image.tools.TransformTools;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.FxTask;
import mara.mybox.image.file.ImageFileWriters;
import mara.mybox.tools.FileTmpTools;
import mara.mybox.value.AppPaths;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2023-12-1
* @License Apache License Version 2.0
*/
public class ImageDemos {
public static void shear(FxTask demoTask, List<String> files,
BufferedImage demoImage, File demoFile) {
if (demoTask == null || demoImage == null || files == null) {
return;
}
try {
String path = AppPaths.getGeneratedPath() + File.separator + "imageDemo"
+ File.separator + message("Shear");
if (demoFile != null) {
path += File.separator + demoFile.getName();
} else {
path += File.separator + "x";
}
BufferedImage bufferedImage = TransformTools.shearImage(demoTask, demoImage, 1f, 0, true);
if (!demoTask.isWorking()) {
return;
}
String tmpFile = FileTmpTools.getPathTempFile(path, "radio_(1,0)", ".png").getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, "png", tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
if (!demoTask.isWorking()) {
return;
}
bufferedImage = TransformTools.shearImage(demoTask, demoImage, -1f, 0, true);
if (!demoTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path, "radio_(-1,0)", ".png").getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, "png", tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
if (!demoTask.isWorking()) {
return;
}
bufferedImage = TransformTools.shearImage(demoTask, demoImage, 0, 1f, true);
if (!demoTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path, "radio_(0,1)", ".png").getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, "png", tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
if (!demoTask.isWorking()) {
return;
}
bufferedImage = TransformTools.shearImage(demoTask, demoImage, 0, -1f, true);
if (!demoTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path, "radio_(0,-1)", ".png").getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, "png", tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
if (!demoTask.isWorking()) {
return;
}
bufferedImage = TransformTools.shearImage(demoTask, demoImage, 1.5f, 2, true);
if (!demoTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path, "radio_(1.5,2)", ".png").getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, "png", tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
if (!demoTask.isWorking()) {
return;
}
bufferedImage = TransformTools.shearImage(demoTask, demoImage, 2, -1.5f, true);
if (!demoTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path, "radio_(2,-1.5)", ".png").getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, "png", tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
if (!demoTask.isWorking()) {
return;
}
bufferedImage = TransformTools.shearImage(demoTask, demoImage, -1.5f, 2, true);
if (!demoTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path, "radio_(-1.5,2)", ".png").getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, "png", tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
if (!demoTask.isWorking()) {
return;
}
bufferedImage = TransformTools.shearImage(demoTask, demoImage, -2, -1.5f, true);
if (!demoTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path, "radio_(-2,-1.5)", ".png").getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, "png", tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
if (!demoTask.isWorking()) {
return;
}
} catch (Exception e) {
if (demoTask != null) {
demoTask.setError(e.toString());
} else {
MyBoxLog.error(e.toString());
}
}
}
public static void round(FxTask demoTask, List<String> files,
BufferedImage demoImage, Color color, File demoFile) {
if (demoTask == null || demoImage == null || files == null || color == null) {
return;
}
try {
String path = AppPaths.getGeneratedPath() + File.separator + "imageDemo"
+ File.separator + message("Round");
if (demoFile != null) {
path += File.separator + demoFile.getName();
} else {
path += File.separator + "x";
}
int width = demoImage.getWidth();
int height = demoImage.getHeight();
List<Integer> values = Arrays.asList(1, 2, 4, 8, 10, 20, 30);
BufferedImage bufferedImage;
String tmpFile;
for (int r : values) {
if (demoTask == null || !demoTask.isWorking()) {
return;
}
int v = Math.min(width / r, height / r);
bufferedImage = BufferedImageTools.setRound(demoTask, demoImage, v, v, color);
if (demoTask == null || !demoTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path, message("Round") + v, ".png")
.getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
}
} catch (Exception e) {
if (demoTask != null) {
demoTask.setError(e.toString());
} else {
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/fxml/image/ScaleTools.java | released/MyBox/src/main/java/mara/mybox/fxml/image/ScaleTools.java | package mara.mybox.fxml.image;
import java.awt.image.BufferedImage;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.image.Image;
/**
* @Author Mara
* @CreateDate 2018-11-13 12:38:14
* @License Apache License Version 2.0
*/
public class ScaleTools {
public static Image scaleImage(Image image, float scale) {
int targetW = (int) Math.round(image.getWidth() * scale);
int targetH = (int) Math.round(image.getHeight() * scale);
return scaleImage(image, targetW, targetH);
}
public static Image scaleImage(Image image, int width) {
if (width <= 0 || width == image.getWidth()) {
return image;
}
BufferedImage source = SwingFXUtils.fromFXImage(image, null);
BufferedImage target = mara.mybox.image.tools.ScaleTools.scaleImageWidthKeep(source, width);
Image newImage = SwingFXUtils.toFXImage(target, null);
return newImage;
}
public static Image scaleImage(Image image, int width, int height) {
if (width == image.getWidth() && height == image.getHeight()) {
return image;
}
BufferedImage source = SwingFXUtils.fromFXImage(image, null);
BufferedImage target = mara.mybox.image.tools.ScaleTools.scaleImageBySize(source, width, height);
Image newImage = SwingFXUtils.toFXImage(target, null);
return newImage;
}
public static Image scaleImage(Image image, int width, int height, boolean keepRatio, int keepType) {
BufferedImage source = SwingFXUtils.fromFXImage(image, null);
BufferedImage target = mara.mybox.image.tools.ScaleTools.scaleImage(source, width, height, keepRatio, keepType);
Image newImage = SwingFXUtils.toFXImage(target, null);
return newImage;
}
public static Image demoImage(Image image) {
BufferedImage source = SwingFXUtils.fromFXImage(image, null);
BufferedImage target = mara.mybox.image.tools.ScaleTools.demoImage(source);
Image newImage = SwingFXUtils.toFXImage(target, null);
return newImage;
}
}
| 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/fxml/image/FxColorTools.java | released/MyBox/src/main/java/mara/mybox/fxml/image/FxColorTools.java | package mara.mybox.fxml.image;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Random;
import javafx.scene.paint.Color;
import mara.mybox.color.SRGB;
import mara.mybox.data.StringTable;
import mara.mybox.db.data.ColorData;
import mara.mybox.db.table.TableColor;
import mara.mybox.image.tools.ColorConvertTools;
import mara.mybox.tools.DoubleTools;
import mara.mybox.value.AppValues;
import mara.mybox.value.Languages;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2018-11-13 12:38:14
* @License Apache License Version 2.0
*/
public class FxColorTools {
public static Map<String, Color> WebColors, ChineseColors, JapaneseColors;
public static Map<Color, String> WebColorNames, ChineseColorNames, JapaneseColorNames;
public static int compareColor(Color o1, Color o2) {
double diff = o2.getHue() - o1.getHue();
if (diff > 0) {
return 1;
} else if (diff < 0) {
return -1;
} else {
diff = o2.getSaturation() - o1.getSaturation();
if (diff > 0) {
return 1;
} else if (diff < 0) {
return -1;
} else {
diff = o2.getBrightness() - o1.getBrightness();
if (diff > 0) {
return 1;
} else if (diff < 0) {
return -1;
} else {
diff = o2.getOpacity() - o1.getOpacity();
if (diff > 0) {
return 1;
} else if (diff < 0) {
return -1;
} else {
return 0;
}
}
}
}
}
public static String colorNameDisplay(TableColor tableColor, Color color) {
if (color == null) {
return "";
}
ColorData data = tableColor.read(color);
if (data != null) {
return data.display();
}
data = new ColorData(FxColorTools.color2rgba(color));
return data.display();
}
public static String colorDisplaySimple(Color color) {
if (color == null) {
return "";
}
String s = FxColorTools.color2rgba(color) + "\n";
s += "sRGB " + Languages.message("Red") + ":" + Math.round(color.getRed() * 255) + " "
+ Languages.message("Green") + ":" + Math.round(color.getGreen() * 255) + " "
+ Languages.message("Blue") + ":" + Math.round(color.getBlue() * 255)
+ Languages.message("Opacity") + ":" + Math.round(color.getOpacity() * 100) + "%\n";
s += "HSB " + Languages.message("Hue") + ":" + Math.round(color.getHue()) + " "
+ Languages.message("Saturation") + ":" + Math.round(color.getSaturation() * 100) + "% "
+ Languages.message("Brightness") + ":" + Math.round(color.getBrightness() * 100) + "%\n";
return s;
}
public static String color2rgb(Color color) {
return String.format("#%02X%02X%02X",
(int) (color.getRed() * 255),
(int) (color.getGreen() * 255),
(int) (color.getBlue() * 255));
}
public static String color2RGBA(Color color) {
return String.format("#%02X%02X%02X%02X",
(int) (color.getRed() * 255),
(int) (color.getGreen() * 255),
(int) (color.getBlue() * 255),
(int) (color.getOpacity() * 255));
}
public static String color2css(Color color) {
return "rgba(" + (int) (color.getRed() * 255) + ","
+ (int) (color.getGreen() * 255) + ","
+ (int) (color.getBlue() * 255) + ","
+ color.getOpacity() + ")";
}
public static String color2hsla(Color color) {
return "hsla("
+ Math.round(color.getHue()) + ","
+ Math.round(color.getSaturation() * 100) + "%,"
+ Math.round(color.getBrightness() * 100) + "%,"
+ DoubleTools.scale2(color.getOpacity()) + ")";
}
public static String color2rgba(Color color) {
return String.format("0x%02X%02X%02X%02X",
(int) (color.getRed() * 255),
(int) (color.getGreen() * 255),
(int) (color.getBlue() * 255),
(int) (color.getOpacity() * 255));
}
public static Color value2color(int value) {
return ColorConvertTools.converColor(new java.awt.Color(value, true));
}
public static Color invert(Color color) {
return new Color(1 - color.getRed(), 1 - color.getGreen(), 1 - color.getBlue(), color.getOpacity());
}
public static boolean isLightColor(Color color) {
return color.grayscale().getRed() > 0.5;
}
public static boolean isTransparent(Color color) {
return color.equals(Color.TRANSPARENT);
}
public static Color foreColor(Color backColor) {
return isLightColor(backColor) ? Color.BLACK : Color.WHITE;
}
public static int color2Value(Color color) {
return color == null ? AppValues.InvalidInteger
: ColorConvertTools.converColor(color).getRGB();
}
public static int web2Value(String web) {
try {
return FxColorTools.color2Value(Color.web(web));
} catch (Exception e) {
return AppValues.InvalidInteger;
}
}
public static java.awt.Color toAwtColor(Color color) {
java.awt.Color newColor = new java.awt.Color((int) (color.getRed() * 255),
(int) (color.getGreen() * 255),
(int) (color.getBlue() * 255),
(int) (color.getOpacity() * 255));
return newColor;
}
public static java.awt.Color cssToAwt(String css) {
return toAwtColor(Color.web(css));
}
public static String randomRGB() {
Random random = new Random();
return randomRGB(random);
}
public static String randomRGB(Random random) {
String color = String.format("#%02X%02X%02X",
random.nextInt(256),
random.nextInt(256),
random.nextInt(256));
return color;
}
public static List<String> randomRGB(int size) {
Random random = new Random();
List<String> colors = new ArrayList<>();
if (size > 256 * 256 * 256 - 1) {
return null;
}
while (colors.size() < size) {
while (true) {
String color = randomRGB(random);
if (!colors.contains(color)) {
colors.add(color);
break;
}
}
}
return colors;
}
public static String randomRGBExcept(Collection<String> excepts) {
Random random = new Random();
while (true) {
String color = randomRGB(random);
if (!excepts.contains(color)) {
return color;
}
}
}
public static String randomRGBA() {
Random random = new Random();
return randomRGBA(random);
}
public static String randomRGBA(Random random) {
while (true) {
String color = String.format("0x%02X%02X%02X%02X",
random.nextInt(256),
random.nextInt(256),
random.nextInt(256),
random.nextInt(256));
if (!"0xFFFFFFFF".equals(color)) {
return color;
}
}
}
public static Color randomColor() {
return Color.web(randomRGB());
}
public static Color randomColor(Random random) {
return Color.web(randomRGB(random));
}
public static List<String> randomRGBA(int size) {
Random random = new Random();
List<String> colors = new ArrayList<>();
if (size > 256 * 256 * 256 - 1) {
return null;
}
while (colors.size() < size) {
while (true) {
String color = randomRGBA(random);
if (!colors.contains(color)) {
colors.add(color);
break;
}
}
}
return colors;
}
public static String randomRGBAExcept(Collection<String> excepts) {
Random random = new Random();
while (true) {
String color = randomRGBA(random);
if (!excepts.contains(color)) {
return color;
}
}
}
public static String color2rgb(java.awt.Color color) {
return String.format("#%02X%02X%02X",
color.getRed(), color.getGreen(), color.getBlue());
}
public static String color2css(java.awt.Color color) {
return "rgba(" + color.getRed() + ","
+ color.getGreen() + ","
+ color.getBlue() + ","
+ color.getAlpha() / 255f + ")";
}
public static String hsb2rgba(float h, float s, float b) {
return color2rgba(Color.hsb(h, s, b));
}
public static String color2AlphaHex(java.awt.Color color) {
return String.format("#%02X%02X%02X%02X",
color.getAlpha(), color.getRed(), color.getGreen(), color.getBlue());
}
public static float[] color2srgb(Color color) {
float[] srgb = new float[3];
srgb[0] = (float) color.getRed();
srgb[1] = (float) color.getGreen();
srgb[2] = (float) color.getBlue();
return srgb;
}
public static double[] toDouble(Color color) {
double[] srgb = new double[3];
srgb[0] = color.getRed();
srgb[1] = color.getGreen();
srgb[2] = color.getBlue();
return srgb;
}
public static double[] SRGBtoAdobeRGB(Color color) {
return SRGB.SRGBtoAdobeRGB(toDouble(color));
}
public static double[] SRGBtoAppleRGB(Color color) {
return SRGB.SRGBtoAppleRGB(toDouble(color));
}
public static int calculateColorDistanceSquare(Color color1, Color color2) {
if (color1 == null || color2 == null) {
return Integer.MAX_VALUE;
}
double redDiff = (color1.getRed() - color2.getRed()) * 255;
double greenDiff = (color1.getGreen() - color2.getGreen()) * 255;
double blueDiff = (color1.getBlue() - color2.getBlue()) * 255;
int v = (int) Math.round(2 * redDiff * redDiff + 4 * greenDiff * greenDiff + 3 * blueDiff * blueDiff);
return v;
}
// distance2 = Math.pow(distance, 2)
// distance: 0-255
public static boolean isColorMatchSquare(Color color1, Color color2, int distance2) {
if (color1 == null || color2 == null) {
return false;
}
if (color1.equals(color2)) {
return true;
} else if (distance2 == 0 || color1.equals(Color.TRANSPARENT) || color2.equals(Color.TRANSPARENT)) {
return false;
}
return calculateColorDistanceSquare(color1, color2) <= distance2;
}
public static StringTable colorsTable(StringTable table, ColorData color1, ColorData color2, ColorData color3) {
List<String> row = new ArrayList<>();
row.add(message("Color"));
row.add("<DIV style=\"width: 50px; background-color:"
+ color2css(color1.getColor()) + "; \"> </DIV>");
row.add("<DIV style=\"width: 50px; background-color:"
+ color2css(color2.getColor()) + "; \"> </DIV>");
row.add("<DIV style=\"width: 50px; background-color:"
+ color2css(color3.getColor()) + "; \"> </DIV>");
table.add(row);
row = new ArrayList<>();
row.addAll(Arrays.asList(message("Name"), color1.getColorName() + "", color2.getColorName() + "", color3.getColorName() + ""));
table.add(row);
row = new ArrayList<>();
row.addAll(Arrays.asList(message("Hue"), color1.getHue(), color2.getHue(), color3.getHue()));
table.add(row);
row = new ArrayList<>();
row.addAll(Arrays.asList(message("Saturation"), color1.getSaturation(), color2.getSaturation(), color3.getSaturation()));
table.add(row);
row = new ArrayList<>();
row.addAll(Arrays.asList(message("Brightness"), color1.getBrightness(), color2.getBrightness(), color3.getBrightness()));
table.add(row);
row = new ArrayList<>();
row.addAll(Arrays.asList(message("RYBAngle"), color1.getRybAngle(), color2.getRybAngle(), color3.getRybAngle()));
table.add(row);
row = new ArrayList<>();
row.addAll(Arrays.asList(message("Opacity"), color1.getOpacity(), color2.getOpacity(), color3.getOpacity()));
table.add(row);
row = new ArrayList<>();
row.addAll(Arrays.asList("RGBA", color1.getRgba(), color2.getRgba(), color3.getRgba()));
table.add(row);
row = new ArrayList<>();
row.addAll(Arrays.asList("RGB", color1.getRgb(), color2.getRgb(), color3.getRgb()));
table.add(row);
row = new ArrayList<>();
row.addAll(Arrays.asList("sRGB", color1.getSrgb(), color2.getSrgb(), color3.getSrgb()));
table.add(row);
row = new ArrayList<>();
row.addAll(Arrays.asList("HSBA", color1.getHsb(), color2.getHsb(), color3.getHsb()));
table.add(row);
row = new ArrayList<>();
row.addAll(Arrays.asList(message("CalculatedCMYK"), color1.getCalculatedCMYK(), color2.getCalculatedCMYK(), color3.getCalculatedCMYK()));
table.add(row);
row = new ArrayList<>();
row.addAll(Arrays.asList("Adobe RGB", color1.getAdobeRGB(), color2.getAdobeRGB(), color3.getAdobeRGB()));
table.add(row);
row = new ArrayList<>();
row.addAll(Arrays.asList("Apple RGB", color1.getAppleRGB(), color2.getAppleRGB(), color3.getAppleRGB()));
table.add(row);
row = new ArrayList<>();
row.addAll(Arrays.asList("ECI RGB", color1.getEciRGB(), color2.getEciRGB(), color3.getEciRGB()));
table.add(row);
row = new ArrayList<>();
row.addAll(Arrays.asList("sRGB Linear", color1.getSRGBLinear(), color2.getSRGBLinear(), color3.getSRGBLinear()));
table.add(row);
row = new ArrayList<>();
row.addAll(Arrays.asList("Adobe RGB Linear", color1.getAdobeRGBLinear(), color2.getAdobeRGBLinear(), color3.getAdobeRGBLinear()));
table.add(row);
row = new ArrayList<>();
row.addAll(Arrays.asList("Apple RGB Linear", color1.getAppleRGBLinear(), color2.getAppleRGBLinear(), color3.getAppleRGBLinear()));
table.add(row);
row = new ArrayList<>();
row.addAll(Arrays.asList("ECI CMYK", color1.getEciCMYK(), color2.getEciCMYK(), color3.getEciCMYK()));
table.add(row);
row = new ArrayList<>();
row.addAll(Arrays.asList("Adobe CMYK Uncoated FOGRA29", color1.getAdobeCMYK(), color2.getAdobeCMYK(), color3.getAdobeCMYK()));
table.add(row);
row = new ArrayList<>();
row.addAll(Arrays.asList("XYZ", color1.getXyz(), color2.getXyz(), color3.getXyz()));
table.add(row);
row = new ArrayList<>();
row.addAll(Arrays.asList("CIE-L*ab", color1.getCieLab(), color2.getCieLab(), color3.getCieLab()));
table.add(row);
row = new ArrayList<>();
row.addAll(Arrays.asList("LCH(ab)", color1.getLchab(), color2.getLchab(), color3.getLchab()));
table.add(row);
row = new ArrayList<>();
row.addAll(Arrays.asList("CIE-L*uv", color1.getCieLuv(), color2.getCieLuv(), color3.getCieLuv()));
table.add(row);
row = new ArrayList<>();
row.addAll(Arrays.asList("LCH(uv)", color1.getLchuv(), color2.getLchuv(), color3.getLchuv()));
table.add(row);
row = new ArrayList<>();
row.addAll(Arrays.asList(message("Value"), color1.getColorValue() + "", color2.getColorValue() + "", color3.getColorValue() + ""));
table.add(row);
return table;
}
}
| 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/fxml/image/CropTools.java | released/MyBox/src/main/java/mara/mybox/fxml/image/CropTools.java | package mara.mybox.fxml.image;
import java.awt.image.BufferedImage;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.image.Image;
import javafx.scene.paint.Color;
import mara.mybox.image.tools.ColorConvertTools;
import mara.mybox.data.DoubleRectangle;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.FxTask;
/**
* @Author Mara
* @CreateDate 2018-11-13 12:38:14
* @License Apache License Version 2.0
*/
public class CropTools {
public static Image cropInsideFx(FxTask task, Image image, DoubleRectangle rect, Color bgColor) {
if (image == null || rect == null || rect.isEmpty() || bgColor == null) {
return image;
}
BufferedImage source = SwingFXUtils.fromFXImage(image, null);
BufferedImage target = mara.mybox.image.data.CropTools.cropInside(task,
source, rect, ColorConvertTools.converColor(bgColor));
if (target == null || (task != null && !task.isWorking())) {
return null;
}
Image newImage = SwingFXUtils.toFXImage(target, null);
return newImage;
}
public static Image cropOutsideFx(FxTask task, Image image, DoubleRectangle rect, Color bgColor) {
try {
if (image == null || rect == null || rect.isEmpty() || bgColor == null) {
return image;
}
BufferedImage source = SwingFXUtils.fromFXImage(image, null);
if (source == null) {
return image;
}
BufferedImage target = mara.mybox.image.data.CropTools.cropOutside(task,
source, rect, ColorConvertTools.converColor(bgColor));
if (target == null || (task != null && !task.isWorking())) {
return null;
}
Image newImage = SwingFXUtils.toFXImage(target, null);
return newImage;
} catch (Exception e) {
MyBoxLog.debug(e);
return image;
}
}
public static Image cropOutsideFx(FxTask task, Image image, DoubleRectangle rect) {
return cropOutsideFx(task, image, rect, Color.TRANSPARENT);
}
public static Image cropOutsideFx(FxTask task, Image image, double x1, double y1, double x2, double y2) {
return cropOutsideFx(task, image, DoubleRectangle.xy12(x1, y1, x2, y2), Color.TRANSPARENT);
}
}
| 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/fxml/image/ShapeDemos.java | released/MyBox/src/main/java/mara/mybox/fxml/image/ShapeDemos.java | package mara.mybox.fxml.image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.List;
import mara.mybox.controller.ControlImageText;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.FxTask;
import mara.mybox.image.data.PixelsBlend;
import mara.mybox.image.data.PixelsBlendFactory;
import mara.mybox.image.file.ImageFileWriters;
import mara.mybox.image.tools.ImageTextTools;
import mara.mybox.image.tools.ScaleTools;
import mara.mybox.tools.FileTmpTools;
import mara.mybox.value.AppPaths;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2023-12-1
* @License Apache License Version 2.0
*/
public class ShapeDemos {
public static void blendImage(FxTask currentTask, List<String> files, String op,
BufferedImage baseImage, BufferedImage overlay, int x, int y, File demoFile) {
if (currentTask == null || baseImage == null || overlay == null || files == null) {
return;
}
try {
BufferedImage baseBI = ScaleTools.demoImage(baseImage);
BufferedImage overlayBI = ScaleTools.demoImage(overlay);
String path = AppPaths.getGeneratedPath() + File.separator + "imageDemo"
+ File.separator + op;
if (demoFile != null) {
path += File.separator + demoFile.getName();
} else {
path += File.separator + "x";
}
PixelsBlend.ImagesBlendMode mode;
PixelsBlend blender;
BufferedImage blended;
String tmpFile;
for (String name : PixelsBlendFactory.blendModes()) {
if (currentTask == null || !currentTask.isWorking()) {
return;
}
mode = PixelsBlendFactory.blendMode(name);
blender = PixelsBlendFactory.create(mode).setBlendMode(mode);
blender.setWeight(1.0F).setBaseAbove(false)
.setBaseTransparentAs(PixelsBlend.TransparentAs.Another)
.setOverlayTransparentAs(PixelsBlend.TransparentAs.Another);
blended = PixelsBlend.blend(currentTask, overlayBI, baseBI, x, y, blender);
if (currentTask == null || !currentTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path, name + "-" + message("Opacity")
+ "1_" + message("Overlay") + "_" + message("BaseImage"), ".png").getAbsolutePath();
if (ImageFileWriters.writeImageFile(currentTask, blended, tmpFile)) {
files.add(tmpFile);
currentTask.setInfo(tmpFile);
}
if (currentTask == null || !currentTask.isWorking()) {
return;
}
blender.setWeight(0.5F).setBaseAbove(false).setBaseTransparentAs(PixelsBlend.TransparentAs.Another)
.setOverlayTransparentAs(PixelsBlend.TransparentAs.Another);
blended = PixelsBlend.blend(currentTask, overlayBI, baseBI, x, y, blender);
if (currentTask == null || !currentTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path, name + "-" + message("Opacity") + "0.5_"
+ message("Overlay") + "_" + message("BaseImage"), ".png").getAbsolutePath();
if (ImageFileWriters.writeImageFile(currentTask, blended, tmpFile)) {
files.add(tmpFile);
currentTask.setInfo(tmpFile);
}
if (currentTask == null || !currentTask.isWorking()) {
return;
}
blender.setWeight(0.5F).setBaseAbove(false).setBaseTransparentAs(PixelsBlend.TransparentAs.Transparent)
.setOverlayTransparentAs(PixelsBlend.TransparentAs.Another);
blended = PixelsBlend.blend(currentTask, overlayBI, baseBI, x, y, blender);
if (currentTask == null || !currentTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path, name + "-" + message("Opacity") + "0.5_"
+ message("Transparent") + "_" + message("BaseImage"), ".png").getAbsolutePath();
if (ImageFileWriters.writeImageFile(currentTask, blended, tmpFile)) {
files.add(tmpFile);
currentTask.setInfo(tmpFile);
}
if (currentTask == null || !currentTask.isWorking()) {
return;
}
blender.setWeight(0.5F).setBaseAbove(false).setBaseTransparentAs(PixelsBlend.TransparentAs.Transparent)
.setOverlayTransparentAs(PixelsBlend.TransparentAs.Another);
blended = PixelsBlend.blend(currentTask, overlayBI, baseBI, x, y, blender);
if (currentTask == null || !currentTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path, name + "-" + message("Opacity") + "0.5_"
+ message("Transparent") + "_" + message("Transparent"), ".png").getAbsolutePath();
if (ImageFileWriters.writeImageFile(currentTask, blended, tmpFile)) {
files.add(tmpFile);
currentTask.setInfo(tmpFile);
}
if (currentTask == null || !currentTask.isWorking()) {
return;
}
}
} catch (Exception e) {
if (currentTask != null) {
currentTask.setError(e.toString());
} else {
MyBoxLog.error(e.toString());
}
}
}
public static void text(FxTask currentTask, List<String> files,
BufferedImage baseImage, ControlImageText optionsController, File demoFile) {
if (currentTask == null || baseImage == null || optionsController == null || files == null) {
return;
}
try {
String path = AppPaths.getGeneratedPath() + File.separator + "imageDemo"
+ File.separator + message("Text");
if (demoFile != null) {
path += File.separator + demoFile.getName();
} else {
path += File.separator + "x";
}
PixelsBlend.ImagesBlendMode mode;
PixelsBlend blend;
BufferedImage blended;
String tmpFile;
for (String name : PixelsBlendFactory.blendModes()) {
if (currentTask == null || !currentTask.isWorking()) {
return;
}
mode = PixelsBlendFactory.blendMode(name);
blend = PixelsBlendFactory.create(mode).setBlendMode(mode);
blend.setWeight(1.0F).setBaseAbove(false).setBaseTransparentAs(
PixelsBlend.TransparentAs.Another).setOverlayTransparentAs(PixelsBlend.TransparentAs.Another);
blended = ImageTextTools.addText(currentTask, baseImage, optionsController.setBlend(blend));
if (currentTask == null || !currentTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path, name + "-" + message("Opacity")
+ "1_" + message("Overlay") + "_" + message("BaseImage"), ".png").getAbsolutePath();
if (ImageFileWriters.writeImageFile(currentTask, blended, tmpFile)) {
files.add(tmpFile);
currentTask.setInfo(tmpFile);
}
if (currentTask == null || !currentTask.isWorking()) {
return;
}
blend.setWeight(0.5F).setBaseAbove(false).setBaseTransparentAs(PixelsBlend.TransparentAs.Another)
.setOverlayTransparentAs(PixelsBlend.TransparentAs.Another);
blended = ImageTextTools.addText(currentTask, baseImage, optionsController.setBlend(blend));
if (currentTask == null || !currentTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path, name + "-" + message("Opacity") + "0.5_"
+ message("Overlay") + "_" + message("BaseImage"), ".png").getAbsolutePath();
if (ImageFileWriters.writeImageFile(currentTask, blended, tmpFile)) {
files.add(tmpFile);
currentTask.setInfo(tmpFile);
}
if (currentTask == null || !currentTask.isWorking()) {
return;
}
blend.setWeight(0.5F).setBaseAbove(false).setBaseTransparentAs(PixelsBlend.TransparentAs.Transparent)
.setOverlayTransparentAs(PixelsBlend.TransparentAs.Another);
blended = ImageTextTools.addText(currentTask, baseImage, optionsController.setBlend(blend));
if (currentTask == null || !currentTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path, name + "-" + message("Opacity") + "0.5_"
+ message("Transparent") + "_" + message("BaseImage"), ".png").getAbsolutePath();
if (ImageFileWriters.writeImageFile(currentTask, blended, tmpFile)) {
files.add(tmpFile);
currentTask.setInfo(tmpFile);
}
if (currentTask == null || !currentTask.isWorking()) {
return;
}
blend.setWeight(0.5F).setBaseAbove(false).setBaseTransparentAs(PixelsBlend.TransparentAs.Transparent)
.setOverlayTransparentAs(PixelsBlend.TransparentAs.Another);
blended = ImageTextTools.addText(currentTask, baseImage, optionsController.setBlend(blend));
if (currentTask == null || !currentTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path, name + "-" + message("Opacity") + "0.5_"
+ message("Transparent") + "_" + message("Transparent"), ".png").getAbsolutePath();
if (ImageFileWriters.writeImageFile(currentTask, blended, tmpFile)) {
files.add(tmpFile);
currentTask.setInfo(tmpFile);
}
if (currentTask == null || !currentTask.isWorking()) {
return;
}
}
} catch (Exception e) {
if (currentTask != null) {
currentTask.setError(e.toString());
} else {
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/fxml/image/ImageViewInfoTask.java | released/MyBox/src/main/java/mara/mybox/fxml/image/ImageViewInfoTask.java | package mara.mybox.fxml.image;
import javafx.application.Platform;
import javafx.scene.control.IndexedCell;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import mara.mybox.controller.BaseController;
import mara.mybox.fxml.FxTask;
import mara.mybox.image.data.ImageInformation;
import mara.mybox.value.AppVariables;
/**
* @Author Mara
* @CreateDate 2023-12-9
* @License Apache License Version 2.0
*/
public class ImageViewInfoTask<Void> extends FxTask<Void> {
private IndexedCell cell;
private ImageInformation item = null;
private ImageView view = null;
public ImageViewInfoTask(BaseController controller) {
this.controller = controller;
}
public ImageViewInfoTask<Void> setCell(IndexedCell cell) {
this.cell = cell;
return this;
}
public ImageViewInfoTask<Void> setItem(ImageInformation item) {
this.item = item;
return this;
}
public ImageViewInfoTask<Void> setView(ImageView view) {
this.view = view;
return this;
}
@Override
public void run() {
if (view == null || item == null) {
return;
}
int width = item.getWidth() > AppVariables.thumbnailWidth
? AppVariables.thumbnailWidth : (int) item.getWidth();
Image image = item.loadThumbnail(this, width);
if (image != null) {
Platform.runLater(new Runnable() {
@Override
public void run() {
view.setImage(image);
view.setRotate(item.getThumbnailRotation());
view.setFitWidth(width);
if (cell != null) {
cell.setGraphic(view);
}
}
});
}
}
}
| 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/fxml/image/PaletteTools.java | released/MyBox/src/main/java/mara/mybox/fxml/image/PaletteTools.java | package mara.mybox.fxml.image;
import java.io.File;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;
import javafx.event.ActionEvent;
import javafx.scene.control.MenuItem;
import javafx.scene.paint.Color;
import javafx.stage.Window;
import mara.mybox.image.tools.ColorConvertTools;
import mara.mybox.controller.BaseController;
import mara.mybox.controller.ColorPalettePopupController;
import mara.mybox.controller.ControlColorPaletteSelector;
import mara.mybox.controller.ControlColorSet;
import mara.mybox.db.DerbyBase;
import mara.mybox.db.data.ColorData;
import mara.mybox.db.data.ColorDataTools;
import mara.mybox.db.data.ColorPaletteName;
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.FxFileTools;
import mara.mybox.fxml.FxTask;
import mara.mybox.fxml.style.StyleData;
import mara.mybox.fxml.style.StyleData.StyleColor;
import mara.mybox.value.AppVariables;
import static mara.mybox.value.Colors.color;
import mara.mybox.value.Languages;
import static mara.mybox.value.Languages.message;
import mara.mybox.value.UserConfig;
/**
* @Author Mara
* @CreateDate 2021-11-22
* @License Apache License Version 2.0
*/
public class PaletteTools {
public static List<MenuItem> paletteExamplesMenu(BaseController parent) {
try {
List<MenuItem> menus = new ArrayList<>();
MenuItem menu;
menu = new MenuItem(defaultPaletteName(AppVariables.CurrentLangName));
menu.setOnAction((ActionEvent e) -> {
importPalette(parent, defaultPaletteName(AppVariables.CurrentLangName));
});
menus.add(menu);
menu = new MenuItem(message("WebCommonColors"));
menu.setOnAction((ActionEvent e) -> {
importPalette(parent, message("WebCommonColors"));
});
menus.add(menu);
menu = new MenuItem(message("ChineseTraditionalColors"));
menu.setOnAction((ActionEvent e) -> {
importPalette(parent, message("ChineseTraditionalColors"));
});
menus.add(menu);
menu = new MenuItem(message("JapaneseTraditionalColors"));
menu.setOnAction((ActionEvent e) -> {
importPalette(parent, message("JapaneseTraditionalColors"));
});
menus.add(menu);
menu = new MenuItem(message("HexaColors"));
menu.setOnAction((ActionEvent e) -> {
importPalette(parent, message("HexaColors"));
});
menus.add(menu);
menu = new MenuItem(message("ArtHuesWheel") + "-" + message("Colors12"));
menu.setOnAction((ActionEvent e) -> {
importPalette(parent, message("ArtHuesWheel") + "-" + message("Colors12"));
});
menus.add(menu);
menu = new MenuItem(message("ArtHuesWheel") + "-" + message("Colors24"));
menu.setOnAction((ActionEvent e) -> {
importPalette(parent, message("ArtHuesWheel") + "-" + message("Colors24"));
});
menus.add(menu);
menu = new MenuItem(message("ArtHuesWheel") + "-" + message("Colors360"));
menu.setOnAction((ActionEvent e) -> {
importPalette(parent, message("ArtHuesWheel") + "-" + message("Colors360"));
});
menus.add(menu);
menu = new MenuItem(message("OpticalHuesWheel") + "-" + message("Colors12"));
menu.setOnAction((ActionEvent e) -> {
importPalette(parent, message("OpticalHuesWheel") + "-" + message("Colors12"));
});
menus.add(menu);
menu = new MenuItem(message("OpticalHuesWheel") + "-" + message("Colors24"));
menu.setOnAction((ActionEvent e) -> {
importPalette(parent, message("OpticalHuesWheel") + "-" + message("Colors24"));
});
menus.add(menu);
menu = new MenuItem(message("OpticalHuesWheel") + "-" + message("Colors360"));
menu.setOnAction((ActionEvent e) -> {
importPalette(parent, message("OpticalHuesWheel") + "-" + message("Colors360"));
});
menus.add(menu);
menu = new MenuItem(message("ArtPaints"));
menu.setOnAction((ActionEvent e) -> {
importPalette(parent, message("ArtPaints"));
});
menus.add(menu);
menu = new MenuItem(message("MyBoxColors"));
menu.setOnAction((ActionEvent e) -> {
importPalette(parent, message("MyBoxColors"));
});
menus.add(menu);
menu = new MenuItem(message("GrayScale"));
menu.setOnAction((ActionEvent e) -> {
importPalette(parent, message("GrayScale"));
});
menus.add(menu);
return menus;
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
public static void importPalette(BaseController parent, String paletteName) {
if (parent == null || paletteName == null) {
return;
}
if (parent.getTask() != null) {
parent.getTask().cancel();
}
FxTask task = new FxTask<Void>(parent) {
@Override
protected boolean handle() {
List<ColorData> colors;
String fileLang = Languages.embedFileLang();
if (defaultPaletteName(AppVariables.CurrentLangName).equals(paletteName)) {
colors = defaultColors(AppVariables.CurrentLangName);
} else if (message("WebCommonColors").equals(paletteName)) {
File file = FxFileTools.getInternalFile("/data/examples/ColorsWeb.csv",
"data", "ColorsWeb.csv", true);
colors = ColorDataTools.readCSV(this, file, true);
} else if (message("ArtPaints").equals(paletteName)) {
File file = FxFileTools.getInternalFile("/data/examples/ColorsArtPaints.csv",
"data", "ColorsArtPaints.csv", true);
colors = ColorDataTools.readCSV(this, file, true);
} else if (message("ChineseTraditionalColors").equals(paletteName)) {
File file = FxFileTools.getInternalFile("/data/examples/ColorsChinese.csv",
"data", "ColorsChinese.csv", true);
colors = ColorDataTools.readCSV(this, file, true);
} else if (message("JapaneseTraditionalColors").equals(paletteName)) {
File file = FxFileTools.getInternalFile("/data/examples/ColorsJapanese.csv",
"data", "ColorsJapanese.csv", true);
colors = ColorDataTools.readCSV(this, file, true);
} else if (message("HexaColors").equals(paletteName)) {
File file = FxFileTools.getInternalFile("/data/examples/ColorsColorhexa.csv",
"data", "ColorsColorhexa.csv", true);
colors = ColorDataTools.readCSV(this, file, true);
} else if (message("MyBoxColors").equals(paletteName)) {
colors = new ArrayList<>();
for (StyleColor style : StyleData.StyleColor.values()) {
colors.add(new ColorData(color(style, true).getRGB(), message("MyBoxColor" + style.name() + "Dark")));
colors.add(new ColorData(color(style, false).getRGB(), message("MyBoxColor" + style.name() + "Light")));
}
} else if ((message("ArtHuesWheel") + "-" + message("Colors12")).equals(paletteName)) {
File file = FxFileTools.getInternalFile("/data/examples/ColorsRYB12_" + fileLang + ".csv",
"data", "ColorsRYB12_" + fileLang + ".csv", true);
colors = ColorDataTools.readCSV(this, file, true);
} else if ((message("ArtHuesWheel") + "-" + message("Colors360")).equals(paletteName)) {
colors = artHuesWheel(AppVariables.CurrentLangName, 1);
} else if ((message("OpticalHuesWheel") + "-" + message("Colors12")).equals(paletteName)) {
colors = opticalHuesWheel(AppVariables.CurrentLangName, 30);
} else if ((message("OpticalHuesWheel") + "-" + message("Colors24")).equals(paletteName)) {
colors = opticalHuesWheel(AppVariables.CurrentLangName, 15);
} else if ((message("OpticalHuesWheel") + "-" + message("Colors360")).equals(paletteName)) {
colors = opticalHuesWheel(AppVariables.CurrentLangName, 1);
} else if ((message("GrayScale")).equals(paletteName)) {
colors = greyScales(AppVariables.CurrentLangName);
} else {
File file = FxFileTools.getInternalFile("/data/examples/ColorsRYB24_" + fileLang + ".csv",
"data", "ColorsRYB24_" + fileLang + ".csv", true);
colors = ColorDataTools.readCSV(this, file, true);
}
if (colors == null || colors.isEmpty()) {
return false;
}
colors.addAll(speicalColors(AppVariables.CurrentLangName));
try (Connection conn = DerbyBase.getConnection()) {
ColorPaletteName palette = new TableColorPaletteName().findAndCreate(conn, paletteName);
if (palette == null) {
return false;
}
TableColorPalette tableColorPalette = new TableColorPalette();
tableColorPalette.clear(conn, palette.getCpnid());
tableColorPalette.write(conn, palette.getCpnid(), colors, true, false);
} catch (Exception e) {
error = e.toString();
return false;
}
return true;
}
@Override
protected void whenSucceeded() {
afterPaletteChanged(parent, paletteName);
}
};
parent.setTask(task);
parent.start(task);
}
public static void importFile(BaseController parent,
File file, String paletteName, boolean reOrder) {
if (parent == null || (parent.getTask() != null && !parent.getTask().isQuit())
|| file == null || !file.exists()) {
return;
}
FxTask task = new FxTask<Void>(parent) {
@Override
protected boolean handle() {
try (Connection conn = DerbyBase.getConnection()) {
List<ColorData> colors = ColorDataTools.readCSV(this, file, reOrder);
if (colors == null || colors.isEmpty()) {
return false;
}
if (paletteName == null || paletteName.isBlank()) {
new TableColor().writeData(conn, colors, true);
} else {
ColorPaletteName palette = new TableColorPaletteName().findAndCreate(conn, paletteName);
if (palette == null) {
return false;
}
new TableColorPalette().write(conn, palette.getCpnid(), colors, true, false);
}
} catch (Exception e) {
error = e.toString();
return false;
}
return true;
}
@Override
protected void whenSucceeded() {
afterPaletteChanged(parent, paletteName);
}
};
parent.setTask(task);
parent.start(task);
}
public static List<ColorData> opticalHuesWheel(String lang, int step) {
try {
List<ColorData> colors = new ArrayList<>();
for (int hue = 0; hue < 360; hue += step) {
Color color = Color.hsb(hue, 1f, 1f);
ColorData data = new ColorData(color).calculate();
data.setColorName(message(lang, "Hue") + ":" + Math.round(data.getColor().getHue()));
colors.add(data);
}
return colors;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public static List<ColorData> artHuesWheel(String lang, int step) {
try {
List<ColorData> colors = new ArrayList<>();
for (int angle = 0; angle < 360; angle += step) {
java.awt.Color color = ColorConvertTools.ryb2rgb(angle);
ColorData data = new ColorData(color.getRGB()).calculate();
data.setColorName(message(lang, "RYBAngle") + ":" + angle + " "
+ message(lang, "Hue") + ":" + Math.round(data.getColor().getHue()));
colors.add(data);
}
return colors;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public static List<ColorData> greyScales(String lang) {
try {
List<ColorData> colors = new ArrayList<>();
for (int v = 0; v < 256; v++) {
Color color = Color.gray(v / 255d);
ColorData data = new ColorData(color).calculate();
data.setColorName(message(lang, "Gray") + ":" + Math.round(color.getRed() * 255));
colors.add(data);
}
return colors;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public static List<ColorData> speicalColors(String lang) {
try {
List<ColorData> colors = new ArrayList<>();
colors.add(new ColorData(FxColorTools.color2rgba(Color.WHITE), message(lang, "White")).calculate());
colors.add(new ColorData(FxColorTools.color2rgba(Color.LIGHTGREY), message(lang, "LightGrey")).calculate());
colors.add(new ColorData(FxColorTools.color2rgba(Color.GREY), message(lang, "Grey")).calculate());
colors.add(new ColorData(FxColorTools.color2rgba(Color.BLACK), message(lang, "Black")).calculate());
colors.add(new ColorData(0, message(lang, "Transparent")).calculate());
return colors;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public static String defaultPaletteName(String lang) {
return message(lang, "DefaultPalette");
}
public static List<ColorData> defaultColors(String lang) {
try {
List<ColorData> colors = new ArrayList<>();
colors.add(new ColorData(FxColorTools.color2rgba(Color.RED), message(lang, "Red")).calculate());
colors.add(new ColorData(FxColorTools.color2rgba(Color.ORANGE), message(lang, "Orange")).calculate());
colors.add(new ColorData(FxColorTools.color2rgba(Color.YELLOW), message(lang, "Yellow")).calculate());
colors.add(new ColorData(FxColorTools.color2rgba(Color.GREENYELLOW), message(lang, "GreenYellow")).calculate());
colors.add(new ColorData(FxColorTools.color2rgba(Color.GREEN), message(lang, "Green")).calculate());
colors.add(new ColorData(FxColorTools.color2rgba(Color.LIGHTSEAGREEN), message(lang, "SeaGreen")).calculate());
colors.add(new ColorData(FxColorTools.color2rgba(Color.DODGERBLUE), message(lang, "Blue")).calculate());
colors.add(new ColorData(FxColorTools.color2rgba(Color.BLUE), message(lang, "MediumBlue")).calculate());
colors.add(new ColorData(FxColorTools.color2rgba(Color.PURPLE), message(lang, "Purple")).calculate());
colors.add(new ColorData(FxColorTools.color2rgba(Color.PINK), message(lang, "Pink")).calculate());
colors.add(new ColorData(FxColorTools.color2rgba(Color.DEEPSKYBLUE), message(lang, "SkyBlue")).calculate());
colors.add(new ColorData(FxColorTools.color2rgba(Color.GOLD), message(lang, "GoldColor")).calculate());
return colors;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public static ColorPaletteName defaultPalette(String lang, Connection conn) {
try {
if (conn == null) {
return null;
}
boolean ac = conn.getAutoCommit();
conn.setAutoCommit(true);
ColorPaletteName palette = new TableColorPaletteName().findAndCreate(conn, defaultPaletteName(lang));
if (palette == null) {
conn.setAutoCommit(ac);
return null;
}
conn.setAutoCommit(false);
long paletteid = palette.getCpnid();
TableColorPalette tableColorPalette = new TableColorPalette();
if (tableColorPalette.size(conn, paletteid) == 0) {
List<ColorData> colors = defaultColors(lang);
colors.addAll(speicalColors(lang));
tableColorPalette.write(conn, palette.getCpnid(), colors, true, false);
conn.commit();
}
conn.setAutoCommit(ac);
return palette;
} catch (Exception e) {
MyBoxLog.error(e);
return null;
}
}
public static void afterPaletteChanged(BaseController parent, String paletteName) {
if (paletteName == null || paletteName.isBlank()) {
return;
}
UserConfig.setString("ColorPalettePopupPalette", paletteName);
List<Window> windows = new ArrayList<>();
windows.addAll(Window.getWindows());
for (Window window : windows) {
Object object = window.getUserData();
if (object != null && object instanceof ColorPalettePopupController) {
try {
ColorPalettePopupController controller = (ColorPalettePopupController) object;
controller.loadColors();
break;
} catch (Exception e) {
}
}
}
if (parent == null) {
return;
}
if (parent instanceof ControlColorPaletteSelector) {
ControlColorPaletteSelector controller = (ControlColorPaletteSelector) parent;
UserConfig.setString(controller.getBaseName() + "Palette", paletteName);
controller.loadPalettes();
parent.popSuccessful();
} else if (parent instanceof ControlColorSet) {
ControlColorSet controller = (ControlColorSet) parent;
controller.showColorPalette();
}
}
}
| 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/fxml/image/ImageViewTools.java | released/MyBox/src/main/java/mara/mybox/fxml/image/ImageViewTools.java | package mara.mybox.fxml.image;
import javafx.geometry.Bounds;
import javafx.scene.control.ScrollPane;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.image.PixelReader;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import mara.mybox.data.DoublePoint;
import mara.mybox.fxml.LocateTools;
/**
* @Author Mara
* @CreateDate 2018-6-11
* @License Apache License Version 2.0
*/
public class ImageViewTools {
public static void imageSize(ScrollPane sPane, ImageView iView) {
try {
if (iView == null || iView.getImage() == null || sPane == null) {
return;
}
iView.setFitWidth(iView.getImage().getWidth());
iView.setFitHeight(iView.getImage().getHeight());
LocateTools.moveCenter(sPane, iView);
// MyBoxLog.console(iView.getImage().getWidth() + " " + iView.getImage().getHeight());
// iView.setLayoutY(10);
} catch (Exception e) {
// MyBoxLog.error(e.toString());
}
}
public static void paneSize(ScrollPane sPane, ImageView iView) {
try {
if (iView == null || iView.getImage() == null || sPane == null) {
return;
}
Bounds bounds = sPane.getBoundsInParent();
double ratioW = bounds.getWidth() / iView.getImage().getWidth();
double ratioH = bounds.getHeight() / iView.getImage().getHeight();
if (ratioW < ratioH) {
double w = bounds.getWidth() - 10;
iView.setFitHeight(iView.getImage().getHeight() * w / iView.getImage().getWidth());
iView.setFitWidth(w);
} else {
double h = bounds.getHeight() - 10;
iView.setFitWidth(iView.getImage().getWidth() * h / iView.getImage().getHeight());
iView.setFitHeight(h);
}
LocateTools.moveCenter(sPane, iView);
} catch (Exception e) {
// MyBoxLog.error(e.toString());
}
}
public static void zoomIn(ScrollPane sPane, ImageView iView, int xZoomStep, int yZoomStep) {
double currentWidth = iView.getFitWidth();
if (currentWidth == -1) {
currentWidth = iView.getImage().getWidth();
}
iView.setFitWidth(currentWidth + xZoomStep);
double currentHeight = iView.getFitHeight();
if (currentHeight == -1) {
currentHeight = iView.getImage().getHeight();
}
iView.setFitHeight(currentHeight + yZoomStep);
LocateTools.moveCenter(sPane, iView);
}
public static void zoomOut(ScrollPane sPane, ImageView iView, int xZoomStep, int yZoomStep) {
double currentWidth = iView.getFitWidth();
if (currentWidth == -1) {
currentWidth = iView.getImage().getWidth();
}
if (currentWidth <= xZoomStep) {
return;
}
iView.setFitWidth(currentWidth - xZoomStep);
double currentHeight = iView.getFitHeight();
if (currentHeight == -1) {
currentHeight = iView.getImage().getHeight();
}
if (currentHeight <= yZoomStep) {
return;
}
iView.setFitHeight(currentHeight - yZoomStep);
LocateTools.moveCenter(sPane, iView);
}
public static DoublePoint getImageXY(MouseEvent event, ImageView view) {
if (event == null || view.getImage() == null) {
return null;
}
double offsetX = event.getX() - view.getLayoutX() - view.getX();
double offsetY = event.getY() - view.getLayoutY() - view.getY();
// if (offsetX < 0 || offsetX >= view.getBoundsInParent().getWidth()
// || offsetY < 0 || offsetY >= view.getBoundsInParent().getHeight()) {
// return null;
// }
double x = offsetX * view.getImage().getWidth() / view.getBoundsInParent().getWidth();
double y = offsetY * view.getImage().getHeight() / view.getBoundsInParent().getHeight();
return new DoublePoint(x, y);
}
public static Color viewPixel(MouseEvent event, ImageView view) {
DoublePoint p = ImageViewTools.getImageXY(event, view);
if (p == null) {
return null;
}
return viewPixel(p, view);
}
public static Color viewPixel(DoublePoint p, ImageView view) {
return imagePixel(p, view.getImage());
}
public static Color imagePixel(DoublePoint p, Image image) {
if (p == null || image == null) {
return null;
}
int x = (int) p.getX();
int y = (int) p.getY();
if (x >= 0 && x < image.getWidth()
&& y >= 0 && y < image.getHeight()) {
PixelReader pixelReader = image.getPixelReader();
return pixelReader.getColor(x, y);
} else {
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/fxml/image/ColorDemos.java | released/MyBox/src/main/java/mara/mybox/fxml/image/ColorDemos.java | package mara.mybox.fxml.image;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.image.Image;
import mara.mybox.color.ColorMatch;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.FxTask;
import mara.mybox.image.data.ImageBinary;
import mara.mybox.image.data.ImageQuantization;
import mara.mybox.image.data.ImageQuantization.QuantizationAlgorithm;
import mara.mybox.image.data.ImageQuantizationFactory;
import mara.mybox.image.data.ImageScope;
import mara.mybox.image.data.PixelsOperation;
import mara.mybox.image.data.PixelsOperationFactory;
import mara.mybox.image.file.ImageFileWriters;
import mara.mybox.tools.FileTmpTools;
import mara.mybox.value.AppPaths;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2023-12-1
* @License Apache License Version 2.0
*/
public class ColorDemos {
public static void replaceColor(FxTask demoTask, List<String> files,
PixelsOperation pixelsOperation, File demoFile) {
if (demoTask == null || pixelsOperation == null || files == null) {
return;
}
try {
pixelsOperation.setTask(demoTask);
String path = AppPaths.getGeneratedPath() + File.separator + "imageDemo"
+ File.separator + message("ReplaceColor");
if (demoFile != null) {
path += File.separator + demoFile.getName();
} else {
path += File.separator + "x";
}
BufferedImage bufferedImage = pixelsOperation
.setBoolPara1(true).setBoolPara2(false).setBoolPara3(false)
.start();
if (!demoTask.isWorking()) {
return;
}
String tmpFile = FileTmpTools.getPathTempFile(path, message("Hue"), ".png").getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, "png", tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
if (!demoTask.isWorking()) {
return;
}
bufferedImage = pixelsOperation
.setBoolPara1(false).setBoolPara2(true).setBoolPara3(false).start();
if (!demoTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path, message("Saturation"), ".png").getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, "png", tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
if (!demoTask.isWorking()) {
return;
}
bufferedImage = pixelsOperation
.setBoolPara1(false).setBoolPara2(false).setBoolPara3(true)
.start();
if (!demoTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path, message("Brightness"), ".png").getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, "png", tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
if (!demoTask.isWorking()) {
return;
}
bufferedImage = pixelsOperation
.setBoolPara1(false).setBoolPara2(true).setBoolPara3(false)
.start();
if (!demoTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path, message("All"), ".png").getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, "png", tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
} catch (Exception e) {
if (demoTask != null) {
demoTask.setError(e.toString());
} else {
MyBoxLog.error(e.toString());
}
}
}
public static void adjustColor(FxTask demoTask, List<String> files,
BufferedImage demoImage, ImageScope scope, File demoFile) {
try {
String path = AppPaths.getGeneratedPath() + File.separator + "imageDemo"
+ File.separator + message("AdjustColor");
if (demoFile != null) {
path += File.separator + demoFile.getName();
} else {
path += File.separator + "x";
}
PixelsOperation pixelsOperation;
BufferedImage bufferedImage;
String tmpFile;
pixelsOperation = PixelsOperationFactory.create(demoImage,
scope, PixelsOperation.OperationType.Color, PixelsOperation.ColorActionType.Set);
pixelsOperation.setColorPara1(Color.PINK)
.setBoolPara1(true).setBoolPara2(false).setBoolPara3(false)
.setTask(demoTask);
bufferedImage = pixelsOperation.start();
tmpFile = FileTmpTools.getPathTempFile(path, message("Color") + "_" + message("Filter"), ".png")
.getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, "png", tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
if (!demoTask.isWorking()) {
return;
}
pixelsOperation = PixelsOperationFactory.create(demoImage,
scope, PixelsOperation.OperationType.Brightness, PixelsOperation.ColorActionType.Increase)
.setFloatPara1(0.5f).setTask(demoTask);
bufferedImage = pixelsOperation.start();
tmpFile = FileTmpTools.getPathTempFile(path, message("Brightness") + "_" + message("Increase"), ".png")
.getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, "png", tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
if (!demoTask.isWorking()) {
return;
}
pixelsOperation = PixelsOperationFactory.create(demoImage,
scope, PixelsOperation.OperationType.Hue, PixelsOperation.ColorActionType.Decrease)
.setFloatPara1(0.3f).setTask(demoTask);
bufferedImage = pixelsOperation.start();
tmpFile = FileTmpTools.getPathTempFile(path, message("Hue") + "_" + message("Decrease"), ".png")
.getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, "png", tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
if (!demoTask.isWorking()) {
return;
}
pixelsOperation = PixelsOperationFactory.create(demoImage,
scope, PixelsOperation.OperationType.Saturation, PixelsOperation.ColorActionType.Increase)
.setFloatPara1(0.5f).setTask(demoTask);
bufferedImage = pixelsOperation.start();
tmpFile = FileTmpTools.getPathTempFile(path, message("Saturation") + "_" + message("Increase"), ".png")
.getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, "png", tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
if (!demoTask.isWorking()) {
return;
}
pixelsOperation = PixelsOperationFactory.create(demoImage,
scope, PixelsOperation.OperationType.Opacity, PixelsOperation.ColorActionType.Decrease)
.setIntPara1(128).setTask(demoTask);
bufferedImage = pixelsOperation.start();
tmpFile = FileTmpTools.getPathTempFile(path, message("Opacity") + "_" + message("Decrease"), ".png")
.getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, "png", tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
if (!demoTask.isWorking()) {
return;
}
pixelsOperation = PixelsOperationFactory.create(demoImage,
scope, PixelsOperation.OperationType.Yellow, PixelsOperation.ColorActionType.Increase)
.setIntPara1(60).setTask(demoTask);
bufferedImage = pixelsOperation.start();
tmpFile = FileTmpTools.getPathTempFile(path, message("Yellow") + "_" + message("Increase"), ".png")
.getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, "png", tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
if (!demoTask.isWorking()) {
return;
}
pixelsOperation = PixelsOperationFactory.create(demoImage,
scope, PixelsOperation.OperationType.Magenta, PixelsOperation.ColorActionType.Decrease)
.setIntPara1(60).setTask(demoTask);
bufferedImage = pixelsOperation.start();
tmpFile = FileTmpTools.getPathTempFile(path, message("Magenta") + "_" + message("Decrease"), ".png")
.getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, "png", tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
if (!demoTask.isWorking()) {
return;
}
adjustColor(demoTask, files, demoImage, scope, path,
PixelsOperation.OperationType.RGB, PixelsOperation.ColorActionType.Invert,
message("RGB") + "_" + message("Invert"));
if (!demoTask.isWorking()) {
return;
}
adjustColor(demoTask, files, demoImage, scope, path,
PixelsOperation.OperationType.Red, PixelsOperation.ColorActionType.Invert,
message("Red") + "_" + message("Invert"));
if (!demoTask.isWorking()) {
return;
}
adjustColor(demoTask, files, demoImage, scope, path,
PixelsOperation.OperationType.Green, PixelsOperation.ColorActionType.Invert,
message("Green") + "_" + message("Invert"));
if (!demoTask.isWorking()) {
return;
}
adjustColor(demoTask, files, demoImage, scope, path,
PixelsOperation.OperationType.Blue, PixelsOperation.ColorActionType.Invert,
message("Blue") + "_" + message("Invert"));
if (!demoTask.isWorking()) {
return;
}
adjustColor(demoTask, files, demoImage, scope, path,
PixelsOperation.OperationType.Yellow, PixelsOperation.ColorActionType.Invert,
message("Yellow") + "_" + message("Invert"));
if (!demoTask.isWorking()) {
return;
}
adjustColor(demoTask, files, demoImage, scope, path,
PixelsOperation.OperationType.Magenta, PixelsOperation.ColorActionType.Invert,
message("Magenta") + "_" + message("Invert"));
if (!demoTask.isWorking()) {
return;
}
adjustColor(demoTask, files, demoImage, scope, path,
PixelsOperation.OperationType.Cyan, PixelsOperation.ColorActionType.Invert,
message("Cyan") + "_" + message("Invert"));
if (!demoTask.isWorking()) {
return;
}
adjustColor(demoTask, files, demoImage, scope, path,
PixelsOperation.OperationType.Red, PixelsOperation.ColorActionType.Filter,
message("Red") + "_" + message("Filter"));
if (!demoTask.isWorking()) {
return;
}
adjustColor(demoTask, files, demoImage, scope, path,
PixelsOperation.OperationType.Green, PixelsOperation.ColorActionType.Filter,
message("Green") + "_" + message("Filter"));
if (!demoTask.isWorking()) {
return;
}
adjustColor(demoTask, files, demoImage, scope, path,
PixelsOperation.OperationType.Blue, PixelsOperation.ColorActionType.Filter,
message("Blue") + "_" + message("Filter"));
if (!demoTask.isWorking()) {
return;
}
adjustColor(demoTask, files, demoImage, scope, path,
PixelsOperation.OperationType.Yellow, PixelsOperation.ColorActionType.Filter,
message("Yellow") + "_" + message("Filter"));
if (!demoTask.isWorking()) {
return;
}
adjustColor(demoTask, files, demoImage, scope, path,
PixelsOperation.OperationType.Magenta, PixelsOperation.ColorActionType.Filter,
message("Magenta") + "_" + message("Filter"));
if (!demoTask.isWorking()) {
return;
}
adjustColor(demoTask, files, demoImage, scope, path,
PixelsOperation.OperationType.Cyan, PixelsOperation.ColorActionType.Filter,
message("Cyan") + "_" + message("Filter"));
} catch (Exception e) {
MyBoxLog.error(e.toString());
}
}
public static void adjustColor(FxTask demoTask, List<String> files,
BufferedImage demoImage, ImageScope scope, String path,
PixelsOperation.OperationType type,
PixelsOperation.ColorActionType action, String name) {
try {
PixelsOperation pixelsOperation = PixelsOperationFactory.create(
demoImage, scope, type, action)
.setTask(demoTask);
BufferedImage bufferedImage = pixelsOperation.start();
String tmpFile = FileTmpTools.getPathTempFile(path, name, ".png").getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, "png", tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
} catch (Exception e) {
if (demoTask != null) {
demoTask.setError(e.toString());
} else {
MyBoxLog.error(e.toString());
}
}
}
public static void blendColor(FxTask currentTask, List<String> files, BufferedImage baseImage,
javafx.scene.paint.Color color, File demoFile) {
if (currentTask == null || baseImage == null || files == null) {
return;
}
if (color == null) {
color = javafx.scene.paint.Color.PINK;
}
Image overlay = FxImageTools.createImage(
(int) (baseImage.getWidth() * 7 / 8), (int) (baseImage.getHeight() * 7 / 8),
color);
int x = (int) (baseImage.getWidth() - overlay.getWidth()) / 2;
int y = (int) (baseImage.getHeight() - overlay.getHeight()) / 2;
ShapeDemos.blendImage(currentTask, files, message("BlendColor"),
baseImage, SwingFXUtils.fromFXImage(overlay, null), x, y, demoFile);
}
public static void blackWhite(FxTask demoTask, List<String> files,
ImageBinary binary, File demoFile) {
if (demoTask == null || binary == null || files == null) {
return;
}
try {
String path = AppPaths.getGeneratedPath() + File.separator + "imageDemo"
+ File.separator + message("BlackOrWhite");
if (demoFile != null) {
path += File.separator + demoFile.getName();
} else {
path += File.separator + "x";
}
binary.setTask(demoTask);
int threshold = binary.getIntPara1();
BufferedImage bufferedImage = binary
.setAlgorithm(ImageBinary.BinaryAlgorithm.Default)
.setIsDithering(true)
.start();
String tmpFile = FileTmpTools.getPathTempFile(path, message("Default")
+ "_" + message("Dithering"), ".png").getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, "png", tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
if (demoTask == null || !demoTask.isWorking()) {
return;
}
bufferedImage = binary
.setAlgorithm(ImageBinary.BinaryAlgorithm.Default)
.setIsDithering(false)
.start();
tmpFile = FileTmpTools.getPathTempFile(path, message("Default"), ".png").getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, "png", tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
if (demoTask == null || !demoTask.isWorking()) {
return;
}
List<Integer> inputs = new ArrayList<>();
inputs.addAll(Arrays.asList(64, 96, 112, 128, 144, 160, 176, 198, 228));
if (threshold > 0 && threshold < 255 && !inputs.contains(threshold)) {
inputs.add(threshold);
}
for (int v : inputs) {
if (demoTask == null || !demoTask.isWorking()) {
return;
}
bufferedImage = binary
.setAlgorithm(ImageBinary.BinaryAlgorithm.Threshold)
.setIntPara1(v)
.setIsDithering(true)
.setTask(demoTask)
.start();
tmpFile = FileTmpTools.getPathTempFile(path, message("Threshold") + v
+ "_" + message("Dithering"), ".png").getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, "png", tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
bufferedImage = binary
.setAlgorithm(ImageBinary.BinaryAlgorithm.Threshold)
.setIntPara1(v)
.setIsDithering(false)
.setTask(demoTask)
.start();
tmpFile = FileTmpTools.getPathTempFile(path, message("Threshold") + v, ".png").getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, "png", tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
}
int otsu = ImageBinary.threshold(demoTask, binary.getImage());
bufferedImage = binary
.setAlgorithm(ImageBinary.BinaryAlgorithm.Threshold)
.setIntPara1(otsu)
.setIsDithering(true)
.setTask(demoTask)
.start();
tmpFile = FileTmpTools.getPathTempFile(path, message("OTSU")
+ otsu + "_" + message("Dithering"), ".png").getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, "png", tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
if (demoTask == null || !demoTask.isWorking()) {
return;
}
bufferedImage = binary
.setAlgorithm(ImageBinary.BinaryAlgorithm.Threshold)
.setIntPara1(otsu)
.setIsDithering(false)
.setTask(demoTask)
.start();
tmpFile = FileTmpTools.getPathTempFile(path, message("OTSU") + otsu, ".png").getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, "png", tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
} catch (Exception e) {
MyBoxLog.error(e.toString());
}
}
public static void sepia(FxTask demoTask, List<String> files,
PixelsOperation pixelsOperation, File demoFile) {
if (demoTask == null || pixelsOperation == null || files == null) {
return;
}
try {
String path = AppPaths.getGeneratedPath() + File.separator + "imageDemo"
+ File.separator + message("Sepia");
if (demoFile != null) {
path += File.separator + demoFile.getName();
} else {
path += File.separator + "x";
}
pixelsOperation.setTask(demoTask);
List<Integer> values = Arrays.asList(60, 80, 20, 50, 10, 5, 100, 15, 20);
for (int v : values) {
if (demoTask == null || !demoTask.isWorking()) {
return;
}
BufferedImage bufferedImage = pixelsOperation.setIntPara1(v).start();
if (demoTask == null || !demoTask.isWorking()) {
return;
}
String tmpFile = FileTmpTools.getPathTempFile(path, message("Intensity") + v, ".png")
.getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
}
} catch (Exception e) {
MyBoxLog.error(e.toString());
}
}
public static void reduceColors(FxTask demoTask, List<String> files,
BufferedImage demoImage, File demoFile) {
if (demoTask == null || demoImage == null || files == null) {
return;
}
try {
String path = AppPaths.getGeneratedPath() + File.separator + "imageDemo"
+ File.separator + message("ReduceColors");
if (demoFile != null) {
path += File.separator + demoFile.getName();
} else {
path += File.separator + "x";
}
ImageQuantization quantization;
BufferedImage bufferedImage;
String tmpFile;
ColorMatch colorMatch = new ColorMatch();
for (QuantizationAlgorithm a : QuantizationAlgorithm.values()) {
if (demoTask == null || !demoTask.isWorking()) {
return;
}
quantization = ImageQuantizationFactory.create(demoTask, demoImage, null,
a, 8, 256, 1, 1, 1, false, true, true, colorMatch, 10000);
bufferedImage = quantization.setTask(demoTask).start();
if (demoTask == null || !demoTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path,
message(quantization.getAlgorithm().name()) + "_" + message("Colors") + "8", ".png")
.getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
if (demoTask == null || !demoTask.isWorking()) {
return;
}
quantization = ImageQuantizationFactory.create(demoTask, demoImage, null,
a, 27, 1024, 1, 1, 1, false, true, true, colorMatch, 10000);
bufferedImage = quantization.setTask(demoTask).start();
if (demoTask == null || !demoTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path,
message(quantization.getAlgorithm().name()) + "_" + message("Colors") + "27", ".png")
.getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
if (demoTask == null || !demoTask.isWorking()) {
return;
}
quantization = ImageQuantizationFactory.create(demoTask, demoImage, null,
a, 256, 1024, 2, 4, 3, false, true, true, colorMatch, 10000);
bufferedImage = quantization.setTask(demoTask).start();
if (demoTask == null || !demoTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path,
message(quantization.getAlgorithm().name()) + "_" + message("Colors") + "256", ".png")
.getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
}
} catch (Exception e) {
MyBoxLog.error(e.toString());
}
}
public static void thresholding(FxTask demoTask, List<String> files,
BufferedImage demoImage, File demoFile) {
if (demoTask == null || demoImage == null || files == null) {
return;
}
try {
String path = AppPaths.getGeneratedPath() + File.separator + "imageDemo"
+ File.separator + message("Thresholding");
if (demoFile != null) {
path += File.separator + demoFile.getName();
} else {
path += File.separator + "x";
}
PixelsOperation op = PixelsOperationFactory.create(
demoImage, null, PixelsOperation.OperationType.Thresholding)
.setIsDithering(false).setTask(demoTask);
BufferedImage bufferedImage = op.setIntPara1(128).setIntPara2(255).setIntPara3(0).start();
if (demoTask == null || !demoTask.isWorking()) {
return;
}
String tmpFile = FileTmpTools.getPathTempFile(path, message("Threshold") + "128_"
+ message("BigValue") + "255_" + message("SmallValue") + "0", ".png")
.getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
if (demoTask == null || !demoTask.isWorking()) {
return;
}
bufferedImage = op.setIntPara1(60).setIntPara2(190).setIntPara3(10).start();
if (demoTask == null || !demoTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path, message("Threshold") + "60_"
+ message("BigValue") + "190_" + message("SmallValue") + "10", ".png")
.getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
if (demoTask == null || !demoTask.isWorking()) {
return;
}
bufferedImage = op.setIntPara1(200).setIntPara2(255).setIntPara3(60).start();
if (demoTask == null || !demoTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path, message("Threshold") + "200_"
+ message("BigValue") + "255_" + message("SmallValue") + "60", ".png")
.getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
if (demoTask == null || !demoTask.isWorking()) {
return;
}
bufferedImage = op.setIntPara1(160).setIntPara2(225).setIntPara3(0).start();
if (demoTask == null || !demoTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path, message("Threshold") + "160_"
+ message("BigValue") + "225_" + message("SmallValue") + "0", ".png")
.getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
} 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/fxml/image/ScopeTools.java | released/MyBox/src/main/java/mara/mybox/fxml/image/ScopeTools.java | package mara.mybox.fxml.image;
import java.awt.Color;
import javafx.scene.image.Image;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.FxTask;
import mara.mybox.image.data.ImageScope;
import mara.mybox.image.data.PixelsOperation;
import mara.mybox.image.data.PixelsOperationFactory;
import mara.mybox.image.tools.ColorConvertTools;
/**
* @Author Mara
* @CreateDate 2018-11-13 12:38:14
* @License Apache License Version 2.0
*/
public class ScopeTools {
public static Image selectedScope(FxTask task, Image srcImage, ImageScope scope, Color bgColor,
boolean cutMargins, boolean exclude, boolean ignoreTransparent) {
try {
if (scope == null) {
return srcImage;
} else {
PixelsOperation pixelsOperation = PixelsOperationFactory.createFX(srcImage, scope,
PixelsOperation.OperationType.SelectPixels)
.setColorPara1(bgColor)
.setExcludeScope(exclude)
.setSkipTransparent(ignoreTransparent)
.setTask(task);
Image scopeImage = pixelsOperation.startFx();
if (cutMargins) {
return MarginTools.cutMarginsByColor(task, scopeImage,
ColorConvertTools.converColor(bgColor),
0, true, true, true, true);
} else {
return scopeImage;
}
}
} catch (Exception e) {
MyBoxLog.debug(e);
return null;
}
}
public static Image maskScope(FxTask task, Image srcImage, ImageScope scope,
boolean exclude, boolean ignoreTransparent) {
try {
PixelsOperation pixelsOperation = PixelsOperationFactory.createFX(
srcImage, scope,
PixelsOperation.OperationType.ShowScope)
.setExcludeScope(exclude)
.setSkipTransparent(ignoreTransparent)
.setTask(task);
return pixelsOperation.startFx();
} catch (Exception e) {
MyBoxLog.debug(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/fxml/image/PixelDemos.java | released/MyBox/src/main/java/mara/mybox/fxml/image/PixelDemos.java | package mara.mybox.fxml.image;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import mara.mybox.db.data.ConvolutionKernel;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.FxTask;
import mara.mybox.image.data.ImageContrast;
import mara.mybox.image.data.ImageContrast.ContrastAlgorithm;
import mara.mybox.image.data.ImageConvolution;
import mara.mybox.image.data.ImageMosaic;
import mara.mybox.image.data.ImageMosaic.MosaicType;
import mara.mybox.image.file.ImageFileWriters;
import mara.mybox.image.tools.BufferedImageTools;
import mara.mybox.image.tools.BufferedImageTools.Direction;
import mara.mybox.image.tools.ColorConvertTools;
import mara.mybox.tools.FileTmpTools;
import mara.mybox.value.AppPaths;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2023-12-1
* @License Apache License Version 2.0
*/
public class PixelDemos {
public static void mosaic(FxTask demoTask, List<String> files, BufferedImage demoImage,
MosaicType type, File demoFile) {
if (demoTask == null || demoImage == null || files == null) {
return;
}
try {
String path = AppPaths.getGeneratedPath() + File.separator + "imageDemo"
+ File.separator + message("Mosaic");
if (demoFile != null) {
path += File.separator + demoFile.getName();
} else {
path += File.separator + "x";
}
ImageMosaic mosaic = ImageMosaic.create().setType(type);
mosaic.setImage(demoImage).setTask(demoTask);
List<Integer> values = Arrays.asList(1, 3, 5, 8, 10, 15, 20, 25, 30, 50, 60, 80, 100);
BufferedImage bufferedImage;
String tmpFile;
for (int v : values) {
if (demoTask == null || !demoTask.isWorking()) {
return;
}
bufferedImage = mosaic.setIntensity(v).start();
if (demoTask == null || !demoTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path, message("Intensity") + "_" + v, ".png")
.getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
}
} catch (Exception e) {
MyBoxLog.error(e.toString());
}
}
public static void shadow(FxTask demoTask, List<String> files, BufferedImage demoImage,
Color color, File demoFile) {
if (demoTask == null || color == null || files == null) {
return;
}
try {
String path = AppPaths.getGeneratedPath() + File.separator + "imageDemo"
+ File.separator + message("Shadow");
if (demoFile != null) {
path += File.separator + demoFile.getName();
} else {
path += File.separator + "x";
}
int offsetX = Math.max(30, demoImage.getWidth() / 20);
int offsetY = Math.max(30, demoImage.getHeight() / 20);
shadow(demoTask, files, demoImage, path, color, offsetX, offsetY, true);
shadow(demoTask, files, demoImage, path, color, offsetX, -offsetY, true);
shadow(demoTask, files, demoImage, path, color, -offsetX, offsetY, true);
shadow(demoTask, files, demoImage, path, color, -offsetX, -offsetY, true);
shadow(demoTask, files, demoImage, path, color, offsetX, offsetY, false);
shadow(demoTask, files, demoImage, path, color, offsetX, -offsetY, false);
shadow(demoTask, files, demoImage, path, color, -offsetX, offsetY, false);
shadow(demoTask, files, demoImage, path, color, -offsetX, -offsetY, false);
} catch (Exception e) {
if (demoTask != null) {
demoTask.setError(e.toString());
} else {
MyBoxLog.error(e.toString());
}
}
}
public static void shadow(FxTask demoTask, List<String> files, BufferedImage demoImage,
String path, Color color, int offsetX, int offsetY, boolean blur) {
try {
BufferedImage bufferedImage = BufferedImageTools.addShadow(demoTask, demoImage,
-offsetX, -offsetY, color, blur);
String tmpFile = FileTmpTools.getPathTempFile(path,
ColorConvertTools.color2css(color)
+ "_x-" + offsetX + "_y-" + offsetY + (blur ? ("_" + message("Blur")) : ""),
".png")
.getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, "png", tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
} catch (Exception e) {
if (demoTask != null) {
demoTask.setError(e.toString());
} else {
MyBoxLog.error(e.toString());
}
}
}
public static void smooth(FxTask demoTask, List<String> files,
ImageConvolution convolution, File demoFile) {
if (demoTask == null || convolution == null || files == null) {
return;
}
try {
String path = AppPaths.getGeneratedPath() + File.separator + "imageDemo"
+ File.separator + message("Smooth");
if (demoFile != null) {
path += File.separator + demoFile.getName();
} else {
path += File.separator + "x";
}
List<Integer> values = Arrays.asList(1, 2, 3, 4);
BufferedImage bufferedImage;
String tmpFile;
for (int v : values) {
if (demoTask == null || !demoTask.isWorking()) {
return;
}
bufferedImage = convolution
.setKernel(ConvolutionKernel.makeAverageBlur(v))
.setTask(demoTask)
.start();
if (demoTask == null || !demoTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path,
message("AverageBlur") + "_" + message("Intensity") + v, ".png")
.getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
if (demoTask == null || !demoTask.isWorking()) {
return;
}
bufferedImage = convolution
.setKernel(ConvolutionKernel.makeGaussBlur(v))
.setTask(demoTask)
.start();
if (demoTask == null || !demoTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path,
message("GaussianBlur") + "_" + message("Intensity") + v, ".png")
.getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
if (demoTask == null || !demoTask.isWorking()) {
return;
}
bufferedImage = convolution
.setKernel(ConvolutionKernel.makeMotionBlur(v))
.setTask(demoTask)
.start();
if (demoTask == null || !demoTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path,
message("MotionBlur") + "_" + message("Intensity") + v, ".png")
.getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
}
} catch (Exception e) {
if (demoTask != null) {
demoTask.setError(e.toString());
} else {
MyBoxLog.error(e.toString());
}
}
}
public static void sharpen(FxTask demoTask, List<String> files,
ImageConvolution convolution, File demoFile) {
if (demoTask == null || convolution == null || files == null) {
return;
}
try {
String path = AppPaths.getGeneratedPath() + File.separator + "imageDemo"
+ File.separator + message("Sharpen");
if (demoFile != null) {
path += File.separator + demoFile.getName();
} else {
path += File.separator + "x";
}
BufferedImage bufferedImage = convolution
.setKernel(ConvolutionKernel.makeUnsharpMasking(1))
.setTask(demoTask)
.start();
if (!demoTask.isWorking()) {
return;
}
String tmpFile = FileTmpTools.getPathTempFile(path, message("UnsharpMasking") + "_1", ".png").getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, "png", tmpFile)) {
files.add(tmpFile);
if (!demoTask.isWorking()) {
return;
}
demoTask.setInfo(tmpFile);
}
bufferedImage = convolution
.setKernel(ConvolutionKernel.makeUnsharpMasking(2))
.setTask(demoTask)
.start();
if (!demoTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path, message("UnsharpMasking") + "_2", ".png").getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, "png", tmpFile)) {
files.add(tmpFile);
if (!demoTask.isWorking()) {
return;
}
demoTask.setInfo(tmpFile);
}
bufferedImage = convolution
.setKernel(ConvolutionKernel.makeUnsharpMasking(2))
.setTask(demoTask)
.start();
if (!demoTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path, message("UnsharpMasking") + "_3", ".png").getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, "png", tmpFile)) {
files.add(tmpFile);
if (!demoTask.isWorking()) {
return;
}
demoTask.setInfo(tmpFile);
}
bufferedImage = convolution
.setKernel(ConvolutionKernel.makeUnsharpMasking(2))
.setTask(demoTask)
.start();
if (!demoTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path, message("UnsharpMasking") + "_4", ".png").getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, "png", tmpFile)) {
files.add(tmpFile);
if (!demoTask.isWorking()) {
return;
}
demoTask.setInfo(tmpFile);
}
bufferedImage = convolution
.setKernel(ConvolutionKernel.MakeSharpenEightNeighborLaplace())
.setTask(demoTask)
.start();
if (!demoTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path, message("EightNeighborLaplace"), ".png").getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, "png", tmpFile)) {
files.add(tmpFile);
if (!demoTask.isWorking()) {
return;
}
demoTask.setInfo(tmpFile);
}
bufferedImage = convolution
.setKernel(ConvolutionKernel.MakeSharpenFourNeighborLaplace())
.setTask(demoTask)
.start();
if (!demoTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path, message("FourNeighborLaplace"), ".png").getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, "png", tmpFile)) {
files.add(tmpFile);
if (!demoTask.isWorking()) {
return;
}
demoTask.setInfo(tmpFile);
}
} catch (Exception e) {
if (demoTask != null) {
demoTask.setError(e.toString());
} else {
MyBoxLog.error(e.toString());
}
}
}
public static void contrast(FxTask demoTask, List<String> files,
BufferedImage demoImage, File demoFile) {
if (demoTask == null || demoImage == null || files == null) {
return;
}
try {
String path = AppPaths.getGeneratedPath() + File.separator + "imageDemo"
+ File.separator + message("Contrast");
if (demoFile != null) {
path += File.separator + demoFile.getName();
} else {
path += File.separator + "x";
}
ImageContrast contrast = new ImageContrast();
contrast.setImage(demoImage).setTask(demoTask);
BufferedImage bufferedImage = contrast
.setAlgorithm(ContrastAlgorithm.SaturationHistogramEqualization)
.start();
if (demoTask == null || !demoTask.isWorking()) {
return;
}
String tmpFile = FileTmpTools.getPathTempFile(path,
message("Saturation") + "-" + message("HistogramEqualization"), ".png")
.getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, "png", tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
if (demoTask == null || !demoTask.isWorking()) {
return;
}
bufferedImage = contrast
.setAlgorithm(ContrastAlgorithm.BrightnessHistogramEqualization)
.start();
if (demoTask == null || !demoTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path,
message("Brightness") + "-" + message("HistogramEqualization"), ".png").getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, "png", tmpFile)) {
files.add(tmpFile);
if (!demoTask.isWorking()) {
return;
}
demoTask.setInfo(tmpFile);
}
if (demoTask == null || !demoTask.isWorking()) {
return;
}
bufferedImage = contrast
.setAlgorithm(ContrastAlgorithm.SaturationBrightnessHistogramEqualization)
.start();
if (demoTask == null || !demoTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path,
message("SaturationBrightness") + "-" + message("HistogramEqualization"), ".png").getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, "png", tmpFile)) {
files.add(tmpFile);
if (!demoTask.isWorking()) {
return;
}
demoTask.setInfo(tmpFile);
}
if (demoTask == null || !demoTask.isWorking()) {
return;
}
bufferedImage = contrast
.setAlgorithm(ContrastAlgorithm.GrayHistogramEqualization)
.start();
if (demoTask == null || !demoTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path,
message("Gray") + "-" + message("HistogramEqualization"), ".png").getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, "png", tmpFile)) {
files.add(tmpFile);
if (!demoTask.isWorking()) {
return;
}
demoTask.setInfo(tmpFile);
}
if (demoTask == null || !demoTask.isWorking()) {
return;
}
long size = (long) (demoImage.getWidth() * demoImage.getHeight());
List<Integer> pvalues = new ArrayList<>(Arrays.asList(1, 5, 10, 20, 30));
long threshold = (long) (size * 0.05);
for (int v : pvalues) {
if (demoTask == null || !demoTask.isWorking()) {
return;
}
bufferedImage = contrast
.setAlgorithm(ContrastAlgorithm.SaturationHistogramStretching)
.setThreshold(threshold).setPercentage(v)
.start();
if (demoTask == null || !demoTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path,
message("Saturation") + "-" + message("HistogramStretching") + "_"
+ message("Percentage") + v, ".png")
.getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
if (demoTask == null || !demoTask.isWorking()) {
return;
}
bufferedImage = contrast
.setAlgorithm(ContrastAlgorithm.BrightnessHistogramStretching)
.setThreshold(threshold).setPercentage(v)
.start();
if (demoTask == null || !demoTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path,
message("Brightness") + "-" + message("HistogramStretching") + "_"
+ message("Percentage") + v, ".png")
.getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
if (demoTask == null || !demoTask.isWorking()) {
return;
}
bufferedImage = contrast
.setAlgorithm(ContrastAlgorithm.SaturationBrightnessHistogramStretching)
.setThreshold(threshold).setPercentage(v)
.start();
if (demoTask == null || !demoTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path,
message("SaturationBrightness") + "-" + message("HistogramStretching") + "_"
+ message("Percentage") + v, ".png")
.getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
if (demoTask == null || !demoTask.isWorking()) {
return;
}
bufferedImage = contrast
.setAlgorithm(ContrastAlgorithm.GrayHistogramStretching)
.setThreshold(threshold).setPercentage(v)
.start();
if (demoTask == null || !demoTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path,
message("Gray") + "-" + message("HistogramStretching") + "_"
+ message("Percentage") + v, ".png")
.getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
}
List<Integer> values = new ArrayList<>(Arrays.asList(5, 15, 30, 50, -5, -15, -30, -50));
for (int v : values) {
if (demoTask == null || !demoTask.isWorking()) {
return;
}
bufferedImage = contrast
.setAlgorithm(ContrastAlgorithm.SaturationHistogramShifting)
.setOffset(v)
.start();
if (demoTask == null || !demoTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path,
message("Saturation") + "-" + message("HistogramShifting") + "_" + v, ".png")
.getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
if (demoTask == null || !demoTask.isWorking()) {
return;
}
bufferedImage = contrast
.setAlgorithm(ContrastAlgorithm.BrightnessHistogramShifting)
.setOffset(v)
.start();
if (demoTask == null || !demoTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path,
message("Brightness") + "-" + message("HistogramShifting") + "_" + v, ".png")
.getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
if (demoTask == null || !demoTask.isWorking()) {
return;
}
bufferedImage = contrast
.setAlgorithm(ContrastAlgorithm.SaturationBrightnessHistogramShifting)
.setOffset(v)
.start();
if (demoTask == null || !demoTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path,
message("SaturationBrightness") + "-" + message("HistogramShifting") + "_" + v, ".png")
.getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
if (demoTask == null || !demoTask.isWorking()) {
return;
}
bufferedImage = contrast
.setAlgorithm(ContrastAlgorithm.GrayHistogramShifting)
.setOffset(v)
.start();
if (demoTask == null || !demoTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path,
message("Gray") + "-" + message("HistogramShifting") + "_" + v, ".png")
.getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
}
} catch (Exception e) {
MyBoxLog.error(e.toString());
}
}
public static void edge(FxTask demoTask, List<String> files,
BufferedImage demoImage, File demoFile) {
if (demoTask == null || demoImage == null || files == null) {
return;
}
try {
String path = AppPaths.getGeneratedPath() + File.separator + "imageDemo"
+ File.separator + message("EdgeDetection");
if (demoFile != null) {
path += File.separator + demoFile.getName();
} else {
path += File.separator + "x";
}
ImageConvolution convolution = ImageConvolution.create();
convolution.setImage(demoImage).setTask(demoTask);
convolution(demoTask, files, path,
convolution.setKernel(ConvolutionKernel.makeEdgeDetectionEightNeighborLaplace()));
if (demoTask == null || !demoTask.isWorking()) {
return;
}
convolution(demoTask, files, path,
convolution.setKernel(ConvolutionKernel.makeEdgeDetectionEightNeighborLaplaceInvert()));
if (demoTask == null || !demoTask.isWorking()) {
return;
}
convolution(demoTask, files, path,
convolution.setKernel(ConvolutionKernel.makeEdgeDetectionFourNeighborLaplace()));
if (demoTask == null || !demoTask.isWorking()) {
return;
}
convolution(demoTask, files, path,
convolution.setKernel(ConvolutionKernel.makeEdgeDetectionFourNeighborLaplaceInvert()));
if (demoTask == null || !demoTask.isWorking()) {
return;
}
} catch (Exception e) {
MyBoxLog.error(e.toString());
}
}
public static void emboss(FxTask demoTask, List<String> files,
BufferedImage demoImage, File demoFile) {
if (demoTask == null || demoImage == null || files == null) {
return;
}
try {
String path = AppPaths.getGeneratedPath() + File.separator + "imageDemo"
+ File.separator + message("Emboss");
if (demoFile != null) {
path += File.separator + demoFile.getName();
} else {
path += File.separator + "x";
}
ImageConvolution convolution = ImageConvolution.create();
convolution.setImage(demoImage).setTask(demoTask);
for (Direction d : Direction.values()) {
convolution(demoTask, files, path,
convolution.setKernel(ConvolutionKernel.makeEmbossKernel(d, 3, ConvolutionKernel.Color.Grey)));
if (demoTask == null || !demoTask.isWorking()) {
return;
}
convolution(demoTask, files, path,
convolution.setKernel(ConvolutionKernel.makeEmbossKernel(d, 5, ConvolutionKernel.Color.Grey)));
if (demoTask == null || !demoTask.isWorking()) {
return;
}
}
} catch (Exception e) {
MyBoxLog.error(e.toString());
}
}
public static void convolution(FxTask demoTask, List<String> files,
String path, ImageConvolution convolution) {
try {
BufferedImage bufferedImage = convolution.setColor(ConvolutionKernel.Color.Keep).start();
if (demoTask == null || !demoTask.isWorking()) {
return;
}
String tmpFile = FileTmpTools.getPathTempFile(path, convolution.getKernel().getName(), ".png")
.getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
if (demoTask == null || !demoTask.isWorking()) {
return;
}
bufferedImage = convolution.setColor(ConvolutionKernel.Color.Grey).start();
if (demoTask == null || !demoTask.isWorking()) {
return;
}
tmpFile = FileTmpTools.getPathTempFile(path, convolution.getKernel().getName()
+ "_" + message("Grey"), ".png").getAbsolutePath();
if (ImageFileWriters.writeImageFile(demoTask, bufferedImage, tmpFile)) {
files.add(tmpFile);
demoTask.setInfo(tmpFile);
}
} 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/fxml/image/MarginTools.java | released/MyBox/src/main/java/mara/mybox/fxml/image/MarginTools.java | package mara.mybox.fxml.image;
import java.awt.image.BufferedImage;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.Group;
import javafx.scene.SnapshotParameters;
import javafx.scene.effect.Blend;
import javafx.scene.effect.BlendMode;
import javafx.scene.effect.ColorInput;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.image.PixelReader;
import javafx.scene.image.PixelWriter;
import javafx.scene.image.WritableImage;
import javafx.scene.paint.Color;
import mara.mybox.data.DoubleRectangle;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.FxTask;
/**
* @Author Mara
* @CreateDate 2018-11-13 12:38:14
* @License Apache License Version 2.0
*/
public class MarginTools {
public static Image cutTransparentMargins(FxTask task, Image image) {
return cutMarginsByColor(task, image, Color.TRANSPARENT, 10, true, true, true, true);
}
public static Image cutMarginsByWidth(FxTask task, Image image,
int MarginWidth, boolean cutTop, boolean cutBottom, boolean cutLeft, boolean cutRight) {
try {
int imageWidth = (int) image.getWidth();
int imageHeight = (int) image.getHeight();
int top = 0;
int bottom = imageHeight;
int left = 0;
int right = imageWidth;
if (cutTop) {
top = MarginWidth;
}
if (cutBottom) {
bottom -= MarginWidth;
}
if (cutLeft) {
left = MarginWidth;
}
if (cutRight) {
right -= MarginWidth;
}
return CropTools.cropOutsideFx(task, image, left, top, right, bottom);
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
public static Image cutMarginsByColor(FxTask task, Image image, Color mColor, int colorDistance,
boolean cutTop, boolean cutBottom, boolean cutLeft, boolean cutRight) {
try {
int width = (int) image.getWidth();
int height = (int) image.getHeight();
PixelReader pixelReader = image.getPixelReader();
int top = 0;
int bottom = height;
int left = 0;
int right = width;
int distance2 = colorDistance * colorDistance;
if (cutTop) {
for (int j = 0; j < height; ++j) {
if (task != null && !task.isWorking()) {
return null;
}
boolean notMatch = false;
for (int i = 0; i < width; ++i) {
if (task != null && !task.isWorking()) {
return null;
}
if (!FxColorTools.isColorMatchSquare(pixelReader.getColor(i, j), mColor, distance2)) {
notMatch = true;
break;
}
}
if (notMatch) {
top = j;
break;
}
}
}
// MyBoxLog.debug("top: " + top);
if (top < 0) {
return null;
}
if (cutBottom) {
for (int j = height - 1; j >= 0; --j) {
if (task != null && !task.isWorking()) {
return null;
}
boolean notMatch = false;
for (int i = 0; i < width; ++i) {
if (task != null && !task.isWorking()) {
return null;
}
if (!FxColorTools.isColorMatchSquare(pixelReader.getColor(i, j), mColor, distance2)) {
notMatch = true;
break;
}
}
if (notMatch) {
bottom = j + 1;
break;
}
}
}
// MyBoxLog.debug("bottom: " + bottom);
if (bottom < 0) {
return null;
}
if (cutLeft) {
for (int i = 0; i < width; ++i) {
if (task != null && !task.isWorking()) {
return null;
}
boolean notMatch = false;
for (int j = 0; j < height; ++j) {
if (task != null && !task.isWorking()) {
return null;
}
if (!FxColorTools.isColorMatchSquare(pixelReader.getColor(i, j), mColor, distance2)) {
notMatch = true;
break;
}
}
if (notMatch) {
left = i;
break;
}
}
}
// MyBoxLog.debug("left: " + left);
if (left < 0) {
return null;
}
if (cutRight) {
for (int i = width - 1; i >= 0; --i) {
if (task != null && !task.isWorking()) {
return null;
}
boolean notMatch = false;
for (int j = 0; j < height; ++j) {
if (task != null && !task.isWorking()) {
return null;
}
if (!FxColorTools.isColorMatchSquare(pixelReader.getColor(i, j), mColor, distance2)) {
notMatch = true;
break;
}
}
if (notMatch) {
right = i + 1;
break;
}
}
}
// MyBoxLog.debug("right: " + right);
if (right < 0) {
return null;
}
// MyBoxLog.debug(left + " " + top + " " + right + " " + bottom);
return CropTools.cropOutsideFx(task, image, left, top, right, bottom);
} catch (Exception e) {
MyBoxLog.error(e.toString());
return null;
}
}
public static Image dragMarginsFx(FxTask task, Image image, Color color, DoubleRectangle rect) {
try {
if (image == null || rect == null) {
return image;
}
int iwidth = (int) image.getWidth();
int iheight = (int) image.getHeight();
int rwidth = (int) rect.getWidth();
int rheight = (int) rect.getHeight();
int rx = (int) rect.getX();
int ry = (int) rect.getY();
PixelReader pixelReader = image.getPixelReader();
WritableImage newImage = new WritableImage(rwidth, rheight);
PixelWriter pixelWriter = newImage.getPixelWriter();
int ix;
int iy;
for (int j = 0; j < rheight; ++j) {
if (task != null && !task.isWorking()) {
return null;
}
for (int i = 0; i < rwidth; ++i) {
if (task != null && !task.isWorking()) {
return null;
}
ix = i + rx;
iy = j + ry;
if (ix >= 0 && ix < iwidth && iy >= 0 && iy < iheight) {
pixelWriter.setColor(i, j, pixelReader.getColor(ix, iy));
} else {
pixelWriter.setColor(i, j, color);
}
}
}
return newImage;
} catch (Exception e) {
MyBoxLog.error(e.toString());
return image;
}
}
public static Image addMarginsFx(FxTask task, Image image, Color color, int MarginWidth,
boolean addTop, boolean addBottom, boolean addLeft, boolean addRight) {
if (image == null || MarginWidth <= 0) {
return image;
}
return addMarginsFx(task, image, color,
addTop ? MarginWidth : -1,
addBottom ? MarginWidth : -1,
addLeft ? MarginWidth : -1,
addRight ? MarginWidth : -1);
}
public static Image addMarginsFx(FxTask task, Image image, Color color,
int top, int bottom, int left, int right) {
try {
if (image == null) {
return image;
}
int width = (int) image.getWidth();
int height = (int) image.getHeight();
// MyBoxLog.debug(width + " " + height);
int totalWidth = width;
int totalHegiht = height;
int x1 = 0;
int y1 = 0;
if (left > 0) {
totalWidth += left;
x1 = left;
}
if (right > 0) {
totalWidth += right;
}
if (top > 0) {
totalHegiht += top;
y1 = top;
}
if (bottom > 0) {
totalHegiht += bottom;
}
// MyBoxLog.debug(totalWidth + " " + totalHegiht);
PixelReader pixelReader = image.getPixelReader();
WritableImage newImage = new WritableImage(totalWidth, totalHegiht);
PixelWriter pixelWriter = newImage.getPixelWriter();
pixelWriter.setPixels(x1, y1, width, height, pixelReader, 0, 0);
// MyBoxLog.debug(x1 + " " + y1);
if (left > 0) {
for (int x = 0; x < left; x++) {
if (task != null && !task.isWorking()) {
return null;
}
for (int y = 0; y < totalHegiht; y++) {
if (task != null && !task.isWorking()) {
return null;
}
pixelWriter.setColor(x, y, color);
}
}
}
if (right > 0) {
for (int x = totalWidth - 1; x > totalWidth - right - 1; x--) {
if (task != null && !task.isWorking()) {
return null;
}
for (int y = 0; y < totalHegiht; y++) {
if (task != null && !task.isWorking()) {
return null;
}
pixelWriter.setColor(x, y, color);
}
}
}
if (top > 0) {
for (int y = 0; y < top; y++) {
if (task != null && !task.isWorking()) {
return null;
}
for (int x = 0; x < totalWidth; x++) {
if (task != null && !task.isWorking()) {
return null;
}
pixelWriter.setColor(x, y, color);
}
}
}
if (bottom > 0) {
for (int y = totalHegiht - 1; y > totalHegiht - bottom - 1; y--) {
if (task != null && !task.isWorking()) {
return null;
}
for (int x = 0; x < totalWidth; x++) {
if (task != null && !task.isWorking()) {
return null;
}
pixelWriter.setColor(x, y, color);
}
}
}
return newImage;
} catch (Exception e) {
MyBoxLog.error(e.toString());
return image;
}
}
// This way may fail for big image
public static Image addMarginsFx2(Image image, Color color, int MarginWidth,
boolean addTop, boolean addBottom, boolean addLeft, boolean addRight) {
try {
if (image == null || MarginWidth <= 0) {
return image;
}
Group group = new Group();
double imageWidth = image.getWidth();
double imageHeight = image.getHeight();
double totalWidth = image.getWidth();
double totalHeight = image.getHeight();
ImageView view = new ImageView(image);
view.setPreserveRatio(true);
view.setFitWidth(imageWidth);
view.setFitHeight(imageHeight);
if (addLeft) {
view.setX(MarginWidth);
totalWidth += MarginWidth;
} else {
view.setX(0);
}
if (addTop) {
view.setY(MarginWidth);
totalHeight += MarginWidth;
} else {
view.setY(0);
}
if (addBottom) {
totalHeight += MarginWidth;
}
if (addRight) {
totalWidth += MarginWidth;
}
group.getChildren().add(view);
Blend blend = new Blend(BlendMode.SRC_OVER);
blend.setBottomInput(new ColorInput(0, 0, totalWidth, totalHeight, color));
group.setEffect(blend);
SnapshotParameters parameters = new SnapshotParameters();
parameters.setFill(Color.TRANSPARENT);
WritableImage newImage = group.snapshot(parameters, null);
return newImage;
} catch (Exception e) {
MyBoxLog.error(e.toString());
return image;
}
}
public static Image blurMarginsNoAlpha(FxTask task, Image image, int blurWidth,
boolean blurTop, boolean blurBottom, boolean blurLeft, boolean blurRight) {
if (image == null || blurWidth <= 0) {
return image;
}
BufferedImage source = SwingFXUtils.fromFXImage(image, null);
BufferedImage target = mara.mybox.image.tools.MarginTools.blurMarginsNoAlpha(task, source,
blurWidth, blurTop, blurBottom, blurLeft, blurRight);
if (target == null || (task != null && !task.isWorking())) {
return null;
}
Image newImage = SwingFXUtils.toFXImage(target, null);
return newImage;
}
public static Image blurMarginsAlpha(FxTask task, Image image,
int blurWidth, boolean blurTop, boolean blurBottom, boolean blurLeft, boolean blurRight) {
if (image == null || blurWidth <= 0) {
return image;
}
BufferedImage source = SwingFXUtils.fromFXImage(image, null);
BufferedImage target = mara.mybox.image.tools.MarginTools.blurMarginsAlpha(task, source,
blurWidth, blurTop, blurBottom, blurLeft, blurRight);
if (target == null || (task != null && !task.isWorking())) {
return null;
}
Image newImage = SwingFXUtils.toFXImage(target, null);
return newImage;
}
}
| 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/fxml/cell/TableDateCell.java | released/MyBox/src/main/java/mara/mybox/fxml/cell/TableDateCell.java | package mara.mybox.fxml.cell;
import java.util.Date;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.util.Callback;
import mara.mybox.tools.DateTools;
/**
* @Author Mara
* @CreateDate 2020-7-7
* @License Apache License Version 2.0
*/
public class TableDateCell<T> extends TableCell<T, Date>
implements Callback<TableColumn<T, Date>, TableCell<T, Date>> {
@Override
public TableCell<T, Date> call(TableColumn<T, Date> param) {
TableCell<T, Date> cell = new TableCell<T, Date>() {
@Override
public void updateItem(Date item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null) {
setText(null);
setGraphic(null);
return;
}
setText(DateTools.textEra(item));
setGraphic(null);
}
};
return cell;
}
}
| 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/fxml/cell/TableDataBooleanEditCell.java | released/MyBox/src/main/java/mara/mybox/fxml/cell/TableDataBooleanEditCell.java | package mara.mybox.fxml.cell;
import java.util.List;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.util.Callback;
import mara.mybox.controller.BaseData2DTableController;
import mara.mybox.db.data.Data2DColumn;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.tools.StringTools;
/**
* @Author Mara
* @CreateDate 2022-10-5
* @License Apache License Version 2.0
*/
public class TableDataBooleanEditCell extends TableCheckboxCell<List<String>, String> {
protected BaseData2DTableController dataTable;
protected Data2DColumn dataColumn;
protected int colIndex;
public TableDataBooleanEditCell(BaseData2DTableController dataTable, Data2DColumn dataColumn, int colIndex) {
super();
this.dataTable = dataTable;
this.dataColumn = dataColumn;
this.colIndex = colIndex;
}
@Override
protected boolean getCellValue(int rowIndex) {
try {
if (rowIndex < 0 || rowIndex >= dataTable.getTableData().size()) {
return false;
}
List<String> row = dataTable.getTableData().get(rowIndex);
return StringTools.isTrue(row.get(colIndex));
} catch (Exception e) {
return false;
}
}
@Override
protected void setCellValue(int rowIndex, boolean value) {
try {
if (isChanging || rowIndex < 0
|| rowIndex >= dataTable.getTableData().size()) {
return;
}
List<String> row = dataTable.getTableData().get(rowIndex);
if ((value + "").equalsIgnoreCase(getItem())) {
return;
}
isChanging = true;
row.set(colIndex, value + "");
dataTable.getTableData().set(rowIndex, row);
isChanging = false;
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
@Override
public void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
setStyle(null);
if (empty) {
setText(null);
setGraphic(null);
return;
}
try {
setStyle(dataTable.getData2D().cellStyle(dataTable.getStyleFilter(),
rowIndex(), dataColumn.getColumnName()));
} catch (Exception e) {
}
}
public static Callback<TableColumn, TableCell>
create(BaseData2DTableController dataTable, Data2DColumn dataColumn, int colIndex) {
return new Callback<TableColumn, TableCell>() {
@Override
public TableCell call(TableColumn param) {
return new TableDataBooleanEditCell(dataTable, dataColumn, colIndex);
}
};
}
}
| 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/fxml/cell/TreeTableFileSizeCell.java | released/MyBox/src/main/java/mara/mybox/fxml/cell/TreeTableFileSizeCell.java | package mara.mybox.fxml.cell;
import javafx.scene.control.TreeTableCell;
import javafx.scene.control.TreeTableColumn;
import javafx.util.Callback;
import mara.mybox.tools.FileTools;
/**
* @Author Mara
* @CreateDate 2019-11-12
* @Version 1.0
* @Description
* @License Apache License Version 2.0
*/
public class TreeTableFileSizeCell<T> extends TreeTableCell<T, Long>
implements Callback<TreeTableColumn<T, Long>, TreeTableCell<T, Long>> {
@Override
public TreeTableCell<T, Long> call(TreeTableColumn<T, Long> param) {
TreeTableCell<T, Long> cell = new TreeTableCell<T, Long>() {
@Override
protected void updateItem(final Long item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null || item <= 0) {
setText(null);
setGraphic(null);
return;
}
setText(FileTools.showFileSize(item));
setGraphic(null);
}
};
return cell;
}
}
| 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/fxml/cell/TableLatitudeCell.java | released/MyBox/src/main/java/mara/mybox/fxml/cell/TableLatitudeCell.java | package mara.mybox.fxml.cell;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.util.Callback;
/**
* @Author Mara
* @CreateDate 2020-2-22
* @License Apache License Version 2.0
*/
public class TableLatitudeCell<T> extends TableCell<T, Double>
implements Callback<TableColumn<T, Double>, TableCell<T, Double>> {
@Override
public TableCell<T, Double> call(TableColumn<T, Double> param) {
TableCell<T, Double> cell = new TableCell<T, Double>() {
@Override
public void updateItem(Double item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null) {
setGraphic(null);
setText(null);
setTextFill(null);
return;
}
if (item >= -90 && item <= 90) {
setText(item + "");
} else {
setText(null);
}
setGraphic(null);
}
};
return cell;
}
}
| 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/fxml/cell/TreeTableIDCell.java | released/MyBox/src/main/java/mara/mybox/fxml/cell/TreeTableIDCell.java | package mara.mybox.fxml.cell;
import javafx.scene.control.TreeTableCell;
import javafx.scene.control.TreeTableColumn;
import javafx.util.Callback;
/**
* @Author Mara
* @CreateDate 2023-4-9
* @License Apache License Version 2.0
*/
public class TreeTableIDCell<T> extends TreeTableCell<T, Long>
implements Callback<TreeTableColumn<T, Long>, TreeTableCell<T, Long>> {
@Override
public TreeTableCell<T, Long> call(TreeTableColumn<T, Long> param) {
TreeTableCell<T, Long> cell = new TreeTableCell<T, Long>() {
@Override
protected void updateItem(final Long item, boolean empty) {
super.updateItem(item, empty);
setGraphic(null);
if (empty || item == null || item < 0) {
setText(null);
return;
}
setText(item + "");
}
};
return cell;
}
}
| 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/fxml/cell/TableDataEnumCell.java | released/MyBox/src/main/java/mara/mybox/fxml/cell/TableDataEnumCell.java | package mara.mybox.fxml.cell;
import java.util.List;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.EventHandler;
import javafx.scene.Node;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableRow;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.ComboBoxTableCell;
import javafx.scene.input.MouseEvent;
import javafx.util.Callback;
import mara.mybox.controller.BaseData2DTableController;
import mara.mybox.db.data.ColumnDefinition.ColumnType;
import mara.mybox.db.data.Data2DColumn;
import mara.mybox.fxml.style.NodeStyleTools;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2021-10-26
* @License Apache License Version 2.0
*/
public class TableDataEnumCell<S, T> extends ComboBoxTableCell<S, T> {
protected BaseData2DTableController dataTable;
protected Data2DColumn dataColumn;
protected int maxVisibleCount;
public TableDataEnumCell(BaseData2DTableController dataTable, Data2DColumn dataColumn,
ObservableList<T> valueslist, int maxCount) {
super(valueslist);
this.dataTable = dataTable;
this.dataColumn = dataColumn;
setComboBoxEditable(dataColumn.getType() == ColumnType.EnumerationEditable);
maxVisibleCount = maxCount;
if (maxVisibleCount <= 0) {
maxVisibleCount = 10;
}
setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
TableView<S> table = getTableView();
if (table != null && table.getItems() != null) {
int index = rowIndex();
if (index < table.getItems().size()) {
table.edit(index, getTableColumn());
}
}
}
});
}
@Override
public void startEdit() {
super.startEdit();
Node g = getGraphic();
if (g != null && g instanceof ComboBox) {
ComboBox cb = (ComboBox) g;
cb.setVisibleRowCount(maxVisibleCount);
cb.setValue(getItem());
if (isComboBoxEditable()) {
NodeStyleTools.setTooltip(cb.getEditor(), message("EditCellComments"));
}
}
}
public int rowIndex() {
try {
TableRow row = getTableRow();
if (row == null) {
return -1;
}
int index = row.getIndex();
if (index >= 0 && index < getTableView().getItems().size()) {
return index;
} else {
return -2;
}
} catch (Exception e) {
return -3;
}
}
@Override
public void updateItem(T item, boolean empty) {
super.updateItem(item, empty);
setStyle(null);
if (empty) {
setText(null);
setGraphic(null);
return;
}
try {
setStyle(dataTable.getData2D().cellStyle(dataTable.getStyleFilter(),
rowIndex(), dataColumn.getColumnName()));
} catch (Exception e) {
}
if (dataColumn.getType() == ColumnType.EnumeratedShort) {
setText(dataColumn.formatValue(item));
} else {
setText(item != null ? item + "" : null);
}
}
public static <S, T> Callback<TableColumn<S, T>, TableCell<S, T>> create(
BaseData2DTableController dataTable, Data2DColumn dataColumn,
List<T> items, int maxVisibleCount) {
return new Callback<TableColumn<S, T>, TableCell<S, T>>() {
@Override
public TableCell<S, T> call(TableColumn<S, T> param) {
ObservableList<T> olist = FXCollections.observableArrayList();
for (T item : items) {
olist.add(item);
}
return new TableDataEnumCell<>(dataTable, dataColumn, olist, maxVisibleCount);
}
};
}
}
| 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/fxml/cell/TableRowSelectionCell.java | released/MyBox/src/main/java/mara/mybox/fxml/cell/TableRowSelectionCell.java | package mara.mybox.fxml.cell;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.ListChangeListener;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableRow;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.CheckBoxTableCell;
import javafx.util.Callback;
/**
* @Author Mara
* @CreateDate 2021-10-26
* @License Apache License Version 2.0
*/
public class TableRowSelectionCell<S, T> extends CheckBoxTableCell<S, T> {
protected TableView tableView;
protected SimpleBooleanProperty checked;
protected boolean selectingRow, checkingBox;
protected ChangeListener<Boolean> checkedListener;
protected ListChangeListener selectedListener;
public TableRowSelectionCell(TableView tView) {
tableView = tView;
checked = new SimpleBooleanProperty(false);
selectingRow = checkingBox = false;
getStyleClass().add("row-number");
initListeners();
tableView.getSelectionModel().getSelectedIndices().addListener(selectedListener);
checked.addListener(checkedListener);
setSelectedStateCallback(new Callback<Integer, ObservableValue<Boolean>>() {
@Override
public synchronized ObservableValue<Boolean> call(Integer index) {
int row = rowIndex();
if (row < 0) {
setText("");
return null;
}
setText("" + (row + 1));
checkingBox = true;
checked.set(tableView.getSelectionModel().isSelected(row));
checkingBox = false;
return checked;
}
});
}
private void initListeners() {
checkedListener = new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue ov, Boolean oldValue, Boolean newValue) {
int row = rowIndex();
if (checkingBox || row < 0) {
return;
}
selectingRow = true;
if (newValue) {
tableView.getSelectionModel().select(row);
} else {
tableView.getSelectionModel().clearSelection(row);
}
selectingRow = false;
}
};
selectedListener = new ListChangeListener<Integer>() {
@Override
public void onChanged(ListChangeListener.Change c) {
int row = rowIndex();
if (checked == null || selectingRow || row < 0) {
return;
}
checkingBox = true;
checked.set(tableView.getSelectionModel().isSelected(row));
checkingBox = false;
}
};
}
public int rowIndex() {
try {
TableRow row = getTableRow();
if (row == null) {
return -1;
}
int index = row.getIndex();
if (index >= 0 && index < getTableView().getItems().size()) {
return index;
} else {
return -2;
}
} catch (Exception e) {
return -3;
}
}
public static <S, T> Callback<TableColumn<S, T>, TableCell<S, T>> create(TableView tableView) {
return new Callback<TableColumn<S, T>, TableCell<S, T>>() {
@Override
public TableCell<S, T> call(TableColumn<S, T> param) {
return new TableRowSelectionCell<>(tableView);
}
};
}
public SimpleBooleanProperty getSelected() {
return checked;
}
public void setSelected(SimpleBooleanProperty selected) {
this.checked = selected;
}
}
| 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/fxml/cell/TableColorCell.java | released/MyBox/src/main/java/mara/mybox/fxml/cell/TableColorCell.java | package mara.mybox.fxml.cell;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.paint.Color;
import javafx.scene.paint.Paint;
import javafx.scene.shape.Rectangle;
import javafx.util.Callback;
/**
* @Author Mara
* @CreateDate 2020-1-8
* @License Apache License Version 2.0
*/
public class TableColorCell<T> extends TableCell<T, Color>
implements Callback<TableColumn<T, Color>, TableCell<T, Color>> {
@Override
public TableCell<T, Color> call(TableColumn<T, Color> param) {
final Rectangle rectangle;
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
rectangle = new Rectangle(30, 20);
TableCell<T, Color> cell = new TableCell<T, Color>() {
@Override
protected void updateItem(Color item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null) {
setGraphic(null);
} else {
rectangle.setFill((Paint) item);
setGraphic(rectangle);
}
}
};
return cell;
}
}
| 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/fxml/cell/TreeTableDateCell.java | released/MyBox/src/main/java/mara/mybox/fxml/cell/TreeTableDateCell.java | package mara.mybox.fxml.cell;
import java.util.Date;
import javafx.scene.control.TreeTableCell;
import javafx.scene.control.TreeTableColumn;
import javafx.util.Callback;
import mara.mybox.tools.DateTools;
/**
* @Author Mara
* @CreateDate 2023-4-9
* @License Apache License Version 2.0
*/
public class TreeTableDateCell<T> extends TreeTableCell<T, Date>
implements Callback<TreeTableColumn<T, Date>, TreeTableCell<T, Date>> {
@Override
public TreeTableCell<T, Date> call(TreeTableColumn<T, Date> param) {
TreeTableCell<T, Date> cell = new TreeTableCell<T, Date>() {
@Override
protected void updateItem(final Date item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null) {
setText(null);
setGraphic(null);
return;
}
setText(DateTools.textEra(item));
setGraphic(null);
}
};
return cell;
}
}
| 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/fxml/cell/TableRowIndexCell.java | released/MyBox/src/main/java/mara/mybox/fxml/cell/TableRowIndexCell.java | package mara.mybox.fxml.cell;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.util.Callback;
/**
* @Author Mara
* @CreateDate 2023-7-8
* @License Apache License Version 2.0
*/
public class TableRowIndexCell<T> extends TableCell<T, Object>
implements Callback<TableColumn<T, Object>, TableCell<T, Object>> {
@Override
public TableCell<T, Object> call(TableColumn<T, Object> param) {
TableCell<T, Object> cell = new TableCell<T, Object>() {
@Override
public void updateItem(Object item, boolean empty) {
super.updateItem(item, empty);
setText(null);
setGraphic(null);
if (empty || item == null) {
return;
}
try {
int v = getTableRow().getIndex();
if (v >= 0) {
setText((v + 1) + "");
}
} catch (Exception e) {
}
}
};
return cell;
}
}
| 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/fxml/cell/TreeConditionCell.java | released/MyBox/src/main/java/mara/mybox/fxml/cell/TreeConditionCell.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package mara.mybox.fxml.cell;
import javafx.scene.Node;
import javafx.scene.control.CheckBox;
import javafx.scene.control.cell.CheckBoxTreeCell;
import mara.mybox.fxml.ConditionNode;
import mara.mybox.fxml.style.NodeStyleTools;
import mara.mybox.fxml.NodeTools;
/**
* @Author Mara
* @CreateDate 2020-4-18
* @License Apache License Version 2.0
*/
public class TreeConditionCell extends CheckBoxTreeCell<ConditionNode> {
@Override
public void updateItem(ConditionNode item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null) {
setText(null);
setGraphic(null);
return;
}
setText(item.getText());
Node node = getGraphic();
if (node != null && node instanceof CheckBox) {
CheckBox checkBox = (CheckBox) node;
if (item.getCondition() != null && !item.getCondition().isBlank()) {
NodeStyleTools.setTooltip(checkBox, item.getCondition());
} else {
NodeStyleTools.removeTooltip(checkBox);
}
}
}
}
| 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/fxml/cell/ListColorCell.java | released/MyBox/src/main/java/mara/mybox/fxml/cell/ListColorCell.java | package mara.mybox.fxml.cell;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.ListCell;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
/**
* @Author Mara
* @CreateDate 2019-3-15 14:30:16
* @Version 1.0
* @Description
* @License Apache License Version 2.0
*/
public class ListColorCell extends ListCell<Color> {
private final Rectangle rectangle;
public ListColorCell() {
setContentDisplay(ContentDisplay.LEFT);
rectangle = new Rectangle(30, 20);
}
@Override
protected void updateItem(Color item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null) {
setGraphic(null);
setText(null);
} else {
rectangle.setFill(item);
setGraphic(rectangle);
setText(item.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/fxml/cell/TableImageCell.java | released/MyBox/src/main/java/mara/mybox/fxml/cell/TableImageCell.java | package mara.mybox.fxml.cell;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.util.Callback;
import mara.mybox.value.AppVariables;
/**
* @Author Mara
* @CreateDate 2019-3-15 14:17:47
* @Version 1.0
* @Description
* @License Apache License Version 2.0
*/
public class TableImageCell<T> extends TableCell<T, Image>
implements Callback<TableColumn<T, Image>, TableCell<T, Image>> {
@Override
public TableCell<T, Image> call(TableColumn<T, Image> param) {
final ImageView imageview = new ImageView();
imageview.setPreserveRatio(true);
imageview.setFitWidth(AppVariables.thumbnailWidth);
imageview.setFitHeight(AppVariables.thumbnailWidth);
TableCell<T, Image> cell = new TableCell<T, Image>() {
@Override
public void updateItem(Image item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null) {
setText(null);
setGraphic(null);
return;
}
imageview.setImage(item);
setGraphic(imageview);
}
};
return cell;
}
}
| 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/fxml/cell/ListImageCell.java | released/MyBox/src/main/java/mara/mybox/fxml/cell/ListImageCell.java | package mara.mybox.fxml.cell;
import javafx.scene.control.ListCell;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
/**
* @Author Mara
* @CreateDate 2019-3-15 14:17:47
* @License Apache License Version 2.0
*/
public class ListImageCell extends ListCell<Image> {
private ImageView view;
private final int height;
public ListImageCell() {
height = 30;
init();
}
public ListImageCell(int height) {
this.height = height;
init();
}
private void init() {
view = new ImageView();
view.setPreserveRatio(true);
view.setFitHeight(height);
}
@Override
protected void updateItem(Image item, boolean empty) {
super.updateItem(item, empty);
if (!empty && item != null) {
view.setImage(item);
setGraphic(view);
setText(item.getUrl());
} else {
setGraphic(null);
setText(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/fxml/cell/TableIDCell.java | released/MyBox/src/main/java/mara/mybox/fxml/cell/TableIDCell.java | package mara.mybox.fxml.cell;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.util.Callback;
/**
* @Author Mara
* @CreateDate 2025-4-25
* @License Apache License Version 2.0
*/
public class TableIDCell<T> extends TableCell<T, Long>
implements Callback<TableColumn<T, Long>, TableCell<T, Long>> {
@Override
public TableCell<T, Long> call(TableColumn<T, Long> param) {
TableCell<T, Long> cell = new TableCell<T, Long>() {
@Override
protected void updateItem(final Long item, boolean empty) {
super.updateItem(item, empty);
setGraphic(null);
if (empty || item == null || item < 0) {
setText(null);
return;
}
setText(item + "");
}
};
return cell;
}
}
| 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/fxml/cell/TableDurationCell.java | released/MyBox/src/main/java/mara/mybox/fxml/cell/TableDurationCell.java | package mara.mybox.fxml.cell;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.text.Text;
import javafx.util.Callback;
import mara.mybox.tools.DateTools;
/**
* @Author Mara
* @CreateDate 2019-3-15 14:24:30
* @Version 1.0
* @Description
* @License Apache License Version 2.0
*/
public class TableDurationCell<T> extends TableCell<T, Long>
implements Callback<TableColumn<T, Long>, TableCell<T, Long>> {
@Override
public TableCell<T, Long> call(TableColumn<T, Long> param) {
TableCell<T, Long> cell = new TableCell<T, Long>() {
private final Text text = new Text();
@Override
protected void updateItem(final Long item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null || item <= 0) {
setText(null);
setGraphic(null);
return;
}
text.setText(DateTools.datetimeMsDuration(item));
setGraphic(text);
}
};
return cell;
}
}
| 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/fxml/cell/TableDataColorEditCell.java | released/MyBox/src/main/java/mara/mybox/fxml/cell/TableDataColorEditCell.java | package mara.mybox.fxml.cell;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.Node;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.util.Callback;
import mara.mybox.controller.ColorPalettePopupController;
import mara.mybox.controller.BaseData2DTableController;
import mara.mybox.db.data.Data2DColumn;
import mara.mybox.db.table.TableColor;
import mara.mybox.fxml.image.FxColorTools;
import mara.mybox.fxml.style.NodeStyleTools;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2022-10-8
* @License Apache License Version 2.0
*/
public class TableDataColorEditCell extends TableDataEditCell {
protected TableColor tableColor;
protected Rectangle rectangle;
protected String msgPrefix;
public TableDataColorEditCell(BaseData2DTableController dataTable, Data2DColumn dataColumn, TableColor tableColor) {
super(dataTable, dataColumn);
this.tableColor = tableColor;
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
rectangle = new Rectangle(30, 20);
rectangle.setStroke(Color.BLACK);
rectangle.setStrokeWidth(1);
msgPrefix = message("ClickColorToPalette");
}
@Override
public void editCell() {
Node g = getGraphic();
if (g == null || !(g instanceof Rectangle)) {
return;
}
ColorPalettePopupController inputController = ColorPalettePopupController.open(dataTable, rectangle);
inputController.getSetNotify().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue ov, Boolean oldValue, Boolean newValue) {
Color color = (Color) rectangle.getFill();
setCellValue(color.toString());
inputController.closeStage();
}
});
}
@Override
public void displayData(String item) {
Color color;
try {
color = Color.web(item);
} catch (Exception e) {
color = Color.WHITE;
}
if (tableColor == null) {
tableColor = new TableColor();
}
rectangle.setFill(color);
NodeStyleTools.setTooltip(rectangle, msgPrefix + "\n---------\n"
+ FxColorTools.colorNameDisplay(tableColor, color));
setGraphic(rectangle);
}
public static Callback<TableColumn, TableCell> create(BaseData2DTableController dataTable,
Data2DColumn dataColumn, TableColor tableColor) {
return new Callback<TableColumn, TableCell>() {
@Override
public TableCell call(TableColumn param) {
return new TableDataColorEditCell(dataTable, dataColumn, tableColor);
}
};
}
}
| 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/fxml/cell/TableBooleanCell.java | released/MyBox/src/main/java/mara/mybox/fxml/cell/TableBooleanCell.java | package mara.mybox.fxml.cell;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.image.ImageView;
import javafx.util.Callback;
import mara.mybox.fxml.style.StyleTools;
/**
* @Author Mara
* @CreateDate 2019-3-15 14:17:47
* @License Apache License Version 2.0
*/
public class TableBooleanCell<T> extends TableCell<T, Boolean>
implements Callback<TableColumn<T, Boolean>, TableCell<T, Boolean>> {
@Override
public TableCell<T, Boolean> call(TableColumn<T, Boolean> param) {
final ImageView imageview = StyleTools.getIconImageView("iconYes.png");
imageview.setPreserveRatio(true);
TableCell<T, Boolean> cell = new TableCell<T, Boolean>() {
@Override
public void updateItem(Boolean item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null || !item) {
setText(null);
setGraphic(null);
return;
}
setGraphic(imageview);
setText(null);
}
};
return cell;
}
}
| 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/fxml/cell/TableTextTruncCell.java | released/MyBox/src/main/java/mara/mybox/fxml/cell/TableTextTruncCell.java | package mara.mybox.fxml.cell;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.util.Callback;
/**
* @Author Mara
* @CreateDate 2021-7-3
* @License Apache License Version 2.0
*/
public class TableTextTruncCell<T> extends TableCell<T, String>
implements Callback<TableColumn<T, String>, TableCell<T, String>> {
@Override
public TableCell<T, String> call(TableColumn<T, String> param) {
TableCell<T, String> cell = new TableCell<T, String>() {
@Override
public void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null) {
setText(null);
setGraphic(null);
return;
}
setText(item.length() > 80 ? item.substring(0, 80) : item);
}
};
return cell;
}
}
| 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/fxml/cell/TableCheckboxCell.java | released/MyBox/src/main/java/mara/mybox/fxml/cell/TableCheckboxCell.java | package mara.mybox.fxml.cell;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.control.TableRow;
import javafx.scene.control.cell.CheckBoxTableCell;
import javafx.util.Callback;
/**
* @Author Mara
* @CreateDate 2021-11-13
* @License Apache License Version 2.0
*/
public class TableCheckboxCell<S, T> extends CheckBoxTableCell<S, T> {
protected SimpleBooleanProperty checked;
protected ChangeListener<Boolean> checkedListener;
protected boolean isChanging;
public TableCheckboxCell() {
checked = new SimpleBooleanProperty(false);
setSelectedStateCallback(new Callback<Integer, ObservableValue<Boolean>>() {
@Override
public synchronized ObservableValue<Boolean> call(Integer index) {
if (isChanging) {
return checked;
}
int rowIndex = rowIndex();
if (rowIndex < 0) {
return null;
}
isChanging = true;
checked.set(getCellValue(rowIndex));
isChanging = false;
return checked;
}
});
checkedListener = new ChangeListener<Boolean>() {
@Override
public synchronized void changed(ObservableValue ov, Boolean oldValue, Boolean newValue) {
if (isChanging) {
return;
}
int rowIndex = rowIndex();
if (rowIndex < 0) {
return;
}
setCellValue(rowIndex, newValue);
}
};
checked.addListener(checkedListener);
}
protected boolean getCellValue(int rowIndex) {
return false;
}
protected void setCellValue(int rowIndex, boolean value) {
}
public int rowIndex() {
try {
TableRow row = getTableRow();
if (row == null) {
return -1;
}
int index = row.getIndex();
if (index >= 0 && index < getTableView().getItems().size()) {
return index;
} else {
return -2;
}
} catch (Exception e) {
return -3;
}
}
public SimpleBooleanProperty getSelected() {
return checked;
}
public void setSelected(SimpleBooleanProperty selected) {
this.checked = selected;
}
}
| 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/fxml/cell/TableFileNameCell.java | released/MyBox/src/main/java/mara/mybox/fxml/cell/TableFileNameCell.java | package mara.mybox.fxml.cell;
import java.awt.image.BufferedImage;
import java.io.File;
import javafx.application.Platform;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.control.IndexedCell;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.image.ImageView;
import javafx.util.Callback;
import mara.mybox.controller.BaseController;
import mara.mybox.fxml.FxTask;
import mara.mybox.image.file.ImageFileReaders;
import mara.mybox.tools.FileNameTools;
import mara.mybox.value.AppVariables;
import mara.mybox.value.FileExtensions;
/**
* @Author Mara
* @CreateDate 2019-3-15 14:17:47
* @License Apache License Version 2.0
*/
public class TableFileNameCell<T> extends TableCell<T, String>
implements Callback<TableColumn<T, String>, TableCell<T, String>> {
protected int thumbWidth = AppVariables.thumbnailWidth;
private BaseController controller;
public TableFileNameCell(BaseController controller) {
this.controller = controller;
}
public TableFileNameCell(int imageSize) {
this.thumbWidth = imageSize;
}
@Override
public TableCell<T, String> call(TableColumn<T, String> param) {
final ImageView imageview = new ImageView();
imageview.setPreserveRatio(true);
imageview.setFitWidth(thumbWidth);
imageview.setFitHeight(thumbWidth);
TableCell<T, String> cell = new TableCell<T, String>() {
@Override
public void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
setText(null);
setGraphic(null);
if (empty || item == null) {
return;
}
setText(item);
String suffix = FileNameTools.ext(item).toLowerCase();
if (FileExtensions.SupportedImages.contains(suffix)) {
ImageViewFileTask task = new ImageViewFileTask(controller)
.setCell(this).setView(imageview)
.setFilename(item).setThumbWidth(thumbWidth);
Thread thread = new Thread(task);
thread.setDaemon(false);
thread.start();
}
}
};
return cell;
}
public class ImageViewFileTask<Void> extends FxTask<Void> {
private IndexedCell cell;
private String filename = null;
private ImageView view = null;
private int thumbWidth = AppVariables.thumbnailWidth;
public ImageViewFileTask(BaseController controller) {
this.controller = controller;
}
public ImageViewFileTask<Void> setCell(IndexedCell cell) {
this.cell = cell;
return this;
}
public ImageViewFileTask<Void> setFilename(String filename) {
this.filename = filename;
return this;
}
public ImageViewFileTask<Void> setView(ImageView view) {
this.view = view;
return this;
}
public ImageViewFileTask<Void> setThumbWidth(int thumbWidth) {
this.thumbWidth = thumbWidth;
return this;
}
@Override
public void run() {
if (view == null || filename == null) {
return;
}
File file = new File(filename);
BufferedImage image = ImageFileReaders.readImage(this, file, thumbWidth);
if (image != null) {
Platform.runLater(new Runnable() {
@Override
public void run() {
view.setImage(SwingFXUtils.toFXImage(image, null));
if (cell != null) {
cell.setGraphic(view);
}
}
});
}
}
}
}
| 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/fxml/cell/TreeTableTextTrimCell.java | released/MyBox/src/main/java/mara/mybox/fxml/cell/TreeTableTextTrimCell.java | package mara.mybox.fxml.cell;
import javafx.scene.control.TreeTableCell;
import javafx.scene.control.TreeTableColumn;
import javafx.util.Callback;
import mara.mybox.tools.StringTools;
import mara.mybox.value.AppVariables;
/**
* @Author Mara
* @CreateDate 2023-4-9
* @License Apache License Version 2.0
*/
public class TreeTableTextTrimCell<T> extends TreeTableCell<T, String>
implements Callback<TreeTableColumn<T, String>, TreeTableCell<T, String>> {
@Override
public TreeTableCell<T, String> call(TreeTableColumn<T, String> param) {
TreeTableCell<T, String> cell = new TreeTableCell<T, String>() {
@Override
protected void updateItem(final String item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null) {
setText(null);
setGraphic(null);
return;
}
setText(StringTools.abbreviate(item, AppVariables.titleTrimSize));
setGraphic(null);
}
};
return cell;
}
}
| 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/fxml/cell/TableTextAreaEditCell.java | released/MyBox/src/main/java/mara/mybox/fxml/cell/TableTextAreaEditCell.java | package mara.mybox.fxml.cell;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.util.Callback;
import javafx.util.converter.DefaultStringConverter;
import mara.mybox.controller.BaseController;
import mara.mybox.controller.BaseInputController;
import mara.mybox.controller.TextInputController;
import mara.mybox.dev.MyBoxLog;
/**
* @Author Mara
* @CreateDate 2022-9-22
* @License Apache License Version 2.0
*/
public class TableTextAreaEditCell<S> extends TableAutoCommitCell<S, String> {
protected BaseController parent;
protected String comments;
public TableTextAreaEditCell(BaseController parent, String comments) {
super(new DefaultStringConverter());
this.parent = parent;
this.comments = comments;
}
protected String getCellValue() {
return getItem();
}
@Override
public boolean setCellValue(String inValue) {
try {
String value = inValue;
if (value != null) {
value = value.replaceAll("\\\\n", "\n");
}
return super.setCellValue(value);
} catch (Exception e) {
MyBoxLog.debug(e);
return false;
}
}
@Override
public void editCell() {
BaseInputController inputController = TextInputController.open(parent, name(), getCellValue());
inputController.setCommentsLabel(comments);
inputController.getNotify().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> v, Boolean ov, Boolean nv) {
setCellValue(inputController.getInputString());
inputController.close();
}
});
}
public static <S> Callback<TableColumn<S, String>, TableCell<S, String>>
create(BaseController parent, String comments) {
return new Callback<TableColumn<S, String>, TableCell<S, String>>() {
@Override
public TableCell<S, String> call(TableColumn<S, String> param) {
return new TableTextAreaEditCell<>(parent, comments);
}
};
}
}
| 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/fxml/cell/TableImageInfoCell.java | released/MyBox/src/main/java/mara/mybox/fxml/cell/TableImageInfoCell.java | package mara.mybox.fxml.cell;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.image.ImageView;
import javafx.util.Callback;
import mara.mybox.controller.BaseController;
import mara.mybox.fxml.image.ImageViewInfoTask;
import mara.mybox.image.data.ImageInformation;
/**
* @Author Mara
* @CreateDate 2019-3-15 14:17:47
* @License Apache License Version 2.0
*/
public class TableImageInfoCell<T> extends TableCell<T, ImageInformation>
implements Callback<TableColumn<T, ImageInformation>, TableCell<T, ImageInformation>> {
private final BaseController controller;
public TableImageInfoCell(BaseController controller) {
this.controller = controller;
}
@Override
public TableCell<T, ImageInformation> call(TableColumn<T, ImageInformation> param) {
final ImageView imageview = new ImageView();
imageview.setPreserveRatio(true);
TableCell<T, ImageInformation> cell = new TableCell<T, ImageInformation>() {
@Override
public void updateItem(ImageInformation item, boolean empty) {
super.updateItem(item, empty);
setText(null);
setGraphic(null);
if (empty || item == null) {
return;
}
ImageViewInfoTask task = new ImageViewInfoTask(controller)
.setCell(this).setView(imageview).setItem(item);
Thread thread = new Thread(task);
thread.setDaemon(false);
thread.start();
}
};
return cell;
}
}
| 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/fxml/cell/TableDataCell.java | released/MyBox/src/main/java/mara/mybox/fxml/cell/TableDataCell.java | package mara.mybox.fxml.cell;
import java.util.List;
import javafx.util.converter.DefaultStringConverter;
import mara.mybox.controller.BaseData2DTableController;
import mara.mybox.db.data.Data2DColumn;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.value.UserConfig;
/**
* @Author Mara
* @CreateDate 2022-9-26
* @License Apache License Version 2.0
*/
public class TableDataCell extends TableAutoCommitCell<List<String>, String> {
protected BaseData2DTableController dataTable;
protected Data2DColumn dataColumn;
protected final int trucSize = 200;
protected boolean supportMultipleLine;
public TableDataCell(BaseData2DTableController dataTable, Data2DColumn dataColumn) {
super(new DefaultStringConverter());
this.dataTable = dataTable;
this.dataColumn = dataColumn;
supportMultipleLine = dataTable.getData2D().supportMultipleLine() && dataColumn.supportMultipleLine();
}
protected String getCellValue() {
return getItem();
}
@Override
public boolean setCellValue(String inValue) {
try {
String value = inValue;
if (value != null && supportMultipleLine) {
value = value.replaceAll("\\\\n", "\n");
}
return super.setCellValue(value);
} catch (Exception e) {
MyBoxLog.debug(e);
return false;
}
}
@Override
public boolean valid(String value) {
try {
if (!dataTable.getData2D().validValue(value)) {
return false;
}
if (!dataTable.getData2D().rejectInvalidWhenEdit()) {
return true;
}
return dataColumn.validValue(value);
} catch (Exception e) {
return false;
}
}
@Override
public void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
setStyle(null);
if (empty) {
setText(null);
setGraphic(null);
return;
}
setDataStyle(item);
displayData(item);
}
public void displayData(String item) {
try {
String s = item;
if (s != null && s.length() > trucSize) {
s = s.substring(0, trucSize);
}
setText(s);
} catch (Exception e) {
setText(item);
}
}
public void setDataStyle(String item) {
try {
String style = dataTable.getData2D().cellStyle(dataTable.getStyleFilter(),
rowIndex(), dataColumn.getColumnName());
if (style != null) {
setStyle(style);
} else if (dataColumn.validValue(item)) {
setStyle(null);
} else {
setStyle(UserConfig.badStyle());
}
} catch (Exception 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/fxml/cell/ListGeographyCodeCell.java | released/MyBox/src/main/java/mara/mybox/fxml/cell/ListGeographyCodeCell.java | package mara.mybox.fxml.cell;
import javafx.scene.control.ListCell;
import mara.mybox.data.GeographyCode;
/**
* @Author Mara
* @CreateDate 2020-3-21
* @License Apache License Version 2.0
*/
public class ListGeographyCodeCell extends ListCell<GeographyCode> {
@Override
protected void updateItem(GeographyCode item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null) {
setGraphic(null);
setText(null);
} else {
setText(item.getName());
}
}
}
| 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/fxml/cell/TableDataCoordinateEditCell.java | released/MyBox/src/main/java/mara/mybox/fxml/cell/TableDataCoordinateEditCell.java | package mara.mybox.fxml.cell;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.util.Callback;
import mara.mybox.controller.BaseData2DTableController;
import mara.mybox.controller.Data2DCoordinatePickerController;
import mara.mybox.db.data.Data2DColumn;
/**
* @Author Mara
* @CreateDate 2022-10-8
* @License Apache License Version 2.0
*/
public class TableDataCoordinateEditCell extends TableDataEditCell {
public TableDataCoordinateEditCell(BaseData2DTableController dataTable, Data2DColumn dataColumn) {
super(dataTable, dataColumn);
}
@Override
public void editCell() {
Data2DCoordinatePickerController.open(dataTable, editingRow);
}
public static Callback<TableColumn, TableCell> create(BaseData2DTableController dataControl, Data2DColumn dataColumn) {
return new Callback<TableColumn, TableCell>() {
@Override
public TableCell call(TableColumn param) {
return new TableDataCoordinateEditCell(dataControl, dataColumn);
}
};
}
}
| 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/fxml/cell/TableNumberCell.java | released/MyBox/src/main/java/mara/mybox/fxml/cell/TableNumberCell.java | package mara.mybox.fxml.cell;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.text.Text;
import javafx.util.Callback;
import mara.mybox.tools.StringTools;
import mara.mybox.value.AppValues;
/**
* @Author Mara
* @CreateDate 2019-3-15 14:24:30
* @License Apache License Version 2.0
*/
public class TableNumberCell<T> extends TableCell<T, Long>
implements Callback<TableColumn<T, Long>, TableCell<T, Long>> {
private boolean notPermitNegative = false;
public TableNumberCell(boolean notPermitNegative) {
this.notPermitNegative = notPermitNegative;
}
@Override
public TableCell<T, Long> call(TableColumn<T, Long> param) {
TableCell<T, Long> cell = new TableCell<T, Long>() {
private final Text text = new Text();
@Override
protected void updateItem(final Long item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null
|| item == AppValues.InvalidLong
|| (notPermitNegative && item < 0)) {
setText(null);
setGraphic(null);
return;
}
text.setText(StringTools.format(item));
setGraphic(text);
}
};
return cell;
}
}
| 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/fxml/cell/TableShortEnumCell.java | released/MyBox/src/main/java/mara/mybox/fxml/cell/TableShortEnumCell.java | package mara.mybox.fxml.cell;
import java.util.List;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.EventHandler;
import javafx.scene.Node;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableRow;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.ComboBoxTableCell;
import javafx.scene.input.MouseEvent;
import javafx.util.Callback;
import mara.mybox.controller.BaseData2DTableController;
import mara.mybox.db.data.Data2DColumn;
import mara.mybox.fxml.style.NodeStyleTools;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2021-10-26
* @License Apache License Version 2.0
*/
public class TableShortEnumCell extends ComboBoxTableCell<List<String>, String> {
protected BaseData2DTableController dataTable;
protected Data2DColumn dataColumn;
protected int maxVisibleCount;
public TableShortEnumCell(BaseData2DTableController dataTable, Data2DColumn dataColumn,
ObservableList<String> items, int maxCount, boolean editable) {
super(items);
setComboBoxEditable(editable);
maxVisibleCount = maxCount;
if (maxVisibleCount <= 0) {
maxVisibleCount = 10;
}
this.dataTable = dataTable;
this.dataColumn = dataColumn;
setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
TableView<List<String>> table = getTableView();
if (table != null && table.getItems() != null) {
int index = rowIndex();
if (index < table.getItems().size()) {
table.edit(index, getTableColumn());
}
}
}
});
}
@Override
public void startEdit() {
super.startEdit();
Node g = getGraphic();
if (g != null && g instanceof ComboBox) {
ComboBox cb = (ComboBox) g;
cb.setVisibleRowCount(maxVisibleCount);
cb.setValue(getItem());
if (isComboBoxEditable()) {
NodeStyleTools.setTooltip(cb.getEditor(), message("EditCellComments"));
}
}
}
public int rowIndex() {
try {
TableRow row = getTableRow();
if (row == null) {
return -1;
}
int index = row.getIndex();
if (index >= 0 && index < getTableView().getItems().size()) {
return index;
} else {
return -2;
}
} catch (Exception e) {
return -3;
}
}
@Override
public void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
setStyle(null);
if (empty) {
setText(null);
setGraphic(null);
return;
}
try {
setStyle(dataTable.getData2D().cellStyle(dataTable.getStyleFilter(),
rowIndex(), dataColumn.getColumnName()));
} catch (Exception e) {
}
// setText(item);
}
public static Callback<TableColumn, TableCell> create(
BaseData2DTableController dataTable, Data2DColumn dataColumn, List<String> items,
int maxVisibleCount, boolean editable) {
return new Callback<TableColumn, TableCell>() {
@Override
public TableCell call(TableColumn param) {
ObservableList<String> olist = FXCollections.observableArrayList();
for (String item : items) {
olist.add(item);
}
return new TableShortEnumCell(dataTable, dataColumn, olist, maxVisibleCount, editable);
}
};
}
}
| 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/fxml/cell/TableDataBooleanDisplayCell.java | released/MyBox/src/main/java/mara/mybox/fxml/cell/TableDataBooleanDisplayCell.java | package mara.mybox.fxml.cell;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.image.ImageView;
import javafx.util.Callback;
import mara.mybox.controller.BaseData2DTableController;
import mara.mybox.db.data.Data2DColumn;
import mara.mybox.fxml.style.StyleTools;
import mara.mybox.tools.StringTools;
/**
* @Author Mara
* @CreateDate 2022-10-1
* @License Apache License Version 2.0
*/
public class TableDataBooleanDisplayCell extends TableDataCell {
protected ImageView imageview;
public TableDataBooleanDisplayCell(BaseData2DTableController dataTable, Data2DColumn dataColumn) {
super(dataTable, dataColumn);
imageview = StyleTools.getIconImageView("iconYes.png");
imageview.setPreserveRatio(true);
}
@Override
public void displayData(String item) {
setText(null);
setGraphic(StringTools.isTrue(item) ? imageview : null);
}
public static Callback<TableColumn, TableCell>
create(BaseData2DTableController dataTable, Data2DColumn dataColumn) {
return new Callback<TableColumn, TableCell>() {
@Override
public TableCell call(TableColumn param) {
return new TableDataBooleanDisplayCell(dataTable, dataColumn);
}
};
}
}
| 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/fxml/cell/TreeTableEraCell.java | released/MyBox/src/main/java/mara/mybox/fxml/cell/TreeTableEraCell.java | package mara.mybox.fxml.cell;
import javafx.scene.control.TreeTableCell;
import javafx.scene.control.TreeTableColumn;
import javafx.util.Callback;
import mara.mybox.tools.DateTools;
import mara.mybox.value.AppValues;
/**
* @Author Mara
* @CreateDate 2019-3-15 14:24:30
* @Version 1.0
* @Description
* @License Apache License Version 2.0
*/
public class TreeTableEraCell<T> extends TreeTableCell<T, Long>
implements Callback<TreeTableColumn<T, Long>, TreeTableCell<T, Long>> {
@Override
public TreeTableCell<T, Long> call(TreeTableColumn<T, Long> param) {
TreeTableCell<T, Long> cell = new TreeTableCell<T, Long>() {
@Override
protected void updateItem(final Long item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null || item == AppValues.InvalidLong) {
setText(null);
setGraphic(null);
return;
}
setText(DateTools.textEra(item));
setGraphic(null);
}
};
return cell;
}
}
| 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/fxml/cell/TableColorEditCell.java | released/MyBox/src/main/java/mara/mybox/fxml/cell/TableColorEditCell.java | package mara.mybox.fxml.cell;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.EventHandler;
import javafx.scene.Node;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.TableCell;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.scene.paint.Paint;
import javafx.scene.shape.Rectangle;
import mara.mybox.controller.BaseController;
import mara.mybox.controller.ColorPalettePopupController;
import mara.mybox.db.table.TableColor;
import mara.mybox.fxml.image.FxColorTools;
import mara.mybox.fxml.style.NodeStyleTools;
import static mara.mybox.value.Languages.message;
/**
* Reference:
* https://stackoverflow.com/questions/24694616/how-to-enable-commit-on-focuslost-for-tableview-treetableview
* By Ogmios
*
* @Author Mara
* @CreateDate 2020-12-03
* @License Apache License Version 2.0
*/
public class TableColorEditCell<S> extends TableCell<S, Color> {
protected BaseController parent;
protected TableColor tableColor;
protected Rectangle rectangle;
protected String msgPrefix;
public TableColorEditCell(BaseController parent, TableColor tableColor) {
this.parent = parent;
this.tableColor = tableColor;
if (this.tableColor == null) {
this.tableColor = new TableColor();
}
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
rectangle = new Rectangle(30, 20);
rectangle.setStroke(Color.BLACK);
rectangle.setStrokeWidth(1);
msgPrefix = message("ClickColorToPalette");
this.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
setColor();
}
});
}
@Override
protected void updateItem(Color item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setGraphic(null);
return;
}
if (item == null) {
rectangle.setFill(Color.WHITE);
NodeStyleTools.setTooltip(rectangle, msgPrefix);
} else {
rectangle.setFill((Paint) item);
NodeStyleTools.setTooltip(rectangle, msgPrefix + "\n---------\n"
+ FxColorTools.colorNameDisplay(tableColor, item));
}
setGraphic(rectangle);
}
public void setColor() {
Node g = getGraphic();
if (g == null || !(g instanceof Rectangle)) {
return;
}
ColorPalettePopupController controller = ColorPalettePopupController.open(parent, rectangle);
controller.getSetNotify().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue ov, Boolean oldValue, Boolean newValue) {
if (controller == null) {
return;
}
colorChanged(getIndex(), (Color) rectangle.getFill());
controller.close();
}
});
}
public void colorChanged(int index, Color color) {
}
}
| 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/fxml/cell/TreeTableSelectionCell.java | released/MyBox/src/main/java/mara/mybox/fxml/cell/TreeTableSelectionCell.java | package mara.mybox.fxml.cell;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.ListChangeListener;
import javafx.scene.control.TreeTableCell;
import javafx.scene.control.TreeTableColumn;
import javafx.scene.control.TreeTableView;
import javafx.scene.control.cell.CheckBoxTreeTableCell;
import javafx.util.Callback;
import mara.mybox.dev.MyBoxLog;
/**
* @Author Mara
* @CreateDate 2021-10-26
* @License Apache License Version 2.0
*/
public class TreeTableSelectionCell<S, T> extends CheckBoxTreeTableCell<S, T> {
protected TreeTableView treeView;
protected SimpleBooleanProperty checked;
protected boolean selectingRow, checkingBox;
protected ChangeListener<Boolean> checkedListener;
protected ListChangeListener selectedListener;
public TreeTableSelectionCell(TreeTableView tView) {
treeView = tView;
checked = new SimpleBooleanProperty(false);
selectingRow = checkingBox = false;
getStyleClass().add("row-number");
// treeView.getSelectionModel().getSelectedIndices().addListener(selectedListener);
// checked.addListener(checkedListener);
setSelectedStateCallback(new Callback<Integer, ObservableValue<Boolean>>() {
@Override
public synchronized ObservableValue<Boolean> call(Integer index) {
MyBoxLog.console(index);
if (index < 0) {
return null;
}
checkingBox = true;
checked.set(isChecked());
checkingBox = false;
return checked;
}
});
selectedProperty().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue v, Boolean ov, Boolean nv) {
MyBoxLog.console(nv + " " + getTableRow().getIndex());
}
});
}
public boolean isChecked() {
return true;
}
@Override
public void updateItem(T item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null) {
setText(null);
setGraphic(null);
}
}
public static <S, T> Callback<TreeTableColumn<S, T>, TreeTableCell<S, T>> create(TreeTableView treeView) {
return new Callback<TreeTableColumn<S, T>, TreeTableCell<S, T>>() {
@Override
public TreeTableCell<S, T> call(TreeTableColumn<S, T> param) {
return new TreeTableSelectionCell<>(treeView);
}
};
}
public SimpleBooleanProperty getSelected() {
return checked;
}
public void setSelected(SimpleBooleanProperty selected) {
this.checked = selected;
}
}
| 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/fxml/cell/TablePercentageCell.java | released/MyBox/src/main/java/mara/mybox/fxml/cell/TablePercentageCell.java | package mara.mybox.fxml.cell;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.util.Callback;
import mara.mybox.tools.DoubleTools;
/**
* @Author Mara
* @CreateDate 2019-3-15 14:17:47
* @Version 1.0
* @Description
* @License Apache License Version 2.0
*/
public class TablePercentageCell<T> extends TableCell<T, Double>
implements Callback<TableColumn<T, Double>, TableCell<T, Double>> {
@Override
public TableCell<T, Double> call(TableColumn<T, Double> param) {
TableCell<T, Double> cell = new TableCell<T, Double>() {
@Override
public void updateItem(Double item, boolean empty) {
super.updateItem(item, empty);
setGraphic(null);
if (empty || item == null) {
setText(null);
return;
}
if (!DoubleTools.invalidDouble(item)) {
setText(DoubleTools.scale(item * 100.0d, 2) + "");
} else {
setText(null);
}
}
};
return cell;
}
}
| 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/fxml/cell/CellTools.java | released/MyBox/src/main/java/mara/mybox/fxml/cell/CellTools.java | package mara.mybox.fxml.cell;
import javafx.scene.control.ComboBox;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.util.Callback;
import mara.mybox.db.data.Data2DColumn;
/**
* @Author Mara
* @CreateDate 2025-12-14
* @License Apache License Version 2.0
*/
public class CellTools {
public static void makeColumnComboBox(ComboBox<Data2DColumn> colSelector) {
if (colSelector == null) {
return;
}
Callback<ListView<Data2DColumn>, ListCell<Data2DColumn>> colFactory
= new Callback<ListView<Data2DColumn>, ListCell<Data2DColumn>>() {
@Override
public ListCell<Data2DColumn> call(ListView<Data2DColumn> param) {
ListCell<Data2DColumn> cell = new ListCell<Data2DColumn>() {
@Override
public void updateItem(Data2DColumn item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null) {
setText(null);
setGraphic(null);
return;
}
setText(item.getLabel());
}
};
return cell;
}
};
colSelector.setButtonCell(colFactory.call(null));
colSelector.setCellFactory(colFactory);
}
public static void selectItem(ComboBox<Data2DColumn> colSelector, String name) {
if (colSelector == null || name == null) {
return;
}
for (Data2DColumn col : colSelector.getItems()) {
if (name.equals(col.getColumnName()) || name.equals(col.getLabel())) {
colSelector.getSelectionModel().select(col);
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/mara/mybox/fxml/cell/TableTextTrimCell.java | released/MyBox/src/main/java/mara/mybox/fxml/cell/TableTextTrimCell.java | package mara.mybox.fxml.cell;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.util.Callback;
import mara.mybox.tools.StringTools;
import mara.mybox.value.AppVariables;
/**
* @Author Mara
* @CreateDate 2023-9-18
* @License Apache License Version 2.0
*/
public class TableTextTrimCell<T> extends TableCell<T, String>
implements Callback<TableColumn<T, String>, TableCell<T, String>> {
@Override
public TableCell<T, String> call(TableColumn<T, String> param) {
TableCell<T, String> cell = new TableCell<T, String>() {
@Override
protected void updateItem(final String item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null) {
setText(null);
setGraphic(null);
return;
}
setText(StringTools.abbreviate(item, AppVariables.titleTrimSize));
setGraphic(null);
}
};
return cell;
}
}
| 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/fxml/cell/TableLongitudeCell.java | released/MyBox/src/main/java/mara/mybox/fxml/cell/TableLongitudeCell.java | package mara.mybox.fxml.cell;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.util.Callback;
/**
* @Author Mara
* @CreateDate 2020-2-22
* @License Apache License Version 2.0
*/
public class TableLongitudeCell<T> extends TableCell<T, Double>
implements Callback<TableColumn<T, Double>, TableCell<T, Double>> {
@Override
public TableCell<T, Double> call(TableColumn<T, Double> param) {
TableCell<T, Double> cell = new TableCell<T, Double>() {
@Override
public void updateItem(Double item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null) {
setGraphic(null);
setText(null);
setTextFill(null);
return;
}
if (item >= -180 && item <= 180) {
setText(item + "");
} else {
setText(null);
}
setGraphic(null);
}
};
return cell;
}
}
| 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/fxml/cell/ListImageItemCell.java | released/MyBox/src/main/java/mara/mybox/fxml/cell/ListImageItemCell.java | package mara.mybox.fxml.cell;
import javafx.scene.control.ListCell;
import mara.mybox.data.ImageItem;
/**
* @Author Mara
* @CreateDate 2020-1-5
* @License Apache License Version 2.0
*/
public class ListImageItemCell extends ListCell<ImageItem> {
protected int height = 60;
public ListImageItemCell() {
}
public ListImageItemCell(int imageSize) {
this.height = imageSize;
}
@Override
public void updateItem(ImageItem item, boolean empty) {
super.updateItem(item, empty);
setText(null);
if (empty || item == null) {
setGraphic(null);
return;
}
setGraphic(item.makeNode(height, 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/fxml/cell/TableFileSizeCell.java | released/MyBox/src/main/java/mara/mybox/fxml/cell/TableFileSizeCell.java | package mara.mybox.fxml.cell;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.text.Text;
import javafx.util.Callback;
import mara.mybox.tools.FileTools;
/**
* @Author Mara
* @CreateDate 2019-3-15 14:24:30
* @License Apache License Version 2.0
*/
public class TableFileSizeCell<T> extends TableCell<T, Long>
implements Callback<TableColumn<T, Long>, TableCell<T, Long>> {
@Override
public TableCell<T, Long> call(TableColumn<T, Long> param) {
TableCell<T, Long> cell = new TableCell<T, Long>() {
private final Text text = new Text();
@Override
protected void updateItem(final Long item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null || item <= 0) {
setText(null);
setGraphic(null);
return;
}
text.setText(FileTools.showFileSize(item));
setGraphic(text);
}
};
return cell;
}
}
| 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/fxml/cell/TableEraCell.java | released/MyBox/src/main/java/mara/mybox/fxml/cell/TableEraCell.java | package mara.mybox.fxml.cell;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.util.Callback;
import mara.mybox.data.Era;
import mara.mybox.tools.DateTools;
/**
* @Author Mara
* @CreateDate 2020-7-7
* @License Apache License Version 2.0
*/
public class TableEraCell<T> extends TableCell<T, Era>
implements Callback<TableColumn<T, Era>, TableCell<T, Era>> {
@Override
public TableCell<T, Era> call(TableColumn<T, Era> param) {
TableCell<T, Era> cell = new TableCell<T, Era>() {
@Override
public void updateItem(Era item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null) {
setText(null);
setGraphic(null);
return;
}
setText(DateTools.textEra(item));
setGraphic(null);
}
};
return cell;
}
}
| 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/fxml/cell/TableDataColumnCell.java | released/MyBox/src/main/java/mara/mybox/fxml/cell/TableDataColumnCell.java | package mara.mybox.fxml.cell;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.util.Callback;
import mara.mybox.controller.ControlData2DColumns;
import mara.mybox.controller.Data2DColumnEditController;
/**
* @Author Mara
* @CreateDate 2022-10-4
* @License Apache License Version 2.0
*/
public class TableDataColumnCell<S, T> extends TableAutoCommitCell<S, T> {
protected ControlData2DColumns columnsControl;
public TableDataColumnCell(ControlData2DColumns columnsControl) {
super(null);
this.columnsControl = columnsControl;
}
@Override
public void editCell() {
Data2DColumnEditController.open(columnsControl, editingRow);
}
@Override
public boolean setCellValue(T value) {
return true;
}
public static <S, T> Callback<TableColumn<S, T>, TableCell<S, T>> create(ControlData2DColumns columnsControl) {
return new Callback<TableColumn<S, T>, TableCell<S, T>>() {
@Override
public TableCell<S, T> call(TableColumn<S, T> param) {
return new TableDataColumnCell(columnsControl);
}
};
}
}
| 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/fxml/cell/TableDataDisplayCell.java | released/MyBox/src/main/java/mara/mybox/fxml/cell/TableDataDisplayCell.java | package mara.mybox.fxml.cell;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.util.Callback;
import mara.mybox.controller.BaseData2DTableController;
import mara.mybox.db.data.Data2DColumn;
/**
* @Author Mara
* @CreateDate 2022-9-26
* @License Apache License Version 2.0
*/
public class TableDataDisplayCell extends TableDataCell {
public TableDataDisplayCell(BaseData2DTableController dataTable, Data2DColumn dataColumn) {
super(dataTable, dataColumn);
}
@Override
public void startEdit() {
}
@Override
public void commitEdit(String inValue) {
}
@Override
public boolean commit(String value) {
return true;
}
public static Callback<TableColumn, TableCell> create(BaseData2DTableController dataTable, Data2DColumn dataColumn) {
return new Callback<TableColumn, TableCell>() {
@Override
public TableCell call(TableColumn param) {
return new TableDataDisplayCell(dataTable, dataColumn);
}
};
}
}
| 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/fxml/cell/TableMessageCell.java | released/MyBox/src/main/java/mara/mybox/fxml/cell/TableMessageCell.java | package mara.mybox.fxml.cell;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.util.Callback;
import mara.mybox.value.AppVariables;
import mara.mybox.value.Languages;
/**
* @Author Mara
* @CreateDate 2020-02-08
* @License Apache License Version 2.0
*/
public class TableMessageCell<T> extends TableCell<T, String>
implements Callback<TableColumn<T, String>, TableCell<T, String>> {
@Override
public TableCell<T, String> call(TableColumn<T, String> param) {
TableCell<T, String> cell = new TableCell<T, String>() {
@Override
public void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null) {
setText(null);
setGraphic(null);
return;
}
setText(Languages.message(item));
setGraphic(null);
}
};
return cell;
}
}
| 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/fxml/cell/TableDataEditCell.java | released/MyBox/src/main/java/mara/mybox/fxml/cell/TableDataEditCell.java | package mara.mybox.fxml.cell;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.util.Callback;
import mara.mybox.controller.BaseData2DTableController;
import mara.mybox.controller.TextInputController;
import mara.mybox.db.data.Data2DColumn;
/**
* @Author Mara
* @CreateDate 2022-9-26
* @License Apache License Version 2.0
*/
public class TableDataEditCell extends TableDataCell {
public TableDataEditCell(BaseData2DTableController dataTable, Data2DColumn dataColumn) {
super(dataTable, dataColumn);
}
@Override
public void editCell() {
String s = getItem();
if (supportMultipleLine && s != null && (s.contains("\n") || s.length() > 200)) {
TextInputController inputController = TextInputController.open(dataTable, name(), s);
inputController.getNotify().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
String value = inputController.getInputString();
setCellValue(value);
inputController.close();
}
});
} else {
super.editCell();
}
}
public static Callback<TableColumn, TableCell> create(BaseData2DTableController dataTable, Data2DColumn dataColumn) {
return new Callback<TableColumn, TableCell>() {
@Override
public TableCell call(TableColumn param) {
return new TableDataEditCell(dataTable, dataColumn);
}
};
}
}
| 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/fxml/cell/TableDataDateEditCell.java | released/MyBox/src/main/java/mara/mybox/fxml/cell/TableDataDateEditCell.java | package mara.mybox.fxml.cell;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.util.Callback;
import mara.mybox.controller.BaseData2DTableController;
import mara.mybox.controller.DateInputController;
import mara.mybox.db.data.Data2DColumn;
/**
* @Author Mara
* @CreateDate 2022-10-2
* @License Apache License Version 2.0
*/
public class TableDataDateEditCell extends TableDataEditCell {
public TableDataDateEditCell(BaseData2DTableController dataControl, Data2DColumn dataColumn) {
super(dataControl, dataColumn);
}
@Override
public void editCell() {
DateInputController inputController
= DateInputController.open(dataTable, name(), getCellValue(), dataColumn.getType());
inputController.getNotify().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
String value = inputController.getInputString();
setCellValue(value);
inputController.close();
}
});
}
public static Callback<TableColumn, TableCell> create(BaseData2DTableController dataControl, Data2DColumn dataColumn) {
return new Callback<TableColumn, TableCell>() {
@Override
public TableCell call(TableColumn param) {
return new TableDataDateEditCell(dataControl, dataColumn);
}
};
}
}
| 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/fxml/cell/TableDoubleCell.java | released/MyBox/src/main/java/mara/mybox/fxml/cell/TableDoubleCell.java | package mara.mybox.fxml.cell;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.util.Callback;
import mara.mybox.tools.DoubleTools;
/**
* @Author Mara
* @CreateDate 2019-3-15 14:17:47
* @Version 1.0
* @Description
* @License Apache License Version 2.0
*/
public class TableDoubleCell<T> extends TableCell<T, Double>
implements Callback<TableColumn<T, Double>, TableCell<T, Double>> {
@Override
public TableCell<T, Double> call(TableColumn<T, Double> param) {
TableCell<T, Double> cell = new TableCell<T, Double>() {
@Override
public void updateItem(Double item, boolean empty) {
super.updateItem(item, empty);
setGraphic(null);
if (empty || item == null) {
setText(null);
return;
}
if (!DoubleTools.invalidDouble(item)) {
setText(item + "");
} else {
setText(null);
}
}
};
return cell;
}
}
| 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/fxml/cell/TableTimeCell.java | released/MyBox/src/main/java/mara/mybox/fxml/cell/TableTimeCell.java | package mara.mybox.fxml.cell;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.util.Callback;
import mara.mybox.tools.DateTools;
import mara.mybox.value.AppValues;
/**
* @Author Mara
* @CreateDate 2020-7-7
* @License Apache License Version 2.0
*/
public class TableTimeCell<T> extends TableCell<T, Long>
implements Callback<TableColumn<T, Long>, TableCell<T, Long>> {
@Override
public TableCell<T, Long> call(TableColumn<T, Long> param) {
TableCell<T, Long> cell = new TableCell<T, Long>() {
@Override
public void updateItem(Long item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null || item == AppValues.InvalidLong) {
setText(null);
setGraphic(null);
return;
}
setText(DateTools.textEra(item));
setGraphic(null);
}
};
return cell;
}
}
| 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/fxml/cell/TableAutoCommitCell.java | released/MyBox/src/main/java/mara/mybox/fxml/cell/TableAutoCommitCell.java | package mara.mybox.fxml.cell;
import java.text.SimpleDateFormat;
import java.util.Date;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.scene.Node;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableColumn.CellEditEvent;
import javafx.scene.control.TablePosition;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.util.Callback;
import javafx.util.StringConverter;
import javafx.util.converter.DateTimeStringConverter;
import javafx.util.converter.DefaultStringConverter;
import mara.mybox.data.Era;
import mara.mybox.dev.MyBoxLog;
import mara.mybox.fxml.converter.ColorStringConverter;
import mara.mybox.fxml.converter.DoubleStringFromatConverter;
import mara.mybox.fxml.converter.EraStringConverter;
import mara.mybox.fxml.converter.FloatStringFromatConverter;
import mara.mybox.fxml.converter.IntegerStringFromatConverter;
import mara.mybox.fxml.converter.LongStringFromatConverter;
import mara.mybox.fxml.converter.ShortStringFromatConverter;
import mara.mybox.fxml.style.NodeStyleTools;
import mara.mybox.value.AppVariables;
import static mara.mybox.value.Languages.message;
import mara.mybox.value.TimeFormats;
import mara.mybox.value.UserConfig;
/**
* Reference:
* https://stackoverflow.com/questions/24694616/how-to-enable-commit-on-focuslost-for-tableview-treetableview
* By Ogmios
*
* @Author Mara
* @CreateDate 2020-12-03
* @License Apache License Version 2.0
*
* This is an old issue since 2011
* https://bugs.openjdk.java.net/browse/JDK-8089514
* https://bugs.openjdk.java.net/browse/JDK-8089311
*/
public class TableAutoCommitCell<S, T> extends TextFieldTableCell<S, T> {
protected String editingText;
protected int editingRow = -1;
protected ChangeListener<Boolean> focusListener;
protected ChangeListener<String> editListener;
protected EventHandler<KeyEvent> keyReleasedHandler;
public TableAutoCommitCell() {
this(null);
}
public TableAutoCommitCell(StringConverter<T> conv) {
super(conv);
setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
mouseClicked(event);
}
});
}
public void mouseClicked(MouseEvent event) {
startEdit();
}
public TextField editor() {
Node g = getGraphic();
if (g != null && g instanceof TextField) {
return (TextField) g;
} else {
return null;
}
}
public int size() {
try {
return getTableView().getItems().size();
} catch (Exception e) {
// MyBoxLog.debug(e);
return -1;
}
}
public int rowIndex() {
int rowIndex = -2;
try {
int v = getTableRow().getIndex();
if (v >= 0 && v < size()) {
rowIndex = v;
}
} catch (Exception e) {
}
return rowIndex;
}
public boolean isEditingRow() {
int rowIndex = rowIndex();
return rowIndex >= 0 && editingRow == rowIndex;
}
public boolean validText(String text) {
try {
return valid(getConverter().fromString(text));
} catch (Exception e) {
return false;
}
}
public boolean valid(final T value) {
return true;
}
public boolean changed(final T value) {
T oValue = getItem();
if (oValue == null) {
return value != null;
} else {
return !oValue.equals(value);
}
}
protected String name() {
return message("TableRowNumber") + " " + (rowIndex() + 1) + "\n"
+ getTableColumn().getText();
}
public boolean initEditor() {
editingRow = rowIndex();
return editingRow >= 0;
}
@Override
public void startEdit() {
try {
if (!initEditor()) {
return;
}
editCell();
} catch (Exception e) {
MyBoxLog.console(e);
}
}
public void editCell() {
try {
super.startEdit();
clearEditor();
TextField editor = editor();
if (editor == null) {
return;
}
if (focusListener == null) {
initListeners();
}
editingText = editor.getText();
editor.focusedProperty().addListener(focusListener);
editor.textProperty().addListener(editListener);
editor.setOnKeyReleased(keyReleasedHandler);
editor.setStyle(null);
NodeStyleTools.setTooltip(editor, message("EditCellComments"));
} catch (Exception e) {
MyBoxLog.console(e);
}
}
public void initListeners() {
focusListener = new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
try {
if (!newValue) {
if (AppVariables.commitModificationWhenDataCellLoseFocus && isEditingRow()) {
commitEdit(getConverter().fromString(editingText));
} else {
clearEditor();
cancelCell();
}
editingRow = -1;
}
} catch (Exception e) {
}
}
};
editListener = new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
try {
if (!isEditingRow()) {
return;
}
TextField editor = editor();
if (editor == null) {
return;
}
editingText = editor.getText();
if (validText(editingText)) {
editor.setStyle(null);
} else {
editor.setStyle(UserConfig.badStyle());
}
} catch (Exception e) {
}
}
};
keyReleasedHandler = new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent event) {
switch (event.getCode()) {
case ESCAPE:
cancelCell();
event.consume();
break;
case TAB:
if (event.isShiftDown()) {
getTableView().getSelectionModel().selectPrevious();
} else {
getTableView().getSelectionModel().selectNext();
}
event.consume();
break;
case UP:
getTableView().getSelectionModel().selectAboveCell();
event.consume();
break;
case DOWN:
getTableView().getSelectionModel().selectBelowCell();
event.consume();
break;
default:
break;
}
}
};
}
public void clearEditor() {
try {
TextField editor = editor();
if (editor == null) {
return;
}
if (focusListener != null) {
editor.focusedProperty().removeListener(focusListener);
}
if (editListener != null) {
editor.textProperty().removeListener(editListener);
}
editor.setOnKeyReleased(null);
editor.setStyle(null);
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
@Override
public void commitEdit(T value) {
try {
clearEditor();
boolean valid = valid(value);
boolean changed = changed(value);
if (!isEditingRow() || !valid || !changed) {
cancelCell();
} else {
setCellValue(value);
}
editingRow = -1;
} catch (Exception e) {
MyBoxLog.debug(e);
}
}
public boolean setCellValue(T value) {
try {
if (isEditing()) {
super.commitEdit(value);
} else {
return commit(value);
}
return true;
} catch (Exception e) {
MyBoxLog.debug(e);
return false;
}
}
public boolean commit(T value) {
try {
TableView<S> table = getTableView();
if (table != null && isEditingRow()) {
TableColumn<S, T> column = getTableColumn();
if (column == null) {
cancelCell();
} else {
TablePosition<S, T> pos = new TablePosition<>(table, editingRow, column);
CellEditEvent<S, T> ev = new CellEditEvent<>(table, pos, TableColumn.editCommitEvent(), value);
Event.fireEvent(column, ev);
updateItem(value, false);
}
} else {
cancelCell();
}
if (table != null) {
table.edit(-1, null);
}
return true;
} catch (Exception e) {
MyBoxLog.debug(e);
return false;
}
}
public void cancelCell() {
editingRow = -1;
cancelEdit();
updateItem(getItem(), false);
}
/*
static
*/
public static <S> Callback<TableColumn<S, String>, TableCell<S, String>> forStringColumn() {
return new Callback<TableColumn<S, String>, TableCell<S, String>>() {
@Override
public TableCell<S, String> call(TableColumn<S, String> param) {
return new TableAutoCommitCell<>(new DefaultStringConverter());
}
};
}
public static <S> Callback<TableColumn<S, Integer>, TableCell<S, Integer>> forIntegerColumn() {
return new Callback<TableColumn<S, Integer>, TableCell<S, Integer>>() {
@Override
public TableCell<S, Integer> call(TableColumn<S, Integer> param) {
return new TableAutoCommitCell<>(new IntegerStringFromatConverter());
}
};
}
public static <S> Callback<TableColumn<S, Long>, TableCell<S, Long>> forLongColumn() {
return new Callback<TableColumn<S, Long>, TableCell<S, Long>>() {
@Override
public TableCell<S, Long> call(TableColumn<S, Long> param) {
return new TableAutoCommitCell<>(new LongStringFromatConverter());
}
};
}
public static <S> Callback<TableColumn<S, Float>, TableCell<S, Float>> forFloatColumn() {
return new Callback<TableColumn<S, Float>, TableCell<S, Float>>() {
@Override
public TableCell<S, Float> call(TableColumn<S, Float> param) {
return new TableAutoCommitCell<>(new FloatStringFromatConverter());
}
};
}
public static <S> Callback<TableColumn<S, Double>, TableCell<S, Double>> forDoubleColumn() {
return new Callback<TableColumn<S, Double>, TableCell<S, Double>>() {
@Override
public TableCell<S, Double> call(TableColumn<S, Double> param) {
return new TableAutoCommitCell<>(new DoubleStringFromatConverter());
}
};
}
public static <S> Callback<TableColumn<S, Short>, TableCell<S, Short>> forShortColumn() {
return new Callback<TableColumn<S, Short>, TableCell<S, Short>>() {
@Override
public TableCell<S, Short> call(TableColumn<S, Short> param) {
return new TableAutoCommitCell<>(new ShortStringFromatConverter());
}
};
}
public static <S> Callback<TableColumn<S, Date>, TableCell<S, Date>> forDateTimeColumn() {
return new Callback<TableColumn<S, Date>, TableCell<S, Date>>() {
@Override
public TableCell<S, Date> call(TableColumn<S, Date> param) {
return new TableAutoCommitCell<>(new DateTimeStringConverter(new SimpleDateFormat(TimeFormats.Datetime)));
}
};
}
public static <S> Callback<TableColumn<S, Era>, TableCell<S, Era>> forEraColumn() {
return new Callback<TableColumn<S, Era>, TableCell<S, Era>>() {
@Override
public TableCell<S, Era> call(TableColumn<S, Era> param) {
return new TableAutoCommitCell<>(new EraStringConverter());
}
};
}
public static <S> Callback<TableColumn<S, Color>, TableCell<S, Color>> forColorColumn() {
return new Callback<TableColumn<S, Color>, TableCell<S, Color>>() {
@Override
public TableCell<S, Color> call(TableColumn<S, Color> param) {
return new TableAutoCommitCell<>(new ColorStringConverter());
}
};
}
}
| 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/fxml/style/StyleData.java | released/MyBox/src/main/java/mara/mybox/fxml/style/StyleData.java | package mara.mybox.fxml.style;
/**
* @Author Mara
* @CreateDate 2019-4-26 7:16:14
* @License Apache License Version 2.0
*/
public class StyleData {
public static enum StyleColor {
Red, Blue, LightBlue, Pink, Orange, Green, Customize
}
private String id, name, comments, shortcut, iconName;
public StyleData(String id) {
this.id = id;
}
public StyleData(String id, String name, String shortcut, String iconName) {
this.id = id;
this.name = name;
this.shortcut = shortcut;
this.iconName = iconName;
}
public StyleData(String id, String name, String comments, String shortcut, String iconName) {
this.id = id;
this.name = name;
this.comments = comments;
this.shortcut = shortcut;
this.iconName = iconName;
}
/*
get/set
*/
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getShortcut() {
return shortcut;
}
public void setShortcut(String shortcut) {
this.shortcut = shortcut;
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
public String getIconName() {
return iconName;
}
public void setIconName(String iconName) {
this.iconName = iconName;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = 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/mara/mybox/fxml/style/StyleRadioButton.java | released/MyBox/src/main/java/mara/mybox/fxml/style/StyleRadioButton.java | package mara.mybox.fxml.style;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2021-7-30
* @License Apache License Version 2.0
*/
public class StyleRadioButton {
public static StyleData radioButtonStyle(String id) {
if (id == null || id.isEmpty()) {
return null;
}
StyleData d = equals(id);
if (d != null) {
return d;
}
return start(id);
}
private static StyleData equals(String id) {
switch (id) {
case "miaoRadio":
return new StyleData(id, message("Meow"), message("MiaoPrompt"), "", "iconCat.png");
case "lineRadio":
return new StyleData(id, message("StraightLine"), "", "iconLine.png");
case "rectangleRadio":
return new StyleData(id, message("Rectangle"), "", "iconRectangle.png");
case "circleRadio":
return new StyleData(id, message("Circle"), "", "iconCircle.png");
case "ellipseRadio":
return new StyleData(id, message("Ellipse"), "", "iconEllipse.png");
case "polylineRadio":
return new StyleData(id, message("Polyline"), "", "iconPolyline.png");
case "polylinesRadio":
return new StyleData(id, message("Graffiti"), "", "iconPolylines.png");
case "polygonRadio":
return new StyleData(id, message("Polygon"), "", "iconStar.png");
case "quadraticRadio":
return new StyleData(id, message("QuadraticCurve"), "", "iconQuadratic.png");
case "cubicRadio":
return new StyleData(id, message("CubicCurve"), "", "iconCubic.png");
case "arcRadio":
return new StyleData(id, message("ArcCurve"), "", "iconArc.png");
case "svgRadio":
return new StyleData(id, message("SVGPath"), "", "iconSVG.png");
case "eraserRadio":
return new StyleData(id, message("Eraser"), "", "iconEraser.png");
case "mosaicRadio":
return new StyleData(id, message("Mosaic"), "", "iconMosaic.png");
case "frostedRadio":
return new StyleData(id, message("FrostedGlass"), "", "iconFrosted.png");
case "horizontalBarChartRadio":
return new StyleData(id, message("HorizontalBarChart"), "", "iconBarChartH.png");
case "barChartRadio":
return new StyleData(id, message("BarChart"), "", "iconBarChart.png");
case "stackedBarChartRadio":
return new StyleData(id, message("StackedBarChart"), "", "iconStackedBarChart.png");
case "verticalLineChartRadio":
return new StyleData(id, message("VerticalLineChart"), "", "iconLineChartV.png");
case "lineChartRadio":
return new StyleData(id, message("LineChart"), "", "iconLineChart.png");
case "pieRadio":
return new StyleData(id, message("PieChart"), "", "iconPieChart.png");
case "areaChartRadio":
return new StyleData(id, message("AreaChart"), "", "iconAreaChart.png");
case "stackedAreaChartRadio":
return new StyleData(id, message("StackedAreaChart"), "", "iconStackedAreaChart.png");
case "scatterChartRadio":
return new StyleData(id, message("ScatterChart"), "", "iconScatterChart.png");
case "bubbleChartRadio":
return new StyleData(id, message("BubbleChart"), "", "iconBubbleChart.png");
case "mapRadio":
return new StyleData(id, message("Map"), "", "iconMap.png");
case "pcxSelect":
return new StyleData(id, "pcx", message("PcxComments"), "", "");
case "setRadio":
return new StyleData(id, message("Set"), "", "");
case "plusRadio":
return new StyleData(id, message("Plus"), "", "");
case "minusRadio":
return new StyleData(id, message("Minus"), "", "");
case "filterRadio":
return new StyleData(id, message("Filter"), "", "");
case "invertRadio":
return new StyleData(id, message("Invert"), "", "");
case "colorRGBRadio":
return new StyleData(id, message("RGB"), "", "");
case "colorBrightnessRadio":
return new StyleData(id, message("Brightness"), "", "iconBrightness.png");
case "colorHueRadio":
return new StyleData(id, message("Hue"), "", "iconHue.png");
case "colorSaturationRadio":
return new StyleData(id, message("Saturation"), "", "iconSaturation.png");
case "colorRedRadio":
return new StyleData(id, message("Red"), "", "");
case "colorGreenRadio":
return new StyleData(id, message("Green"), "", "");
case "colorBlueRadio":
return new StyleData(id, message("Blue"), "", "");
case "colorYellowRadio":
return new StyleData(id, message("Yellow"), "", "");
case "colorCyanRadio":
return new StyleData(id, message("Cyan"), "", "");
case "colorMagentaRadio":
return new StyleData(id, message("Magenta"), "", "");
case "colorOpacityRadio":
return new StyleData(id, message("Opacity"), "", "iconOpacity.png");
case "listRadio":
return new StyleData(id, message("List"), "", "iconList.png");
case "thumbRadio":
return new StyleData(id, message("ThumbnailsList"), "", "iconThumbsList.png");
case "gridRadio":
return new StyleData(id, message("Grid"), "", "iconBrowse.png");
case "codesRaido":
return new StyleData(id, message("HtmlCodes"), "", "iconMeta.png");
case "treeRadio":
return new StyleData(id, message("Tree"), "", "iconTree.png");
case "richRadio":
return new StyleData(id, message("RichText"), "", "iconEdit.png");
case "mdRadio":
return new StyleData(id, "Markdown", "", "iconMarkdown.png");
case "textsRadio":
return new StyleData(id, message("Texts"), "", "iconTxt.png");
case "htmlRadio":
return new StyleData(id, message("Html"), "", "iconHtml.png");
case "ocrRadio":
return new StyleData(id, message("OCR"), "", "iconOCR.png");
case "wholeRadio":
return new StyleData(id, message("WholeImage"), "", "iconSelectAll.png");
case "matting4Radio":
return new StyleData(id, message("Matting4"), "", "iconColorFill4.png");
case "matting8Radio":
return new StyleData(id, message("Matting8"), "", "iconColorFill.png");
case "outlineRadio":
return new StyleData(id, message("Outline"), "", "iconButterfly.png");
case "imageRadio":
return new StyleData(id, message("Image"), "", "iconImage.png");
}
return null;
}
private static StyleData start(String id) {
if (id.startsWith("csv")) {
return new StyleData(id, "CSV", "", "iconCSV.png");
}
if (id.startsWith("excel")) {
return new StyleData(id, "Excel", "", "iconExcel.png");
}
if (id.startsWith("texts")) {
return new StyleData(id, message("Texts"), "", "iconTxt.png");
}
if (id.startsWith("matrix")) {
return new StyleData(id, message("Matrix"), "", "iconMatrix.png");
}
if (id.startsWith("database")) {
return new StyleData(id, message("DatabaseTable"), "", "iconDatabase.png");
}
if (id.startsWith("systemClipboard")) {
return new StyleData(id, message("SystemClipboard"), "", "iconSystemClipboard.png");
}
if (id.startsWith("myBoxClipboard")) {
return new StyleData(id, message("MyBoxClipboard"), "", "iconClipboard.png");
}
if (id.startsWith("html")) {
return new StyleData(id, "Html", "", "iconHtml.png");
}
if (id.startsWith("xml")) {
return new StyleData(id, "XML", "", "iconXML.png");
}
if (id.startsWith("pdf")) {
return new StyleData(id, "PDF", "", "iconPDF.png");
}
if (id.startsWith("json")) {
return new StyleData(id, "json", "", "iconJSON.png");
}
if (id.startsWith("table")) {
return new StyleData(id, message("Table"), "", "iconGrid.png");
}
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/fxml/style/StyleToggleButton.java | released/MyBox/src/main/java/mara/mybox/fxml/style/StyleToggleButton.java | package mara.mybox.fxml.style;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2021-7-30
* @License Apache License Version 2.0
*/
public class StyleToggleButton {
public static StyleData toggleButtonStyle(String id) {
if (id == null || id.isEmpty()) {
return null;
}
StyleData d = match(id);
if (d != null) {
return d;
}
return startsWith(id);
}
private static StyleData match(String id) {
switch (id) {
case "pickColorButton":
return new StyleData("pickColorButton", message("PickColor"), "", "iconPickColor.png");
case "fullScreenButton":
return new StyleData(id, message("FullScreen"), "", "iconExpand.png");
case "soundButton":
return new StyleData(id, message("Mute"), "", "iconMute.png");
}
return null;
}
private static StyleData startsWith(String id) {
if (id.startsWith("cat")) {
return new StyleData(id, message("Meow"), "", "iconCat.png");
}
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/fxml/style/HtmlStyles.java | released/MyBox/src/main/java/mara/mybox/fxml/style/HtmlStyles.java | package mara.mybox.fxml.style;
import static mara.mybox.value.Languages.message;
/**
* @Author Mara
* @CreateDate 2021-8-1
* @License Apache License Version 2.0
*/
public class HtmlStyles {
public enum HtmlStyle {
Table, Default, Article, Console, Blackboard, Ago, Book, Grey
}
public static final String TableStyle
= " table { max-width:95%; margin : 10px; border-style: solid; border-width:2px; border-collapse: collapse;} \n"
+ " th, td { border-style: solid; border-width:1px; padding: 8px; border-collapse: collapse;} \n"
+ " th { font-weight:bold; text-align:center;} \n"
+ " tr { height: 1.2em; } \n"
+ " .center { text-align:center; max-width:95%; } \n"
+ " .valueBox { border-style: solid; border-width:1px; border-color:black; padding: 5px; border-radius:5px;} \n"
+ " .boldText { font-weight:bold; } \n";
public static final String ArticleStyle
= TableStyle
+ " body { margin:0 auto; width: 900px; } \n"
+ " img { max-width: 900px; } \n";
public static final String DefaultStyle
= ArticleStyle
+ " .valueText { color:#2e598a; } \n";
public static final String ConsoleStyle
= TableStyle
+ " body { background-color:black; color:#CCFF99; }\n"
+ " a:link {color: dodgerblue}\n"
+ " a:visited {color: #DDDDDD}\n"
+ " .valueBox { border-color:#CCFF99;}\n"
+ " .valueText { color:skyblue; }\n";
public static final String BlackboardStyle
= TableStyle
+ " body { background-color:#336633; color:white; }\n"
+ " a:link {color: aqua}\n"
+ " a:visited {color: #DDDDDD}\n"
+ " .valueBox { border-color:white; }\n"
+ " .valueText { color:wheat; }\n";
public static final String AgoStyle
= TableStyle
+ " body { background-color:darkblue; color:white; }\n"
+ " a:link {color: springgreen}\n"
+ " a:visited {color: #DDDDDD}\n"
+ " .valueBox { border-color:white;}\n"
+ " .valueText { color:yellow; }\n";
public static final String BookStyle
= TableStyle
+ " body { background-color:#F6F1EB; color:black; }\n";
public static final String GreyStyle
= TableStyle
+ " body { background-color:#ececec; color:black; }\n";
public static HtmlStyles.HtmlStyle styleName(String styleName) {
for (HtmlStyles.HtmlStyle style : HtmlStyles.HtmlStyle.values()) {
if (style.name().equals(styleName) || message(style.name()).equals(styleName)) {
return style;
}
}
return HtmlStyles.HtmlStyle.Default;
}
public static String styleValue(HtmlStyles.HtmlStyle style) {
switch (style) {
case Table:
return HtmlStyles.TableStyle;
case Default:
return HtmlStyles.DefaultStyle;
case Article:
return HtmlStyles.ArticleStyle;
case Console:
return HtmlStyles.ConsoleStyle;
case Blackboard:
return HtmlStyles.BlackboardStyle;
case Ago:
return HtmlStyles.AgoStyle;
case Book:
return HtmlStyles.BookStyle;
case Grey:
return HtmlStyles.GreyStyle;
}
return HtmlStyles.DefaultStyle;
}
public static String styleValue(String styleName) {
return styleValue(styleName(styleName));
}
}
| java | Apache-2.0 | 107ddc379fd2f4caad37e85c29367d21089b568c | 2026-01-05T02:30:12.428303Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.