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/alpha/MyBox/src/main/java/mara/mybox/controller/ColorsCustomizeController.java
alpha/MyBox/src/main/java/mara/mybox/controller/ColorsCustomizeController.java
package mara.mybox.controller; import java.sql.Connection; import javafx.fxml.FXML; import javafx.scene.control.RadioButton; import javafx.scene.control.TextField; import javafx.scene.paint.Color; import mara.mybox.image.tools.ColorConvertTools; import mara.mybox.db.Database; import mara.mybox.db.DerbyBase; import mara.mybox.db.data.ColorData; import mara.mybox.db.table.TableColorPalette; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxSingletonTask; import mara.mybox.fxml.PopTools; import mara.mybox.fxml.WindowTools; import mara.mybox.fxml.style.NodeStyleTools; import mara.mybox.value.Fxmls; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2023-6-7 * @License Apache License Version 2.0 */ public class ColorsCustomizeController extends BaseChildController { protected ColorsManageController manager; @FXML protected RadioButton rybRadio; @FXML protected TextField hueFromInput, hueToInput, hueStepInput, brightnessFromInput, brightnessToInput, brightnessStepInput, opacityFromInput, opacityToInput, opacityStepInput, saturationFromInput, saturationToInput, saturationStepInput; @Override public void setControlsStyle() { try { super.setControlsStyle(); NodeStyleTools.setTooltip(hueFromInput, "0~359"); NodeStyleTools.setTooltip(hueToInput, "0~359"); NodeStyleTools.setTooltip(hueStepInput, "1~359"); NodeStyleTools.setTooltip(brightnessFromInput, "1~100"); NodeStyleTools.setTooltip(brightnessToInput, "1~100"); NodeStyleTools.setTooltip(brightnessStepInput, "1~100"); NodeStyleTools.setTooltip(saturationFromInput, "1~100"); NodeStyleTools.setTooltip(saturationToInput, "1~100"); NodeStyleTools.setTooltip(saturationStepInput, "1~100"); NodeStyleTools.setTooltip(opacityFromInput, "1~100"); NodeStyleTools.setTooltip(opacityToInput, "1~100"); NodeStyleTools.setTooltip(opacityStepInput, "1~100"); } catch (Exception e) { MyBoxLog.debug(e); } } public void setParameters(ColorsManageController manager) { this.manager = manager; } public int pickValue(TextField input, String name, int min, int max) { try { int value = Integer.parseInt(input.getText()); if (value >= min && value <= max) { return value; } } catch (Exception e) { } popError(message("InvalidParameter") + ": " + name); return -1; } @FXML @Override public void okAction() { try { int hueFrom = pickValue(hueFromInput, message("Hue") + "-" + message("From"), 0, 359); if (hueFrom < 0) { return; } int hueTo = pickValue(hueToInput, message("Hue") + "-" + message("To"), 0, 359); if (hueTo < 0) { return; } int hueStep = pickValue(hueStepInput, message("Hue") + "-" + message("ValueStep"), 1, 359); if (hueStep <= 0) { return; } int brightnessFrom = pickValue(brightnessFromInput, message("Brightness") + "-" + message("From"), 1, 100); if (brightnessFrom < 0) { return; } int brightnessTo = pickValue(brightnessToInput, message("Brightness") + "-" + message("To"), 1, 100); if (brightnessTo < 0) { return; } int brightnessStep = pickValue(brightnessStepInput, message("Brightness") + "-" + message("ValueStep"), 1, 100); if (brightnessStep <= 0) { return; } int saturationFrom = pickValue(saturationFromInput, message("Saturation") + "-" + message("From"), 1, 100); if (saturationFrom < 0) { return; } int saturationTo = pickValue(saturationToInput, message("Saturation") + "-" + message("To"), 1, 100); if (saturationTo < 0) { return; } int saturationStep = pickValue(saturationStepInput, message("Saturation") + "-" + message("ValueStep"), 1, 100); if (saturationStep <= 0) { return; } int opacityFrom = pickValue(opacityFromInput, message("Opacity") + "-" + message("From"), 1, 100); if (opacityFrom < 0) { return; } int opacityTo = pickValue(opacityToInput, message("Opacity") + "-" + message("To"), 1, 100); if (opacityTo < 0) { return; } int opacityStep = pickValue(opacityStepInput, message("Opacity") + "-" + message("ValueStep"), 1, 100); if (opacityStep <= 0) { return; } long number = (Math.abs((hueTo - hueFrom) / hueStep) + 1) * (Math.abs((brightnessTo - brightnessFrom) / brightnessStep) + 1) * (Math.abs((opacityTo - opacityFrom) / opacityStep) + 1) * (Math.abs((saturationTo - saturationFrom) / saturationStep) + 1); if (!PopTools.askSure(baseTitle, message("Total") + ": " + number)) { return; } if (task != null) { task.cancel(); } task = new FxSingletonTask<Void>(this) { private int count = 0; @Override protected boolean handle() { TableColorPalette tableColorPalette = manager.tableColorPalette; long paletteid = manager.palettesController.isAllColors() ? -1 : manager.palettesController.currentPaletteId(); boolean ryb = rybRadio.isSelected(); try (Connection conn = DerbyBase.getConnection()) { int hue = hueFrom; conn.setAutoCommit(false); while (true) { if (task == null || isCancelled()) { conn.close(); return true; } int saturation = saturationFrom; while (true) { if (task == null || task.isCancelled()) { conn.close(); return true; } int brightness = brightnessFrom; while (true) { if (task == null || task.isCancelled()) { conn.close(); return true; } int opacity = opacityFrom; while (true) { if (task == null || task.isCancelled()) { conn.close(); return true; } task.setInfo((++count) + " " + (ryb ? message("RYBAngle") : message("Hue")) + ": " + hue + " " + message("Saturation") + ": " + saturation + " " + message("Brightness") + ": " + brightness + " " + message("Opacity") + ": " + brightness + " "); Color color = Color.hsb(ryb ? ColorConvertTools.ryb2hue(hue) : hue, saturation / 100f, brightness / 100f); color = new Color(color.getRed(), color.getGreen(), color.getBlue(), opacity / 100f); ColorData colorData = new ColorData(color) .calculate().setPaletteid(paletteid); tableColorPalette.findAndCreate(conn, colorData, false, false); if (count % Database.BatchSize == 0) { conn.commit(); } if (opacityFrom == opacityTo) { break; } else if (opacityFrom > opacityTo) { opacity -= opacityStep; if (opacity < opacityTo) { break; } } else { opacity += opacityStep; if (opacity > opacityTo) { break; } } } if (brightnessFrom == brightnessTo) { break; } else if (brightnessFrom > brightnessTo) { brightness -= brightnessStep; if (brightness < brightnessTo) { break; } } else { brightness += brightnessStep; if (brightness > brightnessTo) { break; } } } if (saturationFrom == saturationTo) { break; } else if (saturationFrom > saturationTo) { saturation -= saturationStep; if (saturation < saturationTo) { break; } } else { saturation += saturationStep; if (saturation > saturationTo) { break; } } } if (hueFrom == hueTo) { break; } else if (hueFrom > hueTo) { hue -= hueStep; if (hue < hueTo) { break; } } else { hue += hueStep; if (hue > hueTo) { break; } } } conn.commit(); } catch (Exception e) { error = e.toString(); return false; } return true; } @Override protected void whenSucceeded() { close(); } @Override protected void taskQuit() { super.taskQuit(); if (count > 0) { manager.refreshPalette(); manager.popInformation(message("Create") + ": " + count); } } }; start(task); } catch (Exception e) { MyBoxLog.error(e); } } /* static methods */ public static ColorsCustomizeController open(ColorsManageController manager) { ColorsCustomizeController controller = (ColorsCustomizeController) WindowTools.childStage( manager, Fxmls.ColorsCustomizeFxml); if (controller != null) { controller.setParameters(manager); controller.requestMouse(); } return controller; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/controller/MenuBytesEditController.java
alpha/MyBox/src/main/java/mara/mybox/controller/MenuBytesEditController.java
package mara.mybox.controller; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.scene.Node; import javafx.scene.control.Button; import javafx.scene.control.Hyperlink; import javafx.scene.control.Separator; import javafx.scene.input.ContextMenuEvent; import javafx.scene.input.MouseEvent; import javafx.stage.Window; import mara.mybox.data.FileEditInformation; import mara.mybox.db.data.VisitHistory; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.WindowTools; import mara.mybox.fxml.style.NodeStyleTools; import mara.mybox.tools.ByteTools; import mara.mybox.value.Fxmls; import mara.mybox.value.Languages; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2021-7-24 * @License Apache License Version 2.0 */ public class MenuBytesEditController extends MenuTextEditController { public MenuBytesEditController() { baseTitle = Languages.message("Bytes"); } @Override public void setFileType() { setFileType(VisitHistory.FileType.All); } @Override public void setParameters(BaseController parent, Node node, double x, double y) { try { super.setParameters(parent, node, x, y); if (textInput != null && textInput.isEditable()) { addBytesButton(); } } catch (Exception e) { MyBoxLog.error(e); } } public void addBytesButton() { try { if (textInput == null) { return; } addNode(new Separator()); List<Node> number = new ArrayList<>(); for (int i = 0; i <= 9; ++i) { String s = i + ""; Button button = new Button(s); String value = ByteTools.stringToHexFormat(s); button.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { textInput.insertText(textInput.getSelection().getStart(), value); parentController.getMyWindow().requestFocus(); textInput.requestFocus(); } }); NodeStyleTools.setTooltip(button, value); number.add(button); } addFlowPane(number); addNode(new Separator()); List<Node> AZ = new ArrayList<>(); for (char i = 'A'; i <= 'Z'; ++i) { String s = i + ""; String value = ByteTools.stringToHexFormat(s); Button button = new Button(s); button.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { textInput.insertText(textInput.getSelection().getStart(), value); parentController.getMyWindow().requestFocus(); textInput.requestFocus(); } }); NodeStyleTools.setTooltip(button, value); AZ.add(button); } addFlowPane(AZ); addNode(new Separator()); List<Node> az = new ArrayList<>(); for (char i = 'a'; i <= 'z'; ++i) { String s = i + ""; String value = ByteTools.stringToHexFormat(s); Button button = new Button(s); button.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { textInput.insertText(textInput.getSelection().getStart(), value); parentController.getMyWindow().requestFocus(); textInput.requestFocus(); } }); NodeStyleTools.setTooltip(button, value); az.add(button); } addFlowPane(az); addNode(new Separator()); List<String> names = Arrays.asList("LF", "CR", Languages.message("Space"), "!", "\"", "#", "$", "%", "&", "'", "(", ")", "*", "+", "-", ",", ".", "/", ":", ";", "<", "=", ">", "?", "@", "[", "]", "\\", "^", "_", "`", "{", "}", "|", "~"); List<Node> special = new ArrayList<>(); for (int i = 0; i < names.size(); i++) { String name = names.get(i); Button button = new Button(name); if (name.equals(Languages.message("Space"))) { name = " "; } else if (name.equals("LF")) { name = "\n"; } else if (name.equals("CR")) { name = "\r"; } String value = ByteTools.stringToHexFormat(name); button.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { textInput.insertText(textInput.getSelection().getStart(), value); parentController.getMyWindow().requestFocus(); textInput.requestFocus(); } }); NodeStyleTools.setTooltip(button, value); special.add(button); } addFlowPane(special); Hyperlink link = new Hyperlink(Languages.message("AsciiTable")); link.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { openLink("https://www.ascii-code.com/"); } }); addNode(link); } catch (Exception e) { MyBoxLog.error(e); } } @FXML @Override public void editAction() { BytesEditorController.edit(textInput.getText()); } @FXML public void hexAction() { String text = textInput.getText(); text = ByteTools.formatTextHex(text); if (text != null) { if (text.isEmpty()) { return; } String hex; if (parentController instanceof BytesEditorController) { BytesEditorController c = (BytesEditorController) parentController; FileEditInformation info = c.sourceInformation; hex = ByteTools.formatHex(text, info.getLineBreak(), info.getLineBreakWidth(), info.getLineBreakValue()); } else { hex = ByteTools.formatHex(text, FileEditInformation.Line_Break.Width, 30, "0A"); } isSettingValues = true; textInput.setText(hex); isSettingValues = false; } else { popError(message("InvalidData")); } } @FXML @Override public boolean popAction() { if (textInput == null) { return false; } BytesPopController.open(parentController, textInput); return true; } /* static methods */ public static MenuBytesEditController openBytes(BaseController parent, Node node, double x, double y) { try { if (parent == null || node == null) { return null; } List<Window> windows = new ArrayList<>(); windows.addAll(Window.getWindows()); for (Window window : windows) { Object object = window.getUserData(); if (object != null && object instanceof MenuBytesEditController) { try { MenuBytesEditController controller = (MenuBytesEditController) object; if (controller.textInput != null && controller.textInput.equals(node)) { controller.close(); } } catch (Exception e) { } } } MenuBytesEditController controller = (MenuBytesEditController) WindowTools.referredTopStage( parent, Fxmls.MenuBytesEditFxml); controller.setParameters(parent, node, x, y); return controller; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static MenuBytesEditController openBytes(BaseController parent, Node node, MouseEvent event) { return openBytes(parent, node, event.getScreenX() + 40, event.getScreenY() + 40); } public static MenuBytesEditController openBytes(BaseController parent, Node node, ContextMenuEvent event) { return openBytes(parent, node, event.getScreenX() + 40, event.getScreenY() + 40); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/controller/BytesFindBatchOptions.java
alpha/MyBox/src/main/java/mara/mybox/controller/BytesFindBatchOptions.java
package mara.mybox.controller; /** * @Author Mara * @CreateDate 2023-5-10 * @License Apache License Version 2.0 */ public class BytesFindBatchOptions extends FindReplaceBatchOptions { public BytesFindBatchOptions() { TipsLabelKey = "BytesFindBatchTips"; } @Override protected void checkFindInput(String string) { validateFindBytes(string); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/controller/ControlSvgTranscode.java
alpha/MyBox/src/main/java/mara/mybox/controller/ControlSvgTranscode.java
package mara.mybox.controller; import java.awt.Rectangle; import javafx.fxml.FXML; import javafx.scene.control.TextField; import mara.mybox.data.SVG; import mara.mybox.dev.MyBoxLog; import mara.mybox.tools.SvgTools; import org.w3c.dom.Document; /** * @Author Mara * @CreateDate 2023-6-24 * @License Apache License Version 2.0 */ public class ControlSvgTranscode extends BaseController { protected float width, height, inputWidth, inputHeight; protected Rectangle area, inputArea; @FXML protected TextField widthInput, heightInput, areaInput; public void checkInputs() { inputWidth = 0f; try { inputWidth = Float.parseFloat(widthInput.getText()); } catch (Exception e) { } inputHeight = 0f; try { inputHeight = Float.parseFloat(heightInput.getText()); } catch (Exception e) { } inputArea = SvgTools.viewBox(areaInput.getText()); } public void checkValues(Document doc) { try { float docWidth = 0f; float docHeight = 0f; Rectangle docArea = null; if (doc != null) { SVG svg = new SVG(doc); docWidth = svg.getWidth(); docHeight = svg.getHeight(); docArea = svg.getViewBox(); } width = inputWidth > 0 ? inputWidth : docWidth; height = inputHeight > 0 ? inputHeight : docHeight; area = inputArea == null ? inputArea : docArea; } catch (Exception e) { MyBoxLog.debug(e); } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/controller/ControlImageMosaic.java
alpha/MyBox/src/main/java/mara/mybox/controller/ControlImageMosaic.java
package mara.mybox.controller; import java.util.Arrays; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.fxml.FXML; import javafx.scene.control.ComboBox; import mara.mybox.image.data.ImageMosaic; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.ValidationTools; import static mara.mybox.value.Languages.message; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2019-9-2 * @License Apache License Version 2.0 */ public class ControlImageMosaic extends BaseController { protected int intensity; @FXML protected ComboBox<String> intensitySelector; @Override public void initControls() { try { super.initControls(); intensity = UserConfig.getInt(baseName + "Intensity", 80); if (intensity <= 0) { intensity = 80; } intensitySelector.getItems().addAll(Arrays.asList("80", "20", "50", "10", "5", "100", "15", "20", "60")); intensitySelector.setValue(intensity + ""); intensitySelector.valueProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue ov, String oldValue, String newValue) { checkIntensity(); } }); } catch (Exception e) { MyBoxLog.error(e); } } public boolean checkIntensity() { int v; try { v = Integer.parseInt(intensitySelector.getValue()); } catch (Exception e) { v = -1; } if (v > 0) { intensity = v; ValidationTools.setEditorNormal(intensitySelector); return true; } else { popError(message("InvalidParameter") + ": " + message("Intensity")); ValidationTools.setEditorBadStyle(intensitySelector); return false; } } public ImageMosaic pickValues(ImageMosaic.MosaicType type) { if (!checkIntensity()) { return null; } return ImageMosaic.create().setType(type).setIntensity(intensity); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/controller/ImageBase64Controller.java
alpha/MyBox/src/main/java/mara/mybox/controller/ImageBase64Controller.java
package mara.mybox.controller; import java.io.File; import java.nio.charset.Charset; import java.util.Optional; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.fxml.FXML; import javafx.scene.control.Alert; import javafx.scene.control.ButtonBar; import javafx.scene.control.ButtonType; import javafx.scene.control.CheckBox; import javafx.scene.control.Label; import javafx.scene.control.RadioButton; import javafx.scene.control.TextArea; import javafx.scene.control.TextInputControl; import javafx.scene.control.ToggleGroup; import javafx.scene.layout.Region; import javafx.stage.Stage; import mara.mybox.image.tools.BufferedImageTools; import mara.mybox.db.data.VisitHistory; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.PopTools; import mara.mybox.fxml.FxSingletonTask; import mara.mybox.fxml.TextClipboardTools; import mara.mybox.tools.DateTools; import mara.mybox.tools.FileNameTools; import mara.mybox.tools.StringTools; import mara.mybox.tools.TextFileTools; import static mara.mybox.value.Languages.message; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2022-5-5 * @License Apache License Version 2.0 */ public class ImageBase64Controller extends BaseController { protected Charset charset; @FXML protected ToggleGroup formatGroup; @FXML protected TextArea resultArea; @FXML protected CheckBox tagCheck; public ImageBase64Controller() { baseTitle = message("ImageBase64"); } @Override public void setFileType() { setFileType(VisitHistory.FileType.Image, VisitHistory.FileType.Text); } @Override public void initControls() { try { super.initControls(); tagCheck.setSelected(UserConfig.getBoolean(baseName + "Tag", true)); tagCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldValue, Boolean newValue) { UserConfig.setBoolean(baseName + "Tag", tagCheck.isSelected()); } }); } catch (Exception e) { MyBoxLog.error(e); } } @Override public void sourceFileChanged(final File file) { sourceFile = file; clearAction(); } @FXML @Override public void startAction() { if (sourceFile == null || UserConfig.badStyle().equals(sourceFileInput.getStyle())) { popError(message("InvalidParameter")); return; } String format = ((RadioButton) formatGroup.getSelectedToggle()).getText(); convert(this, sourceFile, resultArea, bottomLabel, format, tagCheck.isSelected()); } @FXML @Override public void saveAction() { saveAsAction(); } @FXML @Override public void saveAsAction() { String format = ((RadioButton) formatGroup.getSelectedToggle()).getText(); saveAs(this, resultArea.getText(), format); } @FXML @Override public void clearAction() { resultArea.clear(); bottomLabel.setText(""); } @FXML @Override public void copyAction() { TextClipboardTools.copyToSystemClipboard(this, resultArea.getText()); } public static void convert(BaseController controller, File file, TextInputControl resultArea, Label label, String format, boolean withTag) { if (file == null) { controller.popError(message("InvalidParameter")); return; } if (file.length() > 100 * 1024) { if (!PopTools.askSure(controller.getTitle(), message("GeneratedDataMayLarge"))) { return; } } if (controller.task != null && !controller.task.isQuit()) { return; } if (!(controller instanceof MenuHtmlCodesController)) { resultArea.clear(); } if (label != null) { label.setText(""); } controller.task = new FxSingletonTask<Void>(controller) { private String imageBase64; @Override protected boolean handle() { try { imageBase64 = BufferedImageTools.base64(this, file, format); if (imageBase64 == null) { if (isWorking()) { error = message("Failed"); } else { error = message("Canceled"); } return false; } if (withTag) { imageBase64 = "<img src=\"data:image/" + format + ";base64," + imageBase64 + "\" >"; } return imageBase64 != null; } catch (Exception e) { error = e.toString(); return false; } } @Override protected void whenSucceeded() { long len = imageBase64.length(); String lenString = StringTools.format(len); if (len > 50 * 1024) { Alert alert = new Alert(Alert.AlertType.CONFIRMATION); alert.setTitle(controller.baseTitle); alert.setContentText(message("Length") + ": " + lenString); alert.getDialogPane().setMinHeight(Region.USE_PREF_SIZE); ButtonType buttonLoad = new ButtonType(message("Load")); ButtonType buttonSave = new ButtonType(message("Save")); ButtonType buttonCancel = new ButtonType(message("Cancel"), ButtonBar.ButtonData.CANCEL_CLOSE); alert.getButtonTypes().setAll(buttonLoad, buttonSave, buttonCancel); Stage stage = (Stage) alert.getDialogPane().getScene().getWindow(); stage.setAlwaysOnTop(true); stage.toFront(); Optional<ButtonType> result = alert.showAndWait(); if (result == null || !result.isPresent()) { imageBase64 = null; return; } if (result.get() == buttonSave) { saveAs(controller, imageBase64, format); return; } } if (controller instanceof MenuHtmlCodesController) { ((MenuHtmlCodesController) controller).insertText(imageBase64); } else { resultArea.setText(imageBase64); } if (label != null) { label.setText(lenString); } } }; controller.start(controller.task); } public static void saveAs(BaseController controller, String results, String format) { if (results == null || results.isEmpty()) { controller.popError(message("NoData")); return; } String name = controller.sourceFile != null ? FileNameTools.prefix(controller.sourceFile.getName()) : DateTools.nowFileString(); File file = controller.saveCurrentFile(VisitHistory.FileType.Text, name + "_" + format + "_Base64"); if (file == null) { return; } if (controller.task != null && !controller.task.isQuit()) { return; } controller.task = new FxSingletonTask<Void>(controller) { @Override protected boolean handle() { return TextFileTools.writeFile(file, results) != null; } @Override protected void whenSucceeded() { controller.recordFileWritten(file); controller.browse(file.getParentFile()); } }; controller.start(controller.task); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/controller/DataTreeDeleteController.java
alpha/MyBox/src/main/java/mara/mybox/controller/DataTreeDeleteController.java
package mara.mybox.controller; import java.sql.Connection; import java.sql.PreparedStatement; import java.util.List; import javafx.fxml.FXML; import mara.mybox.db.Database; import mara.mybox.db.DerbyBase; import mara.mybox.db.data.DataNode; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxSingletonTask; import mara.mybox.fxml.WindowTools; import mara.mybox.value.Fxmls; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2022-3-14 * @License Apache License Version 2.0 */ public class DataTreeDeleteController extends BaseDataTreeController { protected BaseDataTreeController dataController; public void setParameters(BaseDataTreeController parent, DataNode node) { try { if (parent == null) { close(); return; } dataController = parent; selectionType = DataNode.SelectionType.Multiple; initDataTree(dataController.nodeTable, node); } catch (Exception e) { MyBoxLog.error(e); } } @Override public String initTitle() { return nodeTable.getTreeName() + " - " + message("DeleteNodes"); } @FXML @Override public void okAction() { List<Long> selectedIDs = selectedIDs(); if (selectedIDs == null || selectedIDs.isEmpty()) { popError(message("SelectNodes")); return; } if (task != null) { task.cancel(); } task = new FxSingletonTask<Void>(this) { private int count = 0; @Override protected boolean handle() { try (Connection conn = DerbyBase.getConnection(); PreparedStatement delete = conn.prepareStatement( "DELETE FROM " + nodeTable.getTableName() + " WHERE nodeid=?")) { conn.setAutoCommit(false); for (long nodeid : selectedIDs) { delete.setLong(1, nodeid); delete.addBatch(); if (count > 0 && (count % Database.BatchSize == 0)) { count += nodeTable.executeBatch(conn, delete); } } count += nodeTable.executeBatch(conn, delete); return count > 0; } catch (Exception e) { error = e.toString(); return false; } } @Override protected void finalAction() { super.finalAction(); if (count > 0) { loadTree(); if (WindowTools.isRunning(dataController)) { dataController.loadTree(); } } } }; start(task); } /* static methods */ public static DataTreeDeleteController open(BaseDataTreeController parent, DataNode node) { DataTreeDeleteController controller = (DataTreeDeleteController) WindowTools.childStage(parent, Fxmls.DataTreeDeleteFxml); controller.setParameters(parent, node); controller.requestMouse(); return controller; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/controller/ImageBlackWhiteController.java
alpha/MyBox/src/main/java/mara/mybox/controller/ImageBlackWhiteController.java
package mara.mybox.controller; import java.util.List; import javafx.fxml.FXML; import javafx.scene.image.Image; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.fxml.WindowTools; import mara.mybox.fxml.image.ColorDemos; import mara.mybox.image.data.ImageBinary; import mara.mybox.image.data.ImageScope; import mara.mybox.value.Fxmls; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2019-9-2 * @License Apache License Version 2.0 */ public class ImageBlackWhiteController extends BasePixelsController { protected ImageBinary imageBinary; @FXML protected ControlImageBinary binaryController; public ImageBlackWhiteController() { baseTitle = message("BlackOrWhite"); } @Override protected void initMore() { try { super.initMore(); operation = message("BlackOrWhite"); binaryController.setParameters(imageController.imageView); } catch (Exception e) { MyBoxLog.error(e); } } @Override public boolean checkOptions() { if (!super.checkOptions()) { return false; } imageBinary = binaryController.pickValues(-1); if (imageBinary == null) { return false; } if (imageBinary.getAlgorithm() != ImageBinary.BinaryAlgorithm.Default) { opInfo = message("Threshold") + ": " + imageBinary.getIntPara1(); } return true; } @Override protected Image handleImage(FxTask currentTask, Image inImage, ImageScope inScope) { try { imageBinary.setImage(inImage) .setScope(inScope) .setExcludeScope(excludeScope()) .setSkipTransparent(skipTransparent()) .setTask(currentTask); return imageBinary.startFx(); } catch (Exception e) { displayError(e.toString()); return null; } } @Override protected void makeDemoFiles(FxTask currentTask, List<String> files, Image demoImage) { try { imageBinary = binaryController.pickValues(128); if (imageBinary == null) { return; } imageBinary.setImage(demoImage); ColorDemos.blackWhite(currentTask, files, imageBinary, srcFile()); } catch (Exception e) { MyBoxLog.error(e.toString()); } } /* static methods */ public static ImageBlackWhiteController open(BaseImageController parent) { try { if (parent == null) { return null; } ImageBlackWhiteController controller = (ImageBlackWhiteController) WindowTools.referredStage( parent, Fxmls.ImageBlackWhiteFxml); controller.setParameters(parent); return controller; } catch (Exception e) { MyBoxLog.error(e); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/controller/TextLocateController.java
alpha/MyBox/src/main/java/mara/mybox/controller/TextLocateController.java
package mara.mybox.controller; import javafx.fxml.FXML; import javafx.scene.control.RadioButton; import javafx.scene.control.TextField; import javafx.scene.control.ToggleGroup; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.WindowTools; import mara.mybox.value.Fxmls; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2023-7-19 * @License Apache License Version 2.0 */ public class TextLocateController extends BaseChildController { protected BaseTextController fileController; protected long locateLine, locateObject; // 0-based protected long from, to; // 0-based, exlcuded end @FXML protected ToggleGroup locateGroup; @FXML protected RadioButton lineNumberRadio, objectLocationRadio, linesRangeRadio, objectRangeRadio; @FXML protected TextField lineNumberInput, objectLocationInput, lineFromInput, lineToInput, objectFromInput, objectToInput; public void setParameters(BaseTextController parent) { try { fileController = parent; if (fileController == null || fileController.sourceInformation == null) { close(); return; } baseName = fileController.baseName; setFileType(fileController.TargetFileType); setTitle(message("Locate") + " - " + fileController.getTitle()); if (fileController.isBytes()) { objectLocationRadio.setText(message("ByteLocation")); objectRangeRadio.setText(message("BytesRange")); } locateLine = locateObject = from = to = -1; } catch (Exception e) { MyBoxLog.error(e); } } public boolean checkLineNumber() { if (!lineNumberRadio.isSelected()) { return true; } int v; try { v = Integer.parseInt(lineNumberInput.getText()); } catch (Exception e) { v = -1; } if (v > 0 && v <= fileController.sourceInformation.getRowsNumber()) { locateLine = v - 1; // 0-based return true; } else { popError(message("InvalidParameter") + ": " + message("LineNumber")); return false; } } public boolean checkObjectLocation() { if (!objectLocationRadio.isSelected()) { return true; } int v; try { v = Integer.parseInt(objectLocationInput.getText()); } catch (Exception e) { v = -1; } if (v > 0 && v <= fileController.sourceInformation.getObjectsNumber()) { locateObject = v - 1; // 0-based return true; } else { popError(message("InvalidParameter") + ": " + objectLocationRadio.getText()); return false; } } public boolean checkLinesRange() { if (!linesRangeRadio.isSelected()) { return true; } long f, t, total = fileController.sourceInformation.getRowsNumber(); try { f = Long.parseLong(lineFromInput.getText()) - 1; } catch (Exception e) { f = -1; } if (f < 0 || f >= total) { popError(message("InvalidParameters") + ": " + message("LinesRange")); return false; } try { t = Long.parseLong(lineToInput.getText()); } catch (Exception e) { t = -1; } if (t < 0 || t > total || f > t) { popError(message("InvalidParameters") + ": " + message("LinesRange")); return false; } from = f; to = t; return true; } public boolean checkObjectsRange() { if (!objectRangeRadio.isSelected()) { return true; } long f, t, total = fileController.sourceInformation.getObjectsNumber(); try { f = Long.parseLong(objectFromInput.getText()) - 1; } catch (Exception e) { f = -1; } if (f < 0 || f >= total) { popError(message("InvalidParameters") + ": " + objectRangeRadio.getText()); return false; } try { t = Long.parseLong(objectToInput.getText()); } catch (Exception e) { t = -1; } if (t < 0 || t > total || f > t) { popError(message("InvalidParameters") + ": " + objectRangeRadio.getText()); return false; } from = f; to = t; return true; } public boolean checkValues() { return checkLineNumber() && checkObjectLocation() && checkLinesRange() && checkObjectsRange(); } @FXML @Override public void okAction() { if (!checkValues()) { return; } boolean ok; if (lineNumberRadio.isSelected()) { ok = fileController.locateLine(locateLine); } else if (objectLocationRadio.isSelected()) { ok = fileController.locateObject(locateObject); } else if (linesRangeRadio.isSelected()) { ok = fileController.locateLinesRange(from, to); } else if (objectRangeRadio.isSelected()) { ok = fileController.locateObjectsRange(from, to); } else { return; } if (ok && closeAfterCheck.isSelected()) { close(); } } /* static methods */ public static TextLocateController open(BaseTextController parent) { try { if (parent == null) { return null; } TextLocateController controller = (TextLocateController) WindowTools.referredTopStage( parent, Fxmls.TextLocateFxml); controller.setParameters(parent); return controller; } catch (Exception e) { MyBoxLog.error(e); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/controller/ControlChartXYSelection.java
alpha/MyBox/src/main/java/mara/mybox/controller/ControlChartXYSelection.java
package mara.mybox.controller; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.value.ObservableValue; import javafx.fxml.FXML; import javafx.scene.control.RadioButton; import javafx.scene.control.Toggle; import javafx.scene.control.ToggleGroup; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.chart.ChartOptions.ChartType; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2022-1-19 * @License Apache License Version 2.0 */ public class ControlChartXYSelection extends BaseController { protected ChartType chartType, lastType; protected String chartName; protected SimpleBooleanProperty typeNodify; @FXML protected ToggleGroup chartGroup; @FXML protected RadioButton barChartRadio, stackedBarChartRadio, lineChartRadio, scatterChartRadio, areaChartRadio, stackedAreaChartRadio; public ControlChartXYSelection() { TipsLabelKey = "DataChartXYTips"; } @Override public void initControls() { try { super.initControls(); typeNodify = new SimpleBooleanProperty(); lastType = null; chartType = null; checkType(); chartGroup.selectedToggleProperty().addListener( (ObservableValue<? extends Toggle> observable, Toggle oldValue, Toggle newValue) -> { checkType(); }); } catch (Exception e) { MyBoxLog.error(e); } } public ChartType checkType() { try { lastType = chartType; if (barChartRadio.isSelected()) { chartType = ChartType.Bar; chartName = message("BarChart"); } else if (stackedBarChartRadio.isSelected()) { chartType = ChartType.StackedBar; chartName = message("StackedBarChart"); } else if (lineChartRadio.isSelected()) { chartType = ChartType.Line; chartName = message("LineChart"); } else if (scatterChartRadio.isSelected()) { chartType = ChartType.Scatter; chartName = message("ScatterChart"); } else if (areaChartRadio.isSelected()) { chartType = ChartType.Area; chartName = message("AreaChart"); } else if (stackedAreaChartRadio.isSelected()) { chartType = ChartType.StackedArea; chartName = message("StackedAreaChart"); } typeNodify.set(!typeNodify.get()); } catch (Exception e) { MyBoxLog.error(e); } return chartType; } public boolean needChangeData() { return lastType == ChartType.Bubble || chartType == ChartType.Bubble; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/controller/BaseDataConvertController.java
alpha/MyBox/src/main/java/mara/mybox/controller/BaseDataConvertController.java
package mara.mybox.controller; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import javafx.fxml.FXML; import javafx.scene.control.CheckBox; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; import mara.mybox.data.PaginatedPdfTable; import mara.mybox.data2d.Data2D_Attributes.TargetType; import static mara.mybox.data2d.Data2D_Attributes.TargetType.Append; import static mara.mybox.data2d.Data2D_Attributes.TargetType.CSV; import static mara.mybox.data2d.Data2D_Attributes.TargetType.DatabaseTable; import static mara.mybox.data2d.Data2D_Attributes.TargetType.Excel; import static mara.mybox.data2d.Data2D_Attributes.TargetType.HTML; import static mara.mybox.data2d.Data2D_Attributes.TargetType.Insert; import static mara.mybox.data2d.Data2D_Attributes.TargetType.JSON; import static mara.mybox.data2d.Data2D_Attributes.TargetType.Matrix; import static mara.mybox.data2d.Data2D_Attributes.TargetType.MyBoxClipboard; import static mara.mybox.data2d.Data2D_Attributes.TargetType.PDF; import static mara.mybox.data2d.Data2D_Attributes.TargetType.Replace; import static mara.mybox.data2d.Data2D_Attributes.TargetType.Text; import static mara.mybox.data2d.Data2D_Attributes.TargetType.XML; import mara.mybox.data2d.DataMatrix; import mara.mybox.data2d.writer.Data2DWriter; import mara.mybox.data2d.writer.DataFileCSVWriter; import mara.mybox.data2d.writer.DataFileExcelWriter; import mara.mybox.data2d.writer.DataFileTextWriter; import mara.mybox.data2d.writer.DataMatrixWriter; import mara.mybox.data2d.writer.DataTableWriter; import mara.mybox.data2d.writer.HtmlWriter; import mara.mybox.data2d.writer.JsonWriter; import mara.mybox.data2d.writer.MyBoxClipboardWriter; import mara.mybox.data2d.writer.PdfWriter; import mara.mybox.data2d.writer.SystemClipboardWriter; import mara.mybox.data2d.writer.XmlWriter; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.style.HtmlStyles; import static mara.mybox.value.Languages.message; import mara.mybox.value.UserConfig; import org.apache.pdfbox.pdmodel.common.PDRectangle; /** * @Author Mara * @CreateDate 2020-12-05 * @License Apache License Version 2.0 */ public class BaseDataConvertController extends BaseTaskController { @FXML protected TextArea cssArea; @FXML protected TextField widthList; @FXML protected ControlTextOptions csvWriteController; @FXML protected CheckBox excelWithNamesCheck, currentSheetOnlyCheck; @FXML protected ControlTextOptions textWriteOptionsController; @FXML protected ControlPdfWriteOptions pdfOptionsController; @FXML protected ControlMatrixOptions matrixOptionsController; public void initControls(String name) { baseName = name; initCSV(); initExcel(); initTexts(); initMatrix(); initPDF(); initHtml(); } private void initCSV() { if (csvWriteController != null) { csvWriteController.setControls(baseName + "CSVWrite", false, false); } } private void initExcel() { if (excelWithNamesCheck != null) { excelWithNamesCheck.setSelected(UserConfig.getBoolean(baseName + "ExcelTargetWithNames", true)); } if (currentSheetOnlyCheck != null) { currentSheetOnlyCheck.setSelected(UserConfig.getBoolean(baseName + "ExcelCurrentSheetOnly", false)); } } private void initTexts() { if (textWriteOptionsController != null) { textWriteOptionsController.setControls(baseName + "TextWrite", false, true); } } private void initMatrix() { if (matrixOptionsController != null) { matrixOptionsController.setParameters(baseName); } } private void initHtml() { if (cssArea != null) { cssArea.setText(UserConfig.getString(baseName + "Css", HtmlStyles.TableStyle)); } } private void initPDF() { if (pdfOptionsController != null) { pdfOptionsController.set(baseName, false); pdfOptionsController.pixSizeRadio.setDisable(true); pdfOptionsController.standardSizeRadio.setSelected(true); } } public DataFileCSVWriter pickCSVWriter() { try { DataFileCSVWriter writer = new DataFileCSVWriter(); if (csvWriteController != null) { if (csvWriteController.invalidDelimiter()) { popError(message("InvalidParameter") + ": " + message("Delimiter")); return null; } writer.setCharset(csvWriteController.getCharset()) .setDelimiter(csvWriteController.getDelimiterName()) .setWriteHeader(csvWriteController.withName()); } return writer; } catch (Exception e) { MyBoxLog.error(e); return null; } } public DataFileExcelWriter pickExcelWriter() { try { DataFileExcelWriter writer = new DataFileExcelWriter(); if (excelWithNamesCheck != null) { UserConfig.setBoolean(baseName + "ExcelTargetWithNames", excelWithNamesCheck.isSelected()); writer.setWriteHeader(excelWithNamesCheck.isSelected()); } if (currentSheetOnlyCheck != null) { UserConfig.setBoolean(baseName + "ExcelCurrentSheetOnly", currentSheetOnlyCheck.isSelected()); writer.setCurrentSheetOnly(currentSheetOnlyCheck.isSelected()); } return writer; } catch (Exception e) { MyBoxLog.error(e); return null; } } public DataFileTextWriter pickTextWriter() { try { DataFileTextWriter writer = new DataFileTextWriter(); if (textWriteOptionsController != null) { if (textWriteOptionsController.invalidDelimiter()) { popError(message("InvalidParameter") + ": " + message("Delimiter")); return null; } writer.setCharset(textWriteOptionsController.getCharset()) .setDelimiter(textWriteOptionsController.getDelimiterName()) .setWriteHeader(textWriteOptionsController.withName()); } return writer; } catch (Exception e) { MyBoxLog.error(e); return null; } } public String matrixType() { return matrixOptionsController != null ? matrixOptionsController.pickType() : "Double"; } public DataMatrixWriter pickMatrixWriter() { try { DataMatrixWriter writer = new DataMatrixWriter(); writer.setDataType(matrixType()) .setCharset(Charset.forName("UTF-8")) .setDelimiter(DataMatrix.MatrixDelimiter) .setWriteHeader(false); return writer; } catch (Exception e) { MyBoxLog.error(e); return null; } } public PdfWriter pickPDFWriter() { try { PdfWriter writer = new PdfWriter(); if (pdfOptionsController != null) { if (!pdfOptionsController.pickValues()) { return null; } List<Integer> columnWidths = new ArrayList<>(); String w = widthList.getText(); if (w != null && !w.isBlank()) { String[] values = w.split(","); for (String value : values) { try { int v = Integer.parseInt(value.trim()); if (v > 0) { columnWidths.add(v); } } catch (Exception e) { } } } writer.setPdfTable(PaginatedPdfTable.create() .setPageSize(new PDRectangle(pdfOptionsController.pageWidth, pdfOptionsController.pageHeight)) .setTtf(pdfOptionsController.getTtfFile()) .setFontSize(pdfOptionsController.fontSize) .setMargin(pdfOptionsController.marginSize) .setColumnWidths(columnWidths) .setDefaultZoom(pdfOptionsController.zoom) .setHeader(pdfOptionsController.getHeader()) .setFooter(pdfOptionsController.getFooter()) .setShowPageNumber(pdfOptionsController.showPageNumber)); } return writer; } catch (Exception e) { MyBoxLog.error(e); return null; } } public HtmlWriter pickHtmlWriter() { try { HtmlWriter writer = new HtmlWriter(); if (cssArea != null) { String css = cssArea.getText(); UserConfig.setString(baseName + "Css", css); writer.setCss(css); } return writer; } catch (Exception e) { MyBoxLog.error(e); return null; } } public Data2DWriter pickWriter(TargetType format) { try { if (format == null) { return null; } Data2DWriter writer = null; switch (format) { case CSV: writer = pickCSVWriter(); break; case Excel: writer = pickExcelWriter(); break; case Text: writer = pickTextWriter(); break; case Matrix: writer = pickMatrixWriter(); break; case DatabaseTable: writer = new DataTableWriter(); break; case MyBoxClipboard: writer = new MyBoxClipboardWriter(); break; case SystemClipboard: writer = new SystemClipboardWriter(); break; case HTML: writer = pickHtmlWriter(); break; case PDF: writer = pickPDFWriter(); break; case JSON: writer = new JsonWriter(); break; case XML: writer = new XmlWriter(); break; case Replace: case Insert: case Append: writer = new SystemClipboardWriter(); break; } if (writer != null) { } return writer; } catch (Exception e) { MyBoxLog.error(e); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/controller/ControlHtmlMaker.java
alpha/MyBox/src/main/java/mara/mybox/controller/ControlHtmlMaker.java
package mara.mybox.controller; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.WebViewTools; import mara.mybox.fxml.style.HtmlStyles; /** * @Author Mara * @CreateDate 2018-7-31 * @License Apache License Version 2.0 */ public class ControlHtmlMaker extends BaseHtmlFormat { protected ControlDataHtml htmlController; public void setParameters(ControlDataHtml controller) { try { this.htmlController = controller; webViewController.linkInNewTab = true; webViewController.defaultStyle = HtmlStyles.TableStyle; } catch (Exception e) { MyBoxLog.error(e); } } @Override protected void updateStatus(boolean changed) { super.updateStatus(changed); if (!isSettingValues && htmlController != null) { htmlController.valueChanged(changed); } } @Override public String htmlCodes(String html) { return html; // return HtmlReadTools.body(html, false); } @Override public String htmlInWebview() { return WebViewTools.getHtml(webEngine); // return HtmlReadTools.body(WebViewTools.getHtml(webEngine), false); } @Override public String htmlByRichEditor() { return richEditorController.getContents(); // return HtmlReadTools.body(richEditorController.getContents(), false); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/controller/ImageAlphaAddBatchController.java
alpha/MyBox/src/main/java/mara/mybox/controller/ImageAlphaAddBatchController.java
package mara.mybox.controller; import java.awt.image.BufferedImage; import java.util.Arrays; import javafx.beans.binding.Bindings; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.fxml.FXML; import javafx.scene.control.ComboBox; import javafx.scene.control.RadioButton; import javafx.scene.control.Toggle; import javafx.scene.control.ToggleGroup; import javafx.scene.layout.HBox; import mara.mybox.image.tools.AlphaTools; import mara.mybox.image.data.ImageAttributes; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.fxml.ValidationTools; import mara.mybox.image.file.ImageFileReaders; import mara.mybox.value.FileFilters; import mara.mybox.value.Languages; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2018-9-25 * @License Apache License Version 2.0 */ public class ImageAlphaAddBatchController extends BaseImageEditBatchController { private float opacityValue; private boolean useOpacityValue; private BufferedImage alphaImage; private AlphaBlendMode blendMode; public static enum AlphaBlendMode { Set, KeepOriginal, Plus } @FXML protected ToggleGroup alphaGroup, alphaAddGroup; @FXML protected HBox alphaFileBox; @FXML protected RadioButton opacityRadio, tifRadio; @FXML protected ComboBox<String> opacityBox; public ImageAlphaAddBatchController() { baseTitle = Languages.message("ImageAlphaAdd"); sourceExtensionFilter = FileFilters.AlphaImageExtensionFilter; targetExtensionFilter = sourceExtensionFilter; } @Override public void initControls() { try { super.initControls(); startButton.disableProperty().unbind(); startButton.disableProperty().bind(sourceFileInput.styleProperty().isEqualTo(UserConfig.badStyle()) .or(opacityBox.getEditor().styleProperty().isEqualTo(UserConfig.badStyle())) .or(Bindings.isEmpty(tableView.getItems())) ); } catch (Exception e) { MyBoxLog.debug(e); } } @Override public void initOptionsSection() { try { super.initOptionsSection(); alphaGroup.selectedToggleProperty().addListener(new ChangeListener<Toggle>() { @Override public void changed(ObservableValue<? extends Toggle> ov, Toggle old_toggle, Toggle new_toggle) { checkOpacityType(); } }); checkOpacityType(); opacityBox.getItems().addAll(Arrays.asList("50", "10", "60", "80", "100", "90", "20", "30")); opacityBox.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue ov, String oldValue, String newValue) { checkOpacity(); } }); opacityBox.getSelectionModel().select(0); alphaAddGroup.selectedToggleProperty().addListener(new ChangeListener<Toggle>() { @Override public void changed(ObservableValue<? extends Toggle> ov, Toggle old_toggle, Toggle new_toggle) { checkOpacityAdd(); } }); checkOpacityAdd(); } catch (Exception e) { MyBoxLog.error(e); } } private void checkOpacityType() { alphaFileBox.setDisable(true); sourceFileInput.setStyle(null); opacityBox.setDisable(true); ValidationTools.setEditorNormal(opacityBox); useOpacityValue = opacityRadio.isSelected(); if (useOpacityValue) { opacityBox.setDisable(false); checkOpacity(); } else { alphaFileBox.setDisable(false); checkSourceFileInput(); } } private void checkOpacity() { try { int v = Integer.parseInt(opacityBox.getValue()); if (v >= 0 && v <= 100) { opacityValue = v / 100f; ValidationTools.setEditorNormal(opacityBox); } else { ValidationTools.setEditorBadStyle(opacityBox); } } catch (Exception e) { ValidationTools.setEditorBadStyle(opacityBox); } } private void checkOpacityAdd() { String selected = ((RadioButton) alphaAddGroup.getSelectedToggle()).getText(); if (Languages.message("Plus").equals(selected)) { blendMode = AlphaBlendMode.Plus; } else if (Languages.message("Keep").equals(selected)) { blendMode = AlphaBlendMode.KeepOriginal; } else { blendMode = AlphaBlendMode.Set; } } @Override public boolean makeMoreParameters() { if (!super.makeMoreParameters()) { return false; } if (tifRadio.isSelected()) { targetFileSuffix = "tif"; } else { targetFileSuffix = "png"; } attributes = new ImageAttributes(targetFileSuffix); return true; } @Override public boolean beforeHandleFiles(FxTask currentTask) { if (!useOpacityValue) { alphaImage = ImageFileReaders.readImage(currentTask, sourceFile); return alphaImage != null; } return true; } @Override protected BufferedImage handleImage(FxTask currentTask, BufferedImage source) { try { if (source.getColorModel().hasAlpha() && blendMode == AlphaBlendMode.KeepOriginal) { errorString = Languages.message("NeedNotHandle"); return null; } BufferedImage target; if (useOpacityValue) { target = AlphaTools.addAlpha(currentTask, source, opacityValue, blendMode == AlphaBlendMode.Plus); } else { target = AlphaTools.addAlpha(currentTask, source, alphaImage, blendMode == AlphaBlendMode.Plus); } return target; } catch (Exception e) { MyBoxLog.error(e); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/controller/ControlDataJavascript.java
alpha/MyBox/src/main/java/mara/mybox/controller/ControlDataJavascript.java
package mara.mybox.controller; import java.io.File; import javafx.event.Event; import javafx.fxml.FXML; import javafx.scene.control.Tab; import mara.mybox.db.table.TableNodeJavaScript; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.PopTools; import mara.mybox.fxml.style.HtmlStyles; import mara.mybox.tools.DateTools; import mara.mybox.tools.HtmlWriteTools; import static mara.mybox.value.Languages.message; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2022-3-20 * @License Apache License Version 2.0 */ public class ControlDataJavascript extends BaseJavaScriptController { protected String outputs = ""; @FXML protected Tab htmlTab; @FXML protected ControlWebView outputController; @FXML protected WebAddressController htmlController; @Override public void initEditor() { try { super.initEditor(); outputController.setParent(this, ControlWebView.ScrollType.Bottom); MyBoxLog.console(htmlController != null); htmlWebView = htmlController.webViewController; htmlController.webViewController.setParent(this, ControlWebView.ScrollType.Bottom); htmlController.loadContents(HtmlWriteTools.emptyHmtl(message("AppTitle"))); } catch (Exception e) { MyBoxLog.error(e); } } @Override public void afterTask(boolean ok) { try { outputs += DateTools.nowString() + "<div class=\"valueText\" >" + HtmlWriteTools.stringToHtml(script) + "</div>"; outputs += "<div class=\"valueBox\">" + HtmlWriteTools.stringToHtml(results) + "</div><br><br>"; String html = HtmlWriteTools.html(null, HtmlStyles.DefaultStyle, "<body>" + outputs + "</body>"); outputController.loadContent(html); } catch (Exception e) { MyBoxLog.error(e); } } /* right pane */ @FXML public void editResults() { outputController.editAction(); } @FXML public void clearResults() { outputs = ""; outputController.clear(); } public void edit(String script) { scriptInput.setText(script); } @FXML protected void showHtmlStyle(Event event) { PopTools.popHtmlStyle(event, outputController); } @FXML protected void popHtmlStyle(Event event) { if (UserConfig.getBoolean("HtmlStylesPopWhenMouseHovering", false)) { showHtmlStyle(event); } } /* static */ public static DataTreeNodeEditorController openScriptEditor(BaseController parent) { try { DataTreeNodeEditorController controller = DataTreeNodeEditorController.openTable(parent, new TableNodeJavaScript()); return controller; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static DataTreeNodeEditorController open(ControlWebView controlWebView) { try { DataTreeNodeEditorController controller = openScriptEditor(controlWebView); ((ControlDataJavascript) controller.valuesController).setParameters(controlWebView); return controller; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static DataTreeNodeEditorController loadScript(BaseController parent, String script) { try { DataTreeNodeEditorController controller = openScriptEditor(parent); ((ControlDataJavascript) controller.valuesController).edit(script); return controller; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static DataTreeNodeEditorController openFile(BaseController parent, File file) { try { DataTreeNodeEditorController controller = openScriptEditor(parent); ((ControlDataJavascript) controller.valuesController).selectSourceFile(file); return controller; } catch (Exception e) { MyBoxLog.error(e); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/controller/TextEditorController.java
alpha/MyBox/src/main/java/mara/mybox/controller/TextEditorController.java
package mara.mybox.controller; import java.io.File; import java.util.List; import javafx.event.ActionEvent; import javafx.event.Event; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.scene.control.IndexRange; import javafx.scene.control.MenuItem; import javafx.scene.input.ContextMenuEvent; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.fxml.menu.MenuTools; import mara.mybox.fxml.WindowTools; import mara.mybox.fxml.style.StyleTools; import mara.mybox.tools.ByteTools; import mara.mybox.tools.TextTools; import mara.mybox.value.Fxmls; import mara.mybox.value.Languages; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2018-7-31 * @License Apache License Version 2.0 */ public class TextEditorController extends BaseTextController { public TextEditorController() { baseTitle = Languages.message("TextEditer"); TipsLabelKey = "TextEditerTips"; } @Override public void setFileType() { setTextType(); } @Override protected void initPairBox() { try { super.initPairBox(); if (pairArea == null) { return; } pairArea.setOnContextMenuRequested(new EventHandler<ContextMenuEvent>() { @Override public void handle(ContextMenuEvent event) { MenuBytesEditController.openBytes(myController, pairArea, event); } }); } catch (Exception e) { MyBoxLog.error(e); } } @FXML @Override public void refreshPairAction() { if (isSettingValues || pairArea == null) { return; } isSettingValues = true; String text = mainArea.getText(); if (!text.isEmpty()) { String hex = ByteTools.bytesToHexFormat(text.getBytes(sourceInformation.getCharset())); String hexLF = ByteTools.bytesToHexFormat("\n".getBytes(sourceInformation.getCharset())).trim(); String hexLB = ByteTools.bytesToHexFormat(sourceInformation.getLineBreakValue().getBytes(sourceInformation.getCharset())).trim(); hex = hex.replaceAll(hexLF, hexLB + "\n"); if (sourceInformation.isWithBom()) { hex = TextTools.bomHex(sourceInformation.getCharset().name()) + " " + hex; } pairArea.setText(hex); setPairAreaSelection(); } else { pairArea.clear(); } isSettingValues = false; } @Override protected void setPairAreaSelection() { if (isSettingValues || pairArea == null || !splitPane.getItems().contains(rightPane)) { return; } if (pairTask != null) { pairTask.cancel(); } pairTask = new FxTask<Void>(this) { private IndexRange hexRange; private int bomLen; @Override protected boolean handle() { try { hexRange = null; final String text = mainArea.getText(); if (!text.isEmpty()) { hexRange = TextTools.hexIndex(this, text, sourceInformation.getCharset(), sourceInformation.getLineBreakValue(), mainArea.getSelection()); bomLen = 0; if (sourceInformation.isWithBom()) { bomLen = TextTools.bomHex(sourceInformation.getCharset().name()).length() + 1; } } return hexRange != null; } catch (Exception e) { error = e.toString(); return false; } } @Override protected void whenSucceeded() { isSettingValues = true; pairArea.deselect(); pairArea.selectRange(hexRange.getStart() + bomLen, hexRange.getEnd() + bomLen); pairArea.setScrollTop(mainArea.getScrollTop()); isSettingValues = false; } @Override protected void whenCanceled() { } @Override protected void whenFailed() { } }; start(pairTask, rightPane); } @FXML @Override public void saveAsAction() { TextEditorSaveAsController.open(this); } @FXML @Override public boolean popAction() { TextPopController.openInput(this, mainArea); return true; } @FXML public void popBytesAction() { BytesPopController.open(this, pairArea); } @Override public List<MenuItem> fileMenuItems(Event fevent) { List<MenuItem> items = MenuTools.initMenu(message("File")); MenuItem menu; if (sourceFile != null) { menu = new MenuItem(message("Format"), StyleTools.getIconImageView("iconFormat.png")); menu.setOnAction((ActionEvent menuItemEvent) -> { TextEditorFormatController.open(this); }); items.add(menu); } items.addAll(super.fileMenuItems(fevent)); return items; } /* static */ public static TextEditorController open() { try { TextEditorController controller = (TextEditorController) WindowTools.openStage(Fxmls.TextEditorFxml); if (controller != null) { controller.requestMouse(); } return controller; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static TextEditorController open(File file) { TextEditorController controller = open(); if (controller != null) { controller.sourceFileChanged(file); } return controller; } public static TextEditorController edit(String texts) { TextEditorController controller = open(); if (controller != null) { controller.loadContents(texts); } return controller; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/controller/FilesRenameController.java
alpha/MyBox/src/main/java/mara/mybox/controller/FilesRenameController.java
package mara.mybox.controller; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import javafx.beans.binding.Bindings; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.event.Event; import javafx.fxml.FXML; import javafx.scene.control.CheckBox; import javafx.scene.control.RadioButton; import javafx.scene.control.TextField; import javafx.scene.control.Toggle; import javafx.scene.control.ToggleGroup; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import mara.mybox.data.FileInformation; import mara.mybox.data.FindReplaceString; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.fxml.PopTools; import mara.mybox.fxml.WindowTools; import mara.mybox.tools.FileNameTools; import mara.mybox.tools.FileSortTools; import mara.mybox.tools.FileSortTools.FileSortMode; import mara.mybox.tools.StringTools; import mara.mybox.value.Fxmls; import static mara.mybox.value.Languages.message; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2018-7-4 * @License Apache License Version 2.0 */ public class FilesRenameController extends BaseBatchFileController { protected LinkedHashMap<String, String> names; protected int currentAccum, digit, startNumber; protected RenameType renameType; @FXML protected VBox renameOptionsBox, numberBox, replaceBox; @FXML protected HBox suffixBox, prefixBox, extensionBox; @FXML protected CheckBox fillZeroCheck, originalCheck, stringCheck, accumCheck, suffixCheck, descentCheck, recountCheck, regexCheck; @FXML protected TextField oldStringInput, newStringInput, newExtInput, prefixInput, suffixInput, stringInput; @FXML protected ToggleGroup sortGroup, renameGroup; @FXML protected RadioButton replaceAllRadio; public static enum RenameType { ReplaceSubString, AppendSuffix, AddPrefix, AddSequenceNumber, ChangeExtension } public FilesRenameController() { baseTitle = message("FilesRename"); } @Override public void initTargetSection() { try { super.initTargetSection(); renameGroup.selectedToggleProperty().addListener(new ChangeListener<Toggle>() { @Override public void changed(ObservableValue<? extends Toggle> ov, Toggle old_toggle, Toggle new_toggle) { checkRenameType(); } }); checkRenameType(); fillZeroCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> v, Boolean oldV, Boolean newV) { UserConfig.setBoolean("FileRenameFillZero", fillZeroCheck.isSelected()); } }); fillZeroCheck.setSelected(UserConfig.getBoolean("FileRenameFillZero", true)); startButton.disableProperty().unbind(); startButton.disableProperty().bind( Bindings.isEmpty(tableData) .or(tableController.addFilesButton.disableProperty()) ); } catch (Exception e) { MyBoxLog.debug(e); } } private void checkRenameType() { renameOptionsBox.getChildren().clear(); RadioButton selected = (RadioButton) renameGroup.getSelectedToggle(); if (message("ReplaceSubString").equals(selected.getText())) { renameType = RenameType.ReplaceSubString; renameOptionsBox.getChildren().addAll(replaceBox); } else if (message("AppendSuffix").equals(selected.getText())) { renameType = RenameType.AppendSuffix; renameOptionsBox.getChildren().addAll(suffixBox); } else if (message("AddPrefix").equals(selected.getText())) { renameType = RenameType.AddPrefix; renameOptionsBox.getChildren().addAll(prefixBox); } else if (message("AddSequenceNumber").equals(selected.getText())) { renameType = RenameType.AddSequenceNumber; renameOptionsBox.getChildren().addAll(numberBox); } else if (message("ChangeExtension").equals(selected.getText())) { renameType = RenameType.ChangeExtension; renameOptionsBox.getChildren().addAll(extensionBox); } refreshStyle(renameOptionsBox); } @Override public boolean makeMoreParameters() { switch (renameType) { case ReplaceSubString: if (oldStringInput.getText().isBlank()) { return false; } break; case AddPrefix: if (prefixInput.getText().isBlank()) { return false; } break; case AppendSuffix: if (suffixInput.getText().isBlank()) { return false; } break; case AddSequenceNumber: if (isPreview) { digit = 1; } else { sortFileInformations(tableData); try { digit = Integer.parseInt(digitInput.getText()); } catch (Exception e) { if (tableController.totalFilesNumber <= 0) { digit = tableData.size(); } else { digit = (tableController.totalFilesNumber + "").length(); } } } try { startNumber = Integer.parseInt(acumFromInput.getText()); } catch (Exception e) { startNumber = 0; } currentAccum = startNumber; break; case ChangeExtension: } names = new LinkedHashMap<>(); return super.makeMoreParameters(); } protected FileSortMode checkSortMode() { RadioButton sort = (RadioButton) sortGroup.getSelectedToggle(); boolean desc = descentCheck.isSelected(); FileSortMode sortMode = FileSortMode.ModifyTimeDesc; if (message("OriginalFileName").equals(sort.getText())) { if (desc) { sortMode = FileSortMode.NameDesc; } else { sortMode = FileSortMode.NameAsc; } } else if (message("CreateTime").equals(sort.getText())) { if (desc) { sortMode = FileSortMode.CreateTimeDesc; } else { sortMode = FileSortMode.CreateTimeAsc; } } else if (message("ModifyTime").equals(sort.getText())) { if (desc) { sortMode = FileSortMode.ModifyTimeDesc; } else { sortMode = FileSortMode.ModifyTimeAsc; } } else if (message("Size").equals(sort.getText())) { if (desc) { sortMode = FileSortMode.SizeDesc; } else { sortMode = FileSortMode.SizeAsc; } } else if (message("AddedSequence").equals(sort.getText())) { sortMode = null; } return sortMode; } protected void sortFileInformations(List<FileInformation> files) { FileSortMode sortMode = checkSortMode(); if (sortMode != null) { FileSortTools.sortFileInformations(files, sortMode); } } protected void sortFiles(List<File> files) { FileSortMode sortMode = checkSortMode(); if (sortMode != null) { FileSortTools.sortFiles(files, sortMode); } } @Override public String handleFile(FxTask currentTask, File srcFile, File targetPath) { String newName = makeName(srcFile); names.put(srcFile.getAbsolutePath(), newName); return message("Handling"); } protected String makeName(File file) { if (file == null || !file.exists() || !file.isFile()) { return null; } try { String filePath = file.getParent() + File.separator; String currentName = file.getName(); String newName = null; switch (renameType) { case ReplaceSubString: if (regexCheck.isSelected()) { if (replaceAllRadio.isSelected()) { newName = currentName.replaceAll(oldStringInput.getText(), FileNameTools.filter(newStringInput.getText())); } else { newName = currentName.replaceFirst(oldStringInput.getText(), FileNameTools.filter(newStringInput.getText())); } } else { if (replaceAllRadio.isSelected()) { newName = FindReplaceString.replaceAll(null, currentName, oldStringInput.getText(), FileNameTools.filter(newStringInput.getText())); } else { newName = FindReplaceString.replaceFirst(null, currentName, oldStringInput.getText(), FileNameTools.filter(newStringInput.getText())); } } break; case AddPrefix: newName = FileNameTools.filter(prefixInput.getText()) + currentName; break; case AppendSuffix: newName = FileNameTools.append(currentName, FileNameTools.filter(suffixInput.getText())); break; case AddSequenceNumber: newName = ""; if (originalCheck.isSelected()) { newName += FileNameTools.prefix(currentName); } if (stringCheck.isSelected()) { String s = stringInput.getText(); if (s != null && !s.isEmpty()) { newName += FileNameTools.filter(s); } } String pageNumber = currentAccum + ""; if (fillZeroCheck.isSelected()) { pageNumber = StringTools.fillLeftZero(currentAccum, digit); } newName += pageNumber; currentAccum++; newName += "." + FileNameTools.ext(currentName); break; case ChangeExtension: newName = FileNameTools.replaceExt(currentName, FileNameTools.filter(newExtInput.getText())); break; } if (newName == null || newName.isBlank()) { return null; } return filePath + newName; } catch (Exception e) { showLogs(e.toString()); return null; } } @Override protected boolean handleDirectory(FxTask currentTask, File sourcePath, String targetPath) { if (sourcePath == null || !sourcePath.exists() || !sourcePath.isDirectory()) { return false; } try { File[] srcFiles = sourcePath.listFiles(); if (srcFiles == null) { return false; } if (recountCheck.isSelected()) { currentAccum = startNumber; } List<File> files = new ArrayList<>(); files.addAll(Arrays.asList(srcFiles)); if (renameType == RenameType.AddSequenceNumber) { sortFiles(files); int bdigit = (files.size() + "").length(); if (digit < bdigit) { digit = bdigit; } } for (File file : files) { if (currentTask == null || !currentTask.isWorking()) { return false; } if (file.isFile()) { dirFilesNumber++; if (!match(file)) { continue; } String newName = makeName(file); names.put(file.getAbsolutePath(), newName); if (newName != null) { dirFilesHandled++; } } else if (file.isDirectory() && sourceCheckSubdir) { handleDirectory(currentTask, file, null); } } return true; } catch (Exception e) { MyBoxLog.error(e); return false; } } @Override public void afterTask(boolean ok) { try { super.afterTask(ok); if (names == null || names.isEmpty()) { popError(message("SelectToHandle")); return; } FilesRenameResultsController controller = (FilesRenameResultsController) WindowTools.referredTopStage(this, Fxmls.FilesRenameResultsFxml); controller.handleFiles(names); } catch (Exception e) { MyBoxLog.error(e); } } @FXML protected void showRegexExample(Event event) { PopTools.popRegexExamples(this, oldStringInput, event); } @FXML protected void popRegexExample(Event event) { if (UserConfig.getBoolean("RegexExamplesPopWhenMouseHovering", false)) { showRegexExample(event); } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/controller/IlluminantsController.java
alpha/MyBox/src/main/java/mara/mybox/controller/IlluminantsController.java
package mara.mybox.controller; import java.util.Map; import javafx.beans.binding.Bindings; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.Button; import mara.mybox.color.CIEDataTools; import mara.mybox.color.ChromaticAdaptation; import mara.mybox.color.Illuminant; import mara.mybox.data.StringTable; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxSingletonTask; import mara.mybox.tools.DoubleArrayTools; import mara.mybox.tools.HtmlWriteTools; import mara.mybox.value.Languages; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2019-6-1 * @License Apache License Version 2.0 */ // http://brucelindbloom.com/index.html?Eqn_ChromAdapt.html public class IlluminantsController extends ChromaticityBaseController { protected double sourceWPX, sourceWPY, sourceWPZ, targetWPX, targetWPY, targetWPZ; @FXML public XYZController sourceColorController; @FXML public WhitePointController sourceWPController, targetWPController; @FXML protected Button calculateButton; @FXML protected HtmlTableController illuminantsController; public IlluminantsController() { baseTitle = Languages.message("Illuminants"); exportName = "StandardIlluminants"; } @Override public void initControls() { try { super.initControls(); initAdaptation(); initData(); } catch (Exception e) { MyBoxLog.error(e); } } private void initAdaptation() { initOptions(); calculateButton.disableProperty().bind(Bindings.isEmpty(scaleInput.textProperty()) .or(scaleInput.styleProperty().isEqualTo(UserConfig.badStyle())) .or(Bindings.isEmpty(sourceColorController.xInput.textProperty())) .or(sourceColorController.xInput.styleProperty().isEqualTo(UserConfig.badStyle())) .or(Bindings.isEmpty(sourceColorController.yInput.textProperty())) .or(sourceColorController.yInput.styleProperty().isEqualTo(UserConfig.badStyle())) .or(Bindings.isEmpty(sourceColorController.zInput.textProperty())) .or(sourceColorController.zInput.styleProperty().isEqualTo(UserConfig.badStyle())) .or(Bindings.isEmpty(sourceWPController.xInput.textProperty())) .or(sourceWPController.xInput.styleProperty().isEqualTo(UserConfig.badStyle())) .or(Bindings.isEmpty(sourceWPController.yInput.textProperty())) .or(sourceWPController.yInput.styleProperty().isEqualTo(UserConfig.badStyle())) .or(Bindings.isEmpty(sourceWPController.zInput.textProperty())) .or(sourceWPController.zInput.styleProperty().isEqualTo(UserConfig.badStyle())) .or(Bindings.isEmpty(targetWPController.xInput.textProperty())) .or(targetWPController.xInput.styleProperty().isEqualTo(UserConfig.badStyle())) .or(Bindings.isEmpty(targetWPController.yInput.textProperty())) .or(targetWPController.yInput.styleProperty().isEqualTo(UserConfig.badStyle())) .or(Bindings.isEmpty(targetWPController.zInput.textProperty())) .or(targetWPController.zInput.styleProperty().isEqualTo(UserConfig.badStyle())) ); } private void initData() { if (task != null) { task.cancel(); } task = new FxSingletonTask<Void>(this) { private StringTable table; @Override protected boolean handle() { table = Illuminant.table(scale); return true; } @Override protected void whenSucceeded() { illuminantsController.loadTable(table); } }; start(task); } @FXML public void calculateAction(ActionEvent event) { try { webView.getEngine().loadContent(""); if (calculateButton.isDisabled()) { return; } double[] swp = sourceWPController.relative; double[] twp = targetWPController.relative; if (swp == null || twp == null) { return; } Map<String, Object> run = (Map<String, Object>) ChromaticAdaptation.adapt( sourceColorController.x, sourceColorController.y, sourceColorController.z, swp[0], swp[1], swp[2], twp[0], twp[1], twp[2], algorithm, scale, true); double[] adaptedColor = (double[]) run.get("adaptedColor"); double[] mc = DoubleArrayTools.scale(adaptedColor, scale); String s = Languages.message("CalculatedValues") + ": X=" + mc[0] + " Y=" + mc[1] + " Z=" + mc[2] + "\n"; double[] mr = DoubleArrayTools.scale(CIEDataTools.relative(mc), scale); s += Languages.message("RelativeValues") + ": X=" + mr[0] + " Y=" + mr[1] + " Z=" + mr[2] + "\n"; double[] mn = DoubleArrayTools.scale(CIEDataTools.normalize(mc), scale); s += Languages.message("NormalizedValuesCC") + ": x=" + mn[0] + " y=" + mn[1] + " z=" + mn[2] + "\n" + "\n----------------" + Languages.message("CalculationProcedure") + "----------------\n" + Languages.message("ReferTo") + ": \n" + " http://www.thefullwiki.org/Standard_illuminant#cite_note-30 \n" + " http://brucelindbloom.com/index.html?Eqn_ChromAdapt.html \n\n" + (String) run.get("procedure"); webView.getEngine().loadContent(HtmlWriteTools.codeToHtml(s)); } catch (Exception e) { MyBoxLog.error(e); } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/controller/ControlPdfWriteOptions.java
alpha/MyBox/src/main/java/mara/mybox/controller/ControlPdfWriteOptions.java
package mara.mybox.controller; import java.sql.Connection; import java.util.Arrays; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.fxml.FXML; import javafx.scene.control.CheckBox; import javafx.scene.control.ComboBox; import javafx.scene.control.RadioButton; import javafx.scene.control.TextField; import javafx.scene.control.Toggle; import javafx.scene.control.ToggleGroup; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import mara.mybox.db.DerbyBase; import mara.mybox.db.data.VisitHistory; import mara.mybox.dev.MyBoxLog; import mara.mybox.tools.PdfTools.PdfImageFormat; import static mara.mybox.value.Languages.message; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2020-12-07 * @License Apache License Version 2.0 */ public class ControlPdfWriteOptions extends BaseFileController { protected String author, header, footer, ttfFile; protected boolean isImageSize, includeImageOptions, dithering, showPageNumber, landscape; protected int marginSize, pageWidth, pageHeight, jpegQuality, threshold, fontSize, zoom; protected PdfImageFormat imageFormat; @FXML protected ComboBox<String> marginSelector, standardSizeSelector, jpegQualitySelector, fontSizeSelector, zoomSelector; @FXML protected ControlTTFSelector ttfController; @FXML protected ToggleGroup sizeGroup, imageFormatGroup; @FXML protected RadioButton pixSizeRadio, standardSizeRadio, customSizeRadio, pngRadio, jpgRadio, bwRadio; @FXML protected TextField authorInput, headerInput, footerInput, customWidthInput, customHeightInput, thresholdInput; @FXML protected CheckBox pageNumberCheck, ditherCheck, landscapeCheck; @FXML protected VBox imageOptionsBox; @FXML protected HBox dpiBox; public ControlPdfWriteOptions() { } @Override public void setFileType() { setFileType(VisitHistory.FileType.TTF); } public ControlPdfWriteOptions set(String baseName, boolean imageOptions) { this.baseName = baseName; this.includeImageOptions = imageOptions; ttfController.name(baseName); setControls(); return this; } public void setControls() { try (Connection conn = DerbyBase.getConnection()) { sizeGroup.selectedToggleProperty().addListener(new ChangeListener<Toggle>() { @Override public void changed(ObservableValue<? extends Toggle> ov, Toggle old_toggle, Toggle new_toggle) { checkPageSize(); } }); standardSizeSelector.getItems().addAll(Arrays.asList( "A4 (16k) 21.0cm x 29.7cm", "A5 (32k) 14.8cm x 21.0cm", "A6 (64k) 10.5cm x 14.8cm", "A3 (8k) 29.7cm x 42.0cm", "A2 (4k) 42.0cm x 59.4cm", "A1 (2k) 59.4cm x 84.1cm", "A0 (1k) 84.1cm x 118.9cm", "B5 17.6cm x 25.0cm", "B4 25.0cm x 35.3cm", "B2 35.3cm x 50.0cm", "C4 22.9cm x 32.4cm", "C5 16.2cm x 22.9cm", "C6 11.4cm x 16.2cm" )); standardSizeSelector.setValue(UserConfig.getString(conn, baseName + "PdfStandardSize", "A4 (16k) 21.0cm x 29.7cm")); standardSizeSelector.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> ov, String oldValue, String newValue) { checkStandardValues(); } }); pageWidth = UserConfig.getInt(conn, baseName + "PdfCustomWidth", 1024); customWidthInput.setText(pageWidth + ""); pageHeight = UserConfig.getInt(conn, baseName + "PdfCustomHeight", 500); customHeightInput.setText(pageHeight + ""); marginSelector.getItems().addAll(Arrays.asList("20", "10", "15", "5", "25", "30", "40")); marginSize = UserConfig.getInt(conn, baseName + "PdfMarginSize", 20); marginSelector.setValue(marginSize + ""); fontSizeSelector.getItems().addAll(Arrays.asList( "20", "14", "18", "15", "9", "10", "12", "17", "24", "36", "48", "64", "72", "96")); fontSize = UserConfig.getInt(conn, baseName + "PdfFontSize", 20); fontSizeSelector.getSelectionModel().select(fontSize + ""); zoomSelector.getItems().addAll(Arrays.asList("60", "100", "75", "50", "125", "30", "45", "200")); zoom = UserConfig.getInt(conn, baseName + "PdfZoom", 60); zoomSelector.getSelectionModel().select(zoom + ""); author = UserConfig.getString(conn, baseName + "PdfAuthor", System.getProperty("user.name")); authorInput.setText(author); header = UserConfig.getString(conn, baseName + "PdfHeader", ""); headerInput.setText(header); footer = UserConfig.getString(conn, baseName + "PdfFooter", ""); footerInput.setText(footer); showPageNumber = UserConfig.getBoolean(conn, baseName + "PdfShowPageNumber", true); pageNumberCheck.setSelected(showPageNumber); landscape = UserConfig.getBoolean(conn, baseName + "PdfPageHorizontal", false); landscapeCheck.setSelected(landscape); landscapeCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { checkStandardValues(); } }); initImageOptions(conn); checkPageSize(); } catch (Exception e) { MyBoxLog.error(e, baseName); } } protected void checkPageSize() { standardSizeSelector.setDisable(true); dpiBox.setDisable(true); landscapeCheck.setDisable(true); isImageSize = false; if (pixSizeRadio.isSelected()) { isImageSize = true; } else if (standardSizeRadio.isSelected()) { standardSizeSelector.setDisable(false); dpiBox.setDisable(false); landscapeCheck.setDisable(false); checkStandardValues(); } else if (customSizeRadio.isSelected()) { } } protected void checkStandardValues() { String s = standardSizeSelector.getSelectionModel().getSelectedItem(); switch (s.substring(0, 2)) { case "A4": pageWidth = calculateCmPixels(21.0f, dpi); pageHeight = calculateCmPixels(29.7f, dpi); break; case "A5": pageWidth = calculateCmPixels(14.8f, dpi); pageHeight = calculateCmPixels(21.0f, dpi); break; case "A6": pageWidth = calculateCmPixels(10.5f, dpi); pageHeight = calculateCmPixels(14.8f, dpi); break; case "A3": pageWidth = calculateCmPixels(29.7f, dpi); pageHeight = calculateCmPixels(42.0f, dpi); break; case "A2": pageWidth = calculateCmPixels(42.0f, dpi); pageHeight = calculateCmPixels(59.4f, dpi); break; case "A1": pageWidth = calculateCmPixels(59.4f, dpi); pageHeight = calculateCmPixels(84.1f, dpi); break; case "A0": pageWidth = calculateCmPixels(84.1f, dpi); pageHeight = calculateCmPixels(118.9f, dpi); break; case "B5": pageWidth = calculateCmPixels(17.6f, dpi); pageHeight = calculateCmPixels(25.0f, dpi); break; case "B4": pageWidth = calculateCmPixels(25.0f, dpi); pageHeight = calculateCmPixels(35.3f, dpi); break; case "B2": pageWidth = calculateCmPixels(35.3f, dpi); pageHeight = calculateCmPixels(50.0f, dpi); break; case "C4": pageWidth = calculateCmPixels(22.9f, dpi); pageHeight = calculateCmPixels(32.4f, dpi); break; case "C5": pageWidth = calculateCmPixels(16.2f, dpi); pageHeight = calculateCmPixels(22.9f, dpi); break; case "C6": pageWidth = calculateCmPixels(11.4f, dpi); pageHeight = calculateCmPixels(16.2f, dpi); break; } if (landscapeCheck.isSelected()) { int tmp = pageWidth; pageWidth = pageHeight; pageHeight = tmp; } customWidthInput.setText(pageWidth + ""); customHeightInput.setText(pageHeight + ""); } protected int calculateCmPixels(float cm, int dpi) { return (int) Math.round(cm * dpi / 2.54); } protected void initImageOptions(Connection conn) { try { if (!includeImageOptions) { thisPane.getChildren().removeAll(pixSizeRadio, imageOptionsBox); standardSizeRadio.setSelected(true); return; } jpegQualitySelector.getItems().addAll(Arrays.asList("100", "75", "90", "50", "60", "80", "30", "10")); jpegQuality = UserConfig.getInt(conn, baseName + "PdfJpegQuality", 100); jpegQualitySelector.setValue(jpegQuality + ""); threshold = UserConfig.getInt(conn, baseName + "PdfThreshold", -1); thresholdInput.setText(threshold + ""); dithering = UserConfig.getBoolean(conn, baseName + "PdfImageDithering", true); ditherCheck.setSelected(dithering); } catch (Exception e) { MyBoxLog.error(e, baseName); } } public boolean pickValues() { if (customSizeRadio.isSelected()) { try { pageWidth = Integer.parseInt(customWidthInput.getText()); } catch (Exception e) { pageWidth = -1; } try { pageHeight = Integer.parseInt(customHeightInput.getText()); } catch (Exception e) { pageHeight = -1; } } else if (standardSizeRadio.isSelected()) { try { dpi = Integer.parseInt(dpiSelector.getValue()); } catch (Exception e) { dpi = -1; } if (dpi <= 0) { popError(message("InvalidParameter") + ": " + "DPI"); return false; } } if (!isImageSize) { if (pageWidth <= 0) { popError(message("InvalidParameter") + ": " + message("Width")); return false; } if (pageHeight <= 0) { popError(message("InvalidParameter") + ": " + message("Height")); return false; } } try { fontSize = Integer.parseInt(fontSizeSelector.getValue()); } catch (Exception e) { fontSize = -1; } if (fontSize <= 0) { popError(message("InvalidParameter") + ": " + message("FontSize")); return false; } try { zoom = Integer.parseInt(zoomSelector.getValue()); } catch (Exception e) { zoom = -1; } if (zoom <= 0) { popError(message("InvalidParameter") + ": " + message("DefaultDisplayScale")); return false; } if (includeImageOptions) { if (bwRadio.isSelected()) { try { threshold = Integer.parseInt(thresholdInput.getText()); } catch (Exception e) { threshold = -1; } if (threshold < 0 || threshold > 255) { popError(message("InvalidParameter") + ": " + message("CCITT4")); return false; } imageFormat = PdfImageFormat.Tiff; } else if (jpgRadio.isSelected()) { try { jpegQuality = Integer.parseInt(thresholdInput.getText()); } catch (Exception e) { jpegQuality = -1; } if (jpegQuality < 0 || jpegQuality > 100) { popError(message("InvalidParameter") + ": " + message("JpegQuailty")); return false; } imageFormat = PdfImageFormat.Jpeg; } else { imageFormat = PdfImageFormat.Original; } } try { marginSize = Integer.parseInt(marginSelector.getValue()); } catch (Exception e) { marginSize = 0; } showPageNumber = pageNumberCheck.isSelected(); landscape = landscapeCheck.isSelected(); dithering = ditherCheck.isSelected(); ttfFile = ttfController.ttfFile; author = authorInput.getText(); header = headerInput.getText(); footer = footerInput.getText(); try (Connection conn = DerbyBase.getConnection()) { UserConfig.setInt(conn, baseName + "PdfZoom", zoom); UserConfig.setInt(conn, baseName + "PdfFontSize", fontSize); UserConfig.setInt(conn, baseName + "PdfMarginSize", marginSize); UserConfig.setInt(conn, baseName + "PdfCustomWidth", pageWidth); UserConfig.setInt(conn, baseName + "PdfCustomHeight", pageHeight); UserConfig.setInt(conn, baseName + "PdfThreshold", threshold); UserConfig.setInt(conn, baseName + "PdfJpegQuality", jpegQuality); UserConfig.setString(conn, baseName + "PdfHeader", header); UserConfig.setString(conn, baseName + "PdfAuthor", author); UserConfig.setString(conn, baseName + "PdfFooter", footer); UserConfig.setString(conn, baseName + "PdfStandardSize", standardSizeSelector.getValue()); UserConfig.setBoolean(conn, baseName + "PdfShowPageNumber", showPageNumber); UserConfig.setBoolean(conn, baseName + "PdfPageHorizontal", landscape); UserConfig.setBoolean(conn, baseName + "PdfImageDithering", dithering); } catch (Exception e) { } return true; } /* get */ public String getAuthor() { return author; } public String getHeader() { return header; } public String getFooter() { return footer; } public String getTtfFile() { return ttfFile; } public boolean isIsImageSize() { return isImageSize; } public boolean isDithering() { return dithering; } public boolean isShowPageNumber() { return showPageNumber; } public boolean isLandscape() { return landscape; } public int getMarginSize() { return marginSize; } public int getPageWidth() { return pageWidth; } public int getPageHeight() { return pageHeight; } public int getJpegQuality() { return jpegQuality; } public int getThreshold() { return threshold; } public int getFontSize() { return fontSize; } public int getZoom() { return zoom; } public PdfImageFormat getImageFormat() { return imageFormat; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/controller/ControlLines.java
alpha/MyBox/src/main/java/mara/mybox/controller/ControlLines.java
package mara.mybox.controller; import java.util.ArrayList; import java.util.List; import javafx.beans.property.SimpleStringProperty; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.fxml.FXML; import javafx.scene.control.TableColumn; import javafx.util.Callback; import mara.mybox.data.DoublePoint; import mara.mybox.dev.MyBoxLog; import static mara.mybox.value.Languages.message; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2023-7-15 * @License Apache License Version 2.0 */ public class ControlLines extends BaseTableViewController<List<DoublePoint>> { @FXML protected TableColumn<List<DoublePoint>, String> pointsColumn, numberColumn; @Override public void initControls() { try { super.initControls(); pointsColumn.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<List<DoublePoint>, String>, ObservableValue<String>>() { @Override public ObservableValue<String> call(TableColumn.CellDataFeatures<List<DoublePoint>, String> param) { try { List<DoublePoint> points = param.getValue(); if (points == null) { return null; } return new SimpleStringProperty(DoublePoint.imageCoordinatesToText(points, " ")); } catch (Exception e) { return null; } } }); numberColumn.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<List<DoublePoint>, String>, ObservableValue<String>>() { @Override public ObservableValue<String> call(TableColumn.CellDataFeatures<List<DoublePoint>, String> param) { try { List<DoublePoint> points = param.getValue(); if (points == null) { return null; } return new SimpleStringProperty(points.size() + ""); } catch (Exception e) { return null; } } }); } catch (Exception e) { MyBoxLog.error(e); } } public void loadList(List<List<DoublePoint>> list) { isSettingValues = true; if (list == null || list.isEmpty()) { tableData.clear(); } else { tableData.setAll(DoublePoint.scaleLists(list, UserConfig.imageScale())); } isSettingValues = false; tableChanged(); } public List<List<DoublePoint>> getLines() { List<List<DoublePoint>> list = new ArrayList<>(); for (List<DoublePoint> line : tableData) { List<DoublePoint> nline = new ArrayList<>(); for (DoublePoint p : line) { nline.add(p.copy()); } list.add(nline); } return list; } @FXML @Override public void addAction() { add(-1); } @FXML public void insertAction() { int index = selectedIndix(); if (index < 0) { popError(message("SelectToHandle")); return; } add(index); } public void add(int index) { LineInputController inputController = LineInputController.open(this, message("Add"), null); inputController.getNotify().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue v, Boolean ov, Boolean nv) { List<DoublePoint> line = inputController.picked; if (line == null || line.isEmpty()) { popError(message("InvalidValue")); return; } if (index < 0) { tableData.add(line); } else { tableData.add(index, line); } inputController.close(); } }); } @FXML @Override public void editAction() { try { int index = selectedIndix(); if (index < 0) { popError(message("SelectToHandle")); return; } List<DoublePoint> line = tableData.get(index); LineInputController inputController = LineInputController.open(this, message("Line") + " " + (index + 1), line); inputController.getNotify().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue v, Boolean ov, Boolean nv) { List<DoublePoint> line = inputController.picked; if (line == null || line.isEmpty()) { popError(message("InvalidValue")); return; } inputController.close(); tableData.set(index, line); } }); } catch (Exception e) { MyBoxLog.error(e); } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/controller/ControlImageScope_Base.java
alpha/MyBox/src/main/java/mara/mybox/controller/ControlImageScope_Base.java
package mara.mybox.controller; import java.util.ArrayList; import java.util.List; import javafx.beans.property.SimpleBooleanProperty; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.CheckBox; import javafx.scene.control.ComboBox; import javafx.scene.control.Label; import javafx.scene.control.ListView; import javafx.scene.control.RadioButton; import javafx.scene.control.Tab; import javafx.scene.control.TextField; import javafx.scene.control.ToggleGroup; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.FlowPane; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import mara.mybox.data.DoublePoint; import mara.mybox.data.DoublePolygon; import mara.mybox.db.table.TableColor; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.fxml.image.FxColorTools; import mara.mybox.fxml.image.ScopeTools; import mara.mybox.fxml.style.NodeStyleTools; import mara.mybox.image.data.ImageScope; import static mara.mybox.image.data.ImageScope.ShapeType.Circle; import static mara.mybox.image.data.ImageScope.ShapeType.Ellipse; import static mara.mybox.image.data.ImageScope.ShapeType.Polygon; import static mara.mybox.image.data.ImageScope.ShapeType.Rectangle; import mara.mybox.image.tools.ColorConvertTools; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2021-8-13 * @License Apache License Version 2.0 */ public abstract class ControlImageScope_Base extends BaseShapeController { protected ImageScope scope; protected TableColor tableColor; protected java.awt.Color maskColor; protected float maskOpacity; protected SimpleBooleanProperty showNotify, changedNotify; protected String background; @FXML protected ToggleGroup shapeTypeGroup; @FXML protected Tab shapeTab, colorsTab, matchTab, controlsTab; @FXML protected VBox viewBox, shapeBox, rectangleBox, circleBox, pointsBox, outlineBox; @FXML protected ComboBox<String> opacitySelector; @FXML protected ImageView outlineView; @FXML protected ControlColorSet colorController, maskColorController; @FXML protected ListView<Color> colorsList; @FXML protected ControlPoints pointsController; @FXML protected ControlColorMatch matchController; @FXML protected ControlOutline outlineController; @FXML protected CheckBox shapeExcludedCheck, colorExcludedCheck, scopeExcludeCheck, handleTransparentCheck, clearDataWhenLoadImageCheck; @FXML protected TextField rectLeftTopXInput, rectLeftTopYInput, rightBottomXInput, rightBottomYInput, circleCenterXInput, circleCenterYInput, circleRadiusInput; @FXML protected Button shapeButton, goShapeButton, popScopeButton, clearColorsButton, deleteColorsButton, saveColorsButton; @FXML protected RadioButton wholeRadio, matting4Radio, matting8Radio, rectangleRadio, circleRadio, ellipseRadio, polygonRadio, outlineRadio; @FXML protected Label scopePointsLabel, scopeColorsLabel, pointsSizeLabel, colorsSizeLabel, rectangleLabel; @FXML protected FlowPane shapeOperationsPane; public Image srcImage() { return image; } public java.awt.Color maskColor() { return maskColor; } public Color maskFxColor() { return ColorConvertTools.converColor(maskColor); } public Image scopeImage(FxTask currentTask) { return selectedScope(currentTask, maskColor, false); } public Image selectedScope(FxTask currentTask, java.awt.Color bgColor, boolean cutMargins) { if (pickScopeValues() == null) { return null; } return ScopeTools.selectedScope(currentTask, srcImage(), scope, bgColor, cutMargins, scopeExcludeCheck.isSelected(), !handleTransparentCheck.isSelected()); } public Image maskImage(FxTask currentTask) { return ScopeTools.maskScope(currentTask, srcImage(), scope, scopeExcludeCheck.isSelected(), !handleTransparentCheck.isSelected()); } public boolean isValidScope() { return srcImage() != null && scope != null; } public ImageScope pickScopeValues() { try { if (!pickEnvValues()) { return null; } switch (scope.getShapeType()) { case Matting4: case Matting8: scope.clearPoints(); for (DoublePoint p : pointsController.tableData) { scope.addPoint((int) Math.round(p.getX()), (int) Math.round(p.getY())); } break; case Rectangle: scope.setRectangle(maskRectangleData.copy()); break; case Circle: scope.setCircle(maskCircleData.copy()); break; case Ellipse: scope.setEllipse(maskEllipseData.copy()); break; case Polygon: maskPolygonData = new DoublePolygon(); maskPolygonData.setAll(pointsController.getPoints()); scope.setPolygon(maskPolygonData.copy()); break; } if (!pickColorValues()) { popError(message("InvalidParameters")); return null; } return scope; } catch (Exception e) { MyBoxLog.error(e); return null; } } public boolean pickEnvValues() { try { image = srcImage(); if (image == null || scope == null) { return false; } scope.setImage(image) .setShapeExcluded(shapeExcludedCheck.isSelected()) .setColorExcluded(colorExcludedCheck.isSelected()) .setMaskColor(maskColor) .setMaskOpacity(maskOpacity); if (background != null) { scope.setBackground(background); } else if (sourceFile != null && sourceFile.exists()) { scope.setBackground(sourceFile.getAbsolutePath()); } else { scope.setBackground(null); } return true; } catch (Exception e) { MyBoxLog.error(e); return false; } } public boolean pickColorValues() { try { List<Color> list = colorsList.getItems(); int size = list.size(); colorsSizeLabel.setText(message("Count") + ": " + size); if (size > 100) { colorsSizeLabel.setStyle(NodeStyleTools.redTextStyle()); } else { colorsSizeLabel.setStyle(NodeStyleTools.attributeTextStyle()); } clearColorsButton.setDisable(size == 0); if (list.isEmpty()) { scope.clearColors(); } else { List<java.awt.Color> colors = new ArrayList<>(); for (Color color : list) { colors.add(FxColorTools.toAwtColor(color)); } scope.setColors(colors); } scope.setColorExcluded(colorExcludedCheck.isSelected()); return matchController.pickValuesTo(scope); } 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/alpha/MyBox/src/main/java/mara/mybox/controller/ImageEmbossController.java
alpha/MyBox/src/main/java/mara/mybox/controller/ImageEmbossController.java
package mara.mybox.controller; import java.util.List; import javafx.embed.swing.SwingFXUtils; import javafx.fxml.FXML; import javafx.scene.image.Image; import mara.mybox.db.data.ConvolutionKernel; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.fxml.WindowTools; import mara.mybox.fxml.image.PixelDemos; import mara.mybox.image.data.ImageConvolution; import mara.mybox.image.data.ImageScope; import mara.mybox.value.Fxmls; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2019-9-2 * @License Apache License Version 2.0 */ public class ImageEmbossController extends BasePixelsController { protected ConvolutionKernel kernel; @FXML protected ControlImageEmboss embossController; public ImageEmbossController() { baseTitle = message("Emboss"); } @Override protected void initMore() { try { super.initMore(); operation = message("Emboss"); } catch (Exception e) { MyBoxLog.error(e); } } @Override public boolean checkOptions() { if (!super.checkOptions()) { return false; } kernel = embossController.pickValues(); return kernel != null; } @Override protected Image handleImage(FxTask currentTask, Image inImage, ImageScope inScope) { try { ImageConvolution convolution = ImageConvolution.create(); convolution.setImage(inImage) .setScope(inScope) .setKernel(kernel) .setExcludeScope(excludeScope()) .setSkipTransparent(skipTransparent()) .setTask(currentTask); opInfo = kernel.getName() + " " + message("Color") + ": " + kernel.getColor(); Image emboss = convolution.startFx(); kernel = null; return emboss; } catch (Exception e) { displayError(e.toString()); return null; } } @Override protected void makeDemoFiles(FxTask currentTask, List<String> files, Image demoImage) { PixelDemos.emboss(currentTask, files, SwingFXUtils.fromFXImage(demoImage, null), srcFile()); } /* static methods */ public static ImageEmbossController open(BaseImageController parent) { try { if (parent == null) { return null; } ImageEmbossController controller = (ImageEmbossController) WindowTools.referredStage( parent, Fxmls.ImageEmbossFxml); controller.setParameters(parent); return controller; } catch (Exception e) { MyBoxLog.error(e); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/controller/ImageGreyBatchController.java
alpha/MyBox/src/main/java/mara/mybox/controller/ImageGreyBatchController.java
package mara.mybox.controller; import java.awt.image.BufferedImage; import mara.mybox.image.data.ImageGray; import mara.mybox.fxml.FxTask; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2018-9-23 * @License Apache License Version 2.0 */ public class ImageGreyBatchController extends BaseImageEditBatchController { public ImageGreyBatchController() { baseTitle = message("ImageBatch") + " - " + message("Grey"); } @Override protected BufferedImage handleImage(FxTask currentTask, BufferedImage source) { try { ImageGray imageGray = new ImageGray(source); return imageGray.setTask(currentTask).start(); } catch (Exception e) { displayError(e.toString()); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/controller/ImageReduceColorsBatchController.java
alpha/MyBox/src/main/java/mara/mybox/controller/ImageReduceColorsBatchController.java
package mara.mybox.controller; import java.awt.image.BufferedImage; import java.io.File; import java.util.List; import javafx.fxml.FXML; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.fxml.image.ColorDemos; import mara.mybox.image.data.ImageQuantization; import mara.mybox.image.data.ImageQuantizationFactory; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2018-9-23 * @License Apache License Version 2.0 */ public class ImageReduceColorsBatchController extends BaseImageEditBatchController { @FXML protected ControlImageQuantization optionsController; public ImageReduceColorsBatchController() { baseTitle = message("ImageBatch") + " - " + message("ReduceColors"); } @Override public void initControls() { try { super.initControls(); optionsController.defaultForAnalyse(); } catch (Exception e) { MyBoxLog.error(e); } } @Override public boolean makeMoreParameters() { return super.makeMoreParameters() && optionsController.pickValues(); } @Override protected BufferedImage handleImage(FxTask currentTask, BufferedImage source) { try { ImageQuantization quantization = ImageQuantizationFactory.create( currentTask, source, null, optionsController, false); return quantization.setTask(currentTask).start(); } catch (Exception e) { displayError(e.toString()); return null; } } @Override public void makeDemoFiles(FxTask currentTask, List<String> files, File demoFile, BufferedImage demoImage) { ColorDemos.reduceColors(currentTask, files, demoImage, demoFile); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/controller/ControlFileSelecter.java
alpha/MyBox/src/main/java/mara/mybox/controller/ControlFileSelecter.java
package mara.mybox.controller; import java.io.File; import java.util.List; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.event.Event; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.layout.Region; import javafx.stage.DirectoryChooser; import mara.mybox.db.data.VisitHistory; import mara.mybox.db.data.VisitHistoryTools; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxFileTools; import mara.mybox.fxml.menu.MenuTools; import mara.mybox.fxml.RecentVisitMenu; import mara.mybox.tools.FileTmpTools; import mara.mybox.value.AppVariables; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2020-9-7 * @License Apache License Version 2.0 */ public class ControlFileSelecter extends BaseController { private File file; protected File defaultFile; protected boolean isSource, isDirectory, checkQuit, permitNull, mustExist; protected SimpleBooleanProperty notify; @FXML protected Label label; @FXML protected TextField fileInput; @FXML protected Button openTargetButton; public ControlFileSelecter() { initSelecter(); } public final ControlFileSelecter initSelecter() { file = null; defaultFile = null; isSource = true; isDirectory = false; checkQuit = false; permitNull = false; mustExist = false; notify = new SimpleBooleanProperty(false); return this; } public static ControlFileSelecter create() { return new ControlFileSelecter(); } @Override public void initControls() { super.initControls(); if (fileInput != null) { fileInput.textProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue ov, String oldValue, String newValue) { pickFile(); } }); } label.setMinWidth(Region.USE_PREF_SIZE); } /* make */ public String defaultName() { if (defaultFile == null) { String ext = VisitHistoryTools.defaultExt(TargetFileType); if (isDirectory) { defaultFile = new File(FileTmpTools.generatePath(ext)); } else { defaultFile = FileTmpTools.generateFile(ext); } } return defaultFile.getAbsolutePath(); } public ControlFileSelecter parent(BaseController parent) { return parent(parent, null); } public ControlFileSelecter parent(BaseController parent, String name) { parentController = parent; if (name != null && !name.isBlank()) { baseName = name; } else { if (parentController != null) { baseName = parentController.baseName; } baseName += (isSource ? "Source" : "Target") + (isDirectory ? "Path" : "File"); } return initFile(); } public ControlFileSelecter initFile() { String defaultName = defaultName(); String filename = UserConfig.getString(baseName, defaultName); input(filename); return this; } public void inputFile(File file) { if (fileInput != null) { isSettingValues = true; if (file != null) { fileInput.setText(file.getAbsolutePath()); } else { fileInput.clear(); } isSettingValues = false; } setFile(file); } public void input(String string) { if (fileInput != null) { isSettingValues = true; fileInput.setText(string); isSettingValues = false; } if (string != null) { setFile(new File(string)); } else { setFile(null); } } public File pickFile() { if (isSettingValues || fileInput == null) { return file; } String v = fileInput.getText(); if (v == null || v.isBlank()) { file = null; return file; } File inputfile = new File(v); if (mustExist && (!inputfile.exists() || isDirectory && !inputfile.isDirectory() || !isDirectory && !inputfile.isFile())) { file = null; return file; } return setFile(inputfile); } private File setFile(File infile) { file = infile; if (file != null) { UserConfig.setString(baseName, file.getAbsolutePath()); if (parentController != null) { if (isDirectory) { if (isSource) { parentController.sourcePath = file; } else { parentController.targetPath = file; } } else { if (isSource) { // parentController.sourceFile = file; } else { parentController.targetFile = file; } } } } notify.set(!notify.get()); if (openTargetButton != null) { openTargetButton.setDisable(file == null || !file.exists()); } return file; } public File file() { return file; } public String text() { if (fileInput == null) { return null; } else { return fileInput.getText(); } } /* set */ public ControlFileSelecter type(int fileType) { setFileType(fileType); return this; } public ControlFileSelecter label(String labelString) { label.setText(labelString); // refreshStyle(thisPane); return this; } public ControlFileSelecter defaultFile(File defaultFile) { this.defaultFile = defaultFile; return this; } public ControlFileSelecter isSource(boolean isSource) { this.isSource = isSource; mustExist = isSource; return this; } public ControlFileSelecter isDirectory(boolean isDirectory) { this.isDirectory = isDirectory; return this; } public ControlFileSelecter checkQuit(boolean checkQuit) { this.checkQuit = checkQuit; return this; } public ControlFileSelecter permitNull(boolean permitNull) { this.permitNull = permitNull; return this; } public ControlFileSelecter mustExist(boolean mustExist) { this.mustExist = mustExist; return this; } /* button */ @FXML public void selectFile() { try { File selectedfile; File path = UserConfig.getPath(isSource ? baseName + "SourcePath" : baseName + "TargetPath"); if (path == null) { path = defaultFile; } if (isDirectory) { DirectoryChooser chooser = new DirectoryChooser(); if (path != null && path.exists()) { chooser.setInitialDirectory(path); } selectedfile = chooser.showDialog(getMyStage()); } else { if (isSource) { selectedfile = FxFileTools.selectFile(this, path, sourceExtensionFilter); } else { selectedfile = chooseFile(path, defaultFile != null ? defaultFile.getName() : null, targetExtensionFilter); } } if (selectedfile == null || (mustExist && !selectedfile.exists())) { return; } inputFile(selectedfile); } catch (Exception e) { MyBoxLog.error(e); } } @FXML public void showRecentFilesMenu(Event event) { if (checkQuit && !checkBeforeNextAction()) { return; } if (AppVariables.fileRecentNumber <= 0) { return; } new RecentVisitMenu(this, event, isDirectory) { @Override public List<VisitHistory> recentPaths() { int pathNumber = AppVariables.fileRecentNumber; if (isSource) { return VisitHistoryTools.getRecentPathRead(SourcePathType, pathNumber); } else { return VisitHistoryTools.getRecentPathWrite(TargetPathType, pathNumber); } } @Override public void handleSelect() { selectFile(); } @Override public void handleFile(String fname) { File selectedfile = new File(fname); if (mustExist && !selectedfile.exists()) { selectFile(); return; } if (fileInput != null) { isSettingValues = true; fileInput.setText(selectedfile.getAbsolutePath()); isSettingValues = false; } setFile(selectedfile); } @Override public void handlePath(String fname) { File selectedfile = new File(fname); if (mustExist && !selectedfile.exists()) { selectFile(); return; } if (isDirectory) { if (fileInput != null) { isSettingValues = true; fileInput.setText(selectedfile.getAbsolutePath()); isSettingValues = false; } setFile(selectedfile); } else { UserConfig.setString(isSource ? baseName + "SourcePath" : baseName + "TargetPath", fname); selectFile(); } } }.pop(); } @FXML public void pickRecentFiles(Event event) { if (MenuTools.isPopMenu("RecentVisit") || AppVariables.fileRecentNumber <= 0) { selectFile(); } else { showRecentFilesMenu(event); } } @FXML public void popRecentFiles(Event event) { if (MenuTools.isPopMenu("RecentVisit")) { showRecentFilesMenu(event); } } @FXML @Override public void openTarget() { if (file == null || !file.exists()) { return; } browseURI(file.toURI()); recordFileOpened(file); } @Override public void cleanPane() { try { file = null; defaultFile = null; } catch (Exception e) { } super.cleanPane(); } /* get */ public boolean isIsSource() { return isSource; } public boolean isIsDirectory() { return isDirectory; } public boolean isCheckQuit() { return checkQuit; } public boolean isPermitNull() { return permitNull; } public boolean isMustExist() { return mustExist; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/controller/MainMenuController_Development.java
alpha/MyBox/src/main/java/mara/mybox/controller/MainMenuController_Development.java
package mara.mybox.controller; import com.sun.management.OperatingSystemMXBean; import java.lang.management.ManagementFactory; import java.util.Timer; import java.util.TimerTask; import javafx.application.Platform; import javafx.event.ActionEvent; import javafx.event.Event; import javafx.fxml.FXML; import javafx.geometry.Pos; import javafx.scene.control.CheckMenuItem; import javafx.scene.control.Label; import javafx.scene.control.Menu; import javafx.scene.control.ProgressBar; import javafx.scene.layout.HBox; import javafx.scene.layout.Priority; import javafx.scene.layout.VBox; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.menu.DevelopmentMenu; import mara.mybox.tools.FloatTools; import mara.mybox.value.AppVariables; import mara.mybox.value.Languages; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2021-7-29 * @License Apache License Version 2.0 */ public abstract class MainMenuController_Development extends MainMenuController_Settings { protected HBox memoryBox, cpuBox; protected Timer memoryMonitorTimer, cpuMonitorTimer; protected final int memoryMonitorInterval = 1000, cpuMonitorInterval = 1000; protected Runtime r; protected OperatingSystemMXBean osmxb; protected Label sysMemLabel, myboxMemLabel, sysCpuLabel, myboxCpuLabel; protected ProgressBar sysMemBar, myboxMemBar, sysCpuBar, myboxCpuBar; protected long mb; @FXML protected Menu devMenu; @FXML protected CheckMenuItem monitorMemroyCheck, monitorCpuCheck, detailedDebugCheck, popErrorCheck; @Override public void initControls() { try { super.initControls(); devMenu.setOnShowing((Event e) -> { checkDev(); if (devMenu.getItems().size() < 6) { devMenu.getItems().addAll(DevelopmentMenu.menusList(this)); } }); checkDev(); } catch (Exception e) { MyBoxLog.debug(e); } } protected void checkDev() { monitorMemroyCheck.setSelected(UserConfig.getBoolean("MonitorMemroy", false)); monitorCpuCheck.setSelected(UserConfig.getBoolean("MonitorCpu", false)); popErrorCheck.setSelected(AppVariables.popErrorLogs); detailedDebugCheck.setSelected(AppVariables.detailedDebugLogs); checkMemroyMonitor(); checkCpuMonitor(); } protected void makeMemoryMonitorBox() { sysMemLabel = new Label(); sysMemBar = new ProgressBar(); sysMemBar.setPrefHeight(20); sysMemBar.setPrefWidth(70); myboxMemLabel = new Label(); myboxMemBar = new ProgressBar(); myboxMemBar.setPrefHeight(20); myboxMemBar.setPrefWidth(70); memoryBox = new HBox(); memoryBox.setAlignment(Pos.CENTER_LEFT); memoryBox.setMaxSize(Double.MAX_VALUE, Double.MAX_VALUE); memoryBox.setSpacing(5); VBox.setVgrow(memoryBox, Priority.NEVER); HBox.setHgrow(memoryBox, Priority.ALWAYS); memoryBox.setStyle(" -fx-font-size: 0.8em;"); memoryBox.getChildren().addAll(myboxMemLabel, myboxMemBar, new Label(" "), sysMemLabel, sysMemBar); mb = 1024 * 1024; if (r == null) { r = Runtime.getRuntime(); } if (osmxb == null) { osmxb = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean(); } } protected void startMemoryMonitorTimer() { try { if (memoryBox == null) { return; } stopMemoryMonitorTimer(); memoryMonitorTimer = new Timer(); memoryMonitorTimer.schedule(new TimerTask() { @Override public void run() { Platform.runLater(new Runnable() { @Override public void run() { long physicalFree = osmxb.getFreeMemorySize() / mb; long physicalTotal = osmxb.getTotalMemorySize() / mb; long physicalUse = physicalTotal - physicalFree; String sysInfo = System.getProperty("os.name") + " " + Languages.message("PhysicalMemory") + ":" + physicalTotal + "MB" + " " + Languages.message("Used") + ":" + physicalUse + "MB (" + FloatTools.percentage(physicalUse, physicalTotal) + "%)"; sysMemLabel.setText(sysInfo); sysMemBar.setProgress(physicalUse * 1.0f / physicalTotal); long freeMemory = r.freeMemory() / mb; long totalMemory = r.totalMemory() / mb; long maxMemory = r.maxMemory() / mb; long usedMemory = totalMemory - freeMemory; String myboxInfo = "MyBox" // + " " + AppVariables.getMessage("AvailableProcessors") + ":" + availableProcessors + " " + Languages.message("AvaliableMemory") + ":" + maxMemory + "MB" + " " + Languages.message("Required") + ":" + totalMemory + "MB(" + FloatTools.percentage(totalMemory, maxMemory) + "%)" + " " + Languages.message("Used") + ":" + usedMemory + "MB(" + FloatTools.percentage(usedMemory, maxMemory) + "%)"; myboxMemLabel.setText(myboxInfo); myboxMemBar.setProgress(usedMemory * 1.0f / maxMemory); } }); } }, 0, memoryMonitorInterval); } catch (Exception e) { MyBoxLog.error(e); } } public void stopMemoryMonitorTimer() { if (memoryMonitorTimer != null) { memoryMonitorTimer.cancel(); } memoryMonitorTimer = null; } @FXML protected void checkMemroyMonitor() { boolean v = monitorMemroyCheck.isSelected(); UserConfig.setBoolean("MonitorMemroy", v); if (v) { if (memoryBox == null) { makeMemoryMonitorBox(); } if (!thisPane.getChildren().contains(memoryBox)) { thisPane.getChildren().add(memoryBox); } startMemoryMonitorTimer(); } else { stopMemoryMonitorTimer(); if (memoryBox != null && thisPane.getChildren().contains(memoryBox)) { thisPane.getChildren().remove(memoryBox); } } } protected void makeCpuMonitorBox() { sysCpuLabel = new Label(); sysCpuBar = new ProgressBar(); sysCpuBar.setPrefHeight(20); sysCpuBar.setPrefWidth(70); myboxCpuLabel = new Label(); myboxCpuBar = new ProgressBar(); myboxCpuBar.setPrefHeight(20); myboxCpuBar.setPrefWidth(70); cpuBox = new HBox(); cpuBox.setAlignment(Pos.CENTER_LEFT); cpuBox.setMaxSize(Double.MAX_VALUE, Double.MAX_VALUE); cpuBox.setSpacing(5); VBox.setVgrow(cpuBox, Priority.NEVER); HBox.setHgrow(cpuBox, Priority.ALWAYS); cpuBox.setStyle(" -fx-font-size: 0.8em;"); cpuBox.getChildren().addAll(myboxCpuLabel, myboxCpuBar, new Label(" "), sysCpuLabel, sysCpuBar); if (osmxb == null) { osmxb = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean(); } } protected void startCpuMonitorTimer() { try { if (cpuBox == null) { return; } stopCpuMonitorTimer(); cpuMonitorTimer = new Timer(); cpuMonitorTimer.schedule(new TimerTask() { @Override public void run() { Platform.runLater(new Runnable() { @Override public void run() { float load = (float) osmxb.getCpuLoad(); long s = (long) (osmxb.getSystemLoadAverage() / 1000000000); String sysInfo = System.getProperty("os.name") + " " + Languages.message("SystemLoadAverage") + ":" + s + "s" + " " + Languages.message("SystemCpuUsage") + ":" + FloatTools.roundFloat2(load * 100) + "%"; sysCpuLabel.setText(sysInfo); sysCpuBar.setProgress(load); load = (float) osmxb.getProcessCpuLoad(); s = osmxb.getProcessCpuTime() / 1000000000; String myboxInfo = "MyBox" + " " + Languages.message("RecentCpuTime") + ":" + s + "s" + " " + Languages.message("RecentCpuUsage") + ":" + FloatTools.roundFloat2(load * 100) + "%"; myboxCpuLabel.setText(myboxInfo); myboxCpuBar.setProgress(load); } }); } }, 0, cpuMonitorInterval); } catch (Exception e) { MyBoxLog.error(e); } } public void stopCpuMonitorTimer() { if (cpuMonitorTimer != null) { cpuMonitorTimer.cancel(); } cpuMonitorTimer = null; } @FXML protected void checkCpuMonitor() { boolean v = monitorCpuCheck.isSelected(); UserConfig.setBoolean("MonitorCpu", v); if (v) { if (cpuBox == null) { makeCpuMonitorBox(); } if (!thisPane.getChildren().contains(cpuBox)) { thisPane.getChildren().add(cpuBox); } startCpuMonitorTimer(); } else { stopCpuMonitorTimer(); if (cpuBox != null && thisPane.getChildren().contains(cpuBox)) { thisPane.getChildren().remove(cpuBox); } } } @FXML protected void detailedDebug() { AppVariables.detailedDebugLogs = detailedDebugCheck.isSelected(); UserConfig.setBoolean("DetailedDebugLogs", AppVariables.detailedDebugLogs); } @FXML protected void popError() { AppVariables.popErrorLogs = popErrorCheck.isSelected(); UserConfig.setBoolean("PopErrorLogs", AppVariables.popErrorLogs); } @FXML protected void DevTmp(ActionEvent event) { DevTmpController.open(); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/controller/BaseImageController.java
alpha/MyBox/src/main/java/mara/mybox/controller/BaseImageController.java
package mara.mybox.controller; import java.io.File; import java.util.Arrays; import java.util.List; import javafx.beans.binding.Bindings; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.event.ActionEvent; import javafx.event.Event; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.scene.control.CheckMenuItem; import javafx.scene.control.Menu; import javafx.scene.control.MenuItem; import javafx.scene.control.RadioMenuItem; import javafx.scene.control.SeparatorMenuItem; import javafx.scene.control.ToggleGroup; import javafx.scene.control.Tooltip; import javafx.scene.layout.FlowPane; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; import javafx.scene.text.Text; import mara.mybox.db.data.VisitHistory; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.menu.MenuTools; import mara.mybox.fxml.ValidationTools; import mara.mybox.fxml.style.NodeStyleTools; import mara.mybox.fxml.style.StyleTools; import mara.mybox.tools.FileNameTools; import mara.mybox.tools.FileSortTools; import mara.mybox.tools.FileSortTools.FileSortMode; import mara.mybox.value.FileExtensions; import static mara.mybox.value.Languages.message; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2018-6-24 * @License Apache License Version 2.0 * * BaseImageController < BaseImageController_Actions < BaseImageController_Image * < BaseImageController_MouseEvents < BaseImageController_Mask < * BaseImageController_Base */ public class BaseImageController extends BaseImageController_Actions { @FXML protected FlowPane buttonsPane; public BaseImageController() { baseTitle = message("Image"); } @Override public void initValues() { try { super.initValues(); isPickingColor = imageChanged = false; loadWidth = defaultLoadWidth = -1; frameIndex = framesNumber = 0; sizeChangeAware = 1; zoomStep = xZoomStep = yZoomStep = 20; if (maskPane != null) { if (borderLine == null) { borderLine = new Rectangle(); borderLine.setFill(Color.web("#ffffff00")); borderLine.setStroke(Color.web("#cccccc")); borderLine.setArcWidth(5); borderLine.setArcHeight(5); maskPane.getChildren().add(borderLine); } if (sizeText == null) { sizeText = new Text(); sizeText.setFill(Color.web("#cccccc")); sizeText.setStrokeWidth(0); maskPane.getChildren().add(sizeText); } if (xyText == null) { xyText = new Text(); maskPane.getChildren().add(xyText); } } if (mainAreaBox == null) { mainAreaBox = imageBox; } } catch (Exception e) { MyBoxLog.error(e); } } @Override public void setFileType() { setFileType(VisitHistory.FileType.Image); } @Override public void setControlsStyle() { try { super.setControlsStyle(); if (zoomStepSelector != null) { NodeStyleTools.setTooltip(zoomStepSelector, new Tooltip(message("ZoomStep"))); } if (pickColorCheck != null) { NodeStyleTools.setTooltip(pickColorCheck, new Tooltip(message("PickColor") + "\nCTRL+k")); } if (loadWidthSelector != null) { NodeStyleTools.setTooltip(loadWidthSelector, new Tooltip(message("ImageLoadWidthCommnets"))); } } catch (Exception e) { MyBoxLog.debug(e); } } @Override public void initControls() { try { super.initControls(); initImageView(); initMaskPane(); initCheckboxs(); if (imageBox != null && imageView != null) { imageBox.disableProperty().bind(imageView.imageProperty().isNull()); } } catch (Exception e) { MyBoxLog.error(e); } } protected void initImageView() { if (imageView == null) { return; } try { imageView.setPreserveRatio(true); imageView.fitWidthProperty().addListener(new ChangeListener<Number>() { @Override public void changed(ObservableValue<? extends Number> ov, Number old_val, Number new_val) { viewSizeChanged(Math.abs(new_val.doubleValue() - old_val.doubleValue())); } }); imageView.fitHeightProperty().addListener(new ChangeListener<Number>() { @Override public void changed(ObservableValue<? extends Number> ov, Number old_val, Number new_val) { viewSizeChanged(Math.abs(new_val.doubleValue() - old_val.doubleValue())); } }); if (scrollPane != null) { scrollPane.widthProperty().addListener(new ChangeListener<Number>() { @Override public void changed(ObservableValue<? extends Number> ov, Number old_val, Number new_val) { paneSizeChanged(Math.abs(new_val.doubleValue() - old_val.doubleValue())); } }); scrollPane.heightProperty().addListener(new ChangeListener<Number>() { @Override public void changed(ObservableValue<? extends Number> ov, Number old_val, Number new_val) { paneSizeChanged(Math.abs(new_val.doubleValue() - old_val.doubleValue())); } }); } zoomStep = UserConfig.getInt(baseName + "ZoomStep", 40); zoomStep = zoomStep <= 0 ? 40 : zoomStep; xZoomStep = zoomStep; yZoomStep = zoomStep; if (zoomStepSelector != null) { zoomStepSelector.getItems().addAll( Arrays.asList("40", "20", "5", "1", "3", "15", "30", "50", "80", "100", "150", "200", "300", "500") ); zoomStepSelector.setValue(zoomStep + ""); zoomStepSelector.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> ov, String oldVal, String newVal) { try { int v = Integer.parseInt(newVal); if (v > 0) { zoomStep = v; UserConfig.setInt(baseName + "ZoomStep", zoomStep); zoomStepSelector.getEditor().setStyle(null); xZoomStep = zoomStep; yZoomStep = zoomStep; zoomStepChanged(); } else { zoomStepSelector.getEditor().setStyle(UserConfig.badStyle()); } } catch (Exception e) { zoomStepSelector.getEditor().setStyle(UserConfig.badStyle()); } } }); } loadWidth = defaultLoadWidth; if (loadWidthSelector != null) { List<String> values = Arrays.asList(message("OriginalSize"), "512", "1024", "256", "128", "2048", "100", "80", "4096"); loadWidthSelector.getItems().addAll(values); int v = UserConfig.getInt(baseName + "LoadWidth", defaultLoadWidth); if (v <= 0) { loadWidth = -1; loadWidthSelector.getSelectionModel().select(0); } else { loadWidth = v; loadWidthSelector.setValue(v + ""); } loadWidthSelector.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue ov, String oldValue, String newValue) { if (message("OriginalSize").equals(newValue)) { loadWidth = -1; } else { try { loadWidth = Integer.parseInt(newValue); } catch (Exception e) { ValidationTools.setEditorBadStyle(loadWidthSelector); return; } } ValidationTools.setEditorNormal(loadWidthSelector); setLoadWidth(); } }); } if (imageView == null) { return; } if (buttonsPane != null) { buttonsPane.disableProperty().bind(Bindings.isNull(imageView.imageProperty())); } if (scrollPane != null) { scrollPane.disableProperty().bind(Bindings.isNull(imageView.imageProperty())); } if (saveButton != null) { saveButton.disableProperty().bind(Bindings.isNull(imageView.imageProperty())); } } catch (Exception e) { MyBoxLog.error(e); } } protected void initCheckboxs() { try { if (pickColorCheck != null) { pickColorCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> ov, Boolean oldVal, Boolean newVal) { isPickingColor = pickColorCheck.isSelected(); checkPickingColor(); } }); } if (rulerXCheck != null) { rulerXCheck.setSelected(UserConfig.getBoolean("ImageRulerXY", false)); rulerXCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldValue, Boolean newValue) { UserConfig.setBoolean("ImageRulerXY", rulerXCheck.isSelected()); drawMaskRulers(); } }); } if (gridCheck != null) { gridCheck.setSelected(UserConfig.getBoolean("ImageGridLines", false)); gridCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldValue, Boolean newValue) { UserConfig.setBoolean("ImageGridLines", gridCheck.isSelected()); drawMaskGrid(); } }); } if (coordinateCheck != null) { coordinateCheck.setSelected(UserConfig.getBoolean("ImagePopCooridnate", false)); coordinateCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldValue, Boolean newValue) { UserConfig.setBoolean("ImagePopCooridnate", coordinateCheck.isSelected()); } }); } } catch (Exception e) { MyBoxLog.error(e); } } @Override public List<MenuItem> fileMenuItems(Event fevent) { try { List<MenuItem> items = MenuTools.initMenu(message("File")); MenuItem menu; if (sourceFile != null) { String fileFormat = FileNameTools.ext(sourceFile.getName()).toLowerCase(); if (FileExtensions.MultiFramesImages.contains(fileFormat)) { menu = new MenuItem(message("Frames"), StyleTools.getIconImageView("iconFrame.png")); menu.setOnAction((ActionEvent menuItemEvent) -> { ImageFramesController.open(this); }); items.add(menu); } if (imageInformation != null) { menu = new MenuItem(message("Information") + " Ctrl+I " + message("Or") + " Alt+I", StyleTools.getIconImageView("iconInfo.png")); menu.setOnAction((ActionEvent menuItemEvent) -> { infoAction(); }); items.add(menu); menu = new MenuItem(message("MetaData"), StyleTools.getIconImageView("iconMeta.png")); menu.setOnAction((ActionEvent menuItemEvent) -> { metaAction(); }); items.add(menu); } menu = new MenuItem(message("Refresh"), StyleTools.getIconImageView("iconRefresh.png")); menu.setOnAction((ActionEvent event) -> { refreshAction(); }); items.add(menu); items.add(new SeparatorMenuItem()); } menu = new MenuItem(message("Create") + " Ctrl+N " + message("Or") + " Alt+N", StyleTools.getIconImageView("iconAdd.png")); menu.setOnAction((ActionEvent event) -> { createAction(); }); items.add(menu); menu = new MenuItem(message("Example"), StyleTools.getIconImageView("iconExamples.png")); menu.setOnAction((ActionEvent menuItemEvent) -> { exampleAction(); }); items.add(menu); boolean imageShown = imageView != null && imageView.getImage() != null; menu = new MenuItem(message("LoadContentInSystemClipboard") + (imageShown ? "" : (" Ctrl+V " + message("Or") + " Alt+V")), StyleTools.getIconImageView("iconImageSystem.png")); menu.setOnAction((ActionEvent event) -> { loadContentInSystemClipboard(); }); items.add(menu); menu = new MenuItem(message("LoadWidth") + ": " + (loadWidth <= 0 ? message("OriginalSize") : ("" + loadWidth)), StyleTools.getIconImageView("iconInput.png")); menu.setOnAction((ActionEvent event) -> { ImageLoadWidthController.open(this); }); items.add(menu); if (imageShown) { menu = new MenuItem(message("SaveAs") + " Ctrl+B " + message("Or") + " Alt+B", StyleTools.getIconImageView("iconSaveAs.png")); menu.setOnAction((ActionEvent event) -> { saveAsAction(); }); items.add(menu); } if (sourceFile == null) { return items; } menu = new MenuItem(message("Rename"), StyleTools.getIconImageView("iconInput.png")); menu.setOnAction((ActionEvent event) -> { renameAction(); }); items.add(menu); menu = new MenuItem(message("DeleteFile") + " DELETE " + message("Or") + " Ctrl+D" + message("Or") + " Alt+D", StyleTools.getIconImageView("iconDelete.png")); menu.setOnAction((ActionEvent event) -> { deleteAction(); }); items.add(menu); items.add(new SeparatorMenuItem()); menu = new MenuItem(message("SystemMethod"), StyleTools.getIconImageView("iconSystemOpen.png")); menu.setOnAction((ActionEvent event) -> { systemMethod(); }); items.add(menu); menu = new MenuItem(message("ImagesBrowser"), StyleTools.getIconImageView("iconBrowse.png")); menu.setOnAction((ActionEvent event) -> { browseAction(); }); items.add(menu); menu = new MenuItem(message("OpenDirectory"), StyleTools.getIconImageView("iconOpenPath.png")); menu.setOnAction((ActionEvent event) -> { openSourcePath(); }); items.add(menu); menu = new MenuItem(message("BrowseFiles"), StyleTools.getIconImageView("iconList.png")); menu.setOnAction((ActionEvent event) -> { FileBrowseController.open(this); }); items.add(menu); if (FileSortTools.hasNextFile(sourceFile, SourceFileType, sortMode)) { menu = new MenuItem(message("NextFile") + " PAGE_DOWN", StyleTools.getIconImageView("iconNext.png")); menu.setOnAction((ActionEvent event) -> { nextAction(); }); items.add(menu); } if (FileSortTools.hasPreviousFile(sourceFile, SourceFileType, sortMode)) { menu = new MenuItem(message("PreviousFile") + " PAGE_UP", StyleTools.getIconImageView("iconPrevious.png")); menu.setOnAction((ActionEvent event) -> { previousAction(); }); items.add(menu); } Menu sortMenu = new Menu(message("Sort")); items.add(sortMenu); ToggleGroup sortGroup = new ToggleGroup(); for (FileSortMode mode : FileSortMode.values()) { String name = mode.name(); RadioMenuItem sortItemMenu = new RadioMenuItem(message(name)); sortItemMenu.setSelected(mode == sortMode); sortItemMenu.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { sortMode = mode; UserConfig.setString(baseName + "SortMode", name); } }); sortItemMenu.setToggleGroup(sortGroup); sortMenu.getItems().add(sortItemMenu); } return items; } catch (Exception e) { MyBoxLog.error(e); return null; } } @Override public List<MenuItem> functionsMenuItems(Event fevent) { try { List<MenuItem> items = MenuTools.initMenu(message("Function")); MenuItem menu = new MenuItem(message("Edit"), StyleTools.getIconImageView("iconEdit.png")); menu.setOnAction((ActionEvent event) -> { editAction(); }); items.add(menu); menu = new MenuItem(message("Pop") + " Ctrl+P " + message("Or") + " Alt+P", StyleTools.getIconImageView("iconPop.png")); menu.setOnAction((ActionEvent event) -> { popAction(); }); items.add(menu); menu = new MenuItem(message("SelectPixels") + " Ctrl+T " + message("Or") + " Alt+T", StyleTools.getIconImageView("iconTarget.png")); menu.setOnAction((ActionEvent event) -> { selectPixels(); }); items.add(menu); menu = new MenuItem(message("Statistic"), StyleTools.getIconImageView("iconStatistic.png")); menu.setOnAction((ActionEvent event) -> { statisticAction(); }); items.add(menu); menu = new MenuItem(message("OCR"), StyleTools.getIconImageView("iconTxt.png")); menu.setOnAction((ActionEvent event) -> { ocrAction(); }); items.add(menu); menu = new MenuItem(message("Split"), StyleTools.getIconImageView("iconSplit.png")); menu.setOnAction((ActionEvent event) -> { splitAction(); }); items.add(menu); menu = new MenuItem(message("ImageSample"), StyleTools.getIconImageView("iconSample.png")); menu.setOnAction((ActionEvent event) -> { sampleAction(); }); items.add(menu); menu = new MenuItem(message("Repeat"), StyleTools.getIconImageView("iconRepeat.png")); menu.setOnAction((ActionEvent event) -> { repeatAction(); }); items.add(menu); if (sourceFile != null) { menu = new MenuItem("SVG", StyleTools.getIconImageView("iconSVG.png")); menu.setOnAction((ActionEvent event) -> { svgAction(); }); items.add(menu); } items.add(new SeparatorMenuItem()); menu = new MenuItem(message("ManageColors"), StyleTools.getIconImageView("iconPalette.png")); menu.setOnAction((ActionEvent event) -> { ColorsManageController.oneOpen(); }); items.add(menu); menu = new MenuItem(message("QueryColor"), StyleTools.getIconImageView("iconColor.png")); menu.setOnAction((ActionEvent event) -> { ColorQueryController.open(); }); items.add(menu); if (mainMenuController == null) { menu = new MenuItem(message("MainPageShortcut"), StyleTools.getIconImageView("iconMyBox.png")); menu.setOnAction((ActionEvent event) -> { mybox(); }); items.add(menu); } return items; } catch (Exception e) { MyBoxLog.error(e); return null; } } @Override public List<MenuItem> operationsMenuItems(Event fevent) { try { List<MenuItem> items = MenuTools.initMenu(message("Operation")); MenuItem menu; menu = new MenuItem(message("Paste") + " Ctrl+V " + message("Or") + " Alt+V", StyleTools.getIconImageView("iconPaste.png")); menu.setOnAction((ActionEvent event) -> { controlAltV(); }); items.add(menu); menu = new MenuItem(message("RotateRight"), StyleTools.getIconImageView("iconRotateRight.png")); menu.setOnAction((ActionEvent event) -> { rotateRight(); }); items.add(menu); menu = new MenuItem(message("RotateLeft"), StyleTools.getIconImageView("iconRotateLeft.png")); menu.setOnAction((ActionEvent event) -> { rotateLeft(); }); items.add(menu); menu = new MenuItem(message("TurnOver"), StyleTools.getIconImageView("iconTurnOver.png")); menu.setOnAction((ActionEvent event) -> { turnOver(); }); items.add(menu); menu = new MenuItem(message("MirrorHorizontal"), StyleTools.getIconImageView("iconHorizontal.png")); menu.setOnAction((ActionEvent event) -> { horizontalAction(); }); items.add(menu); menu = new MenuItem(message("MirrorVertical"), StyleTools.getIconImageView("iconVertical.png")); menu.setOnAction((ActionEvent event) -> { verticalAction(); }); items.add(menu); return items; } catch (Exception e) { MyBoxLog.error(e); return null; } } public Menu copyMenu(Event fevent) { try { Menu copyMenu = new Menu(message("Copy"), StyleTools.getIconImageView("iconCopy.png")); MenuItem menu = new MenuItem(message("Copy"), StyleTools.getIconImageView("iconCopy.png")); menu.setOnAction((ActionEvent event) -> { ImageCopyController.open(this); }); copyMenu.getItems().add(menu); menu = new MenuItem(message("CopyToSystemClipboard") + " Ctrl+C " + message("Or") + " Alt+C", StyleTools.getIconImageView("iconCopySystem.png")); menu.setOnAction((ActionEvent event) -> { copyToSystemClipboard(); }); copyMenu.getItems().add(menu); menu = new MenuItem(message("CopyToMyBoxClipboard"), StyleTools.getIconImageView("iconCopy.png")); menu.setOnAction((ActionEvent event) -> { copyToMyBoxClipboard(); }); copyMenu.getItems().add(menu); menu = new MenuItem(message("ImagesInSystemClipboard"), StyleTools.getIconImageView("iconSystemClipboard.png")); menu.setOnAction((ActionEvent event) -> { ImageInSystemClipboardController.oneOpen(); }); copyMenu.getItems().add(menu); menu = new MenuItem(message("ImagesInMyBoxClipboard"), StyleTools.getIconImageView("iconClipboard.png")); menu.setOnAction((ActionEvent event) -> { ImageInMyBoxClipboardController.oneOpen(); }); copyMenu.getItems().add(menu); return copyMenu; } catch (Exception e) { MyBoxLog.error(e); return null; } } @Override public List<MenuItem> viewMenuItems(Event fevent) { try { List<MenuItem> items = MenuTools.initMenu(message("View")); MenuItem menu = new MenuItem(message("PickColors") + " Ctrl+K " + message("Or") + " Alt+K", StyleTools.getIconImageView("iconPickColor.png")); menu.setOnAction((ActionEvent event) -> { controlAltK(); }); items.add(menu); items.add(copyMenu(fevent)); items.add(new SeparatorMenuItem()); menu = new MenuItem(message("LoadedSize") + " Ctrl+1 " + message("Or") + " Alt+1", StyleTools.getIconImageView("iconLoadSize.png")); menu.setOnAction((ActionEvent event) -> { loadedSize(); }); items.add(menu); menu = new MenuItem(message("PaneSize") + " Ctrl+2 " + message("Or") + " Alt+2", StyleTools.getIconImageView("iconPaneSize.png")); menu.setOnAction((ActionEvent event) -> { paneSize(); }); items.add(menu); menu = new MenuItem(message("ZoomIn") + " Ctrl+3 " + message("Or") + " Alt+3", StyleTools.getIconImageView("iconZoomIn.png")); menu.setOnAction((ActionEvent event) -> { zoomIn(); }); items.add(menu); menu = new MenuItem(message("ZoomOut") + " Ctrl+4 " + message("Or") + " Alt+4", StyleTools.getIconImageView("iconZoomOut.png")); menu.setOnAction((ActionEvent event) -> { zoomOut(); }); items.add(menu); CheckMenuItem reulersItem = new CheckMenuItem(message("Rulers"), StyleTools.getIconImageView("iconXRuler.png")); reulersItem.setSelected(UserConfig.getBoolean("ImageRulerXY", false)); reulersItem.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent cevent) { if (rulerXCheck != null) { rulerXCheck.setSelected(!rulerXCheck.isSelected()); } else { UserConfig.setBoolean("ImageRulerXY", reulersItem.isSelected()); drawMaskRulers(); } } }); items.add(reulersItem); CheckMenuItem gridItem = new CheckMenuItem(message("GridLines"), StyleTools.getIconImageView("iconGrid.png")); gridItem.setSelected(UserConfig.getBoolean("ImageGridLines", false)); gridItem.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent cevent) { if (gridCheck != null) { gridCheck.setSelected(!gridCheck.isSelected()); } else { UserConfig.setBoolean("ImageGridLines", gridItem.isSelected()); drawMaskGrid(); } } }); items.add(gridItem); CheckMenuItem coordItem = new CheckMenuItem(message("Coordinate"), StyleTools.getIconImageView("iconLocation.png")); coordItem.setSelected(UserConfig.getBoolean("ImagePopCooridnate", false)); coordItem.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent cevent) { if (coordinateCheck != null) { coordinateCheck.setSelected(!coordinateCheck.isSelected()); } else { UserConfig.setBoolean("ImagePopCooridnate", coordItem.isSelected()); drawMaskGrid(); } } }); items.add(coordItem); items.add(new SeparatorMenuItem()); menu = new MenuItem(message("ContextMenu") + " F6", StyleTools.getIconImageView("iconMenu.png")); menu.setOnAction((ActionEvent event) -> { popContextMenu(event); }); items.add(menu); menu = new MenuItem(message("Options"), StyleTools.getIconImageView("iconOptions.png")); menu.setOnAction((ActionEvent event) -> { options(); }); items.add(menu); if (TipsLabelKey != null) { menu = new MenuItem(message("Tips"), StyleTools.getIconImageView("iconTips.png")); menu.setOnAction((ActionEvent event) -> { TextPopController.loadText(message(TipsLabelKey)); }); items.add(menu); } return items; } catch (Exception e) { MyBoxLog.error(e); return null; } } @FXML @Override public void nextAction() { try { File file = nextFile(); if (file != null) { sourceFileChanged(file); } } catch (Exception e) { } } @FXML @Override public void previousAction() { try { File file = previousFile(); if (file != null) { sourceFileChanged(file); } } catch (Exception e) { } } @Override public boolean keyPageUp() { previousAction(); return true; } @Override public boolean keyPageDown() { nextAction(); return true; } @Override public boolean controlAltN() { createAction(); return true; } @Override public boolean controlAltC() { if (imageView == null || imageView.getImage() == null || targetIsTextInput()) { return false; } copyToSystemClipboard(); return true; } @Override public boolean controlAltV() { if (imageView == null || targetIsTextInput()) { return false; } if (imageView.getImage() != null) { pasteAction(); } else { loadContentInSystemClipboard(); } return true; } @Override public boolean controlAltS() { if (imageView == null || imageView.getImage() == null) { return false; } saveAction(); return true; } @Override public boolean controlAltB() { if (imageView == null || imageView.getImage() == null) { return false; } saveAsAction(); return true; } @Override public boolean controlAltK() { if (imageView == null || imageView.getImage() == null) { return false; } if (pickColorCheck != null) { pickColorCheck.setSelected(!pickColorCheck.isSelected()); return true; } else if (imageView != null && imageView.getImage() != null) {
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
true
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/controller/HtmlPopController.java
alpha/MyBox/src/main/java/mara/mybox/controller/HtmlPopController.java
package mara.mybox.controller; import java.io.File; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.concurrent.Worker; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.CheckBox; import javafx.scene.web.WebView; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.WebViewTools; import mara.mybox.fxml.WindowTools; import mara.mybox.value.Fxmls; import mara.mybox.value.Languages; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2021-8-7 * @License Apache License Version 2.0 */ public class HtmlPopController extends BaseWebViewController { protected WebView sourceWebView; protected ChangeListener sourceListener; @FXML protected CheckBox refreshChangeCheck; @FXML protected Button refreshButton; public HtmlPopController() { baseTitle = Languages.message("Html"); } public void openWebView(String baseName, WebView sourceWebView, String address) { try { this.baseName = baseName; this.sourceWebView = sourceWebView; loadContents(address, WebViewTools.getHtml(sourceWebView)); setControls(); } catch (Exception e) { MyBoxLog.debug(e); } } public void setControls() { try { sourceListener = new ChangeListener<Worker.State>() { @Override public void changed(ObservableValue ov, Worker.State oldState, Worker.State newState) { if (refreshChangeCheck.isVisible() && refreshChangeCheck.isSelected()) { if (newState == Worker.State.SUCCEEDED) { refreshAction(); } } } }; refreshChangeCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldState, Boolean newState) { if (sourceWebView == null) { refreshChangeCheck.setVisible(false); refreshButton.setVisible(false); return; } if (refreshChangeCheck.isVisible() && refreshChangeCheck.isSelected()) { sourceWebView.getEngine().getLoadWorker().stateProperty().addListener(sourceListener); } else { sourceWebView.getEngine().getLoadWorker().stateProperty().removeListener(sourceListener); } } }); refreshChangeCheck.setSelected(UserConfig.getBoolean(baseName + "Sychronized", true)); } catch (Exception e) { MyBoxLog.debug(e); } } public void openHtml(String baseName, String html, String address) { try { this.baseName = baseName; refreshChangeCheck.setVisible(false); refreshButton.setVisible(false); loadContents(address, html); setControls(); } catch (Exception e) { MyBoxLog.debug(e); } } public void openAddress(String baseName, String address) { try { this.baseName = baseName; refreshChangeCheck.setVisible(false); refreshButton.setVisible(false); loadAddress(address); setControls(); } catch (Exception e) { MyBoxLog.debug(e); } } @FXML @Override public void refreshAction() { if (sourceWebView == null) { refreshChangeCheck.setVisible(false); refreshButton.setVisible(false); return; } loadContents(webViewController.address, WebViewTools.getHtml(sourceWebView)); } @Override public void cleanPane() { try { if (sourceWebView != null) { sourceWebView.getEngine().getLoadWorker().stateProperty().removeListener(sourceListener); } sourceListener = null; sourceWebView = null; } catch (Exception e) { } super.cleanPane(); } /* static */ public static HtmlPopController open(BaseController parent) { try { HtmlPopController controller = (HtmlPopController) WindowTools.topStage(parent, Fxmls.HtmlPopFxml); return controller; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static HtmlPopController openWebView(BaseController parent, WebView srcWebView) { try { if (parent == null || srcWebView == null) { return null; } HtmlPopController controller = open(parent); if (parent instanceof BaseWebViewController) { BaseWebViewController c = (BaseWebViewController) parent; controller.openWebView(parent.baseName, srcWebView, c.webViewController == null ? null : c.webViewController.address); } else { controller.openWebView(parent.baseName, srcWebView, null); } return controller; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static HtmlPopController openHtml(BaseController parent, String html) { try { if (parent == null || html == null) { return null; } HtmlPopController controller = open(parent); if (parent instanceof BaseWebViewController) { BaseWebViewController c = (BaseWebViewController) parent; controller.openHtml(parent.baseName, html, c.webViewController == null ? null : c.webViewController.address); } else { controller.openHtml(parent.baseName, html, null); } return controller; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static HtmlPopController showHtml(BaseController parent, String html) { try { if (html == null) { return null; } HtmlPopController controller = open(parent); controller.openHtml("HtmlPop", html, null); controller.requestMouse(); return controller; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static HtmlPopController openAddress(BaseController parent, String address) { try { if (parent == null || address == null) { return null; } HtmlPopController controller = open(parent); controller.openAddress(parent.baseName, address); return controller; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static HtmlPopController openFile(BaseController parent, File file) { try { if (parent == null || file == null || !file.exists()) { return null; } return openAddress(parent, file.getAbsolutePath()); } catch (Exception e) { MyBoxLog.error(e); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/controller/DataTreeController.java
alpha/MyBox/src/main/java/mara/mybox/controller/DataTreeController.java
package mara.mybox.controller; import java.io.File; import java.sql.Connection; import java.util.ArrayList; import java.util.Date; import java.util.List; import javafx.event.ActionEvent; import javafx.event.Event; import javafx.event.EventHandler; import javafx.scene.control.Menu; import javafx.scene.control.MenuItem; import javafx.scene.control.RadioMenuItem; import javafx.scene.control.SeparatorMenuItem; import javafx.scene.control.ToggleGroup; import mara.mybox.db.DerbyBase; import mara.mybox.db.data.DataNode; import mara.mybox.db.table.BaseNodeTable; import mara.mybox.db.table.TableNodeDataColumn; import mara.mybox.db.table.TableNodeHtml; import mara.mybox.db.table.TableNodeImageScope; import mara.mybox.db.table.TableNodeJEXL; import mara.mybox.db.table.TableNodeJShell; import mara.mybox.db.table.TableNodeJavaScript; import mara.mybox.db.table.TableNodeMacro; import mara.mybox.db.table.TableNodeMathFunction; import mara.mybox.db.table.TableNodeRowExpression; import mara.mybox.db.table.TableNodeSQL; import mara.mybox.db.table.TableNodeText; import mara.mybox.db.table.TableNodeWebFavorite; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxSingletonTask; import mara.mybox.fxml.menu.MenuTools; import mara.mybox.fxml.PopTools; import mara.mybox.fxml.WindowTools; import mara.mybox.fxml.style.StyleTools; import mara.mybox.value.AppVariables; import mara.mybox.value.Fxmls; import static mara.mybox.value.Languages.message; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2024-8-8 * @License Apache License Version 2.0 */ public class DataTreeController extends BaseDataTreeController { @Override public void whenTreeEmpty() { if (!checkEmptyTree || testing) { return; } File file = nodeTable.exampleFile(); if (file != null && PopTools.askSure(getTitle(), message("ImportExamples") + ": " + baseTitle)) { importExamples(null); } } @Override public boolean endForAutoTestingWhenSceneLoaded() { return false; } public void autoTesting(BaseNodeTable table) { try { testing = true; myStage.setIconified(true); AppVariables.autoTestingController.sceneLoaded(); nodeTable = table; nodeTable.clearData(); initDataTree(nodeTable, null, false); importExamples(null); } catch (Exception e) { MyBoxLog.error(e); } } @Override public void notifyLoaded() { super.notifyLoaded(); if (!testing) { return; } close(); } /* operations */ protected void renameNode(DataNode node) { if (node == null || isRoot(node)) { popError(message("SelectToHandle")); return; } String chainName = chainName(node); String name = PopTools.askValue(getBaseTitle(), chainName, message("ChangeNodeTitle"), title(node) + "m"); if (name == null || name.isBlank()) { return; } if (task != null) { task.cancel(); } task = new FxSingletonTask<Void>(this) { private DataNode updated; @Override protected boolean handle() { try (Connection conn = DerbyBase.getConnection()) { updated = node.cloneAll(); updated.setUpdateTime(new Date()); updated.setTitle(name); return nodeTable.updateData(conn, updated) != null; } catch (Exception e) { error = e.toString(); MyBoxLog.error(e); return false; } } @Override protected void whenSucceeded() { refreshNode(updated, false); popSuccessful(); } }; start(task); } protected void reorderNode(DataNode node) { if (node == null || isRoot(node)) { popError(message("SelectToHandle")); return; } float fvalue; try { String value = PopTools.askValue(getBaseTitle(), chainName(node) + "\n" + message("NodeOrderComments"), message("ChangeNodeOrder"), node.getOrderNumber() + ""); fvalue = Float.parseFloat(value); } catch (Exception e) { popError(message("InvalidValue")); return; } if (task != null) { task.cancel(); } task = new FxSingletonTask<Void>(this) { private DataNode updated, parent; @Override protected boolean handle() { try (Connection conn = DerbyBase.getConnection()) { updated = node.cloneAll(); updated.setUpdateTime(new Date()); updated.setOrderNumber(fvalue); if (nodeTable.updateData(conn, updated) == null) { return false; } parent = nodeTable.query(conn, node.getParentid()); updated.setParentNode(parent); return true; } catch (Exception e) { error = e.toString(); MyBoxLog.error(e); return false; } } @Override protected void whenSucceeded() { refreshNode(parent, true); reloadView(updated); popSuccessful(); } }; start(task); } protected void trimDescendantsOrders(DataNode node, boolean allDescendants) { if (node == null) { popError(message("SelectToHandle")); return; } if (task != null) { task.cancel(); } task = new FxSingletonTask<Void>(this) { private int count; @Override protected boolean handle() { try (Connection conn = DerbyBase.getConnection()) { count = nodeTable.trimDescedentsOrders(this, conn, node, allDescendants, 0); } catch (Exception e) { error = e.toString(); // return false; } return count >= 0; } @Override protected void whenSucceeded() { if (count > 0) { refreshNode(node, true); } popSuccessful(); } }; start(task); } protected void copyNodes(DataNode node) { DataTreeCopyController.open(this, node); } protected void moveNodes(DataNode node) { DataTreeMoveController.open(this, node); } public void deleteNodes(DataNode node) { DataTreeDeleteController.open(this, node); } protected void deleteDescendants(DataNode node) { if (node == null) { popError(message("SelectToHandle")); return; } boolean isRoot = isRoot(node); if (isRoot) { if (!PopTools.askSure(getTitle(), message("DeleteDescendants"), message("SureDeleteAll"))) { return; } } else { String chainName = chainName(node); if (!PopTools.askSure(getTitle(), chainName, message("DeleteDescendants"))) { return; } } if (task != null) { task.cancel(); } task = new FxSingletonTask<Void>(this) { @Override protected boolean handle() { return nodeTable.deleteDecentants(node.getNodeid()) >= 0; } @Override protected void whenSucceeded() { refreshNode(node, true); popSuccessful(); } }; start(task); } protected void deleteNodeAndDescendants(DataNode node) { if (node == null) { popError(message("SelectToHandle")); return; } boolean isRoot = isRoot(node); if (!isLeaf(node)) { if (isRoot) { if (!PopTools.askSure(getTitle(), message("DeleteNodeAndDescendants"), message("SureDeleteAll"))) { return; } } else { String chainName = chainName(node); if (!PopTools.askSure(getTitle(), chainName, message("DeleteNodeAndDescendants"))) { return; } } } if (task != null) { task.cancel(); } task = new FxSingletonTask<Void>(this) { private DataNode parent; @Override protected boolean handle() { if (nodeTable.deleteNode(node.getNodeid()) >= 0) { if (isRoot) { parent = node; } else { parent = nodeTable.find(node.getParentid()); } return parent != null; } else { return false; } } @Override protected void whenSucceeded() { refreshNode(parent, true); popSuccessful(); } }; start(task); } protected DataTreeImportController importExamples(DataNode node) { DataTreeImportController importController = (DataTreeImportController) childStage(Fxmls.DataTreeImportFxml); importController.importExamples(this, node); return importController; } protected DataTreeExportController exportNode(DataNode node) { return DataTreeExportController.open(this, node); } protected void importNode(DataNode node) { DataTreeImportController importController = (DataTreeImportController) childStage(Fxmls.DataTreeImportFxml); importController.setParamters(this, node); } protected void manufactureData() { Data2DManufactureController.openDef(nodeTable.dataTable()); } /* events */ @Override public void doubleClicked(Event event, DataNode node) { clicked(event, UserConfig.getString(baseName + "WhenDoubleClickNode", "PopNode"), node); } @Override public void rightClicked(Event event, DataNode node) { clicked(event, UserConfig.getString(baseName + "WhenRightClickNode", "PopMenu"), node); } public void clicked(Event event, String clickAction, DataNode node) { if (clickAction == null) { return; } switch (clickAction) { case "PopMenu": showPopMenu(event, node); break; case "EditNode": editNode(node); break; case "PopNode": popNode(node); break; case "ExecuteNode": executeNode(node); break; case "UnfoldNode": unfoldNode(node); break; default: break; } } /* menu */ @Override public List<MenuItem> popMenu(Event event, DataNode inNode) { DataNode node = inNode != null ? inNode : rootNode; if (node == null) { return null; } List<MenuItem> items = MenuTools.initMenu(label(node)); Menu dataMenu = new Menu(message("Data"), StyleTools.getIconImageView("iconData.png")); dataMenu.getItems().addAll(dataMenuItems(event, node, false)); items.add(dataMenu); Menu treeMenu = new Menu(message("View"), StyleTools.getIconImageView("iconView.png")); treeMenu.getItems().addAll(viewMenuItems(event, node, false)); items.add(treeMenu); items.add(new SeparatorMenuItem()); items.addAll(operationsMenuItems(event, node, false)); return items; } @Override public List<MenuItem> dataMenuItems(Event fevent) { return dataMenuItems(fevent, null, true); } public List<MenuItem> dataMenuItems(Event fevent, DataNode inNode, boolean withTitle) { DataNode node = inNode != null ? inNode : selectedNode(); if (node == null) { return null; } List<MenuItem> items = MenuTools.initMenu(withTitle ? label(node) : null); MenuItem menu = new MenuItem(message("Tags"), StyleTools.getIconImageView("iconTag.png")); menu.setOnAction((ActionEvent menuItemEvent) -> { DataTreeTagsController.manage(this); }); items.add(menu); menu = new MenuItem(message("Examples"), StyleTools.getIconImageView("iconExamples.png")); menu.setOnAction((ActionEvent menuItemEvent) -> { importExamples(node); }); items.add(menu); menu = new MenuItem(message("Export"), StyleTools.getIconImageView("iconExport.png")); menu.setOnAction((ActionEvent menuItemEvent) -> { exportNode(node); }); items.add(menu); menu = new MenuItem(message("Import"), StyleTools.getIconImageView("iconImport.png")); menu.setOnAction((ActionEvent menuItemEvent) -> { importNode(node); }); items.add(menu); menu = new MenuItem(message("DataManufacture"), StyleTools.getIconImageView("iconDatabase.png")); menu.setOnAction((ActionEvent menuItemEvent) -> { manufactureData(); }); items.add(menu); return items; } @Override public List<MenuItem> operationsMenuItems(Event fevent) { return operationsMenuItems(fevent, null, true); } public List<MenuItem> operationsMenuItems(Event fevent, DataNode inNode, boolean withTitle) { DataNode node = inNode != null ? inNode : selectedNode(); if (node == null) { return null; } List<MenuItem> items = MenuTools.initMenu(withTitle ? label(node) : null); items.addAll(updateMenuItems(fevent, node)); items.add(new SeparatorMenuItem()); items.add(doubleClickMenu(fevent, node)); items.add(rightClickMenu(fevent, node)); return items; } public List<MenuItem> updateMenuItems(Event fevent, DataNode inNode) { DataNode node = inNode != null ? inNode : selectedNode(); if (node == null) { return null; } boolean isRoot = isRoot(node); boolean isLeaf = isLeaf(node); List<MenuItem> items = new ArrayList<>(); MenuItem menu = new MenuItem(message("EditNode"), StyleTools.getIconImageView("iconEdit.png")); menu.setOnAction((ActionEvent menuItemEvent) -> { editNode(node); }); items.add(menu); if (nodeTable.isNodeExecutable()) { menu = new MenuItem(message("ExecuteNode"), StyleTools.getIconImageView("iconGo.png")); menu.setOnAction((ActionEvent menuItemEvent) -> { executeNode(node); }); items.add(menu); } menu = new MenuItem(message("AddChildNode"), StyleTools.getIconImageView("iconAdd.png")); menu.setOnAction((ActionEvent menuItemEvent) -> { addChild(node); }); items.add(menu); if (!isRoot) { menu = new MenuItem(message("ChangeNodeTitle"), StyleTools.getIconImageView("iconInput.png")); menu.setOnAction((ActionEvent menuItemEvent) -> { renameNode(node); }); items.add(menu); } MenuItem orderMenuItem = new MenuItem(message("ChangeNodeOrder"), StyleTools.getIconImageView("iconClean.png")); orderMenuItem.setOnAction((ActionEvent menuItemEvent) -> { reorderNode(node); }); if (isLeaf) { if (!isRoot) { items.add(orderMenuItem); } } else { Menu orderMenu = new Menu(message("OrderNumber"), StyleTools.getIconImageView("iconClean.png")); if (!isRoot) { orderMenu.getItems().add(orderMenuItem); } menu = new MenuItem(message("TrimDescendantsOrders"), StyleTools.getIconImageView("iconClean.png")); menu.setOnAction((ActionEvent menuItemEvent) -> { trimDescendantsOrders(node, true); }); orderMenu.getItems().add(menu); menu = new MenuItem(message("TrimChildrenOrders"), StyleTools.getIconImageView("iconClean.png")); menu.setOnAction((ActionEvent menuItemEvent) -> { trimDescendantsOrders(node, false); }); orderMenu.getItems().add(menu); items.add(orderMenu); } menu = new MenuItem(message("CopyNodes"), StyleTools.getIconImageView("iconCopy.png")); menu.setOnAction((ActionEvent menuItemEvent) -> { copyNodes(node); }); items.add(menu); menu = new MenuItem(message("MoveNodes"), StyleTools.getIconImageView("iconMove.png")); menu.setOnAction((ActionEvent menuItemEvent) -> { moveNodes(node); }); items.add(menu); Menu deleteMenu = new Menu(message("Delete"), StyleTools.getIconImageView("iconDelete.png")); if (isLeaf) { menu = new MenuItem(message("DeleteNode"), StyleTools.getIconImageView("iconDelete.png")); menu.setOnAction((ActionEvent menuItemEvent) -> { deleteNodeAndDescendants(node); }); deleteMenu.getItems().add(menu); } else { menu = new MenuItem(message("DeleteNodeAndDescendants"), StyleTools.getIconImageView("iconDelete.png")); menu.setOnAction((ActionEvent menuItemEvent) -> { deleteNodeAndDescendants(node); }); deleteMenu.getItems().add(menu); menu = new MenuItem(message("DeleteDescendants"), StyleTools.getIconImageView("iconDelete.png")); menu.setOnAction((ActionEvent menuItemEvent) -> { deleteDescendants(node); }); deleteMenu.getItems().add(menu); } menu = new MenuItem(message("DeleteNodes"), StyleTools.getIconImageView("iconDelete.png")); menu.setOnAction((ActionEvent menuItemEvent) -> { deleteNodes(node); }); deleteMenu.getItems().add(menu); items.add(deleteMenu); return items; } public Menu doubleClickMenu(Event fevent, DataNode inNode) { Menu clickMenu = new Menu(message("WhenDoubleClickNode"), StyleTools.getIconImageView("iconSelectAll.png")); clickMenu(fevent, inNode, clickMenu, "WhenDoubleClickNode", "EditNode"); return clickMenu; } public Menu rightClickMenu(Event fevent, DataNode inNode) { Menu clickMenu = new Menu(message("WhenRightClickNode"), StyleTools.getIconImageView("iconSelectNone.png")); clickMenu(fevent, inNode, clickMenu, "WhenRightClickNode", "PopMenu"); return clickMenu; } public Menu clickMenu(Event fevent, DataNode inNode, Menu menu, String key, String defaultAction) { ToggleGroup clickGroup = new ToggleGroup(); String currentClick = UserConfig.getString(baseName + key, defaultAction); RadioMenuItem editNodeMenu = new RadioMenuItem(message("EditNode"), StyleTools.getIconImageView("iconEdit.png")); editNodeMenu.setSelected("EditNode".equals(currentClick)); editNodeMenu.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { UserConfig.setString(baseName + key, "EditNode"); } }); editNodeMenu.setToggleGroup(clickGroup); RadioMenuItem unfoldNodeMenu = new RadioMenuItem(message("Unfold"), StyleTools.getIconImageView("iconPlus.png")); unfoldNodeMenu.setSelected("UnfoldNode".equals(currentClick)); unfoldNodeMenu.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { UserConfig.setString(baseName + key, "UnfoldNode"); } }); unfoldNodeMenu.setToggleGroup(clickGroup); RadioMenuItem popNodeMenu = new RadioMenuItem(message("PopNode"), StyleTools.getIconImageView("iconPop.png")); popNodeMenu.setSelected("PopNode".equals(currentClick)); popNodeMenu.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { UserConfig.setString(baseName + key, "PopNode"); } }); popNodeMenu.setToggleGroup(clickGroup); menu.getItems().addAll(editNodeMenu, unfoldNodeMenu, popNodeMenu); if (nodeTable.isNodeExecutable()) { RadioMenuItem executeNodeMenu = new RadioMenuItem(message("ExecuteNode"), StyleTools.getIconImageView("iconGo.png")); executeNodeMenu.setSelected("ExecuteNode".equals(currentClick)); executeNodeMenu.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { UserConfig.setString(baseName + key, "ExecuteNode"); } }); executeNodeMenu.setToggleGroup(clickGroup); menu.getItems().add(executeNodeMenu); } RadioMenuItem nothingMenu = new RadioMenuItem(message("DoNothing")); nothingMenu.setSelected(currentClick == null || "DoNothing".equals(currentClick)); nothingMenu.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { UserConfig.setString(baseName + key, "DoNothing"); } }); nothingMenu.setToggleGroup(clickGroup); RadioMenuItem clickPopMenu = new RadioMenuItem(message("ContextMenu"), StyleTools.getIconImageView("iconMenu.png")); clickPopMenu.setSelected("PopMenu".equals(currentClick)); clickPopMenu.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { UserConfig.setString(baseName + key, "PopMenu"); } }); clickPopMenu.setToggleGroup(clickGroup); menu.getItems().addAll(clickPopMenu, nothingMenu); return menu; } /* static methods */ public static DataTreeController open() { try { DataTreeController controller = (DataTreeController) WindowTools.openStage(Fxmls.DataTreeFxml); controller.requestMouse(); return controller; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static DataTreeController open(BaseController pController, boolean replaceScene, BaseNodeTable table) { try { if (table == null) { return null; } DataTreeController controller; if ((replaceScene || AppVariables.closeCurrentWhenOpenTool) && pController != null) { controller = (DataTreeController) pController.loadScene(Fxmls.DataTreeFxml); } else { controller = open(); } controller.initDataTree(table, null); return controller; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static DataTreeController open(BaseNodeTable table, DataNode node) { try { DataTreeController controller = open(); controller.initDataTree(table, node); return controller; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static DataTreeController textTree(BaseController pController, boolean replaceScene) { return open(pController, replaceScene, new TableNodeText()); } public static DataTreeController htmlTree(BaseController pController, boolean replaceScene) { return open(pController, replaceScene, new TableNodeHtml()); } public static DataTreeController webFavorite(BaseController pController, boolean replaceScene) { return open(pController, replaceScene, new TableNodeWebFavorite()); } public static DataTreeController sql(BaseController pController, boolean replaceScene) { return open(pController, replaceScene, new TableNodeSQL()); } public static DataTreeController mathFunction(BaseController pController, boolean replaceScene) { return open(pController, replaceScene, new TableNodeMathFunction()); } public static DataTreeController imageScope(BaseController pController, boolean replaceScene) { return open(pController, replaceScene, new TableNodeImageScope()); } public static DataTreeController jShell(BaseController pController, boolean replaceScene) { return open(pController, replaceScene, new TableNodeJShell()); } public static DataTreeController jexl(BaseController pController, boolean replaceScene) { return open(pController, replaceScene, new TableNodeJEXL()); } public static DataTreeController javascript(BaseController pController, boolean replaceScene) { return open(pController, replaceScene, new TableNodeJavaScript()); } public static DataTreeController rowExpression(BaseController pController, boolean replaceScene) { return open(pController, replaceScene, new TableNodeRowExpression()); } public static DataTreeController dataColumn(BaseController pController, boolean replaceScene) { return open(pController, replaceScene, new TableNodeDataColumn()); } public static DataTreeController macroCommands(BaseController pController, boolean replaceScene) { return open(pController, replaceScene, new TableNodeMacro()); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/controller/BaseImageController_Mask.java
alpha/MyBox/src/main/java/mara/mybox/controller/BaseImageController_Mask.java
package mara.mybox.controller; import java.util.ArrayList; import java.util.List; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.scene.Cursor; import javafx.scene.Node; import javafx.scene.image.PixelReader; import javafx.scene.input.MouseEvent; import javafx.scene.paint.Color; import javafx.scene.shape.Line; import javafx.scene.text.Font; import javafx.scene.text.Text; import javafx.stage.Window; import mara.mybox.data.DoublePoint; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.image.FxColorTools; import mara.mybox.fxml.image.ImageViewTools; import mara.mybox.tools.DoubleTools; import static mara.mybox.value.Languages.message; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2021-8-10 * @License Apache License Version 2.0 */ public abstract class BaseImageController_Mask extends BaseImageController_Base { public void initMaskPane() { try { if (maskPane == null) { return; } maskPane.prefWidthProperty().bind(imageView.fitWidthProperty()); maskPane.prefHeightProperty().bind(imageView.fitHeightProperty()); if (maskPane.getOnMouseClicked() == null) { maskPane.setOnMouseClicked(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { paneClicked(event); } }); } if (maskPane.getOnMouseMoved() == null) { maskPane.setOnMouseMoved(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { showXY(event); } }); } if (maskPane.getOnMouseDragged() == null) { maskPane.setOnMouseDragged(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { showXY(event); } }); } if (maskPane.getOnMousePressed() == null) { maskPane.setOnMousePressed(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { showXY(event); } }); } if (maskPane.getOnMouseReleased() == null) { maskPane.setOnMouseReleased(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { showXY(event); } }); } } catch (Exception e) { MyBoxLog.error(e); } } /* image */ public void setImageChanged(boolean imageChanged) { this.imageChanged = imageChanged; updateLabelsTitle(); } /* values */ public double viewXRatio() { return viewWidth() / imageWidth(); } public double viewYRatio() { return viewHeight() / imageHeight(); } public double imageXRatio() { return imageWidth() / viewWidth(); } public double imageYRatio() { return imageHeight() / viewHeight(); } public double maskEventX(MouseEvent event) { return event.getX() * imageXRatio(); } public double maskEventY(MouseEvent event) { return event.getY() * imageYRatio(); } public double imageOffsetX(MouseEvent event) { return (event.getX() - mouseX) * imageXRatio(); } public double imageOffsetY(MouseEvent event) { return (event.getY() - mouseY) * imageYRatio(); } public double nodeX(Node node) { return node.getLayoutX() * imageXRatio(); } public double nodeY(Node node) { return node.getLayoutX() * imageXRatio(); } public double scale(double d) { return scale(d, UserConfig.imageScale()); } public double scale(double d, int scale) { return DoubleTools.scale(d, scale); } /* event */ @FXML public void paneClicked(MouseEvent event) { if (imageView.getImage() == null) { imageView.setCursor(Cursor.OPEN_HAND); return; } DoublePoint p = ImageViewTools.getImageXY(event, imageView); paneClicked(event, p); event.consume(); } public void paneClicked(MouseEvent event, DoublePoint p) { } @FXML public void imageClicked(MouseEvent event) { // MyBoxLog.debug("imageClicked"); } @FXML public DoublePoint showXY(MouseEvent event) { if (xyText == null || !xyText.isVisible()) { return null; } if (!isPickingColor && !UserConfig.getBoolean("ImagePopCooridnate", false)) { xyText.setText(""); return null; } DoublePoint p = ImageViewTools.getImageXY(event, imageView); showXY(event, p); return p; } public DoublePoint showXY(MouseEvent event, DoublePoint p) { try { if (p == null) { xyText.setText(""); return null; } int x = (int) p.getX(); int y = (int) p.getY(); String s = (int) Math.round(x / widthRatio()) + "," + (int) Math.round(y / heightRatio()); if (x >= 0 && x < imageView.getImage().getWidth() && y >= 0 && y < imageView.getImage().getHeight()) { PixelReader pixelReader = imageView.getImage().getPixelReader(); Color color = pixelReader.getColor(x, y); s += "\n" + FxColorTools.colorDisplaySimple(color); } if (isPickingColor) { s = pickingColorTips() + "\n" + s; } xyText.setText(s); xyText.setX(event.getX() + 10); xyText.setY(event.getY()); xyText.setFill(xyColor()); xyText.setFont(xyFont()); return p; } catch (Exception e) { MyBoxLog.debug(e); return null; } } public Color xyColor() { return rulerColor(); } public Font xyFont() { return new Font(12); } public String pickingColorTips() { return message("PickingColorsNow"); } @FXML public void controlPressed(MouseEvent event) { scrollPane.setPannable(false); mouseX = event.getX(); mouseY = event.getY(); } /* rulers and grid */ public void drawMaskRulers() { drawMaskGrid(); drawMaskRulerX(); drawMaskRulerY(); } private void drawMaskRulerX() { if (maskPane == null || imageView == null || imageView.getImage() == null) { return; } clearMaskRulerX(); if (UserConfig.getBoolean("ImageRulerXY", false)) { Color strokeColor = Color.web(UserConfig.getString("RulerColor", "#FF0000")); double imageWidth = imageWidth() / widthRatio(); double ratio = viewWidth() / imageWidth; int step = getRulerStep(imageWidth); for (int i = step; i < imageWidth; i += step) { double x = i * ratio; Line line = new Line(x, 0, x, 8); line.setId("MaskRulerX" + i); line.setStroke(strokeColor); line.setStrokeWidth(1); line.setLayoutX(imageView.getLayoutX() + line.getLayoutX()); line.setLayoutY(imageView.getLayoutY() + line.getLayoutY()); maskPane.getChildren().add(line); } String style = " -fx-font-size: 0.8em; "; int step10 = step * 10; for (int i = step10; i < imageWidth; i += step10) { double x = i * ratio; Line line = new Line(x, 0, x, 15); line.setId("MaskRulerX" + i); line.setStroke(strokeColor); line.setStrokeWidth(2); line.setLayoutX(imageView.getLayoutX() + line.getLayoutX()); line.setLayoutY(imageView.getLayoutY() + line.getLayoutY()); maskPane.getChildren().add(line); Text text = new Text(i + " "); text.setStyle(style); text.setFill(strokeColor); text.setLayoutX(imageView.getLayoutX() + x - 10); text.setLayoutY(imageView.getLayoutY() + 30); text.setId("MaskRulerXtext" + i); maskPane.getChildren().add(text); } } } private void clearMaskRulerX() { if (maskPane == null || imageView == null || imageView.getImage() == null) { return; } List<Node> nodes = new ArrayList<>(); nodes.addAll(maskPane.getChildren()); for (Node node : nodes) { if (node.getId() != null && node.getId().startsWith("MaskRulerX")) { maskPane.getChildren().remove(node); node = null; } } } private void drawMaskRulerY() { if (maskPane == null || imageView == null || imageView.getImage() == null) { return; } clearMaskRulerY(); if (UserConfig.getBoolean("ImageRulerXY", false)) { Color strokeColor = Color.web(UserConfig.getString("RulerColor", "#FF0000")); double imageHeight = imageHeight() / heightRatio(); double ratio = viewHeight() / imageHeight; int step = getRulerStep(imageHeight); for (int j = step; j < imageHeight; j += step) { double y = j * ratio; Line line = new Line(0, y, 8, y); line.setId("MaskRulerY" + j); line.setStroke(strokeColor); line.setStrokeWidth(1); line.setLayoutX(imageView.getLayoutX() + line.getLayoutX()); line.setLayoutY(imageView.getLayoutY() + line.getLayoutY()); maskPane.getChildren().add(line); } String style = " -fx-font-size: 0.8em; "; int step10 = step * 10; for (int j = step10; j < imageHeight; j += step10) { double y = j * ratio; Line line = new Line(0, y, 15, y); line.setId("MaskRulerY" + j); line.setStroke(strokeColor); line.setStrokeWidth(2); line.setLayoutX(imageView.getLayoutX() + line.getLayoutX()); line.setLayoutY(imageView.getLayoutY() + line.getLayoutY()); Text text = new Text(j + " "); text.setStyle(style); text.setFill(strokeColor); text.setLayoutX(imageView.getLayoutX() + 25); text.setLayoutY(imageView.getLayoutY() + y + 8); text.setId("MaskRulerYtext" + j); maskPane.getChildren().addAll(line, text); } } } private void clearMaskRulerY() { if (maskPane == null || imageView.getImage() == null) { return; } List<Node> nodes = new ArrayList<>(); nodes.addAll(maskPane.getChildren()); for (Node node : nodes) { if (node.getId() != null && node.getId().startsWith("MaskRulerY")) { maskPane.getChildren().remove(node); node = null; } } } public void drawMaskGrid() { drawMaskGridX(); drawMaskGridY(); } private void drawMaskGridX() { if (maskPane == null || imageView == null || imageView.getImage() == null) { return; } clearMaskGridX(); if (UserConfig.getBoolean("ImageGridLines", false)) { Color lineColor = gridColor(); int lineWidth = UserConfig.getInt("GridLinesWidth", 1); lineWidth = lineWidth <= 0 ? 1 : lineWidth; double imageWidth = imageWidth() / widthRatio(); double imageHeight = imageHeight() / heightRatio(); double wratio = viewWidth() / imageWidth; double hratio = viewHeight() / imageHeight; int istep = getRulerStep(imageWidth); int interval = UserConfig.getInt("GridLinesInterval", -1); interval = interval <= 0 ? istep : interval; float opacity = 0.1f; try { opacity = Float.parseFloat(UserConfig.getString("GridLinesOpacity", "0.1")); } catch (Exception e) { } for (int i = interval; i < imageWidth; i += interval) { double x = i * wratio; Line line = new Line(x, 0, x, imageHeight * hratio); line.setId("GridLinesX" + i); line.setStroke(lineColor); line.setStrokeWidth(lineWidth); line.setLayoutX(imageView.getLayoutX() + line.getLayoutX()); line.setLayoutY(imageView.getLayoutY() + line.getLayoutY()); line.setOpacity(opacity); maskPane.getChildren().add(line); } int step10 = istep * 10; String style = " -fx-font-size: 0.8em; "; for (int i = step10; i < imageWidth; i += step10) { double x = i * wratio; Line line = new Line(x, 0, x, imageHeight * hratio); line.setId("GridLinesX" + i); line.setStroke(lineColor); line.setStrokeWidth(lineWidth + 1); line.setLayoutX(imageView.getLayoutX() + line.getLayoutX()); line.setLayoutY(imageView.getLayoutY() + line.getLayoutY()); line.setOpacity(opacity); maskPane.getChildren().add(line); if (!UserConfig.getBoolean("ImageRulerXY", false)) { Text text = new Text(i + " "); text.setStyle(style); text.setFill(lineColor); text.setLayoutX(imageView.getLayoutX() + x - 10); text.setLayoutY(imageView.getLayoutY() + 15); text.setId("GridLinesXtext" + i); maskPane.getChildren().add(text); } } } } private void drawMaskGridY() { if (maskPane == null || imageView == null || imageView.getImage() == null) { return; } clearMaskGridY(); if (UserConfig.getBoolean("ImageGridLines", false)) { Color lineColor = gridColor(); int lineWidth = UserConfig.getInt("GridLinesWidth", 1); double imageWidth = imageWidth() / widthRatio(); double imageHeight = imageHeight() / heightRatio(); double wratio = viewWidth() / imageWidth; double hratio = viewHeight() / imageHeight; int istep = getRulerStep(imageHeight); int interval = UserConfig.getInt("GridLinesInterval", -1); interval = interval <= 0 ? istep : interval; double w = imageWidth * wratio; float opacity = 0.1f; try { opacity = Float.parseFloat(UserConfig.getString("GridLinesOpacity", "0.1")); } catch (Exception e) { } for (int j = interval; j < imageHeight; j += interval) { double y = j * hratio; Line line = new Line(0, y, w, y); line.setId("GridLinesY" + j); line.setStroke(lineColor); line.setStrokeWidth(lineWidth); line.setLayoutX(imageView.getLayoutX() + line.getLayoutX()); line.setLayoutY(imageView.getLayoutY() + line.getLayoutY()); line.setOpacity(opacity); maskPane.getChildren().add(line); } String style = " -fx-font-size: 0.8em; "; int step10 = istep * 10; for (int j = step10; j < imageHeight; j += step10) { double y = j * hratio; Line line = new Line(0, y, w, y); line.setId("GridLinesY" + j); line.setStroke(lineColor); line.setStrokeWidth(lineWidth + 2); line.setLayoutX(imageView.getLayoutX() + line.getLayoutX()); line.setLayoutY(imageView.getLayoutY() + line.getLayoutY()); line.setOpacity(opacity); maskPane.getChildren().add(line); if (!UserConfig.getBoolean("ImageRulerXY", false)) { Text text = new Text(j + " "); text.setStyle(style); text.setFill(lineColor); text.setLayoutX(imageView.getLayoutX()); text.setLayoutY(imageView.getLayoutY() + y + 8); text.setId("GridLinesYtext" + j); maskPane.getChildren().add(text); } } } } private void clearMaskGridX() { if (maskPane == null || imageView.getImage() == null) { return; } List<Node> nodes = new ArrayList<>(); nodes.addAll(maskPane.getChildren()); for (Node node : nodes) { if (node.getId() != null && node.getId().startsWith("GridLinesX")) { maskPane.getChildren().remove(node); node = null; } } } private void clearMaskGridY() { if (maskPane == null || imageView.getImage() == null) { return; } List<Node> nodes = new ArrayList<>(); nodes.addAll(maskPane.getChildren()); for (Node node : nodes) { if (node.getId() != null && node.getId().startsWith("GridLinesY")) { maskPane.getChildren().remove(node); node = null; } } } protected Color rulerColor() { return Color.web(UserConfig.getString("RulerColor", "#FF0000")); } protected Color gridColor() { return Color.web(UserConfig.getString("GridLinesColor", Color.LIGHTGRAY.toString())); } /* static */ public static void updateMaskRulerXY() { List<Window> windows = new ArrayList<>(); windows.addAll(Window.getWindows()); for (Window window : windows) { Object object = window.getUserData(); if (object != null && object instanceof BaseImageController) { try { BaseImageController controller = (BaseImageController) object; controller.drawMaskRulers(); } catch (Exception e) { } } } } public static void updateMaskGrid() { List<Window> windows = new ArrayList<>(); windows.addAll(Window.getWindows()); for (Window window : windows) { Object object = window.getUserData(); if (object != null && object instanceof BaseImageController) { try { BaseImageController controller = (BaseImageController) object; controller.drawMaskGrid(); } catch (Exception e) { } } } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/controller/Data2DManageQueryController.java
alpha/MyBox/src/main/java/mara/mybox/controller/Data2DManageQueryController.java
package mara.mybox.controller; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.fxml.FXML; import javafx.scene.control.CheckBox; import javafx.scene.control.RadioButton; import javafx.scene.control.Toggle; import javafx.scene.control.ToggleGroup; import mara.mybox.data2d.Data2D; import mara.mybox.db.data.Data2DDefinition; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.WindowTools; import mara.mybox.value.Fxmls; import static mara.mybox.value.Languages.message; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2021-12-28 * @License Apache License Version 2.0 */ public class Data2DManageQueryController extends BaseChildController { protected BaseData2DListController listController; @FXML protected ToggleGroup orderGroup; @FXML protected CheckBox csvCheck, excelCheck, textsCheck, matrixCheck, databaseCheck, myBoxClipboardCheck, descCheck; @FXML protected RadioButton idRadio, nameRadio, rowsRadio, colsRadio, timeRadio, fileRadio; public Data2DManageQueryController() { baseTitle = message("ManageData"); } @Override public void initControls() { try { super.initControls(); csvCheck.setSelected(UserConfig.getBoolean(baseName + "CSV", true)); csvCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldValue, Boolean newValue) { UserConfig.setBoolean(baseName + "CSV", csvCheck.isSelected()); } }); textsCheck.setSelected(UserConfig.getBoolean(baseName + "Text", true)); textsCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldValue, Boolean newValue) { UserConfig.setBoolean(baseName + "Text", textsCheck.isSelected()); } }); excelCheck.setSelected(UserConfig.getBoolean(baseName + "Xlsx", true)); excelCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldValue, Boolean newValue) { UserConfig.setBoolean(baseName + "Xlsx", excelCheck.isSelected()); } }); matrixCheck.setSelected(UserConfig.getBoolean(baseName + "Matrix", true)); matrixCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldValue, Boolean newValue) { UserConfig.setBoolean(baseName + "Matrix", matrixCheck.isSelected()); } }); databaseCheck.setSelected(UserConfig.getBoolean(baseName + "Database", true)); databaseCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldValue, Boolean newValue) { UserConfig.setBoolean(baseName + "Database", databaseCheck.isSelected()); } }); myBoxClipboardCheck.setSelected(UserConfig.getBoolean(baseName + "DataClipboard", true)); myBoxClipboardCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldValue, Boolean newValue) { UserConfig.setBoolean(baseName + "DataClipboard", myBoxClipboardCheck.isSelected()); } }); descCheck.setSelected(UserConfig.getBoolean(baseName + "Desc", false)); descCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldValue, Boolean newValue) { UserConfig.setBoolean(baseName + "Desc", descCheck.isSelected()); } }); String order = UserConfig.getString(baseName + "Order", null); if (message("ID").equals(order)) { idRadio.setSelected(true); } else if (message("Name").equals(order)) { nameRadio.setSelected(true); } else if (message("RowsNumber").equals(order)) { rowsRadio.setSelected(true); } else if (message("ColumnsNumber").equals(order)) { colsRadio.setSelected(true); } else if (message("File").equals(order)) { fileRadio.setSelected(true); } else { timeRadio.setSelected(true); } orderGroup.selectedToggleProperty().addListener(new ChangeListener<Toggle>() { @Override public void changed(ObservableValue ov, Toggle oldValue, Toggle newValue) { UserConfig.setString(baseName + "Order", ((RadioButton) newValue).getText()); } }); } catch (Exception e) { MyBoxLog.error(e); } } public void setParameters(BaseData2DListController manageController) { this.listController = manageController; } @FXML @Override public void selectAllAction() { selectAll(true); } @FXML @Override public void selectNoneAction() { selectAll(false); } public void selectAll(boolean select) { csvCheck.setSelected(select); excelCheck.setSelected(select); textsCheck.setSelected(select); matrixCheck.setSelected(select); databaseCheck.setSelected(select); myBoxClipboardCheck.setSelected(select); } @FXML @Override public void okAction() { try { String condition = ""; if (textsCheck.isSelected()) { condition += " data_type=0 "; } if (csvCheck.isSelected()) { condition += (condition.isEmpty() ? "" : " OR ") + " data_type=1 "; } if (excelCheck.isSelected()) { condition += (condition.isEmpty() ? "" : " OR ") + " data_type=2 "; } if (myBoxClipboardCheck.isSelected()) { condition += (condition.isEmpty() ? "" : " OR ") + " data_type=3 "; } if (matrixCheck.isSelected()) { condition += (condition.isEmpty() ? "" : " OR ") + " data_type=4 "; } if (databaseCheck.isSelected()) { condition += (condition.isEmpty() ? "" : " OR ") + " data_type=5 "; } condition += " AND data_type != " + Data2D.type(Data2DDefinition.DataType.InternalTable); String orderColumns = null; if (idRadio.isSelected()) { orderColumns = " d2did "; } else if (nameRadio.isSelected()) { orderColumns = " data_name "; } else if (rowsRadio.isSelected()) { orderColumns = " rows_number "; } else if (colsRadio.isSelected()) { orderColumns = " columns_number "; } else if (timeRadio.isSelected()) { orderColumns = " modify_time "; } else if (fileRadio.isSelected()) { orderColumns = " file "; } if (orderColumns != null && descCheck.isSelected()) { orderColumns += " DESC "; } listController.queryConditions = condition; listController.orderColumns = orderColumns; listController.refreshAction(); } catch (Exception e) { MyBoxLog.error(e); } } /* static */ public static Data2DManageQueryController open(BaseData2DListController manageController) { try { Data2DManageQueryController controller = (Data2DManageQueryController) WindowTools.referredTopStage( manageController, Fxmls.Data2DManageQueryFxml); controller.setParameters(manageController); controller.requestMouse(); return controller; } catch (Exception e) { MyBoxLog.error(e); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/controller/ControlXmlNodeEdit.java
alpha/MyBox/src/main/java/mara/mybox/controller/ControlXmlNodeEdit.java
package mara.mybox.controller; import javafx.fxml.FXML; import javafx.scene.control.Label; import javafx.scene.control.TreeItem; import mara.mybox.data.XmlTreeNode; import mara.mybox.db.table.TableStringValues; import mara.mybox.dev.MyBoxLog; import mara.mybox.tools.XmlTools; import static mara.mybox.value.Languages.message; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; /** * @Author Mara * @CreateDate 2023-5-16 * @License Apache License Version 2.0 */ public class ControlXmlNodeEdit extends ControlXmlNodeBase { protected TreeItem<XmlTreeNode> treeItem; protected Node node; @FXML protected Label infoLabel; public void setParameters(ControlXmlTree treeController) { this.treeController = treeController; } public void editNode(TreeItem<XmlTreeNode> item) { clearNode(); treeItem = item; if (treeItem == null) { return; } XmlTreeNode currentTreeNode = treeItem.getValue(); if (currentTreeNode == null) { return; } thisPane.setDisable(false); infoLabel.setText(treeController.makeHierarchyNumber(item)); node = currentTreeNode.getNode(); if (node == null) { return; } typeInput.setText(XmlTools.type(node).name()); baseUriInput.setText(node.getBaseURI()); namespaceInput.setText(node.getNamespaceURI()); nameInput.setText(node.getNodeName()); nameInput.setDisable(true); prefixInput.setText(node.getPrefix()); prefixInput.setDisable(true); switch (node.getNodeType()) { case Node.TEXT_NODE: case Node.CDATA_SECTION_NODE: case Node.COMMENT_NODE: case Node.ATTRIBUTE_NODE: case Node.PROCESSING_INSTRUCTION_NODE: tabPane.getTabs().add(0, valueTab); valueArea.setText(XmlTools.value(node)); valueArea.setDisable(false); valueArea.setEditable(true); break; case Node.ELEMENT_NODE: tabPane.getTabs().add(0, attrTab); setAttributes(); break; case Node.DOCUMENT_NODE: tabPane.getTabs().add(0, docTab); Document document = (Document) node; uriInput.setText(document.getDocumentURI()); versionInput.setText(document.getXmlVersion()); encodingInput.setText(document.getXmlEncoding()); standaloneCheck.setSelected(document.getXmlStandalone()); break; case Node.DOCUMENT_TYPE_NODE: case Node.DOCUMENT_FRAGMENT_NODE: case Node.ENTITY_NODE: case Node.ENTITY_REFERENCE_NODE: case Node.NOTATION_NODE: tabPane.getTabs().add(0, valueTab); valueArea.setText(XmlTools.value(node)); valueArea.setDisable(true); valueArea.setEditable(false); break; default: } refreshStyle(tabPane); tabPane.getSelectionModel().select(0); thisPane.setDisable(false); } public void setAttributes() { if (node == null) { return; } NamedNodeMap attrs = node.getAttributes(); if (attrs != null) { for (int i = 0; i < attrs.getLength(); i++) { tableData.add(attrs.item(i)); } } } public Node pickValue() { try { if (node == null) { return null; } switch (node.getNodeType()) { case Node.TEXT_NODE: case Node.CDATA_SECTION_NODE: case Node.COMMENT_NODE: case Node.ATTRIBUTE_NODE: case Node.PROCESSING_INSTRUCTION_NODE: String s = valueArea.getText(); node.setNodeValue(s); if (s != null && !s.isBlank()) { TableStringValues.add("XmlNodeValueHistories", s); } break; case Node.ELEMENT_NODE: NamedNodeMap attrs = node.getAttributes(); if (attrs != null) { Element element = (Element) node; for (int i = attrs.getLength() - 1; i >= 0; i--) { element.removeAttribute(attrs.item(i).getNodeName()); } for (Node attr : tableData) { element.setAttribute(attr.getNodeName(), attr.getNodeValue()); } } break; case Node.DOCUMENT_NODE: Document document = (Document) node; // document.setDocumentURI(uriInput.getText()); // document.setXmlVersion(versionInput.getText()); document.setXmlStandalone(standaloneCheck.isSelected()); break; case Node.DOCUMENT_TYPE_NODE: case Node.DOCUMENT_FRAGMENT_NODE: case Node.ENTITY_NODE: case Node.ENTITY_REFERENCE_NODE: case Node.NOTATION_NODE: default: } return node; } catch (Exception e) { MyBoxLog.error(e); return null; } } @FXML public void okNode() { try { if (treeItem == null) { return; } XmlTreeNode currentTreeNode = treeItem.getValue(); if (currentTreeNode == null) { return; } Node updatedNode = pickValue(); if (updatedNode == null) { return; } XmlTreeNode updatedTreeNode = new XmlTreeNode() .setNode(updatedNode) .setType(XmlTools.type(updatedNode)) .setTitle(updatedNode.getNodeName()) .setValue(XmlTools.value(updatedNode)); treeItem.setValue(updatedTreeNode); editNode(treeItem); treeController.xmlEditor.domChanged(true); treeController.xmlEditor.popInformation(message("UpdateSuccessfully")); } catch (Exception e) { MyBoxLog.error(e); } } @FXML public void recoverNode() { editNode(treeItem); } @Override public void clearNode() { super.clearNode(); node = null; thisPane.setDisable(true); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/controller/ImageCubicController.java
alpha/MyBox/src/main/java/mara/mybox/controller/ImageCubicController.java
package mara.mybox.controller; import javafx.fxml.FXML; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.WindowTools; import mara.mybox.value.Fxmls; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2019-8-13 * @License Apache License Version 2.0 */ public class ImageCubicController extends BaseImageShapeController { @FXML protected ControlCubic cubicController; public ImageCubicController() { baseTitle = message("CubicCurve"); } @Override protected void initMore() { try { super.initMore(); operation = message("CubicCurve"); cubicController.setParameters(this); anchorCheck.setSelected(true); showAnchors = true; popShapeMenu = true; } catch (Exception e) { MyBoxLog.error(e); } } @Override public void setInputs() { cubicController.loadValues(); } @Override public boolean pickShape() { return cubicController.pickValues(); } @Override public void initShape() { try { maskCubicData = null; showMaskCubic(); goAction(); } catch (Exception e) { MyBoxLog.error(e); } } /* static methods */ public static ImageCubicController open(ImageEditorController parent) { try { if (parent == null) { return null; } ImageCubicController controller = (ImageCubicController) WindowTools.referredStage( parent, Fxmls.ImageCubicFxml); controller.setParameters(parent); return controller; } catch (Exception e) { MyBoxLog.error(e); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/controller/SvgTypesettingController.java
alpha/MyBox/src/main/java/mara/mybox/controller/SvgTypesettingController.java
package mara.mybox.controller; import mara.mybox.db.data.VisitHistory; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2023-6-16 * @License Apache License Version 2.0 */ public class SvgTypesettingController extends XmlTypesettingController { public SvgTypesettingController() { baseTitle = message("SvgTypesetting"); } @Override public void setFileType() { setFileType(VisitHistory.FileType.SVG); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/controller/ImageMosaicBatchController.java
alpha/MyBox/src/main/java/mara/mybox/controller/ImageMosaicBatchController.java
package mara.mybox.controller; import java.awt.image.BufferedImage; import java.io.File; import java.util.List; import javafx.fxml.FXML; import mara.mybox.image.data.ImageMosaic; import mara.mybox.fxml.image.PixelDemos; import mara.mybox.fxml.FxTask; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2018-9-23 * @License Apache License Version 2.0 */ public class ImageMosaicBatchController extends BaseImageEditBatchController { protected ImageMosaic mosaic; @FXML protected ControlImageMosaic mosaicController; public ImageMosaicBatchController() { baseTitle = message("ImageBatch") + " - " + message("Mosaic"); } @Override public boolean makeMoreParameters() { if (!super.makeMoreParameters()) { return false; } mosaic = mosaicController.pickValues(ImageMosaic.MosaicType.Mosaic); return mosaic != null; } @Override protected BufferedImage handleImage(FxTask currentTask, BufferedImage source) { return mosaic.setImage(source).setTask(currentTask).start(); } @Override public void makeDemoFiles(FxTask currentTask, List<String> files, File demoFile, BufferedImage demoImage) { PixelDemos.mosaic(currentTask, files, demoImage, ImageMosaic.MosaicType.Mosaic, demoFile); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/controller/BaseSysTableController.java
alpha/MyBox/src/main/java/mara/mybox/controller/BaseSysTableController.java
package mara.mybox.controller; import java.io.File; import java.sql.Connection; import java.util.List; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.Label; import mara.mybox.db.DerbyBase; import mara.mybox.db.table.BaseTable; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxFileTools; import mara.mybox.fxml.FxSingletonTask; import mara.mybox.fxml.FxTask; import mara.mybox.value.FileFilters; import mara.mybox.value.Languages; /** * @param <P> Data * @Author Mara * @CreateDate 2019-12-18 * @License Apache License Version 2.0 */ public abstract class BaseSysTableController<P> extends BaseTablePagesController<P> { protected BaseTable tableDefinition; @FXML protected Button examplesButton, resetButton, importButton, exportButton, chartsButton, queryButton, moveDataButton, orderby; @FXML protected Label queryConditionsLabel; public BaseSysTableController() { tableName = ""; TipsLabelKey = "TableTips"; } @Override public void initValues() { try { super.initValues(); setTableDefinition(); setTableDefinition(tableDefinition); } catch (Exception e) { MyBoxLog.error(e); } } // define tableDefinition here public void setTableDefinition() { } public void setTableDefinition(BaseTable t) { tableDefinition = t; if (tableDefinition != null) { tableName = tableDefinition.getTableName(); idColumnName = tableDefinition.getIdColumnName(); } } @Override public void postLoadedTableData() { super.postLoadedTableData(); if (queryConditionsLabel != null) { queryConditionsLabel.setText(queryConditionsString); } } @Override public List<P> readPageData(FxTask currentTask, Connection conn) { if (tableDefinition != null) { return tableDefinition.queryConditions(conn, queryConditions, orderColumns, pagination.startRowOfCurrentPage, pagination.pageSize); } else { return null; } } @Override public long readDataSize(FxTask currentTask, Connection conn) { long size = 0; if (tableDefinition != null) { if (queryConditions != null) { size = tableDefinition.conditionSize(conn, queryConditions); } else { size = tableDefinition.size(conn); } } dataSizeLoaded = true; return size; } @Override protected int deleteData(FxTask currentTask, List<P> data) { if (data == null || data.isEmpty()) { return 0; } if (tableDefinition != null) { return tableDefinition.deleteData(data); } return 0; } @Override protected long clearData(FxTask currentTask) { if (tableDefinition != null) { return tableDefinition.deleteCondition(queryConditions); } else { return 0; } } @FXML @Override public void refreshAction() { loadTableData(); } @FXML protected void importAction() { File file = FxFileTools.selectFile(this); if (file == null) { return; } if (task != null && !task.isQuit()) { return; } task = new FxSingletonTask<Void>(this) { @Override protected boolean handle() { importData(file); return true; } @Override protected void whenSucceeded() { popSuccessful(); refreshAction(); } }; start(task); } protected void importData(File file) { DerbyBase.importData(tableName, file.getAbsolutePath(), false); } @FXML protected void exportAction() { final File file = chooseFile(defaultTargetPath(), Languages.message(tableName) + ".txt", FileFilters.AllExtensionFilter); if (file == null) { return; } if (task != null && !task.isQuit()) { return; } task = new FxSingletonTask<Void>(this) { @Override protected boolean handle() { DerbyBase.exportData(tableName, file.getAbsolutePath()); recordFileWritten(file); return true; } @Override protected void whenSucceeded() { popSuccessful(); TextEditorController.open(file); } }; start(task); } @FXML protected void analyseAction() { } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/controller/SvgRectangleController.java
alpha/MyBox/src/main/java/mara/mybox/controller/SvgRectangleController.java
package mara.mybox.controller; import javafx.fxml.FXML; import javafx.scene.control.TreeItem; import mara.mybox.data.DoubleRectangle; import mara.mybox.data.XmlTreeNode; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.WindowTools; import mara.mybox.value.Fxmls; import static mara.mybox.value.Languages.message; import org.w3c.dom.Element; /** * @Author Mara * @CreateDate 2023-12-31 * @License Apache License Version 2.0 */ public class SvgRectangleController extends BaseSvgShapeController { @FXML protected ControlRectangle rectController; @Override public void initMore() { try { shapeName = message("Rectangle"); rectController.setParameters(this); anchorCheck.setSelected(true); showAnchors = true; popShapeMenu = true; } catch (Exception e) { MyBoxLog.error(e); } } @Override public boolean elementToShape(Element node) { try { float x, y, w, h, rx = 0, ry = 0; try { x = Float.parseFloat(node.getAttribute("x")); } catch (Exception e) { popError(message("InvalidParameter") + ": x"); return false; } try { y = Float.parseFloat(node.getAttribute("y")); } catch (Exception e) { popError(message("InvalidParameter") + ": y"); return false; } try { w = Float.parseFloat(node.getAttribute("width")); } catch (Exception e) { w = -1f; } if (w <= 0) { popError(message("InvalidParameter") + ": " + message("Width")); return false; } try { h = Float.parseFloat(node.getAttribute("height")); } catch (Exception e) { h = -1f; } if (h <= 0) { popError(message("InvalidParameter") + ": " + message("Height")); return false; } try { rx = Float.parseFloat(node.getAttribute("rx")); } catch (Exception e) { } try { ry = Float.parseFloat(node.getAttribute("ry")); } catch (Exception e) { } maskRectangleData = DoubleRectangle.xywh(x, y, w, h); maskRectangleData.setRoundx(rx); maskRectangleData.setRoundy(ry); return true; } catch (Exception e) { MyBoxLog.error(e); return false; } } @Override public void initShape() { rectController.setRoundList(); } @Override public void showShape() { showMaskRectangle(); } @Override public void setShapeInputs() { rectController.loadValues(); } @Override public boolean shape2Element() { try { if (maskRectangleData == null) { return false; } if (shapeElement == null) { shapeElement = doc.createElement("rect"); } shapeElement.setAttribute("x", scaleValue(maskRectangleData.getX())); shapeElement.setAttribute("y", scaleValue(maskRectangleData.getY())); shapeElement.setAttribute("width", scaleValue(maskRectangleData.getWidth())); shapeElement.setAttribute("height", scaleValue(maskRectangleData.getHeight())); shapeElement.setAttribute("rx", scaleValue(maskRectangleData.getRoundx())); shapeElement.setAttribute("ry", scaleValue(maskRectangleData.getRoundy())); return true; } catch (Exception e) { MyBoxLog.error(e); } return false; } @Override public boolean pickShape() { return rectController.pickValues(); } /* static */ public static SvgRectangleController drawShape(SvgEditorController editor, TreeItem<XmlTreeNode> item, Element element) { try { if (editor == null || item == null) { return null; } SvgRectangleController controller = (SvgRectangleController) WindowTools.childStage( editor, Fxmls.SvgRectangleFxml); controller.setParameters(editor, item, element); return controller; } catch (Exception e) { MyBoxLog.error(e); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/tools/DoubleArrayTools.java
alpha/MyBox/src/main/java/mara/mybox/tools/DoubleArrayTools.java
package mara.mybox.tools; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; /** * @Author Mara * @CreateDate 2018-6-11 17:43:53 * @Description * @License Apache License Version 2.0 */ public class DoubleArrayTools { public static double[] sortArray(double[] numbers) { List<Double> list = new ArrayList<>(); for (double i : numbers) { list.add(i); } Collections.sort(list, new Comparator<Double>() { @Override public int compare(Double p1, Double p2) { if (p1 > p2) { return 1; } else if (p1 < p2) { return -1; } else { return 0; } } }); double[] sorted = new double[numbers.length]; for (int i = 0; i < list.size(); ++i) { sorted[i] = list.get(i); } return sorted; } public static double[] array(double x, double y, double z) { double[] xyz = new double[3]; xyz[0] = x; xyz[1] = y; xyz[2] = z; return xyz; } public static double[] scale(double[] data, int scale) { try { if (data == null) { return null; } double[] result = new double[data.length]; for (int i = 0; i < data.length; ++i) { result[i] = DoubleTools.scale(data[i], scale); } return result; } catch (Exception e) { return null; } } public static double[] normalizeMinMax(double[] array) { try { if (array == null) { return null; } double[] result = new double[array.length]; double min = Double.MAX_VALUE, max = -Double.MAX_VALUE; for (int i = 0; i < array.length; ++i) { double d = array[i]; if (d > max) { max = d; } if (d < min) { min = d; } } if (min == max) { return normalizeSum(array); } else { double s = 1d / (max - min); for (int i = 0; i < array.length; ++i) { result[i] = (array[i] - min) * s; } } return result; } catch (Exception e) { return null; } } public static double[] normalizeSum(double[] array) { try { if (array == null) { return null; } double[] result = new double[array.length]; double sum = 0; for (int i = 0; i < array.length; ++i) { sum += Math.abs(array[i]); } if (sum == 0) { return null; } double s = 1d / sum; for (int i = 0; i < array.length; ++i) { result[i] = array[i] * s; } return result; } catch (Exception e) { return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/tools/DateTools.java
alpha/MyBox/src/main/java/mara/mybox/tools/DateTools.java
package mara.mybox.tools; import java.text.DateFormat; import java.text.MessageFormat; import java.text.ParsePosition; import java.text.SimpleDateFormat; import java.time.Duration; import java.time.Instant; import java.time.LocalDate; import java.time.Period; import java.time.ZoneId; import java.time.ZonedDateTime; import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.Random; import java.util.TimeZone; import mara.mybox.data.Era; import mara.mybox.dev.MyBoxLog; import mara.mybox.value.AppValues; import mara.mybox.value.Languages; import static mara.mybox.value.Languages.message; import mara.mybox.value.TimeFormats; /** * @Author Mara * @CreateDate 2018-6-11 9:44:53 * @License Apache License Version 2.0 */ public class DateTools { /* parse to date */ // strDate does not contain ear code(bc/ad) public static String parseFormat(String strDate) { try { if (strDate == null || strDate.isBlank()) { return null; } String fullString = strDate.trim().replace("T", " "); String parsed = fullString, format; if (parsed.startsWith("-")) { parsed = fullString.substring(1); } int len = parsed.length(); if (len <= 4) { format = TimeFormats.YearA; } else if (parsed.contains("/")) { if (parsed.charAt(4) == '/') { if (parsed.contains(":")) { if (parsed.contains(".")) { format = TimeFormats.DatetimeMsC; } else { format = TimeFormats.DatetimeC; } } else if (parsed.indexOf("/") == parsed.lastIndexOf("/")) { format = TimeFormats.MonthC; } else { format = TimeFormats.DateC; } } else { if (parsed.contains(":")) { if (parsed.contains(".")) { format = TimeFormats.DatetimeMsB; } else { format = TimeFormats.DatetimeB; } } else if (parsed.indexOf("/") == parsed.lastIndexOf("/")) { format = TimeFormats.MonthB; } else { format = TimeFormats.DateB; } } } else if (parsed.contains("-")) { if (parsed.contains(":")) { if (parsed.contains(".")) { format = TimeFormats.DatetimeMsA; } else { format = TimeFormats.DatetimeA; } } else if (parsed.indexOf("-") == parsed.lastIndexOf("-")) { format = TimeFormats.MonthA; } else { format = TimeFormats.DateA; } } else if (parsed.contains(":")) { if (parsed.contains(".")) { format = TimeFormats.TimeMs; } else { format = TimeFormats.Time; } } else { format = TimeFormats.YearA; } if (parsed.contains("+")) { format += " Z"; } return format; } catch (Exception e) { return null; } } public static Date encodeDate(String strDate, int century) { if (strDate == null) { return null; } try { long lv = Long.parseLong(strDate); if (lv >= 10000 || lv <= -10000) { return new Date(lv); } } catch (Exception e) { } String s = strDate.trim().replace("T", " "), format; Locale locale; int len = s.length(); if (s.startsWith(message("zh", "BC") + " ")) { locale = Languages.LocaleZhCN; format = "G " + parseFormat(s.substring((message("zh", "BC") + " ").length(), len)); } else if (s.startsWith(message("zh", "BC"))) { locale = Languages.LocaleZhCN; format = "G" + parseFormat(s.substring((message("zh", "BC")).length(), len)); } else if (s.startsWith(message("zh", "AD") + " ")) { locale = Languages.LocaleZhCN; format = "G " + parseFormat(s.substring((message("zh", "AD") + " ").length(), len)); } else if (s.startsWith(message("zh", "AD"))) { locale = Languages.LocaleZhCN; format = "G" + parseFormat(s.substring((message("zh", "AD")).length(), len)); } else if (s.startsWith(message("en", "BC") + " ")) { locale = Languages.LocaleEn; format = "G " + parseFormat(s.substring((message("en", "BC") + " ").length(), len)); } else if (s.startsWith(message("en", "BC"))) { locale = Languages.LocaleEn; format = "G" + parseFormat(s.substring((message("en", "BC")).length(), len)); } else if (s.startsWith(message("en", "AD") + " ")) { locale = Languages.LocaleEn; format = "G " + parseFormat(s.substring((message("en", "AD") + " ").length(), len)); } else if (s.startsWith(message("en", "AD"))) { locale = Languages.LocaleEn; format = "G" + parseFormat(s.substring((message("en", "AD")).length(), len)); } else if (s.endsWith(" " + message("zh", "BC"))) { locale = Languages.LocaleZhCN; format = parseFormat(s.substring(0, len - (" " + message("zh", "BC")).length())) + " G"; } else if (s.endsWith(message("zh", "BC"))) { locale = Languages.LocaleZhCN; format = parseFormat(s.substring(0, len - message("zh", "BC").length())) + "G"; } else if (s.endsWith(" " + message("zh", "AD"))) { locale = Languages.LocaleZhCN; format = parseFormat(s.substring(0, len - (" " + message("zh", "AD")).length())) + " G"; } else if (s.endsWith(message("zh", "AD"))) { locale = Languages.LocaleZhCN; format = parseFormat(s.substring(0, len - message("zh", "AD").length())) + "G"; } else if (s.endsWith(" " + message("en", "BC"))) { locale = Languages.LocaleEn; format = parseFormat(s.substring(0, len - (" " + message("en", "BC")).length())) + " G"; } else if (s.endsWith(message("en", "BC"))) { locale = Languages.LocaleEn; format = parseFormat(s.substring(0, len - message("en", "BC").length())) + "G"; } else if (s.endsWith(" " + message("en", "AD"))) { locale = Languages.LocaleEn; format = parseFormat(s.substring(0, len - (" " + message("en", "AD")).length())) + " G"; } else if (s.endsWith(message("en", "AD"))) { locale = Languages.LocaleEn; format = parseFormat(s.substring(0, len - message("en", "AD").length())) + "G"; } else { locale = Languages.locale(); format = parseFormat(s); } Date d = encodeDate(s, format, locale, century); return d; } public static Date encodeDate(String strDate) { return encodeDate(strDate, 0); } public static Date encodeDate(String strDate, Locale locale, int century) { return encodeDate(strDate, parseFormat(strDate), locale, century); } public static Date encodeDate(String strDate, String format) { return encodeDate(strDate, format, Locale.getDefault(), 0); } public static Date encodeDate(String strDate, String format, int century) { return encodeDate(strDate, format, Locale.getDefault(), century); } // century. 0: not fix -1:fix as default others:fix as value public static Date encodeDate(String strDate, String format, Locale locale, int century) { if (strDate == null || strDate.isEmpty() || format == null || format.isEmpty()) { return null; } // MyBoxLog.debug(strDate + " " + format + " " + locale + " " + century); try { SimpleDateFormat formatter = new SimpleDateFormat(format, locale); if (century >= 0) { formatter.set2DigitYearStart(new SimpleDateFormat("yyyy") .parse(century > 0 ? century + "" : "0000")); } return formatter.parse(strDate, new ParsePosition(0)); } catch (Exception e) { try { return new Date(Long.parseLong(strDate)); } catch (Exception ex) { return null; } } } public static Date thisMonth() { return DateTools.encodeDate(nowString().substring(0, 7), "yyyy-MM"); } public static Date localDateToDate(LocalDate localDate) { try { ZoneId zoneId = ZoneId.systemDefault(); ZonedDateTime zdt = localDate.atStartOfDay(zoneId); Date date = Date.from(zdt.toInstant()); return date; } catch (Exception e) { return null; } } public static LocalDate dateToLocalDate(Date date) { try { Instant instant = date.toInstant(); ZoneId zoneId = ZoneId.systemDefault(); LocalDate localDate = instant.atZone(zoneId).toLocalDate(); return localDate; } catch (Exception e) { return null; } } public static LocalDate stringToLocalDate(String strDate) { return dateToLocalDate(encodeDate(strDate)); } /* return string */ public static String nowFileString() { return datetimeToString(new Date(), TimeFormats.Datetime2); } public static String nowString() { return datetimeToString(new Date()); } public static String nowString3() { return datetimeToString(new Date(), TimeFormats.Datetime3); } public static String nowDate() { return datetimeToString(new Date(), TimeFormats.Date); } public static String textEra(Era era) { if (era == null || era.getValue() == AppValues.InvalidLong) { return ""; } return textEra(era.getValue(), era.getFormat()); } public static String textEra(String value) { return textEra(encodeDate(value)); } public static String textEra(Date value) { return value == null ? null : textEra(value.getTime()); } public static String textEra(long value) { if (value == AppValues.InvalidLong) { return ""; } return textEra(value, null); } public static String textEra(long value, String format) { if (value == AppValues.InvalidLong) { return ""; } return datetimeToString(new Date(value), format, Languages.locale(), null); } public static String localDateToString(LocalDate localDate) { return dateToString(localDateToDate(localDate)); } public static String datetimeToString(long dvalue) { if (dvalue == AppValues.InvalidLong) { return null; } return datetimeToString(new Date(dvalue)); } public static String datetimeToString(Date theDate) { return datetimeToString(theDate, null, null, null); } public static String datetimeToString(long theDate, String format) { if (theDate == AppValues.InvalidLong) { return null; } return datetimeToString(new Date(theDate), format); } public static String datetimeToString(Date theDate, String format) { return datetimeToString(theDate, format, null, null); } public static String datetimeToString(Date theDate, String inFormat, Locale inLocale, TimeZone inZone) { if (theDate == null) { return null; } String format = inFormat; if (format == null || format.isBlank()) { format = isBC(theDate.getTime()) ? bcFormat() : TimeFormats.Datetime; } Locale locale = inLocale; if (locale == null) { locale = Languages.locale(); } TimeZone zone = inZone; if (zone == null) { zone = getTimeZone(); } SimpleDateFormat formatter = new SimpleDateFormat(format, locale); formatter.setTimeZone(zone); String dateString = formatter.format(theDate); return dateString; } public static String dateToString(Date theDate) { return datetimeToString(theDate, TimeFormats.Date); } public static String dateToMonthString(Date theDate) { return datetimeToString(theDate).substring(0, 7); } public static String dateToYearString(Date theDate) { return datetimeToString(theDate).substring(0, 4); } public static String datetimeMsDuration(long milliseconds) { String f = milliseconds < 0 ? "-" : ""; long ms = Math.abs(milliseconds); String date = dateDuration(ms); String timeMs = timeMsDuration(ms); return f + (date.isBlank() ? timeMs : date + " " + timeMs); } public static String dateDuration(long milliseconds) { String f = milliseconds < 0 ? "-" : ""; long ms = Math.abs(milliseconds); int days = (int) (ms / (24 * 3600 * 1000)); int years = days / 365; days = days % 365; int month = days / 12; days = days % 12; return f + dateDuration(years, month, days); } public static String dateDuration(Date time1, Date time2) { Period period = period(time1, time2); if (period == null) { return null; } String date = dateDuration(period.getYears(), period.getMonths(), period.getDays()); return (period.isNegative() ? "-" : "") + date; } public static String dateDuration(int years, int months, int days) { String date; if (years > 0) { if (months > 0) { if (days > 0) { date = MessageFormat.format(message("DurationYearsMonthsDays"), years, months, days); } else { date = MessageFormat.format(message("DurationYearsMonths"), years, months); } } else if (days > 0) { date = MessageFormat.format(message("DurationYearsDays"), years, days); } else { date = MessageFormat.format(message("DurationYears"), years); } } else { if (months > 0) { if (days > 0) { date = MessageFormat.format(message("DurationMonthsDays"), months, days); } else { date = MessageFormat.format(message("DurationMonths"), months); } } else if (days > 0) { date = MessageFormat.format(message("DurationDays"), days); } else { date = ""; } } return date; } public static String yearsMonthsDuration(Date time1, Date time2) { Period period = period(time1, time2); String date; if (period.getYears() > 0) { date = MessageFormat.format(message("DurationYearsMonths"), period.getYears(), period.getMonths()); } else if (period.getMonths() > 0) { date = MessageFormat.format(message("DurationMonths"), period.getYears(), period.getMonths()); } else { date = ""; } return (period.isNegative() ? "-" : "") + date; } public static String yearsDuration(Date time1, Date time2) { Period period = period(time1, time2); String date; if (period.getYears() > 0) { date = MessageFormat.format(message("DurationYears"), period.getYears()); } else { date = ""; } return (period.isNegative() ? "-" : "") + date; } public static String timeDuration(Date time1, Date time2) { Duration duration = duration(time1, time2); return (duration.isNegative() ? "-" : "") + timeDuration(duration.getSeconds() * 1000); } public static String msDuration(Date time1, Date time2) { return timeMsDuration(time1.getTime() - time2.getTime()); } public static String datetimeDuration(Date time1, Date time2) { return dateDuration(time1, time2) + " " + timeDuration(Math.abs(time1.getTime() - time2.getTime())); } public static String datetimeZoneDuration(Date time1, Date time2) { return dateDuration(time1, time2) + " " + timeDuration(Math.abs(time1.getTime() - time2.getTime())) + " " + TimeZone.getDefault().getDisplayName(); } public static String datetimeMsDuration(Date time1, Date time2) { return dateDuration(time1, time2) + " " + timeMsDuration(Math.abs(time1.getTime() - time2.getTime())); } public static String datetimeMsZoneDuration(Date time1, Date time2) { return dateDuration(time1, time2) + " " + timeMsDuration(Math.abs(time1.getTime() - time2.getTime())) + " " + TimeZone.getDefault().getDisplayName(); } public static String timeDuration(long milliseconds) { long seconds = milliseconds / 1000; String f = seconds < 0 ? "-" : ""; long s = Math.abs(seconds); if (s < 60) { return f + String.format("00:%02d", s); } long minutes = s / 60; s = s % 60; if (minutes < 60) { return f + String.format("%02d:%02d", minutes, s); } long hours = minutes / 60; minutes = minutes % 60; return f + String.format("%02d:%02d:%02d", hours, minutes, s); } public static String timeMsDuration(long milliseconds) { String f = milliseconds < 0 ? "-" : ""; long ms = Math.abs(milliseconds); if (ms < 1000) { return f + String.format("00:00:0.%03d", ms); } long seconds = ms / 1000; ms = ms % 1000; if (seconds < 60) { return f + String.format("00:%02d.%03d", seconds, ms); } long minutes = seconds / 60; seconds = seconds % 60; if (minutes < 60) { return f + String.format("%02d:%02d.%03d", minutes, seconds, ms); } long hours = minutes / 60; minutes = minutes % 60; return f + String.format("%02d:%02d:%02d.%03d", hours, minutes, seconds, ms); } public static String duration(Date time1, Date time2, String format) { if (time1 == null || time2 == null) { return null; } String dFormat = format; if (dFormat == null) { dFormat = TimeFormats.Datetime; } switch (dFormat) { case TimeFormats.Date: return dateDuration(time1, time2); case TimeFormats.Month: return yearsMonthsDuration(time1, time2); case TimeFormats.Year: return yearsDuration(time1, time2); case TimeFormats.Time: return DateTools.timeDuration(time1, time2); case TimeFormats.TimeMs: return msDuration(time1, time2); case TimeFormats.DatetimeMs: return datetimeMsDuration(time1, time2); case TimeFormats.DatetimeZone: return datetimeZoneDuration(time1, time2); case TimeFormats.DatetimeMsZone: return datetimeMsZoneDuration(time1, time2); default: return datetimeDuration(time1, time2); } } public static String randomDateString(Random r, String format) { if (r == null) { r = new Random(); } return datetimeToString(randomTime(r), format); } /* others */ public static void printFormats() { MyBoxLog.console(DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, Locale.ENGLISH).format(new Date())); MyBoxLog.console(DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, Locale.CHINESE).format(new Date())); MyBoxLog.console(DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM, Locale.ENGLISH).format(new Date())); MyBoxLog.console(DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM, Locale.CHINESE).format(new Date())); MyBoxLog.console(DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, Locale.ENGLISH).format(new Date())); MyBoxLog.console(DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, Locale.CHINESE).format(new Date())); MyBoxLog.console(DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL, Locale.ENGLISH).format(new Date())); MyBoxLog.console(DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL, Locale.CHINESE).format(new Date())); } public static TimeZone getTimeZone() { return TimeZone.getDefault(); } public static Duration duration(Date time1, Date time2) { if (time1 == null || time2 == null) { return null; } Instant instant1 = Instant.ofEpochMilli​(time1.getTime()); Instant instant2 = Instant.ofEpochMilli​(time2.getTime()); return Duration.between(instant1, instant2); } public static Period period(Date time1, Date time2) { if (time1 == null || time2 == null) { return null; } LocalDate localDate1 = LocalDate.ofEpochDay(time1.getTime() / (24 * 3600000)); LocalDate localDate2 = LocalDate.ofEpochDay(time2.getTime() / (24 * 3600000)); return Period.between(localDate1, localDate2); } public static long zeroYear() { Calendar ca = Calendar.getInstance(); ca.set(0, 0, 1, 0, 0, 0); return ca.getTime().getTime(); } public static long randomTime(Random r) { if (r == null) { r = new Random(); } return r.nextLong(new Date().getTime() * 100); } public static String bcFormat() { return TimeFormats.Datetime + " G"; } public static boolean isBC(long value) { if (value == AppValues.InvalidLong) { return false; } String s = datetimeToString(new Date(value), bcFormat(), Languages.LocaleEn, null); return s.contains("BC"); } public static boolean isWeekend(long time) { try { Calendar cal = Calendar.getInstance(); cal.setTime(new Date(time)); if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY || cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) { return true; } else { return false; } } catch (Exception e) { return false; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/tools/IntTools.java
alpha/MyBox/src/main/java/mara/mybox/tools/IntTools.java
package mara.mybox.tools; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Random; import mara.mybox.value.AppValues; /** * @Author Mara * @CreateDate 2019-5-28 15:28:13 * @Version 1.0 * @Description * @License Apache License Version 2.0 */ public class IntTools { public static boolean invalidInt(Integer value) { return value == null || value == AppValues.InvalidInteger; } public static int compare(String s1, String s2, boolean desc) { float f1, f2; try { f1 = Integer.parseInt(s1.replaceAll(",", "")); } catch (Exception e) { f1 = Float.NaN; } try { f2 = Integer.parseInt(s2.replaceAll(",", "")); } catch (Exception e) { f2 = Float.NaN; } return FloatTools.compare(f1, f2, desc); } public static int random(int max) { return new Random().nextInt(max); } public static int random(Random r, int max, boolean nonNegative) { if (r == null) { r = new Random(); } int sign = nonNegative ? 1 : r.nextInt(2); int i = r.nextInt(max); return sign == 1 ? i : -i; } public static String format(int v, String format, int scale) { if (invalidInt(v)) { return null; } return NumberTools.format(v, format, scale); } public static int[] sortArray(int[] numbers) { List<Integer> list = new ArrayList<>(); for (int i : numbers) { list.add(i); } Collections.sort(list, new Comparator<Integer>() { @Override public int compare(Integer p1, Integer p2) { if (p1 > p2) { return 1; } else if (p1 < p2) { return -1; } else { return 0; } } }); int[] sorted = new int[numbers.length]; for (int i = 0; i < list.size(); ++i) { sorted[i] = list.get(i); } return sorted; } public static void sortList(List<Integer> numbers) { Collections.sort(numbers, new Comparator<Integer>() { @Override public int compare(Integer p1, Integer p2) { return p1 - p2; } }); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/tools/DoubleTools.java
alpha/MyBox/src/main/java/mara/mybox/tools/DoubleTools.java
package mara.mybox.tools; import java.math.RoundingMode; import java.text.NumberFormat; import java.util.Random; import mara.mybox.db.data.ColumnDefinition.InvalidAs; import mara.mybox.dev.MyBoxLog; import mara.mybox.value.AppValues; import static mara.mybox.value.Languages.message; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2018-6-11 17:43:53 * @License Apache License Version 2.0 */ public class DoubleTools { public static NumberFormat numberFormat; public static boolean invalidDouble(Double value) { return value == null || Double.isNaN(value) || Double.isInfinite(value) || value == AppValues.InvalidDouble; } public static double value(InvalidAs invalidAs) { if (invalidAs == InvalidAs.Zero) { return 0d; } else { return Double.NaN; } } public static String scaleString(String string, InvalidAs invalidAs, int scale) { try { if (scale < 0) { return string; } double d = toDouble(string, invalidAs); return scaleString(d, scale); } catch (Exception e) { return string; } } public static double scale(String string, InvalidAs invalidAs, int scale) { try { double d = toDouble(string, invalidAs); return scale(d, scale); } catch (Exception e) { return value(invalidAs); } } public static double toDouble(String string, InvalidAs invalidAs) { try { double d = Double.parseDouble(string.replaceAll(",", "")); if (invalidDouble(d)) { if (StringTools.isTrue(string)) { return 1; } else if (StringTools.isFalse(string)) { return 0; } return value(invalidAs); } else { return d; } } catch (Exception e) { return value(invalidAs); } } public static double[] toDouble(String[] sVector, InvalidAs invalidAs) { try { if (sVector == null) { return null; } int len = sVector.length; double[] doubleVector = new double[len]; for (int i = 0; i < len; i++) { doubleVector[i] = DoubleTools.toDouble(sVector[i], invalidAs); } return doubleVector; } catch (Exception e) { return null; } } public static double[][] toDouble(String[][] sMatrix, InvalidAs invalidAs) { try { if (sMatrix == null) { return null; } int rsize = sMatrix.length, csize = sMatrix[0].length; double[][] doubleMatrix = new double[rsize][csize]; for (int i = 0; i < rsize; i++) { for (int j = 0; j < csize; j++) { doubleMatrix[i][j] = DoubleTools.toDouble(sMatrix[i][j], invalidAs); } } return doubleMatrix; } catch (Exception e) { return null; } } public static String percentage(double data, double total) { return percentage(data, total, 2); } public static String percentage(double data, double total, int scale) { try { if (total == 0) { return message("Invalid"); } return scale(data * 100 / total, scale) + ""; } catch (Exception e) { return data + ""; } } public static int compare(String s1, String s2, boolean desc) { return compare(toDouble(s1, InvalidAs.Empty), toDouble(s2, InvalidAs.Empty), desc); } // invalid values are counted as smaller public static int compare(double d1, double d2, boolean desc) { if (Double.isNaN(d1)) { if (Double.isNaN(d2)) { return 0; } else { return desc ? 1 : -1; } } else { if (Double.isNaN(d2)) { return desc ? -1 : 1; } else { double diff = d1 - d2; if (diff == 0) { return 0; } else if (diff > 0) { return desc ? -1 : 1; } else { return desc ? 1 : -1; } } } } /* https://stackoverflow.com/questions/322749/retain-precision-with-double-in-java "Do not waste your efford using BigDecimal. In 99.99999% cases you don't need it" "BigDecimal is much slower than double" "The solution depends on what exactly your problem is: - If it's that you just don't like seeing all those noise digits, then fix your string formatting. Don't display more than 15 significant digits (or 7 for float). - If it's that the inexactness of your numbers is breaking things like "if" statements, then you should write if (abs(x - 7.3) < TOLERANCE) instead of if (x == 7.3). - If you're working with money, then what you probably really want is decimal fixed point. Store an integer number of cents or whatever the smallest unit of your currency is. - (VERY UNLIKELY) If you need more than 53 significant bits (15-16 significant digits) of precision, then use a high-precision floating-point type, like BigDecimal." */ public static double scale3(double invalue) { return DoubleTools.scale(invalue, 3); } public static double scale2(double invalue) { return DoubleTools.scale(invalue, 2); } public static double scale6(double invalue) { return DoubleTools.scale(invalue, 6); } public static double imageScale(double invalue) { return DoubleTools.scale(invalue, UserConfig.imageScale()); } public static double scale(double v, int scale) { try { if (scale < 0) { return v; } return Double.parseDouble(scaleString(v, scale)); } catch (Exception e) { return v; } } public static NumberFormat numberFormat() { numberFormat = NumberFormat.getInstance(); numberFormat.setMinimumFractionDigits(0); numberFormat.setGroupingUsed(false); numberFormat.setRoundingMode(RoundingMode.HALF_UP); return numberFormat; } public static String scaleString(double v, int scale) { try { if (scale < 0) { return v + ""; } if (numberFormat == null) { numberFormat(); } numberFormat.setMaximumFractionDigits(scale); return numberFormat.format(v); } catch (Exception e) { MyBoxLog.console(e); return v + ""; } } public static double random(Random r, int max, boolean nonNegative) { if (r == null) { r = new Random(); } int sign = nonNegative ? 1 : r.nextInt(2); sign = sign == 1 ? 1 : -1; double d = r.nextDouble(); int i = max > 0 ? r.nextInt(max) : 0; return sign == 1 ? i + d : -(i + d); } public static String format(double v, String format, int scale) { if (invalidDouble(v)) { return null; } return NumberTools.format(v, format, scale); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/tools/SystemTools.java
alpha/MyBox/src/main/java/mara/mybox/tools/SystemTools.java
package mara.mybox.tools; import java.awt.MouseInfo; import java.awt.Point; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import mara.mybox.dev.MyBoxLog; /** * @Author Mara * @CreateDate 2019-1-3 20:51:26 * @License Apache License Version 2.0 */ public class SystemTools { public static float jreVersion() { return Float.parseFloat(System.getProperty("java.version").substring(0, 3)); } public static String os() { String os = System.getProperty("os.name").toLowerCase(); if (os.contains("windows")) { return "win"; } else if (os.contains("linux")) { return "linux"; } else if (os.contains("mac")) { return "mac"; } else { return "other"; } } public static boolean isLinux() { return os().contains("linux"); } public static boolean isMac() { return os().contains("mac"); } public static boolean isWindows() { return os().contains("win"); } public static void currentThread() { Thread thread = Thread.currentThread(); MyBoxLog.debug(thread.threadId() + " " + thread.getName() + " " + thread.getState()); for (StackTraceElement element : thread.getStackTrace()) { MyBoxLog.debug(element.toString()); } } public static long getAvaliableMemory() { Runtime r = Runtime.getRuntime(); return r.maxMemory() - (r.totalMemory() - r.freeMemory()); } public static long getAvaliableMemoryMB() { return getAvaliableMemory() / (1024 * 1024L); } public static long freeBytes() { return getAvaliableMemory() - 200 * 1024 * 1024; } public static Point getMousePoint() { return MouseInfo.getPointerInfo().getLocation(); } public static String IccProfilePath() { String os = System.getProperty("os.name").toLowerCase(); if (os.contains("windows")) { return "C:\\Windows\\System32\\spool\\drivers\\color"; } else if (os.contains("linux")) { // /usr/share/color/icc // /usr/local/share/color/icc // /home/USER_NAME/.color/icc return "/usr/share/color/icc"; } else if (os.contains("mac")) { // /Library/ColorSync/Profiles // /Users/USER_NAME/Library/ColorSync/Profile return "/Library/ColorSync/Profiles"; } else { return null; } } // https://bugs.openjdk.org/browse/JDK-8266075 // https://docs.oracle.com/en/java/javase/18/docs/api/java.base/java/lang/Process.html#inputReader() public static Charset ConsoleCharset() { try { return Charset.forName(System.getProperty("native.encoding")); } catch (Exception e) { return Charset.defaultCharset(); } } public static String run(String cmd) { try { if (cmd == null || cmd.isBlank()) { return null; } List<String> p = new ArrayList<>(); p.addAll(Arrays.asList(StringTools.splitBySpace(cmd))); return run(p, Charset.defaultCharset()); } catch (Exception e) { return e.toString(); } } public static String run(List<String> command) { return run(command, Charset.defaultCharset()); } public static String run(List<String> command, Charset charset) { try { if (command == null || command.isEmpty()) { return null; } ProcessBuilder pb = new ProcessBuilder(command).redirectErrorStream(true); final Process process = pb.start(); StringBuilder s = new StringBuilder(); try (BufferedReader inReader = process.inputReader(charset)) { String line; while ((line = inReader.readLine()) != null) { s.append(line).append("\n"); } } process.waitFor(); return s.toString(); } catch (Exception e) { return e.toString(); } } public static File runToFile(List<String> command, Charset charset, File file) { try { if (command == null || command.isEmpty() || file == null) { return null; } ProcessBuilder pb = new ProcessBuilder(command).redirectErrorStream(true); final Process process = pb.start(); try (BufferedReader inReader = process.inputReader(charset); BufferedWriter writer = new BufferedWriter(new FileWriter(file, Charset.forName("UTF-8"), false))) { String line; while ((line = inReader.readLine()) != null) { writer.write(line + "\n"); } writer.flush(); } process.waitFor(); return file; } catch (Exception e) { MyBoxLog.error(e); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/tools/MessageDigestTools.java
alpha/MyBox/src/main/java/mara/mybox/tools/MessageDigestTools.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.tools; import java.awt.image.BufferedImage; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.security.MessageDigest; import java.security.Provider; import java.security.Security; import mara.mybox.image.tools.BufferedImageTools; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.value.AppValues; /** * * @author mara */ public class MessageDigestTools { public static byte[] SHA256(byte[] bytes) { return messageDigest(bytes, "SHA-256"); } public static byte[] SHA256(FxTask task, File file) { return messageDigest(task, file, "SHA-256"); } public static byte[] SHA256(FxTask task, BufferedImage image) { return messageDigest(BufferedImageTools.bytes(task, image, "png"), "SHA-256"); } public static byte[] SHA1(byte[] bytes) { return messageDigest(bytes, "SHA-1"); } public static byte[] SHA1(FxTask task, File file) { return messageDigest(task, file, "SHA-1"); } public static byte[] SHA1(FxTask task, BufferedImage image) { return messageDigest(BufferedImageTools.bytes(task, image, "png"), "SHA-1"); } public static void SignatureAlgorithms() { try { for (Provider provider : Security.getProviders()) { for (Provider.Service service : provider.getServices()) { if (service.getType().equals("Signature")) { MyBoxLog.debug(service.getAlgorithm()); } } } } catch (Exception e) { MyBoxLog.debug(e); } } public static byte[] MD5(byte[] bytes) { return messageDigest(bytes, "MD5"); } public static byte[] MD5(FxTask task, File file) { return messageDigest(task, file, "MD5"); } public static byte[] MD5(FxTask task, BufferedImage image) { return messageDigest(BufferedImageTools.bytes(task, image, "png"), "MD5"); } // https://docs.oracle.com/javase/10/docs/specs/security/standard-names.html#messagedigest-algorithms public static byte[] messageDigest(byte[] bytes, String algorithm) { try { if (bytes == null || algorithm == null) { return null; } MessageDigest md = MessageDigest.getInstance(algorithm); byte[] digest = md.digest(bytes); return digest; } catch (Exception e) { MyBoxLog.debug(e); return null; } } public static byte[] messageDigest(FxTask task, File file, String algorithm) { try { MessageDigest md = MessageDigest.getInstance(algorithm); try (final BufferedInputStream in = new BufferedInputStream(new FileInputStream(file))) { byte[] buf = new byte[AppValues.IOBufferLength]; int len; while ((len = in.read(buf)) > 0) { if (task != null && !task.isWorking()) { return null; } md.update(buf, 0, len); } } byte[] digest = md.digest(); return digest; } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { 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/alpha/MyBox/src/main/java/mara/mybox/tools/FileCopyTools.java
alpha/MyBox/src/main/java/mara/mybox/tools/FileCopyTools.java
package mara.mybox.tools; import java.io.File; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import mara.mybox.data.FileSynchronizeAttributes; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2021-8-1 * @License Apache License Version 2.0 */ public class FileCopyTools { public static boolean copyFile(String sourceFile, String targetFile) { return copyFile(new File(sourceFile), new File(targetFile)); } public static boolean copyFile(File sourceFile, File targetFile) { return copyFile(sourceFile, targetFile, false, true); } public static boolean copyFile(File sourceFile, File targetFile, boolean isCanReplace, boolean isCopyAttrinutes) { try { if (sourceFile == null || !sourceFile.isFile() || !sourceFile.exists()) { return false; } if (isCanReplace) { if (isCopyAttrinutes) { Files.copy(Paths.get(sourceFile.getAbsolutePath()), Paths.get(targetFile.getAbsolutePath()), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES); } else { Files.copy(Paths.get(sourceFile.getAbsolutePath()), Paths.get(targetFile.getAbsolutePath()), StandardCopyOption.REPLACE_EXISTING); } } else { if (isCopyAttrinutes) { Files.copy(Paths.get(sourceFile.getAbsolutePath()), Paths.get(targetFile.getAbsolutePath()), StandardCopyOption.COPY_ATTRIBUTES); } else { Files.copy(Paths.get(sourceFile.getAbsolutePath()), Paths.get(targetFile.getAbsolutePath())); } } return true; } catch (Exception e) { MyBoxLog.error(e + "\n" + "Source:" + sourceFile + "\n" + "Target:" + targetFile); return false; } } public static boolean copyFile(File sourceFile, File targetFile, FileSynchronizeAttributes attr) { if (attr == null) { attr = new FileSynchronizeAttributes(); } return copyFile(sourceFile, targetFile, attr.isCanReplace(), attr.isCopyAttrinutes()); } public static FileSynchronizeAttributes copyWholeDirectory(FxTask task, File sourcePath, File targetPath) { FileSynchronizeAttributes attr = new FileSynchronizeAttributes(); copyWholeDirectory(task, sourcePath, targetPath, attr); return attr; } public static boolean copyWholeDirectory(FxTask task, File sourcePath, File targetPath, FileSynchronizeAttributes attr) { return copyWholeDirectory(task, sourcePath, targetPath, attr, true); } public static boolean copyWholeDirectory(FxTask task, File sourcePath, File targetPath, FileSynchronizeAttributes attr, boolean clearTarget) { try { if (sourcePath == null || !sourcePath.exists() || !sourcePath.isDirectory()) { return false; } if (FileTools.isEqualOrSubPath(targetPath.getAbsolutePath(), sourcePath.getAbsolutePath())) { MyBoxLog.error(message("TreeTargetComments")); return false; } if (attr == null) { attr = new FileSynchronizeAttributes(); } if (targetPath.exists()) { if (clearTarget && !FileDeleteTools.deleteDir(task, targetPath)) { return false; } } else { targetPath.mkdirs(); } File[] files = sourcePath.listFiles(); if (files == null) { return false; } for (File file : files) { if (task != null && !task.isWorking()) { return false; } File targetFile = new File(targetPath + File.separator + file.getName()); if (file.isFile()) { if (copyFile(file, targetFile, attr)) { attr.setCopiedFilesNumber(attr.getCopiedFilesNumber() + 1); } else if (!attr.isContinueWhenError()) { return false; } } else if (file.isDirectory()) { if (copyWholeDirectory(task, file, targetFile, attr, clearTarget)) { attr.setCopiedDirectoriesNumber(attr.getCopiedDirectoriesNumber() + 1); } else if (!attr.isContinueWhenError()) { return false; } } } 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/alpha/MyBox/src/main/java/mara/mybox/tools/FileTools.java
alpha/MyBox/src/main/java/mara/mybox/tools/FileTools.java
package mara.mybox.tools; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.attribute.BasicFileAttributes; import java.nio.file.attribute.FileTime; import java.util.Arrays; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.value.FileExtensions; import static mara.mybox.value.Languages.message; import org.apache.commons.io.FileUtils; /** * @Author mara * @CreateDate 2018-6-2 11:01:45 * @Description */ public class FileTools { public static long createTime(final String filename) { try { FileTime t = Files.readAttributes(Paths.get(filename), BasicFileAttributes.class).creationTime(); return t.toMillis(); } catch (Exception e) { return -1; } } public static long createTime(File file) { if (file == null || !file.exists()) { return -1; } return createTime(file.getAbsolutePath()); } public static String showFileSize(long size) { if (size < 1024) { return size + " B"; } else { double kb = size * 1.0d / 1024; if (kb < 1024) { return DoubleTools.scale3(kb) + " KB"; } else { double mb = kb / 1024; if (mb < 1024) { return DoubleTools.scale3(mb) + " MB"; } else { double gb = mb / 1024; return DoubleTools.scale3(gb) + " GB"; } } } } public static String fileInformation(File file) { if (file == null) { return null; } StringBuilder s = new StringBuilder(); s.append(message("FileName")) .append(": ").append(file.getAbsolutePath()).append("\n"); s.append(message("FileSize")) .append(": ").append(FileTools.showFileSize(file.length())).append("\n"); s.append(message("FileModifyTime")) .append(": ").append(DateTools.datetimeToString(file.lastModified())); return s.toString(); } public static boolean isSupportedImage(File file) { if (file == null || !file.isFile()) { return false; } String suffix = FileNameTools.ext(file.getName()).toLowerCase(); return FileExtensions.SupportedImages.contains(suffix); } public static boolean rename(File sourceFile, File targetFile) { try { if (sourceFile == null || !sourceFile.exists() || !sourceFile.isFile() || targetFile == null || targetFile.exists() || sourceFile.equals(targetFile)) { return false; } FileUtils.moveFile(sourceFile, targetFile); return true; } catch (Exception e) { MyBoxLog.error(e, sourceFile + " " + targetFile); return false; } } public static boolean override(File sourceFile, File targetFile) { return override(sourceFile, targetFile, false); } public static boolean override(File sourceFile, File targetFile, boolean noEmpty) { try { if (sourceFile == null || !sourceFile.exists() || !sourceFile.isFile() || targetFile == null || sourceFile.equals(targetFile)) { return false; } if (noEmpty && sourceFile.length() == 0) { return false; } synchronized (targetFile) { if (!FileDeleteTools.delete(targetFile)) { return false; } System.gc(); FileUtils.moveFile(sourceFile, targetFile); } // targetFile.getParentFile().mkdirs(); // Files.move(sourceFile.toPath(), targetFile.toPath(), // StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); return true; } catch (Exception e) { MyBoxLog.error(e, sourceFile + " " + targetFile); return false; } } // Return files number and total length public static long[] countDirectorySize(File dir, boolean countSubdir) { long[] size = new long[2]; try { if (dir == null) { return size; } if (dir.isFile()) { size[0] = 1; size[1] = dir.length(); } else if (dir.isDirectory()) { File[] files = dir.listFiles(); size[0] = 0; size[1] = 0; if (files != null) { for (File file : files) { if (file.isFile()) { size[0]++; size[1] += file.length(); } else if (file.isDirectory()) { if (countSubdir) { long[] fsize = countDirectorySize(file, countSubdir); size[0] += fsize[0]; size[1] += fsize[1]; } } } } } } catch (Exception e) { MyBoxLog.debug(e); } return size; } public static boolean same(FxTask task, File file1, File file2) { return Arrays.equals(MessageDigestTools.SHA1(task, file1), MessageDigestTools.SHA1(task, file2)); } public static int bufSize(File file, int memPart) { Runtime r = Runtime.getRuntime(); long availableMem = r.maxMemory() - (r.totalMemory() - r.freeMemory()); long min = Math.min(file.length(), availableMem / memPart); return min > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) min; } public static boolean hasData(File file) { return file != null && file.exists() && file.isFile() && file.length() > 0; } public static boolean isEqualOrSubPath(String path1, String path2) { if (path1 == null || path1.isBlank() || path2 == null || path2.isBlank()) { return false; } String name1 = path1.endsWith(File.separator) ? path1 : (path1 + File.separator); String name2 = path1.endsWith(File.separator) ? path2 : (path2 + File.separator); return name1.equals(name2) || name1.startsWith(name2); } public static File removeBOM(FxTask task, File file) { if (!hasData(file)) { return file; } String bom = null; try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file))) { byte[] header = new byte[4]; int readLen; if ((readLen = inputStream.read(header, 0, 4)) > 0) { header = ByteTools.subBytes(header, 0, readLen); bom = TextTools.checkCharsetByBom(header); if (bom == null) { return file; } } } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e); } return null; } File tmpFile = FileTmpTools.getTempFile(); try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file)); BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(tmpFile))) { int bomSize = TextTools.bomSize(bom); inputStream.skip(bomSize); int readLen; byte[] buf = new byte[bufSize(file, 16)]; while ((readLen = inputStream.read(buf)) > 0) { if (task != null && !task.isWorking()) { return null; } outputStream.write(buf, 0, readLen); } outputStream.flush(); } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e); } return null; } return tmpFile; } public static File javaIOTmpPath() { return new File(System.getProperty("java.io.tmpdir")); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/tools/BarcodeTools.java
alpha/MyBox/src/main/java/mara/mybox/tools/BarcodeTools.java
package mara.mybox.tools; import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; import com.google.zxing.MultiFormatWriter; import com.google.zxing.client.j2se.MatrixToImageWriter; import com.google.zxing.common.BitMatrix; import com.google.zxing.pdf417.encoder.Compaction; import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; import java.awt.AlphaComposite; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import java.util.HashMap; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.image.file.ImageFileReaders; import mara.mybox.value.AppVariables; import org.krysalis.barcode4j.ChecksumMode; import org.krysalis.barcode4j.HumanReadablePlacement; import org.krysalis.barcode4j.impl.AbstractBarcodeBean; import org.krysalis.barcode4j.impl.codabar.CodabarBean; import org.krysalis.barcode4j.impl.code128.Code128Bean; import org.krysalis.barcode4j.impl.code39.Code39Bean; import org.krysalis.barcode4j.impl.datamatrix.DataMatrixBean; import org.krysalis.barcode4j.impl.fourstate.RoyalMailCBCBean; import org.krysalis.barcode4j.impl.int2of5.Interleaved2Of5Bean; import org.krysalis.barcode4j.impl.pdf417.PDF417Bean; import org.krysalis.barcode4j.impl.postnet.POSTNETBean; import org.krysalis.barcode4j.impl.upcean.EAN13Bean; import org.krysalis.barcode4j.impl.upcean.EAN8Bean; import org.krysalis.barcode4j.impl.upcean.UPCABean; import org.krysalis.barcode4j.impl.upcean.UPCEBean; import org.krysalis.barcode4j.output.bitmap.BitmapCanvasProvider; import thridparty.QRCodeWriter; /** * @Author Mara * @CreateDate 2019-9-24 * @Description * @License Apache License Version 2.0 */ public class BarcodeTools { public enum BarcodeType { QR_Code, PDF_417, DataMatrix, Code39, Code128, Codabar, Interleaved2Of5, ITF_14, POSTNET, EAN13, EAN8, EAN_128, UPCA, UPCE, Royal_Mail_Customer_Barcode, USPS_Intelligent_Mail } public static double defaultModuleWidth(BarcodeType type) { switch (type) { case PDF_417: return new PDF417Bean().getModuleWidth(); case Code39: return new Code39Bean().getModuleWidth(); case Code128: return new Code128Bean().getModuleWidth(); case Codabar: return new CodabarBean().getModuleWidth(); case Interleaved2Of5: return new Interleaved2Of5Bean().getModuleWidth(); case POSTNET: return new POSTNETBean().getModuleWidth(); case EAN13: return new EAN13Bean().getModuleWidth(); case EAN8: return new EAN8Bean().getModuleWidth(); case UPCA: return new UPCABean().getModuleWidth(); case UPCE: return new UPCEBean().getModuleWidth(); case Royal_Mail_Customer_Barcode: return new RoyalMailCBCBean().getModuleWidth(); case DataMatrix: return new DataMatrixBean().getModuleWidth(); } return 0.20f; } public static double defaultBarRatio(BarcodeType type) { switch (type) { case Code39: return new Code39Bean().getWideFactor(); case Codabar: return new CodabarBean().getWideFactor(); case Interleaved2Of5: return new Interleaved2Of5Bean().getWideFactor(); } return 2.0; } public static BufferedImage QR(FxTask task, String code, ErrorCorrectionLevel qrErrorCorrectionLevel, int qrWidth, int qrHeight, int qrMargin, File picFile) { try { HashMap hints = new HashMap(); hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); hints.put(EncodeHintType.ERROR_CORRECTION, qrErrorCorrectionLevel); hints.put(EncodeHintType.MARGIN, qrMargin); QRCodeWriter writer = new QRCodeWriter(); BitMatrix bitMatrix = writer.encode(code, BarcodeFormat.QR_CODE, qrWidth, qrHeight, hints); BufferedImage qrImage = MatrixToImageWriter.toBufferedImage(bitMatrix); if (picFile != null) { BufferedImage pic = ImageFileReaders.readImage(task, picFile); if (pic != null) { double ratio = 2; switch (qrErrorCorrectionLevel) { case L: ratio = 0.16; break; case M: ratio = 0.20; break; case Q: ratio = 0.25; break; case H: ratio = 0.30; break; } // https://www.cnblogs.com/tuyile006/p/3416008.html // ratio = Math.min(2 / 7d, ratio); int width = (int) ((qrImage.getWidth() - writer.getLeftPadding() * 2) * ratio); int height = (int) ((qrImage.getHeight() - writer.getTopPadding() * 2) * ratio); return BarcodeTools.centerPicture(qrImage, pic, width, height); } } return qrImage; } catch (Exception e) { MyBoxLog.error(e.toString()); return null; } } public static BufferedImage centerPicture(BufferedImage source, BufferedImage picture, int w, int h) { try { if (w <= 0 || h <= 0 || picture == null || picture.getWidth() == 0) { return source; } int width = source.getWidth(); int height = source.getHeight(); int ah = h, aw = w; if (w * 1.0f / h > picture.getWidth() * 1.0f / picture.getHeight()) { ah = picture.getHeight() * w / picture.getWidth(); } else { aw = picture.getWidth() * h / picture.getHeight(); } BufferedImage target = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D g = target.createGraphics(); if (AppVariables.ImageHints != null) { g.addRenderingHints(AppVariables.ImageHints); } g.drawImage(source, 0, 0, width, height, null); g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f)); g.drawImage(picture, (width - aw) / 2, (height - ah) / 2, aw, ah, null); g.dispose(); return target; } catch (Exception e) { MyBoxLog.error(e.toString()); return null; } } public static BufferedImage PDF417(String code, int pdf417ErrorCorrectionLevel, Compaction pdf417Compact, int pdf417Width, int pdf417Height, int pdf417Margin) { try { HashMap hints = new HashMap(); hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); hints.put(EncodeHintType.ERROR_CORRECTION, pdf417ErrorCorrectionLevel); hints.put(EncodeHintType.MARGIN, pdf417Margin); if (pdf417Compact == null) { hints.put(EncodeHintType.PDF417_COMPACT, false); } else { hints.put(EncodeHintType.PDF417_COMPACT, true); hints.put(EncodeHintType.PDF417_COMPACTION, pdf417Compact); } BitMatrix bitMatrix = new MultiFormatWriter().encode(code, BarcodeFormat.PDF_417, pdf417Width, pdf417Height, hints); return MatrixToImageWriter.toBufferedImage(bitMatrix); } catch (Exception e) { MyBoxLog.error(e.toString()); return null; } } public static BufferedImage DataMatrix(String code, int dmWidth, int dmHeigh) { try { HashMap hints = new HashMap(); hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); BitMatrix bitMatrix = new MultiFormatWriter().encode(code, BarcodeFormat.DATA_MATRIX, dmWidth, dmHeigh, hints); return MatrixToImageWriter.toBufferedImage(bitMatrix); } catch (Exception e) { MyBoxLog.error(e.toString()); return null; } } public static BufferedImage createBarcode( BarcodeType type, String code, double height, double narrowWidth, double barRatio, double quietWidth, HumanReadablePlacement textPostion, String fontName, int fontSize, int dpi, boolean antiAlias, int orientation, boolean checksum, boolean startstop) { try { AbstractBarcodeBean bean = null; switch (type) { case Code39: Code39Bean code39 = new Code39Bean(); code39.setWideFactor(barRatio); code39.setDisplayChecksum(checksum); code39.setDisplayStartStop(startstop); code39.setExtendedCharSetEnabled(true); code39.setChecksumMode(ChecksumMode.CP_ADD); bean = code39; break; case Code128: Code128Bean code128 = new Code128Bean(); bean = code128; break; case Codabar: CodabarBean codabar = new CodabarBean(); codabar.setWideFactor(barRatio); bean = codabar; break; } if (bean == null) { return null; } bean.setFontName(code); bean.setFontSize(fontSize); bean.setModuleWidth(narrowWidth); bean.setHeight(height); bean.setQuietZone(quietWidth); bean.setMsgPosition(textPostion); BitmapCanvasProvider canvas = new BitmapCanvasProvider( dpi, BufferedImage.TYPE_BYTE_BINARY, antiAlias, orientation); bean.generateBarcode(canvas, code); canvas.finish(); return canvas.getBufferedImage(); } catch (Exception e) { MyBoxLog.error(e.toString()); return null; } } public static BufferedImage createCode39( BarcodeType type, String code, double height, double narrowWidth, double barRatio, double quietWidth, HumanReadablePlacement textPostion, String fontName, int fontSize, int dpi, boolean antiAlias, int orientation, boolean checksum, boolean startstop) { try { Code39Bean code39 = new Code39Bean(); code39.setWideFactor(barRatio); code39.setDisplayChecksum(checksum); code39.setDisplayStartStop(startstop); code39.setExtendedCharSetEnabled(true); code39.setChecksumMode(ChecksumMode.CP_ADD); code39.setFontName(code); code39.setFontSize(fontSize); code39.setModuleWidth(narrowWidth); code39.setHeight(height); code39.setQuietZone(quietWidth); code39.setMsgPosition(textPostion); BitmapCanvasProvider canvas = new BitmapCanvasProvider( dpi, BufferedImage.TYPE_BYTE_BINARY, antiAlias, orientation); code39.generateBarcode(canvas, code); canvas.finish(); return canvas.getBufferedImage(); } catch (Exception e) { MyBoxLog.error(e.toString()); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/tools/FloatTools.java
alpha/MyBox/src/main/java/mara/mybox/tools/FloatTools.java
package mara.mybox.tools; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Random; import static mara.mybox.tools.DoubleTools.numberFormat; import mara.mybox.value.AppValues; /** * @Author Mara * @CreateDate 2019-5-28 15:31:28 * @License Apache License Version 2.0 */ public class FloatTools { public static boolean invalidFloat(Float value) { return value == null || Float.isNaN(value) || Float.isInfinite(value) || value == AppValues.InvalidFloat; } public static String percentage(float data, float total) { try { String format = "#,###.##"; DecimalFormat df = new DecimalFormat(format); return df.format(scale(data * 100 / total, 2)); } catch (Exception e) { return data + ""; } } public static int compare(String s1, String s2, boolean desc) { float f1, f2; try { f1 = Float.parseFloat(s1.replaceAll(",", "")); } catch (Exception e) { f1 = Float.NaN; } try { f2 = Float.parseFloat(s2.replaceAll(",", "")); } catch (Exception e) { f2 = Float.NaN; } return compare(f1, f2, desc); } // invalid values are counted as smaller public static int compare(float f1, float f2, boolean desc) { if (Float.isNaN(f1)) { if (Float.isNaN(f2)) { return 0; } else { return desc ? 1 : -1; } } else { if (Float.isNaN(f2)) { return desc ? -1 : 1; } else { float diff = f1 - f2; if (diff == 0) { return 0; } else if (diff > 0) { return desc ? -1 : 1; } else { return desc ? 1 : -1; } } } } public static float scale(float v, int scale) { try { if (numberFormat == null) { numberFormat(); } numberFormat.setMaximumFractionDigits(scale); return Float.parseFloat(numberFormat.format(v)); } catch (Exception e) { return v; } } public static int toInt(float v) { try { return (int) scale(v, 0); } catch (Exception e) { return (int) v; } } public static float roundFloat2(float fvalue) { return scale(fvalue, 2); } public static float roundFloat5(float fvalue) { return scale(fvalue, 5); } public static double[] toDouble(float[] f) { if (f == null) { return null; } double[] d = new double[f.length]; for (int i = 0; i < f.length; ++i) { d[i] = f[i]; } return d; } public static double[][] toDouble(float[][] f) { if (f == null) { return null; } double[][] d = new double[f.length][f[0].length]; for (int i = 0; i < f.length; ++i) { for (int j = 0; j < f[i].length; ++j) { d[i][j] = f[i][j]; } } return d; } public static float random(Random r, int max, boolean nonNegative) { if (r == null) { r = new Random(); } int sign = nonNegative ? 1 : r.nextInt(2); float f = r.nextFloat(max); return sign == 1 ? f : -f; } public static String format(float v, String format, int scale) { if (invalidFloat(v)) { return null; } return NumberTools.format(v, format, scale); } public static float[] sortArray(float[] numbers) { List<Float> list = new ArrayList<>(); for (float i : numbers) { list.add(i); } Collections.sort(list, new Comparator<Float>() { @Override public int compare(Float p1, Float p2) { if (p1 > p2) { return 1; } else if (p1 < p2) { return -1; } else { return 0; } } }); float[] sorted = new float[numbers.length]; for (int i = 0; i < list.size(); ++i) { sorted[i] = list.get(i); } return sorted; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/tools/OCRTools.java
alpha/MyBox/src/main/java/mara/mybox/tools/OCRTools.java
package mara.mybox.tools; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import mara.mybox.dev.MyBoxLog; import static mara.mybox.value.AppVariables.MyboxDataPath; import mara.mybox.value.Languages; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2019-9-21 * @License Apache License Version 2.0 */ public class OCRTools { // https://github.com/nguyenq/tess4j/blob/master/src/test/java/net/sourceforge/tess4j/Tesseract1Test.java#L177 public static final double MINIMUM_DESKEW_THRESHOLD = 0.05d; public static final String TessDataPath = "TessDataPath"; // Generate each time because user may change the interface language. public static Map<String, String> codeName() { // if (CodeName != null) { // return CodeName; // } Map<String, String> named = new HashMap<>(); named.put("chi_sim", Languages.message("SimplifiedChinese")); named.put("chi_sim_vert", Languages.message("SimplifiedChineseVert")); named.put("chi_tra", Languages.message("TraditionalChinese")); named.put("chi_tra_vert", Languages.message("TraditionalChineseVert")); named.put("eng", Languages.message("English")); named.put("equ", Languages.message("MathEquation")); named.put("osd", Languages.message("OrientationScript")); return named; } public static Map<String, String> nameCode() { // if (NameCode != null) { // return NameCode; // } Map<String, String> codes = codeName(); Map<String, String> names = new HashMap<>(); for (String code : codes.keySet()) { names.put(codes.get(code), code); } return names; } public static List<String> codes() { // if (Codes != null) { // return Codes; // } List<String> Codes = new ArrayList<>(); Codes.add("chi_sim"); Codes.add("chi_sim_vert"); Codes.add("chi_tra"); Codes.add("chi_tra_vert"); Codes.add("eng"); Codes.add("equ"); Codes.add("osd"); return Codes; } public static List<String> names() { // if (Names != null) { // return Names; // } List<String> Names = new ArrayList<>(); Map<String, String> codes = codeName(); for (String code : codes()) { Names.add(codes.get(code)); } return Names; } // Make sure supported language files are under defined data path public static boolean initDataFiles() { try { String pathname = UserConfig.getString(TessDataPath, null); if (pathname == null) { pathname = MyboxDataPath + File.separator + "tessdata"; } File path = new File(pathname); if (!path.exists() || !path.isDirectory()) { path = new File(MyboxDataPath + File.separator + "tessdata"); path.mkdirs(); } File chi_sim = new File(path.getAbsolutePath() + File.separator + "chi_sim.traineddata"); if (!chi_sim.exists()) { File tmp = mara.mybox.fxml.FxFileTools.getInternalFile("/data/tessdata/chi_sim.traineddata"); FileCopyTools.copyFile(tmp, chi_sim); } File chi_sim_vert = new File(path.getAbsolutePath() + File.separator + "chi_sim_vert.traineddata"); if (!chi_sim_vert.exists()) { File tmp = mara.mybox.fxml.FxFileTools.getInternalFile("/data/tessdata/chi_sim_vert.traineddata"); FileCopyTools.copyFile(tmp, chi_sim_vert); } File chi_tra = new File(path.getAbsolutePath() + File.separator + "chi_tra.traineddata"); if (!chi_tra.exists()) { File tmp = mara.mybox.fxml.FxFileTools.getInternalFile("/data/tessdata/chi_tra.traineddata"); FileCopyTools.copyFile(tmp, chi_tra); } File chi_tra_vert = new File(path.getAbsolutePath() + File.separator + "chi_tra_vert.traineddata"); if (!chi_tra_vert.exists()) { File tmp = mara.mybox.fxml.FxFileTools.getInternalFile("/data/tessdata/chi_tra_vert.traineddata"); FileCopyTools.copyFile(tmp, chi_tra_vert); } File equ = new File(path.getAbsolutePath() + File.separator + "equ.traineddata"); if (!equ.exists()) { File tmp = mara.mybox.fxml.FxFileTools.getInternalFile("/data/tessdata/equ.traineddata"); FileCopyTools.copyFile(tmp, equ); } File eng = new File(path.getAbsolutePath() + File.separator + "eng.traineddata"); if (!eng.exists()) { File tmp = mara.mybox.fxml.FxFileTools.getInternalFile("/data/tessdata/eng.traineddata"); FileCopyTools.copyFile(tmp, eng); } File osd = new File(path.getAbsolutePath() + File.separator + "osd.traineddata"); if (!osd.exists()) { File tmp = mara.mybox.fxml.FxFileTools.getInternalFile("/tessdata/osd.traineddata"); FileCopyTools.copyFile(tmp, osd); } UserConfig.setString(TessDataPath, path.getAbsolutePath()); return true; } catch (Exception e) { MyBoxLog.debug(e); return false; } } public static List<String> namesList(boolean copyFiles) { List<String> data = new ArrayList<>(); try { if (copyFiles) { initDataFiles(); } String dataPath = UserConfig.getString(TessDataPath, null); if (dataPath == null) { return data; } data.addAll(names()); List<String> codes = codes(); File[] files = new File(dataPath).listFiles(); if (files != null) { for (File f : files) { String name = f.getName(); if (!f.isFile() || !name.endsWith(".traineddata")) { continue; } String code = name.substring(0, name.length() - ".traineddata".length()); if (codes.contains(code)) { continue; } data.add(code); } } } catch (Exception e) { MyBoxLog.debug(e); } return data; } public static String name(String code) { Map<String, String> codes = codeName(); return codes.get(code); } public static String code(String name) { Map<String, String> names = nameCode(); return names.get(name); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/tools/GeographyCodeTools.java
alpha/MyBox/src/main/java/mara/mybox/tools/GeographyCodeTools.java
package mara.mybox.tools; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.parsers.DocumentBuilderFactory; import mara.mybox.data.GeographyCode; import mara.mybox.data.GeographyCode.AddressLevel; import mara.mybox.data.GeographyCode.CoordinateSystem; import mara.mybox.db.data.DataNode; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxFileTools; import mara.mybox.value.AppValues; import static mara.mybox.value.Languages.message; import mara.mybox.value.UserConfig; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import thridparty.CoordinateConverter; /** * @Author Mara * @CreateDate 2020-8-11 * @License Apache License Version 2.0 */ public class GeographyCodeTools { /* Coordinate System */ public static String coordinateSystemMessageNames() { String s = ""; for (CoordinateSystem v : CoordinateSystem.values()) { if (!s.isBlank()) { s += "\n"; } s += message(v.name()); } return s; } public static CoordinateSystem coordinateSystemByName(String name) { try { return CoordinateSystem.valueOf(name); } catch (Exception e) { return GeographyCode.defaultCoordinateSystem; } } public static CoordinateSystem coordinateSystemByValue(short value) { try { return CoordinateSystem.values()[value]; } catch (Exception e) { return GeographyCode.defaultCoordinateSystem; } } public static short coordinateSystemValue(CoordinateSystem cs) { try { return (short) cs.ordinal(); } catch (Exception e) { return 0; } } public static String coordinateSystemName(short value) { try { return coordinateSystemByValue(value).name(); } catch (Exception e) { return null; } } public static String coordinateSystemMessageName(short value) { try { return message(coordinateSystemName(value)); } catch (Exception e) { return null; } } /* Address Level */ public static String addressLevelMessageNames() { String s = ""; for (AddressLevel v : AddressLevel.values()) { if (!s.isBlank()) { s += "\n"; } s += message(v.name()); } return s; } public static AddressLevel addressLevelByName(String name) { try { return AddressLevel.valueOf(name); } catch (Exception e) { return GeographyCode.defaultAddressLevel; } } public static AddressLevel addressLevelByValue(short value) { try { return AddressLevel.values()[value]; } catch (Exception e) { return GeographyCode.defaultAddressLevel; } } public static short addressLevelValue(AddressLevel level) { try { return (short) level.ordinal(); } catch (Exception e) { return 0; } } public static String addressLevelName(short value) { try { return addressLevelByValue(value).name(); } catch (Exception e) { return null; } } public static String addressLevelMessageName(short value) { try { return message(addressLevelName(value)); } catch (Exception e) { return null; } } /* map */ public static String gaodeMap(int zoom) { try { File map = FxFileTools.getInternalFile("/js/GaoDeMap.html", "js", "GaoDeMap.html", false); String html = TextFileTools.readTexts(null, map); html = html.replace(AppValues.GaoDeMapJavascriptKey, UserConfig.getString("GaoDeMapWebKey", AppValues.GaoDeMapJavascriptKey)) .replace("MyBoxMapZoom", zoom + ""); return html; } catch (Exception e) { MyBoxLog.error(e.toString()); return ""; } } public static File tiandituFile(boolean geodetic, int zoom) { try { File map = FxFileTools.getInternalFile("/js/tianditu.html", "js", "tianditu.html", false); String html = TextFileTools.readTexts(null, map); html = html.replace(AppValues.TianDiTuWebKey, UserConfig.getString("TianDiTuWebKey", AppValues.TianDiTuWebKey)) .replace("MyBoxMapZoom", zoom + ""); if (geodetic) { html = html.replace("'EPSG:900913", "EPSG:4326"); } TextFileTools.writeFile(map, html); return map; } catch (Exception e) { MyBoxLog.error(e.toString()); return null; } } /* Query codes by web service */ public static GeographyCode geoCode(CoordinateSystem coordinateSystem, String address) { try { if (coordinateSystem == null) { return null; } if (coordinateSystem == CoordinateSystem.GCJ_02) { // GaoDe Map only supports info codes of China String urlString = "https://restapi.amap.com/v3/geocode/geo?address=" + URLEncoder.encode(address, "UTF-8") + "&output=xml&key=" + UserConfig.getString("GaoDeMapServiceKey", AppValues.GaoDeMapWebServiceKey); GeographyCode geographyCode = new GeographyCode(); geographyCode.setChineseName(address); geographyCode.setCoordinateSystem(coordinateSystem); return gaodeCode(urlString, geographyCode); } else if (coordinateSystem == CoordinateSystem.CGCS2000) { // http://api.tianditu.gov.cn/geocoder?ds={"keyWord":"泰山"}&tk=0ddeb917def62b4691500526cc30a9b1 String urlString = "http://api.tianditu.gov.cn/geocoder?ds=" + URLEncoder.encode("{\"keyWord\":\"" + address + "\"}", "UTF-8") + "&tk=" + UserConfig.getString("TianDiTuWebKey", AppValues.TianDiTuWebKey); URL url = UrlTools.url(urlString); if (url == null) { return null; } File jsonFile = FileTmpTools.getTempFile(".json"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); connection.connect(); try (final BufferedInputStream inStream = new BufferedInputStream(connection.getInputStream()); final BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(jsonFile))) { byte[] buf = new byte[AppValues.IOBufferLength]; int len; while ((len = inStream.read(buf)) > 0) { outputStream.write(buf, 0, len); } } String data = TextFileTools.readTexts(null, jsonFile); double longitude = -200; double latitude = -200; String flag = "\"lon\":"; int pos = data.indexOf(flag); if (pos >= 0) { String subData = data.substring(pos + flag.length()); flag = ","; pos = subData.indexOf(flag); if (pos >= 0) { try { longitude = Double.parseDouble(subData.substring(0, pos)); } catch (Exception e) { } } } flag = "\"lat\":"; pos = data.indexOf(flag); if (pos >= 0) { String subData = data.substring(pos + flag.length()); flag = ","; pos = subData.indexOf(flag); if (pos >= 0) { try { latitude = Double.parseDouble(subData.substring(0, pos)); } catch (Exception e) { } } } if (validCoordinate(longitude, latitude)) { return GeographyCodeTools.geoCode(coordinateSystem, longitude, latitude); } } return null; } catch (Exception e) { return null; } } public static GeographyCode geoCode(CoordinateSystem coordinateSystem, double longitude, double latitude) { try { if (coordinateSystem == null) { return null; } if (coordinateSystem == CoordinateSystem.GCJ_02) { String urlString = "https://restapi.amap.com/v3/geocode/regeo?location=" + longitude + "," + latitude + "&output=xml&key=" + UserConfig.getString("GaoDeMapServiceKey", AppValues.GaoDeMapWebServiceKey); GeographyCode geographyCode = new GeographyCode(); geographyCode.setLongitude(longitude); geographyCode.setLatitude(latitude); geographyCode.setCoordinateSystem(coordinateSystem); return gaodeCode(urlString, geographyCode); } else if (coordinateSystem == CoordinateSystem.CGCS2000) { String urlString = "http://api.tianditu.gov.cn/geocoder?postStr={'lon':" + longitude + ",'lat':" + latitude + ",'ver':1}&type=geocode&tk=" + UserConfig.getString("TianDiTuWebKey", AppValues.TianDiTuWebKey); GeographyCode geographyCode = new GeographyCode(); geographyCode.setLongitude(longitude); geographyCode.setLatitude(latitude); geographyCode.setCoordinateSystem(coordinateSystem); return tiandituCode(urlString, geographyCode); } return null; } catch (Exception e) { return null; } } //{"result":{"formatted_address":"泰安市泰山区升平街39号(泰山区区政府大院内)泰山区统计局", // "location":{"lon":117.12899999995,"lat":36.19280999998}, // "addressComponent":{"address":"泰山区升平街39号(泰山区区政府大院内)","city":"泰安市", // "county_code":"156370902","nation":"中国","poi_position":"西北","county":"泰山区","city_code":"156370900", // "address_position":"西北","poi":"泰山区统计局","province_code":"156370000","province":"山东省","road":"运粮街", //"road_distance":65,"poi_distance":10,"address_distance":10}},"msg":"ok","status":"0"} public static GeographyCode tiandituCode(String urlString, GeographyCode geographyCode) { try { URL url = UrlTools.url(urlString); if (url == null) { return null; } File jsonFile = FileTmpTools.getTempFile(".json"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); connection.connect(); try (final BufferedInputStream inStream = new BufferedInputStream(connection.getInputStream()); final BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(jsonFile))) { byte[] buf = new byte[AppValues.IOBufferLength]; int len; while ((len = inStream.read(buf)) > 0) { outputStream.write(buf, 0, len); } } String data = TextFileTools.readTexts(null, jsonFile); // MyBoxLog.debug(data); String flag = "\"formatted_address\":\""; int pos = data.indexOf(flag); if (pos >= 0) { String subData = data.substring(pos + flag.length()); flag = "\""; pos = subData.indexOf(flag); if (pos >= 0) { String name = subData.substring(0, pos); setName(geographyCode, name); } } flag = "\"lon\":"; pos = data.indexOf(flag); if (pos >= 0) { String subData = data.substring(pos + flag.length()); flag = ","; pos = subData.indexOf(flag); if (pos >= 0) { try { double longitude = Double.parseDouble(subData.substring(0, pos)); geographyCode.setLongitude(longitude); } catch (Exception e) { } } } flag = "\"lat\":"; pos = data.indexOf(flag); if (pos >= 0) { String subData = data.substring(pos + flag.length()); flag = "}"; pos = subData.indexOf(flag); if (pos >= 0) { try { double latitude = Double.parseDouble(subData.substring(0, pos)); geographyCode.setLatitude(latitude); } catch (Exception e) { } } } flag = "\"address\":\""; pos = data.indexOf(flag); if (pos >= 0) { String subData = data.substring(pos + flag.length()); flag = "\""; pos = subData.indexOf(flag); if (pos >= 0) { String name = subData.substring(0, pos); setName(geographyCode, name); } } flag = "\"city\":\""; pos = data.indexOf(flag); if (pos >= 0) { String subData = data.substring(pos + flag.length()); flag = "\""; pos = subData.indexOf(flag); if (pos >= 0) { geographyCode.setCity(subData.substring(0, pos)); } } flag = "\"county_code\":\""; pos = data.indexOf(flag); if (pos >= 0) { String subData = data.substring(pos + flag.length()); flag = "\""; pos = subData.indexOf(flag); if (pos >= 0) { geographyCode.setCode3(subData.substring(0, pos)); } } flag = "\"nation\":\""; pos = data.indexOf(flag); if (pos >= 0) { String subData = data.substring(pos + flag.length()); flag = "\""; pos = subData.indexOf(flag); if (pos >= 0) { geographyCode.setCountry(subData.substring(0, pos)); } } flag = "\"county\":\""; pos = data.indexOf(flag); if (pos >= 0) { String subData = data.substring(pos + flag.length()); flag = "\""; pos = subData.indexOf(flag); if (pos >= 0) { geographyCode.setCounty(subData.substring(0, pos)); } } flag = "\"city_code\":\""; pos = data.indexOf(flag); if (pos >= 0) { String subData = data.substring(pos + flag.length()); flag = "\""; pos = subData.indexOf(flag); if (pos >= 0) { geographyCode.setCode2(subData.substring(0, pos)); } } flag = "\"poi\":\""; pos = data.indexOf(flag); if (pos >= 0) { String subData = data.substring(pos + flag.length()); flag = "\""; pos = subData.indexOf(flag); if (pos >= 0) { String name = subData.substring(0, pos); setName(geographyCode, name); } } flag = "\"province_code\":\""; pos = data.indexOf(flag); if (pos >= 0) { String subData = data.substring(pos + flag.length()); flag = "\""; pos = subData.indexOf(flag); if (pos >= 0) { geographyCode.setCode1(subData.substring(0, pos)); } } flag = "\"province\":\""; pos = data.indexOf(flag); if (pos >= 0) { String subData = data.substring(pos + flag.length()); flag = "\""; pos = subData.indexOf(flag); if (pos >= 0) { geographyCode.setProvince(subData.substring(0, pos)); } } flag = "\"road\":\""; pos = data.indexOf(flag); if (pos >= 0) { String subData = data.substring(pos + flag.length()); flag = "\""; pos = subData.indexOf(flag); if (pos >= 0) { geographyCode.setVillage(subData.substring(0, pos)); } } // if (!validCoordinate(geographyCode)) { // return null; // } return geographyCode; } catch (Exception e) { MyBoxLog.debug(e); return null; } } // {"status":"1","info":"OK","infocode":"10000","count":"1","geocodes": // [{"formatted_address":"山东省泰安市泰山区泰山","country":"中国","province":"山东省","citycode":"0538", //"city":"泰安市","county":"泰山区","township":[], //"village":{"name":[],"type":[]}, //"building":{"name":[],"type":[]}, //"adcode":"370902","town":[],"number":[],"location":"117.157242,36.164988","levelCode":"兴趣点"}]} public static GeographyCode gaodeCode(String urlString, GeographyCode geographyCode) { try { URL url = UrlTools.url(urlString); if (url == null) { return null; } File xmlFile = HtmlReadTools.download(null, url.toString()); // MyBoxLog.debug(FileTools.readTexts(xmlFile)); Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(xmlFile); NodeList nodes = doc.getElementsByTagName("formatted_address"); if (nodes != null && nodes.getLength() > 0) { String name = nodes.item(0).getTextContent(); setName(geographyCode, name); } nodes = doc.getElementsByTagName("country"); if (nodes != null && nodes.getLength() > 0) { geographyCode.setCountry(nodes.item(0).getTextContent()); } nodes = doc.getElementsByTagName("province"); if (nodes != null && nodes.getLength() > 0) { geographyCode.setProvince(nodes.item(0).getTextContent()); } nodes = doc.getElementsByTagName("citycode"); if (nodes != null && nodes.getLength() > 0) { geographyCode.setCode2(nodes.item(0).getTextContent()); } nodes = doc.getElementsByTagName("city"); if (nodes != null && nodes.getLength() > 0) { geographyCode.setCity(nodes.item(0).getTextContent()); } nodes = doc.getElementsByTagName("district"); if (nodes != null && nodes.getLength() > 0) { geographyCode.setCounty(nodes.item(0).getTextContent()); } nodes = doc.getElementsByTagName("township"); if (nodes != null && nodes.getLength() > 0) { geographyCode.setTown(nodes.item(0).getTextContent()); } nodes = doc.getElementsByTagName("neighborhood"); if (nodes != null && nodes.getLength() > 0) { geographyCode.setVillage(nodes.item(0).getFirstChild().getTextContent()); } nodes = doc.getElementsByTagName("building"); if (nodes != null && nodes.getLength() > 0) { geographyCode.setBuilding(nodes.item(0).getTextContent()); } nodes = doc.getElementsByTagName("adcode"); if (nodes != null && nodes.getLength() > 0) { geographyCode.setCode1(nodes.item(0).getTextContent()); } nodes = doc.getElementsByTagName("streetNumber"); if (nodes != null && nodes.getLength() > 0) { nodes = nodes.item(0).getChildNodes(); if (nodes != null) { Map<String, String> values = new HashMap<>(); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); values.put(node.getNodeName(), node.getTextContent()); } String s = ""; String v = values.get("street"); if (v != null) { s += v; } v = values.get("number"); if (v != null) { s += v; } v = values.get("location"); if (v != null) { s += v; } v = values.get("direction"); if (v != null) { s += v; } v = values.get("distance"); if (v != null) { s += v; } if (geographyCode.getBuilding() == null) { geographyCode.setBuilding(s); } else { setName(geographyCode, s); } } } else { nodes = doc.getElementsByTagName("street"); if (nodes != null && nodes.getLength() > 0) { String s = nodes.item(0).getTextContent(); if (geographyCode.getBuilding() == null) { geographyCode.setBuilding(s); } else { setName(geographyCode, s); } } nodes = doc.getElementsByTagName("number"); if (nodes != null && nodes.getLength() > 0) { geographyCode.setCode5(nodes.item(0).getTextContent()); } if (!validCoordinate(geographyCode)) { nodes = doc.getElementsByTagName("location"); if (nodes != null && nodes.getLength() > 0) { String[] values = nodes.item(0).getFirstChild().getTextContent().split(","); geographyCode.setLongitude(Double.parseDouble(values[0].trim())); geographyCode.setLatitude(Double.parseDouble(values[1].trim())); } else { geographyCode.setLongitude(-200); geographyCode.setLatitude(-200); } } if (geographyCode.getChineseName() == null) { geographyCode.setChineseName(geographyCode.getLongitude() + "," + geographyCode.getLatitude()); } nodes = doc.getElementsByTagName("level"); if (nodes != null && nodes.getLength() > 0) { String v = nodes.item(0).getTextContent(); if (message("zh", "Country").equals(v)) { geographyCode.setLevel(AddressLevel.Country); } else if (message("zh", "Province").equals(v)) { geographyCode.setLevel(AddressLevel.Province); } else if (message("zh", "City").equals(v)) { geographyCode.setLevel(AddressLevel.City); } else if (message("zh", "County").equals(v)) { geographyCode.setLevel(AddressLevel.County); } else if (message("zh", "Town").equals(v)) { geographyCode.setLevel(AddressLevel.Town); } else if (message("zh", "Neighborhood").equals(v)) { geographyCode.setLevel(AddressLevel.Village); } else if (message("zh", "PointOfInterest").equals(v)) { geographyCode.setLevel(AddressLevel.PointOfInterest); } else if (message("zh", "Street").equals(v)) { geographyCode.setLevel(AddressLevel.Village); } else if (message("zh", "Building").equals(v)) { geographyCode.setLevel(AddressLevel.Building); } else { geographyCode.setLevel(AddressLevel.PointOfInterest); } } } // if (!validCoordinate(geographyCode)) { // return null; // } return geographyCode; } catch (Exception e) { MyBoxLog.debug(e); return null; } } public static boolean setName(GeographyCode geographyCode, String name) { if (geographyCode.getChineseName() == null) { geographyCode.setChineseName(name); return true; } else if (!geographyCode.getChineseName().equals(name)) { if (geographyCode.getAlias1() == null) { geographyCode.setAlias1(geographyCode.getChineseName()); geographyCode.setChineseName(name); return true; } else if (!geographyCode.getAlias1().equals(name)) { if (geographyCode.getAlias2() == null) { geographyCode.setAlias2(geographyCode.getChineseName()); geographyCode.setChineseName(name); return true; } else if (!geographyCode.getAlias2().equals(name)) { if (geographyCode.getAlias3() == null) { geographyCode.setAlias3(geographyCode.getChineseName()); geographyCode.setChineseName(name); return true; } else if (!geographyCode.getAlias3().equals(name)) { if (geographyCode.getAlias4() == null) { geographyCode.setAlias4(geographyCode.getChineseName()); geographyCode.setChineseName(name); return true; } else if (!geographyCode.getAlias4().equals(name)) { geographyCode.setAlias5(geographyCode.getChineseName()); geographyCode.setChineseName(name); return true; } } } } } return false; } public static String gaodeConvertService(CoordinateSystem cs) { if (cs == null) { cs = GeographyCode.defaultCoordinateSystem; } switch (cs) { case CGCS2000: return "gps"; case GCJ_02: return "autonavi"; case WGS_84: return "gps"; case BD_09: return "baidu"; case Mapbar: return "mapbar"; default: return "autonavi"; } } /* Convert */ public static GeographyCode fromNode(DataNode node) { if (node == null) { return null; } GeographyCode code = new GeographyCode(); code.setTitle(node.getTitle()); code.setLevel(addressLevelByValue(node.getShortValue("level"))); code.setCoordinateSystem(coordinateSystemByValue(node.getShortValue("coordinate_system"))); double d = node.getDoubleValue("longitude"); code.setLongitude((DoubleTools.invalidDouble(d) || d > 180 || d < -180) ? -200 : d); d = node.getDoubleValue("latitude"); code.setLatitude((DoubleTools.invalidDouble(d) || d > 90 || d < -90) ? -200 : d); code.setAltitude(node.getDoubleValue("altitude")); code.setPrecision(node.getDoubleValue("precision")); code.setChineseName(node.getStringValue("chinese_name")); code.setEnglishName(node.getStringValue("english_name")); code.setContinent(node.getStringValue("continent")); code.setCountry(node.getStringValue("country")); code.setProvince(node.getStringValue("province")); code.setCity(node.getStringValue("city")); code.setCounty(node.getStringValue("county")); code.setTown(node.getStringValue("town")); code.setVillage(node.getStringValue("village")); code.setBuilding(node.getStringValue("building")); code.setPoi(node.getStringValue("poi")); code.setAlias1(node.getStringValue("alias1")); code.setAlias2(node.getStringValue("alias2")); code.setAlias3(node.getStringValue("alias3")); code.setAlias4(node.getStringValue("alias4")); code.setAlias5(node.getStringValue("alias5")); code.setCode1(node.getStringValue("code1")); code.setCode2(node.getStringValue("code2")); code.setCode3(node.getStringValue("code3")); code.setCode4(node.getStringValue("code4")); code.setCode5(node.getStringValue("code5")); code.setDescription(node.getStringValue("description")); d = node.getDoubleValue("area"); code.setArea(DoubleTools.invalidDouble(d) || d <= 0 ? -1 : d); long p = node.getLongValue("population"); code.setPopulation(LongTools.invalidLong(p) || p <= 0 ? -1 : p); return code; } public static DataNode toNode(GeographyCode code) { if (code == null) { return null; } DataNode node = new DataNode(); node.setTitle(code.getTitle()); node.setValue("level", addressLevelValue(code.getLevel())); node.setValue("coordinate_system", coordinateSystemValue(code.getCoordinateSystem())); node.setValue("longitude", code.getLongitude()); node.setValue("latitude", code.getLatitude()); node.setValue("precision", code.getPrecision()); node.setValue("chinese_name", code.getChineseName()); node.setValue("english_name", code.getEnglishName()); node.setValue("continent", code.getContinent()); node.setValue("country", code.getCountry()); node.setValue("province", code.getProvince()); node.setValue("city", code.getCity()); node.setValue("county", code.getCounty()); node.setValue("town", code.getTown()); node.setValue("village", code.getVillage()); node.setValue("building", code.getBuilding()); node.setValue("poi", code.getPoi()); node.setValue("alias1", code.getAlias1()); node.setValue("alias1", code.getAlias1()); node.setValue("alias1", code.getAlias1()); node.setValue("alias1", code.getAlias1()); node.setValue("alias1", code.getAlias1()); node.setValue("code1", code.getCode1()); node.setValue("code1", code.getCode1()); node.setValue("code1", code.getCode1()); node.setValue("code1", code.getCode1()); node.setValue("code1", code.getCode1()); node.setValue("description", code.getDescription()); node.setValue("area", code.getArea()); node.setValue("population", code.getPopulation()); return node; } public static GeographyCode toCGCS2000(GeographyCode code, boolean setCS) { GeographyCode converted = toWGS84(code); if (converted != null && setCS) { converted.setCoordinateSystem(CoordinateSystem.CGCS2000); } return converted; }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
true
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/tools/LongTools.java
alpha/MyBox/src/main/java/mara/mybox/tools/LongTools.java
package mara.mybox.tools; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Random; import mara.mybox.value.AppValues; /** * @Author Mara * @CreateDate 2021-10-4 * @License Apache License Version 2.0 */ public class LongTools { public static boolean invalidLong(Long value) { return value == null || value == AppValues.InvalidLong; } public static int compare(String s1, String s2, boolean desc) { double d1, d2; try { d1 = Long.parseLong(s1.replaceAll(",", "")); } catch (Exception e) { d1 = Double.NaN; } try { d2 = Long.parseLong(s2.replaceAll(",", "")); } catch (Exception e) { d2 = Double.NaN; } return DoubleTools.compare(d1, d2, desc); } public static long random(Random r, int max, boolean nonNegative) { if (r == null) { r = new Random(); } int sign = nonNegative ? 1 : r.nextInt(2); long l = r.nextLong(max); return sign == 1 ? l : -l; } public static String format(long v, String format, int scale) { if (invalidLong(v)) { return null; } return NumberTools.format(v, format, scale); } public static long[] sortArray(long[] numbers) { List<Long> list = new ArrayList<>(); for (long i : numbers) { list.add(i); } Collections.sort(list, new Comparator<Long>() { @Override public int compare(Long p1, Long p2) { if (p1 > p2) { return 1; } else if (p1 < p2) { return -1; } else { return 0; } } }); long[] sorted = new long[numbers.length]; for (int i = 0; i < list.size(); ++i) { sorted[i] = list.get(i); } return sorted; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/tools/HtmlWriteTools.java
alpha/MyBox/src/main/java/mara/mybox/tools/HtmlWriteTools.java
package mara.mybox.tools; import com.vladsch.flexmark.html.HtmlRenderer; import com.vladsch.flexmark.parser.Parser; import com.vladsch.flexmark.util.data.MutableDataHolder; import java.io.File; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; import mara.mybox.controller.HtmlEditorController; import mara.mybox.data.FindReplaceString; import mara.mybox.data.Link; import mara.mybox.data.StringTable; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.fxml.style.HtmlStyles; import static mara.mybox.value.AppValues.Indent; import mara.mybox.value.Languages; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * @Author Mara * @CreateDate 2021-8-1 * @License Apache License Version 2.0 */ public class HtmlWriteTools { /* edit html */ public static File writeHtml(String html) { try { File htmFile = FileTmpTools.getTempFile(".html"); Charset charset = HtmlReadTools.charset(html); TextFileTools.writeFile(htmFile, html, charset); return htmFile; } catch (Exception e) { MyBoxLog.error(e.toString()); return null; } } public static void editHtml(String html) { try { File htmFile = writeHtml(html); HtmlEditorController.openFile(htmFile); } catch (Exception e) { MyBoxLog.error(e.toString()); } } public static void editHtml(String title, String body) { editHtml(html(title, body)); } /* build html */ public static String emptyHmtl(String title) { String body = title == null ? "<BODY>\n\n\n</BODY>\n" : "<BODY>\n<h2>" + title + "</h2>\n</BODY>\n"; return html(title, "utf-8", null, body); } public static String htmlPrefix(String title, String charset, String styleValue) { StringBuilder s = new StringBuilder(); s.append("<HTML>\n").append(Indent).append("<HEAD>\n"); if (charset == null || charset.isBlank()) { charset = "utf-8"; } s.append(Indent).append(Indent) .append("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=") .append(charset).append("\" />\n"); if (title != null && !title.isBlank()) { s.append(Indent).append(Indent).append("<TITLE>") .append(title).append("</TITLE>\n"); } if (styleValue != null && !styleValue.isBlank()) { s.append(Indent).append(Indent).append("<style type=\"text/css\">\n"); s.append(Indent).append(Indent).append(Indent).append(styleValue).append("\n"); s.append(Indent).append(Indent).append("</style>\n"); } s.append(Indent).append("</HEAD>\n"); return s.toString(); } public static String htmlPrefix() { return htmlPrefix(null, "utf-8", HtmlStyles.DefaultStyle); } public static String html(String title, String body) { return html(title, "utf-8", HtmlStyles.DefaultStyle, body); } public static String html(String title, String style, String body) { return html(title, "utf-8", style, body); } public static String html(String title, String charset, String styleValue, String body) { StringBuilder s = new StringBuilder(); s.append(htmlPrefix(title, charset, styleValue)); s.append(body); s.append("</HTML>\n"); return s.toString(); } public static String html(String body) { return html(null, "utf-8", HtmlStyles.DefaultStyle, body); } public static String table(String body) { return html(null, "utf-8", HtmlStyles.TableStyle, body); } public static String style(String html, String styleValue) { try { Document doc = Jsoup.parse(html); if (doc == null) { return null; } Charset charset = doc.charset(); if (charset == null) { charset = Charset.forName("UTF-8"); } return html(doc.title(), charset.name(), styleValue, HtmlReadTools.body(html, true)); } catch (Exception e) { return null; } } public static String addStyle(String html, String style) { try { if (html == null || style == null) { return "InvalidData"; } Document doc = Jsoup.parse(html); if (doc == null) { return null; } doc.head().appendChild(new Element("style").text(style)); return doc.outerHtml(); } catch (Exception e) { MyBoxLog.error(e); return null; } } /* convert html */ public static String escapeHtml(String string) { if (string == null) { return null; } return string.replace("&", "&amp;") .replace("\"", "&quot;") .replace("'", "&#39;") .replace("<", "&lt;") .replace(">", "&gt;") .replace("\\x20", "&nbsp;") .replace("©", "&copy;") .replace("®", "&reg;") .replace("™", "&trade;"); } public static String stringToHtml(String string) { if (string == null) { return null; } return escapeHtml(string) .replaceAll("\r\n|\n|\r", "<BR>\n"); } public static String textToHtml(String text) { if (text == null) { return null; } String body = stringToHtml(text); return html(null, "<BODY>\n<DIV>\n" + body + "\n</DIV>\n</BODY>"); } public static String codeToHtml(String text) { if (text == null) { return null; } return "<PRE><CODE>" + escapeHtml(text) + "</CODE></PRE>"; } public static String htmlToText(String html) { try { if (html == null || html.isBlank()) { return html; } else { return Jsoup.parse(html).wholeText(); } } catch (Exception e) { MyBoxLog.error(e); return null; } } public static String md2html(String md, Parser htmlParser, HtmlRenderer htmlRender) { try { if (htmlParser == null || htmlRender == null || md == null || md.isBlank()) { return null; } com.vladsch.flexmark.util.ast.Node document = htmlParser.parse(md); String html = htmlRender.render(document); return html; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static String md2html(String md) { try { if (md == null || md.isBlank()) { return null; } MutableDataHolder htmlOptions = MarkdownTools.htmlOptions(); Parser htmlParser = Parser.builder(htmlOptions).build(); HtmlRenderer htmlRender = HtmlRenderer.builder(htmlOptions).build(); return md2html(md, htmlParser, htmlRender); } catch (Exception e) { MyBoxLog.error(e); return null; } } public static String setCharset(FxTask task, String html, Charset charset) { try { if (html == null) { return "InvalidData"; } Document doc = Jsoup.parse(html); if (doc == null) { return "InvalidData"; } if (setCharset(task, doc, charset)) { return doc.outerHtml(); } else { return null; } } catch (Exception e) { MyBoxLog.error(e); return null; } } public static boolean setCharset(FxTask task, Document doc, Charset charset) { try { if (doc == null) { return false; } if (charset == null) { charset = Charset.forName("utf-8"); } Elements children = doc.head().children(); for (Element e : children) { if (task != null && !task.isWorking()) { return false; } if (!e.tagName().equalsIgnoreCase("meta")) { continue; } if (e.hasAttr("charset")) { e.remove(); } if ("Content-Type".equalsIgnoreCase(e.attr("http-equiv")) && e.hasAttr("content")) { e.remove(); } } Element meta1 = new Element("meta") .attr("http-equiv", "Content-Type") .attr("content", "text/html; charset=" + charset.name()); Element meta2 = new Element("meta") .attr("charset", charset.name()); doc.head().appendChild(meta1).appendChild(meta2); return true; } catch (Exception e) { MyBoxLog.error(e); return false; } } public static String setEquiv(FxTask task, File htmlFile, Charset charset, String key, String value) { try { if (htmlFile == null || key == null || value == null) { return "InvalidData"; } String html = TextFileTools.readTexts(task, htmlFile, charset); Document doc = Jsoup.parse(html); if (doc == null) { return "InvalidData"; } if (!"Content-Type".equalsIgnoreCase(key)) { if (setCharset(task, doc, charset)) { return doc.outerHtml(); } else { return "Canceled"; } } Elements children = doc.head().children(); for (Element e : children) { if (task != null && !task.isWorking()) { return null; } if (!e.tagName().equalsIgnoreCase("meta") || !e.hasAttr("http-equiv")) { continue; } if (key.equalsIgnoreCase(e.attr("http-equiv")) && e.hasAttr("content")) { e.remove(); } } Element meta1 = new Element("meta") .attr("http-equiv", key) .attr("content", value); doc.head().appendChild(meta1); return doc.outerHtml(); } catch (Exception e) { MyBoxLog.error(e); return null; } } public static String ignoreHead(FxTask task, String html) { try { Document doc = Jsoup.parse(html); if (doc == null) { return "InvalidData"; } doc.head().empty(); Charset charset = doc.charset(); if (charset == null) { charset = Charset.forName("utf-8"); } if (setCharset(task, doc, charset)) { return html; } else { return "Canceled"; } } catch (Exception e) { MyBoxLog.error(e); return null; } } public static String toUTF8(FxTask task, File htmlFile) { return setCharset(task, TextFileTools.readTexts(task, htmlFile), Charset.forName("utf-8")); } public static String setStyle(FxTask task, File htmlFile, Charset charset, String css, boolean ignoreOriginal) { try { if (htmlFile == null || css == null) { return "InvalidData"; } String html = TextFileTools.readTexts(task, htmlFile, charset); Document doc = Jsoup.parse(html); if (doc == null) { return "InvalidData"; } if (charset == null) { charset = TextFileTools.charset(htmlFile); } if (ignoreOriginal) { doc.head().empty(); } if (!setCharset(task, doc, charset)) { return "Canceled"; } doc.head().appendChild(new Element("style").text(css)); return doc.outerHtml(); } catch (Exception e) { MyBoxLog.error(e); return null; } } // files should have been sorted public static boolean generateFrameset(List<File> files, File targetFile) { try { if (files == null || files.isEmpty()) { return false; } String namePrefix = FileNameTools.prefix(targetFile.getName()); File navFile = new File(targetFile.getParent() + File.separator + namePrefix + "_nav.html"); StringBuilder nav = new StringBuilder(); File first = null; for (File file : files) { String filepath = file.getAbsolutePath(); String name = file.getName(); if (filepath.equals(targetFile.getAbsolutePath()) || filepath.equals(navFile.getAbsolutePath())) { FileDeleteTools.delete(file); } else { if (first == null) { first = file; } if (file.getParent().equals(targetFile.getParent())) { nav.append("<a href=\"./").append(name).append("\" target=main>").append(name).append("</a><br>\n"); } else { nav.append("<a href=\"").append(file.toURI()).append("\" target=main>").append(filepath).append("</a><br>\n"); } } } if (first == null) { return false; } String body = nav.toString(); TextFileTools.writeFile(navFile, html(Languages.message("PathIndex"), body)); String frameset = " <FRAMESET border=2 cols=400,*>\n" + "<FRAME name=nav src=\"" + namePrefix + "_nav.html\" />\n"; if (first.getParent().equals(targetFile.getParent())) { frameset += "<FRAME name=main src=\"" + first.getName() + "\" />\n"; } else { frameset += "<FRAME name=main src=\"" + first.toURI() + "\" />\n"; } frameset += "</FRAMESET>"; File frameFile = new File(targetFile.getParent() + File.separator + namePrefix + ".html"); TextFileTools.writeFile(frameFile, html(null, frameset)); return frameFile.exists(); } catch (Exception e) { MyBoxLog.error(e.toString()); return false; } } // files should have been sorted public static void makePathList(File path, List<File> files, Map<File, Link> completedLinks) { if (files == null || files.isEmpty()) { return; } try { String listPrefix = "0000_" + Languages.message("PathIndex") + "_list"; StringBuilder csv = new StringBuilder(); String s = Languages.message("Address") + "," + Languages.message("File") + "," + Languages.message("Title") + "," + Languages.message("Name") + "," + Languages.message("Index") + "," + Languages.message("Time") + "\n"; csv.append(s); List<String> names = new ArrayList<>(); names.addAll(Arrays.asList(Languages.message("File"), Languages.message("Address"), Languages.message("Title"), Languages.message("Name"), Languages.message("Index"), Languages.message("Time"))); StringTable table = new StringTable(names, Languages.message("DownloadHistory")); for (File file : files) { String name = file.getName(); if (name.startsWith(listPrefix)) { FileDeleteTools.delete(file); } else { Link link = completedLinks.get(file); if (link == null) { s = file.getAbsolutePath() + ",,,," + DateTools.datetimeToString(FileTools.createTime(file)); csv.append(s); List<String> row = new ArrayList<>(); row.addAll(Arrays.asList(file.getAbsolutePath(), "", "", "", "", DateTools.datetimeToString(FileTools.createTime(file)))); table.add(row); } else { s = link.getUrl() + "," + file.getAbsolutePath() + "," + (link.getTitle() != null ? link.getTitle() : "") + "," + (link.getName() != null ? link.getName() : "") + "," + (link.getIndex() > 0 ? link.getIndex() : "") + "," + (link.getDlTime() != null ? DateTools.datetimeToString(link.getDlTime()) : "") + "\n"; csv.append(s); List<String> row = new ArrayList<>(); row.addAll(Arrays.asList(file.getAbsolutePath(), link.getUrl().toString(), link.getTitle() != null ? link.getTitle() : "", link.getName() != null ? link.getName() : "", link.getIndex() > 0 ? link.getIndex() + "" : "", link.getDlTime() != null ? DateTools.datetimeToString(link.getDlTime()) : "")); table.add(row); } } } String filename = path.getAbsolutePath() + File.separator + listPrefix + ".csv"; TextFileTools.writeFile(new File(filename), csv.toString()); filename = path.getAbsolutePath() + File.separator + listPrefix + ".html"; TextFileTools.writeFile(new File(filename), table.html()); } catch (Exception e) { MyBoxLog.error(e.toString()); } } public static int replace(FxTask currentTask, org.w3c.dom.Document doc, String findString, boolean reg, boolean caseInsensitive, String color, String bgColor, String font) { if (doc == null) { return 0; } NodeList nodeList = doc.getElementsByTagName("body"); if (nodeList == null || nodeList.getLength() < 1) { return 0; } FindReplaceString finder = FindReplaceString.create().setOperation(FindReplaceString.Operation.FindNext) .setFindString(findString).setIsRegex(reg).setCaseInsensitive(caseInsensitive).setMultiline(true); String replaceSuffix = " style=\"color:" + color + "; background: " + bgColor + "; font-size:" + font + ";\">" + findString + "</span>"; return replace(currentTask, finder, nodeList.item(0), 0, replaceSuffix); } public static int replace(FxTask currentTask, FindReplaceString finder, Node node, int index, String replaceSuffix) { if (node == null || replaceSuffix == null || finder == null) { return index; } String texts = node.getTextContent(); int newIndex = index; if (texts != null && !texts.isBlank()) { StringBuilder s = new StringBuilder(); while (true) { if (currentTask != null && !currentTask.isWorking()) { return -1; } finder.setInputString(texts).setAnchor(0).handleString(currentTask); if (currentTask != null && !currentTask.isWorking()) { return -1; } if (finder.getStringRange() == null) { break; } String replaceString = "<span id=\"MyBoxSearchLocation" + (++newIndex) + "\" " + replaceSuffix; if (finder.getLastStart() > 0) { s.append(texts.substring(0, finder.getLastStart())); } s.append(replaceString); texts = texts.substring(finder.getLastEnd()); } s.append(texts); node.setTextContent(s.toString()); } Node child = node.getFirstChild(); while (child != null) { if (currentTask != null && !currentTask.isWorking()) { return -1; } replace(currentTask, finder, child, newIndex, replaceSuffix); child = child.getNextSibling(); } return newIndex; } public static boolean relinkPage(FxTask task, File httpFile, Map<File, Link> completedLinks, Map<String, File> completedAddresses) { try { if (httpFile == null || !httpFile.exists() || completedAddresses == null) { return false; } Link baseLink = completedLinks.get(httpFile); if (baseLink == null) { return false; } String html = TextFileTools.readTexts(task, httpFile); List<Link> links = HtmlReadTools.links(baseLink.getUrl(), html); String replaced = ""; String unchecked = html; int pos; for (Link link : links) { if (task != null && !task.isWorking()) { return false; } try { String originalAddress = link.getAddressOriginal(); pos = unchecked.indexOf("\"" + originalAddress + "\""); if (pos < 0) { pos = unchecked.indexOf("'" + originalAddress + "'"); } if (pos < 0) { continue; } replaced += unchecked.substring(0, pos); unchecked = unchecked.substring(pos + originalAddress.length() + 2); File linkFile = completedAddresses.get(link.getAddress()); if (linkFile == null || !linkFile.exists()) { replaced += "\"" + originalAddress + "\""; continue; } if (linkFile.getParent().startsWith(httpFile.getParent())) { replaced += "\"" + linkFile.getName() + "\""; } else { replaced += "\"" + linkFile.getAbsolutePath() + "\""; } } catch (Exception e) { // MyBoxLog.debug(e); } } replaced += unchecked; File tmpFile = FileTmpTools.getTempFile(); TextFileTools.writeFile(tmpFile, replaced, TextFileTools.charset(httpFile)); return FileTools.override(tmpFile, httpFile); } catch (Exception e) { MyBoxLog.error(e.toString()); return false; } } public static void makePathFrameset(File path) { try { if (path == null || !path.isDirectory()) { return; } File[] pathFiles = path.listFiles(); if (pathFiles == null || pathFiles.length == 0) { return; } List<File> files = new ArrayList<>(); for (File file : pathFiles) { if (file.isFile()) { files.add(file); } } if (!files.isEmpty()) { Collections.sort(files, new Comparator<File>() { @Override public int compare(File f1, File f2) { return FileNameTools.compareName(f1, f2); } }); File frameFile = new File(path.getAbsolutePath() + File.separator + "0000_" + Languages.message("PathIndex") + ".html"); generateFrameset(files, frameFile); } for (File file : pathFiles) { if (file.isDirectory()) { makePathFrameset(file); } } } 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/alpha/MyBox/src/main/java/mara/mybox/tools/FloatMatrixTools.java
alpha/MyBox/src/main/java/mara/mybox/tools/FloatMatrixTools.java
package mara.mybox.tools; import java.util.Random; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; /** * @Author Mara * @CreateDate 2019-5-18 10:37:15 * @Version 1.0 * @Description * @License Apache License Version 2.0 */ public class FloatMatrixTools { // columnNumber is 0-based public static float[] columnValues(float[][] m, int columnNumber) { if (m == null || m.length == 0 || m[0].length <= columnNumber) { return null; } float[] column = new float[m.length]; for (int i = 0; i < m.length; ++i) { column[i] = m[i][columnNumber]; } return column; } public static float[][] columnVector(float x, float y, float z) { float[][] rv = new float[3][1]; rv[0][0] = x; rv[1][0] = y; rv[2][0] = z; return rv; } public static float[][] columnVector(float[] v) { float[][] rv = new float[v.length][1]; for (int i = 0; i < v.length; ++i) { rv[i][0] = v[i]; } return rv; } public static float[] matrix2Array(FxTask task, float[][] m) { if (m == null || m.length == 0 || m[0].length == 0) { return null; } int h = m.length; int w = m[0].length; float[] a = new float[w * h]; for (int j = 0; j < h; ++j) { if (task != null && !task.isWorking()) { return null; } System.arraycopy(m[j], 0, a, j * w, w); } return a; } public static float[][] array2Matrix(float[] a, int w) { if (a == null || a.length == 0 || w < 1) { return null; } int h = a.length / w; if (h < 1) { return null; } float[][] m = new float[h][w]; for (int j = 0; j < h; ++j) { for (int i = 0; i < w; ++i) { m[j][i] = a[j * w + i]; } } return m; } public static float[][] clone(float[][] matrix) { try { if (matrix == null) { return null; } int rowA = matrix.length, columnA = matrix[0].length; float[][] result = new float[rowA][columnA]; for (int i = 0; i < rowA; ++i) { System.arraycopy(matrix[i], 0, result[i], 0, columnA); } return result; } catch (Exception e) { return null; } } public static Number[][] clone(Number[][] matrix) { try { if (matrix == null) { return null; } int rowA = matrix.length, columnA = matrix[0].length; Number[][] result = new Number[rowA][columnA]; for (int i = 0; i < rowA; ++i) { System.arraycopy(matrix[i], 0, result[i], 0, columnA); } return result; } catch (Exception e) { return null; } } public static String print(float[][] matrix, int prefix, int scale) { try { if (matrix == null) { return ""; } String s = "", p = "", t = " "; for (int b = 0; b < prefix; b++) { p += " "; } int row = matrix.length, column = matrix[0].length; for (int i = 0; i < row; ++i) { s += p; for (int j = 0; j < column; ++j) { float d = FloatTools.scale(matrix[i][j], scale); s += d + t; } s += "\n"; } return s; } catch (Exception e) { return null; } } public static boolean same(float[][] matrixA, float[][] matrixB, int scale) { try { if (matrixA == null || matrixB == null || matrixA.length != matrixB.length || matrixA[0].length != matrixB[0].length) { return false; } int rows = matrixA.length; int columns = matrixA[0].length; for (int i = 0; i < rows; ++i) { for (int j = 0; j < columns; ++j) { if (scale < 0) { if (matrixA[i][j] != matrixB[i][j]) { return false; } } else { float a = FloatTools.scale(matrixA[i][j], scale); float b = FloatTools.scale(matrixB[i][j], scale); if (a != b) { return false; } } } } return true; } catch (Exception e) { return false; } } public static int[][] identityInt(int n) { try { if (n < 1) { return null; } int[][] result = new int[n][n]; for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { if (i == j) { result[i][j] = 1; } } } return result; } catch (Exception e) { return null; } } public static float[][] identityDouble(int n) { try { if (n < 1) { return null; } float[][] result = new float[n][n]; for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { if (i == j) { result[i][j] = 1; } } } return result; } catch (Exception e) { return null; } } public static float[][] randomMatrix(int n) { return randomMatrix(n, n); } public static float[][] randomMatrix(int m, int n) { try { if (n < 1) { return null; } float[][] result = new float[m][n]; Random r = new Random(); for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { result[i][j] = r.nextFloat(); } } return result; } catch (Exception e) { return null; } } public static float[][] vertivalMerge(float[][] matrixA, float[][] matrixB) { try { if (matrixA == null || matrixB == null || matrixA[0].length != matrixB[0].length) { return null; } int rowsA = matrixA.length, rowsB = matrixB.length; int columns = matrixA[0].length; float[][] result = new float[rowsA + rowsB][columns]; for (int i = 0; i < rowsA; ++i) { System.arraycopy(matrixA[i], 0, result[i], 0, columns); } for (int i = 0; i < rowsB; ++i) { System.arraycopy(matrixB[i], 0, result[i + rowsA], 0, columns); } return result; } catch (Exception e) { return null; } } public static float[][] horizontalMerge(float[][] matrixA, float[][] matrixB) { try { if (matrixA == null || matrixB == null || matrixA.length != matrixB.length) { return null; } int rows = matrixA.length; int columnsA = matrixA[0].length, columnsB = matrixB[0].length; int columns = columnsA + columnsB; float[][] result = new float[rows][columns]; for (int i = 0; i < rows; ++i) { System.arraycopy(matrixA[i], 0, result[i], 0, columnsA); System.arraycopy(matrixB[i], 0, result[i], columnsA, columnsB); } return result; } catch (Exception e) { return null; } } public static float[][] add(float[][] matrixA, float[][] matrixB) { try { if (matrixA == null || matrixB == null || matrixA.length != matrixB.length || matrixA[0].length != matrixB[0].length) { return null; } float[][] result = new float[matrixA.length][matrixA[0].length]; for (int i = 0; i < matrixA.length; ++i) { float[] rowA = matrixA[i]; float[] rowB = matrixB[i]; for (int j = 0; j < rowA.length; ++j) { result[i][j] = rowA[j] + rowB[j]; } } return result; } catch (Exception e) { return null; } } public static float[][] subtract(float[][] matrixA, float[][] matrixB) { try { if (matrixA == null || matrixB == null || matrixA.length != matrixB.length || matrixA[0].length != matrixB[0].length) { return null; } float[][] result = new float[matrixA.length][matrixA[0].length]; for (int i = 0; i < matrixA.length; ++i) { float[] rowA = matrixA[i]; float[] rowB = matrixB[i]; for (int j = 0; j < rowA.length; ++j) { result[i][j] = rowA[j] - rowB[j]; } } return result; } catch (Exception e) { return null; } } public static float[][] multiply(float[][] matrixA, float[][] matrixB) { try { int rowA = matrixA.length, columnA = matrixA[0].length; int rowB = matrixB.length, columnB = matrixB[0].length; if (columnA != rowB) { return null; } float[][] result = new float[rowA][columnB]; for (int i = 0; i < rowA; ++i) { for (int j = 0; j < columnB; ++j) { result[i][j] = 0; for (int k = 0; k < columnA; k++) { result[i][j] += matrixA[i][k] * matrixB[k][j]; } } } return result; } catch (Exception e) { MyBoxLog.debug(e); return null; } } public static float[] multiply(float[][] matrix, float[] columnVector) { if (matrix == null || columnVector == null) { return null; } float[] outputs = new float[matrix.length]; for (int i = 0; i < matrix.length; ++i) { float[] row = matrix[i]; outputs[i] = 0f; for (int j = 0; j < Math.min(row.length, columnVector.length); ++j) { outputs[i] += row[j] * columnVector[j]; } } return outputs; } public static float[][] transpose(float[][] matrix) { try { if (matrix == null) { return null; } int rowA = matrix.length, columnA = matrix[0].length; float[][] result = new float[columnA][rowA]; for (int i = 0; i < rowA; ++i) { for (int j = 0; j < columnA; ++j) { result[j][i] = matrix[i][j]; } } return result; } catch (Exception e) { return null; } } public static Number[][] transpose(Number[][] matrix) { try { if (matrix == null) { return null; } int rowA = matrix.length, columnA = matrix[0].length; Number[][] result = new Number[columnA][rowA]; for (int i = 0; i < rowA; ++i) { for (int j = 0; j < columnA; ++j) { result[j][i] = matrix[i][j]; } } return result; } catch (Exception e) { return null; } } public static float[][] normalize(float[][] matrix) { try { if (matrix == null) { return null; } int rowA = matrix.length, columnA = matrix[0].length; float[][] result = new float[rowA][columnA]; float sum = 0; for (int i = 0; i < rowA; ++i) { for (int j = 0; j < columnA; ++j) { sum += matrix[i][j]; } } if (sum == 0) { return null; } for (int i = 0; i < rowA; ++i) { for (int j = 0; j < columnA; ++j) { result[i][j] = matrix[i][j] / sum; } } return result; } catch (Exception e) { return null; } } public static float[][] integer(float[][] matrix) { try { if (matrix == null) { return null; } int rowA = matrix.length, columnA = matrix[0].length; float[][] result = new float[rowA][columnA]; for (int i = 0; i < rowA; ++i) { for (int j = 0; j < columnA; ++j) { result[i][j] = Math.round(matrix[i][j]); } } return result; } catch (Exception e) { return null; } } public static float[][] scale(float[][] matrix, int scale) { try { if (matrix == null) { return null; } int rowA = matrix.length, columnA = matrix[0].length; float[][] result = new float[rowA][columnA]; for (int i = 0; i < rowA; ++i) { for (int j = 0; j < columnA; ++j) { result[i][j] = FloatTools.scale(matrix[i][j], scale); } } return result; } catch (Exception e) { return null; } } public static float[][] multiply(float[][] matrix, float p) { try { if (matrix == null) { return null; } int rowA = matrix.length, columnA = matrix[0].length; float[][] result = new float[rowA][columnA]; for (int i = 0; i < rowA; ++i) { for (int j = 0; j < columnA; ++j) { result[i][j] = matrix[i][j] * p; } } return result; } catch (Exception e) { return null; } } public static float[][] divide(float[][] matrix, float p) { try { if (matrix == null || p == 0) { return null; } int rowA = matrix.length, columnA = matrix[0].length; float[][] result = new float[rowA][columnA]; for (int i = 0; i < rowA; ++i) { for (int j = 0; j < columnA; ++j) { result[i][j] = matrix[i][j] / p; } } return result; } catch (Exception e) { return null; } } public static float[][] power(float[][] matrix, int n) { try { if (matrix == null || n < 0) { return null; } int row = matrix.length, column = matrix[0].length; if (row != column) { return null; } float[][] tmp = clone(matrix); float[][] result = identityDouble(row); while (n > 0) { if (n % 2 > 0) { result = multiply(result, tmp); } tmp = multiply(tmp, tmp); n = n / 2; } return result; } catch (Exception e) { return null; } } public static float[][] inverseByAdjoint(float[][] matrix) { try { if (matrix == null) { return null; } int row = matrix.length, column = matrix[0].length; if (row != column) { return null; } float det = determinantByComplementMinor(matrix); if (det == 0) { return null; } float[][] inverse = new float[row][column]; float[][] adjoint = adjoint(matrix); for (int i = 0; i < row; ++i) { for (int j = 0; j < column; ++j) { inverse[i][j] = adjoint[i][j] / det; } } return inverse; } catch (Exception e) { return null; } } public static float[][] inverse(float[][] matrix) { return inverseByElimination(matrix); } public static float[][] inverseByElimination(float[][] matrix) { try { if (matrix == null) { return null; } int rows = matrix.length, columns = matrix[0].length; if (rows != columns) { return null; } float[][] augmented = new float[rows][columns * 2]; for (int i = 0; i < rows; ++i) { System.arraycopy(matrix[i], 0, augmented[i], 0, columns); augmented[i][i + columns] = 1; } augmented = reducedRowEchelonForm(augmented); float[][] inverse = new float[rows][columns]; for (int i = 0; i < rows; ++i) { for (int j = 0; j < columns; ++j) { inverse[i][j] = augmented[i][j + columns]; } } return inverse; } catch (Exception e) { return null; } } // rowIndex, columnIndex are 0-based. public static float[][] complementMinor(float[][] matrix, int rowIndex, int columnIndex) { try { if (matrix == null || rowIndex < 0 || columnIndex < 0) { return null; } int rows = matrix.length, columns = matrix[0].length; if (rowIndex >= rows || columnIndex >= columns) { return null; } float[][] minor = new float[rows - 1][columns - 1]; int minorRow = 0, minorColumn; for (int i = 0; i < rows; ++i) { if (i == rowIndex) { continue; } minorColumn = 0; for (int j = 0; j < columns; ++j) { if (j == columnIndex) { continue; } minor[minorRow][minorColumn++] = matrix[i][j]; } minorRow++; } return minor; } catch (Exception e) { MyBoxLog.debug(e); return null; } } public static float[][] adjoint(float[][] matrix) { try { if (matrix == null) { return null; } int row = matrix.length, column = matrix[0].length; if (row != column) { return null; } float[][] adjoint = new float[row][column]; if (row == 1) { adjoint[0][0] = matrix[0][0]; return adjoint; } for (int i = 0; i < row; ++i) { for (int j = 0; j < column; ++j) { adjoint[j][i] = (float) Math.pow(-1, i + j) * determinantByComplementMinor(complementMinor(matrix, i, j)); } } return adjoint; } catch (Exception e) { MyBoxLog.debug(e); return null; } } public static float determinant(float[][] matrix) throws Exception { return determinantByElimination(matrix); } public static float determinantByComplementMinor(float[][] matrix) throws Exception { try { if (matrix == null) { throw new Exception("InvalidValue"); } int row = matrix.length, column = matrix[0].length; if (row != column) { throw new Exception("InvalidValue"); } if (row == 1) { return matrix[0][0]; } if (row == 2) { return matrix[0][0] * matrix[1][1] - matrix[1][0] * matrix[0][1]; } float v = 0; for (int j = 0; j < column; ++j) { float[][] minor = complementMinor(matrix, 0, j); v += matrix[0][j] * Math.pow(-1, j) * determinantByComplementMinor(minor); } return v; } catch (Exception e) { // MyBoxLog.debug(e); throw e; } } public static float determinantByElimination(float[][] matrix) throws Exception { try { if (matrix == null) { throw new Exception("InvalidValue"); } int rows = matrix.length, columns = matrix[0].length; if (rows != columns) { throw new Exception("InvalidValue"); } float[][] ref = rowEchelonForm(matrix); if (ref[rows - 1][columns - 1] == 0) { return 0; } float det = 1; for (int i = 0; i < rows; ++i) { det *= ref[i][i]; } return det; } catch (Exception e) { MyBoxLog.debug(e); throw e; } } public static float[][] hadamardProduct(float[][] matrixA, float[][] matrixB) { try { int rowA = matrixA.length, columnA = matrixA[0].length; int rowB = matrixB.length, columnB = matrixB[0].length; if (rowA != rowB || columnA != columnB) { return null; } float[][] result = new float[rowA][columnA]; for (int i = 0; i < rowA; ++i) { for (int j = 0; j < columnA; ++j) { result[i][j] = matrixA[i][j] * matrixB[i][j]; } } return result; } catch (Exception e) { MyBoxLog.debug(e); return null; } } public static float[][] kroneckerProduct(float[][] matrixA, float[][] matrixB) { try { int rowsA = matrixA.length, columnsA = matrixA[0].length; int rowsB = matrixB.length, columnsB = matrixB[0].length; float[][] result = new float[rowsA * rowsB][columnsA * columnsB]; for (int i = 0; i < rowsA; ++i) { for (int j = 0; j < columnsA; ++j) { for (int m = 0; m < rowsB; m++) { for (int n = 0; n < columnsB; n++) { result[i * rowsB + m][j * columnsB + n] = matrixA[i][j] * matrixB[m][n]; } } } } return result; } catch (Exception e) { MyBoxLog.debug(e); return null; } } public static float[][] rowEchelonForm(float[][] matrix) { try { int rows = matrix.length, columns = matrix[0].length; float[][] result = clone(matrix); for (int i = 0; i < Math.min(rows, columns); ++i) { if (result[i][i] == 0) { int row = -1; for (int k = i + 1; k < rows; k++) { if (result[k][i] != 0) { row = k; break; } } if (row < 0) { break; } for (int j = i; j < columns; ++j) { float temp = result[row][j]; result[row][j] = result[i][j]; result[i][j] = temp; } } for (int k = i + 1; k < rows; k++) { if (result[i][i] == 0) { continue; } float ratio = result[k][i] / result[i][i]; for (int j = i; j < columns; ++j) { result[k][j] -= ratio * result[i][j]; } } } return result; } catch (Exception e) { MyBoxLog.debug(e); return null; } } public static float[][] reducedRowEchelonForm(float[][] matrix) { try { int rows = matrix.length, columns = matrix[0].length; float[][] result = rowEchelonForm(matrix); for (int i = Math.min(rows - 1, columns - 1); i >= 0; --i) { float dd = result[i][i]; if (dd == 0) { continue; } for (int k = i - 1; k >= 0; k--) { float ratio = result[k][i] / dd; for (int j = k; j < columns; ++j) { result[k][j] -= ratio * result[i][j]; } } for (int j = i; j < columns; ++j) { result[i][j] = result[i][j] / dd; } } return result; } catch (Exception e) { MyBoxLog.debug(e); return null; } } public static float rank(float[][] matrix) throws Exception { try { if (matrix == null) { throw new Exception("InvalidValue"); } int rows = matrix.length, columns = matrix[0].length; float[][] d = clone(matrix); int i = 0; for (i = 0; i < Math.min(rows, columns); ++i) { if (d[i][i] == 0) { int row = -1; for (int k = i + 1; k < rows; k++) { if (d[k][i] != 0) { row = k; break; } } if (row < 0) { break; } for (int j = i; j < columns; ++j) { float temp = d[row][j]; d[row][j] = d[i][j]; d[i][j] = temp; } } for (int k = i + 1; k < rows; k++) { if (d[i][i] == 0) { continue; } float ratio = d[k][i] / d[i][i]; for (int j = i; j < columns; ++j) { d[k][j] -= ratio * d[i][j]; } } } return i; } catch (Exception e) { MyBoxLog.debug(e); throw e; } } public static float[][] swapRow(float matrix[][], int a, int b) { try { for (int j = 0; j < matrix[0].length; ++j) { float temp = matrix[a][j]; matrix[a][j] = matrix[b][j]; matrix[b][j] = temp; } } catch (Exception e) { } return matrix; } public static float[][] swapColumn(float matrix[][], int columnA, int columnB) { try { for (float[] matrix1 : matrix) { float temp = matrix1[columnA]; matrix1[columnA] = matrix1[columnB]; matrix1[columnB] = temp; } } catch (Exception e) { } return matrix; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/tools/AESTools.java
alpha/MyBox/src/main/java/mara/mybox/tools/AESTools.java
package mara.mybox.tools; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.SecureRandom; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; import java.util.Base64; import java.util.HashMap; import java.util.Map; import java.util.Random; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import mara.mybox.dev.MyBoxLog; /** * Reference: https://www.cnblogs.com/zhupig3028/p/16259271.html * * @Author Mara * @CreateDate 2023-3-29 * @License Apache License Version 2.0 */ // Refer To public class AESTools { private final static String ENCODING = "utf-8"; private final static String ALGORITHM = "AES"; private final static String PATTERN = "AES/ECB/pkcs5padding"; public static final String ALLCHAR = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; public static final String DefaultKey = "8SaT6V9w5xpUr7qs"; public static String encrypt(String plainText) { return encrypt(plainText, DefaultKey); } public static String decrypt(String plainText) { return decrypt(plainText, DefaultKey); } public static String generateAESKey() { StringBuilder sb = new StringBuilder(); Random random = new Random(); for (int i = 0; i < 16; i++) { sb.append(ALLCHAR.charAt(random.nextInt(ALLCHAR.length()))); } return sb.toString(); } public static String generate3DESKey() { StringBuilder sb = new StringBuilder(); Random random = new Random(); for (int i = 0; i < 24; i++) { sb.append(ALLCHAR.charAt(random.nextInt(ALLCHAR.length()))); } return sb.toString(); } public static Map<String, String> genKeyPair() { try { HashMap<String, String> stringStringHashMap = new HashMap<>(); KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA"); keyPairGen.initialize(1024, new SecureRandom()); KeyPair keyPair = keyPairGen.generateKeyPair(); RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); String publicKeyString = Base64.getEncoder().encodeToString(publicKey.getEncoded()); String privateKeyString = Base64.getEncoder().encodeToString((privateKey.getEncoded())); stringStringHashMap.put("0", publicKeyString); stringStringHashMap.put("1", privateKeyString); return stringStringHashMap; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static String encrypt(String plainText, String key) { try { if (plainText == null || key == null || key.length() != 16) { return null; } SecretKey secretKey = new SecretKeySpec(key.getBytes(ENCODING), ALGORITHM); Cipher cipher = Cipher.getInstance(PATTERN); cipher.init(Cipher.ENCRYPT_MODE, secretKey); byte[] encryptData = cipher.doFinal(plainText.getBytes(ENCODING)); return Base64.getEncoder().encodeToString(encryptData); } catch (Exception e) { MyBoxLog.error(e); return null; } } public static String decrypt(String plainText, String key) { try { if (plainText == null || key == null) { return null; } SecretKey secretKey = new SecretKeySpec(key.getBytes(ENCODING), ALGORITHM); Cipher cipher = Cipher.getInstance(PATTERN); cipher.init(Cipher.DECRYPT_MODE, secretKey); byte[] encryptData = cipher.doFinal(Base64.getDecoder().decode(plainText)); return new String(encryptData, ENCODING); } catch (Exception e) { MyBoxLog.error(e); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/tools/HtmlReadTools.java
alpha/MyBox/src/main/java/mara/mybox/tools/HtmlReadTools.java
package mara.mybox.tools; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.zip.GZIPInputStream; import javafx.concurrent.Task; import javax.net.ssl.HttpsURLConnection; import mara.mybox.controller.BaseController; import mara.mybox.controller.HtmlTableController; import mara.mybox.data.Link; import mara.mybox.data.StringTable; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.DownloadTask; import mara.mybox.fxml.FxTask; import mara.mybox.value.AppValues; import static mara.mybox.value.Languages.message; import mara.mybox.value.UserConfig; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; /** * @Author Mara * @CreateDate 2021-8-1 * @License Apache License Version 2.0 */ public class HtmlReadTools { public final static String httpUserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0) Gecko/20100101 Firefox/6.0"; /* read html */ public static File download(FxTask task, String urlAddress) { return download(task, urlAddress, UserConfig.getInt("WebConnectTimeout", 10000), UserConfig.getInt("WebReadTimeout", 10000)); } public static File download(FxTask task, String urlAddress, int connectTimeout, int readTimeout) { try { if (urlAddress == null) { return null; } URL url = UrlTools.url(urlAddress); if (url == null) { return null; } File tmpFile = FileTmpTools.getTempFile(); String protocal = url.getProtocol(); if ("file".equalsIgnoreCase(protocal)) { FileCopyTools.copyFile(new File(url.getFile()), tmpFile); } else if ("https".equalsIgnoreCase(protocal)) { HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); if (connectTimeout > 0) { connection.setConnectTimeout(connectTimeout); } if (readTimeout > 0) { connection.setReadTimeout(readTimeout); } // connection.setRequestProperty("User-Agent", httpUserAgent); connection.connect(); if ("gzip".equalsIgnoreCase(connection.getContentEncoding())) { try (final BufferedInputStream inStream = new BufferedInputStream(new GZIPInputStream(connection.getInputStream())); final BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(tmpFile))) { byte[] buf = new byte[AppValues.IOBufferLength]; int len; while ((len = inStream.read(buf)) > 0) { if (task != null && !task.isWorking()) { return null; } outputStream.write(buf, 0, len); } } } else { try (final BufferedInputStream inStream = new BufferedInputStream(connection.getInputStream()); final BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(tmpFile))) { byte[] buf = new byte[AppValues.IOBufferLength]; int len; while ((len = inStream.read(buf)) > 0) { if (task != null && !task.isWorking()) { return null; } outputStream.write(buf, 0, len); } } } } else if ("http".equalsIgnoreCase(protocal)) { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // connection.setRequestMethod("GET"); // connection.setRequestProperty("User-Agent", httpUserAgent); connection.setConnectTimeout(UserConfig.getInt("WebConnectTimeout", 10000)); connection.setReadTimeout(UserConfig.getInt("WebReadTimeout", 10000)); connection.setUseCaches(false); connection.connect(); if ("gzip".equalsIgnoreCase(connection.getContentEncoding())) { try (final BufferedInputStream inStream = new BufferedInputStream(new GZIPInputStream(connection.getInputStream())); final BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(tmpFile))) { byte[] buf = new byte[AppValues.IOBufferLength]; int len; while ((len = inStream.read(buf)) > 0) { if (task != null && !task.isWorking()) { return null; } outputStream.write(buf, 0, len); } } } else { try (final BufferedInputStream inStream = new BufferedInputStream(connection.getInputStream()); final BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(tmpFile))) { byte[] buf = new byte[AppValues.IOBufferLength]; int len; while ((len = inStream.read(buf)) > 0) { if (task != null && !task.isWorking()) { return null; } outputStream.write(buf, 0, len); } } } } if (tmpFile == null || !tmpFile.exists()) { return null; } if (tmpFile.length() == 0) { FileDeleteTools.delete(tmpFile); return null; } return tmpFile; } catch (Exception e) { // MyBoxLog.console(e.toString() + " " + urlAddress); return null; } } public static String url2html(FxTask task, String urlAddress) { try { if (urlAddress == null) { return null; } URL url = UrlTools.url(urlAddress); if (url == null) { return null; } String protocal = url.getProtocol(); if ("file".equalsIgnoreCase(protocal)) { return TextFileTools.readTexts(task, new File(url.getFile())); } else if ("https".equalsIgnoreCase(protocal) || "http".equalsIgnoreCase(protocal)) { File file = download(task, url.toString()); if (file != null) { return TextFileTools.readTexts(task, file); } } } catch (Exception e) { MyBoxLog.error(e.toString() + " " + urlAddress); } return null; } public static Document url2doc(FxTask task, String urlAddress) { try { String html = url2html(task, urlAddress); if (html != null) { return Jsoup.parse(html); } } catch (Exception e) { MyBoxLog.error(e.toString() + " " + urlAddress); } return null; } public static Document file2doc(FxTask task, File file) { try { if (file == null || !file.exists()) { return null; } String html = TextFileTools.readTexts(task, file); if (html != null) { return Jsoup.parse(html); } } catch (Exception e) { MyBoxLog.error(e.toString() + " " + file); } return null; } public static String baseURI(FxTask task, String urlAddress) { try { Document doc = url2doc(task, urlAddress); if (doc == null) { return null; } return doc.baseUri(); } catch (Exception e) { MyBoxLog.debug(e.toString() + " " + urlAddress); return null; } } public static File url2image(FxTask task, String address, String name) { try { if (address == null) { return null; } String suffix = null; if (name != null && !name.isBlank()) { suffix = FileNameTools.ext(name); } String addrSuffix = FileNameTools.ext(address); if (addrSuffix != null && !addrSuffix.isBlank()) { if (suffix == null || suffix.isBlank() || !addrSuffix.equalsIgnoreCase(suffix)) { suffix = addrSuffix; } } if (suffix == null || (suffix.length() != 3 && !"jpeg".equalsIgnoreCase(suffix) && !"tiff".equalsIgnoreCase(suffix))) { suffix = "jpg"; } File tmpFile = download(task, address); if (tmpFile == null) { return null; } File imageFile = new File(tmpFile.getAbsoluteFile() + "." + suffix); if (FileTools.override(tmpFile, imageFile)) { return imageFile; } else { return null; } } catch (Exception e) { MyBoxLog.debug(e, address); return null; } } public static void requestHead(BaseController controller, String link) { if (controller == null || link == null) { return; } Task infoTask = new DownloadTask() { @Override protected boolean initValues() { readHead = true; address = link; return super.initValues(); } @Override protected void whenSucceeded() { if (head == null) { controller.popError(message("InvalidData")); return; } String table = requestHeadTable(url, head); HtmlTableController.open(table); } @Override protected void whenFailed() { if (error != null) { controller.popError(error); } else { controller.popFailed(); } } }; controller.start(infoTask); } public static Map<String, String> requestHead(URL url) { try { if (!url.getProtocol().startsWith("http")) { return null; } HttpURLConnection connection = NetworkTools.httpConnection(url); Map<String, String> head = HtmlReadTools.requestHead(connection); connection.disconnect(); return head; } catch (Exception e) { MyBoxLog.debug(e); return null; } } public static Map<String, String> requestHead(HttpURLConnection connection) { try { if (connection == null) { return null; } Map<String, String> head = new HashMap(); connection.setRequestMethod("HEAD"); head.put("ResponseCode", connection.getResponseCode() + ""); head.put("ResponseMessage", connection.getResponseMessage()); head.put("RequestMethod", connection.getRequestMethod()); head.put("ContentEncoding", connection.getContentEncoding()); head.put("ContentType", connection.getContentType()); head.put("ContentLength", connection.getContentLength() + ""); head.put("Expiration", DateTools.datetimeToString(connection.getExpiration())); head.put("LastModified", DateTools.datetimeToString(connection.getLastModified())); for (String key : connection.getHeaderFields().keySet()) { head.put("HeaderField_" + key, connection.getHeaderFields().get(key).toString()); } for (String key : connection.getRequestProperties().keySet()) { head.put("RequestProperty_" + key, connection.getRequestProperties().get(key).toString()); } return head; } catch (Exception e) { MyBoxLog.debug(e); return null; } } public static String requestHeadTable(URL url) { return requestHeadTable(url, HtmlReadTools.requestHead(url)); } public static String requestHeadTable(URL url, Map<String, String> head) { try { if (url == null || head == null) { return null; } StringBuilder s = new StringBuilder(); s.append("<h1 class=\"center\">").append(url.toString()).append("</h1>\n"); s.append("<hr>\n"); List<String> names = new ArrayList<>(); names.addAll(Arrays.asList(message("Name"), message("Value"))); StringTable table = new StringTable(names); for (String name : head.keySet()) { if (name.startsWith("HeaderField_") || name.startsWith("RequestProperty_")) { continue; } List<String> row = new ArrayList<>(); row.addAll(Arrays.asList(name, head.get(name))); table.add(row); } s.append(StringTable.tableDiv(table)); s.append("<h2 class=\"center\">").append("Header Fields").append("</h2>\n"); int hlen = "HeaderField_".length(); for (Object key : head.keySet()) { String name = (String) key; if (!name.startsWith("HeaderField_")) { continue; } List<String> row = new ArrayList<>(); row.addAll(Arrays.asList(name.substring(hlen), (String) head.get(key))); table.add(row); } s.append(StringTable.tableDiv(table)); s.append("<h2 class=\"center\">").append("Request Property").append("</h2>\n"); int rlen = "RequestProperty_".length(); for (String name : head.keySet()) { if (!name.startsWith("RequestProperty_")) { continue; } List<String> row = new ArrayList<>(); row.addAll(Arrays.asList(name.substring(rlen), head.get(name))); table.add(row); } s.append(StringTable.tableDiv(table)); return s.toString(); } catch (Exception e) { MyBoxLog.debug(e); return null; } } /* parse html */ public static String title(String html) { Document doc = Jsoup.parse(html); if (doc == null) { return null; } return doc.title(); } public static String head(String html) { Document doc = Jsoup.parse(html); if (doc == null || doc.head() == null) { return null; } return doc.head().outerHtml(); } public static Charset charset(String html) { try { Document doc = Jsoup.parse(html); Charset charset = null; if (doc != null) { charset = doc.charset(); } return charset == null ? Charset.forName("UTF-8") : charset; } catch (Exception e) { return null; } } // public static String body(String html) { // return body(html, false); // } public static String body(String html, boolean withTag) { try { Element body = Jsoup.parse(html).body(); return withTag ? body.outerHtml() : body.html(); } catch (Exception e) { return null; } } public static String toc(String html, int indentSize) { try { if (html == null) { return null; } Document doc = Jsoup.parse(html); if (doc == null) { return null; } org.jsoup.nodes.Element body = doc.body(); if (body == null) { return null; } String indent = ""; for (int i = 0; i < indentSize; i++) { indent += " "; } StringBuilder s = new StringBuilder(); toc(body, indent, s); return s.toString(); } catch (Exception e) { MyBoxLog.error(e.toString()); return null; } } public static void toc(Element element, String indent, StringBuilder s) { try { if (element == null || s == null || indent == null) { return; } String tag = element.tagName(); String content = element.text(); if (tag != null && content != null && !content.isBlank()) { content += "\n"; if (tag.equalsIgnoreCase("h1")) { s.append(content); } else if (tag.equalsIgnoreCase("h2")) { s.append(indent).append(content); } else if (tag.equalsIgnoreCase("h3")) { s.append(indent).append(indent).append(content); } else if (tag.equalsIgnoreCase("h4")) { s.append(indent).append(indent).append(indent).append(content); } else if (tag.equalsIgnoreCase("h5")) { s.append(indent).append(indent).append(indent).append(indent).append(content); } else if (tag.equalsIgnoreCase("h6")) { s.append(indent).append(indent).append(indent).append(indent).append(indent).append(content); } } Elements children = element.children(); if (children == null || children.isEmpty()) { return; } for (org.jsoup.nodes.Element child : children) { toc(child, indent, s); } } catch (Exception e) { MyBoxLog.error(e.toString()); } } public static List<Link> links(URL baseURL, String html) { if (html == null) { return null; } Document doc = Jsoup.parse(html); Elements elements = doc.getElementsByTag("a"); List<Link> links = new ArrayList<>(); for (org.jsoup.nodes.Element element : elements) { String linkAddress = element.attr("href"); try { URL url = UrlTools.fullUrl(baseURL, linkAddress); Link link = Link.create().setUrl(url).setAddress(url.toString()).setAddressOriginal(linkAddress) .setName(element.text()).setTitle(element.attr("title")).setIndex(links.size()); links.add(link); } catch (Exception e) { // MyBoxLog.console(linkAddress); } } return links; } public static List<Link> links(FxTask task, Link addressLink, File path, Link.FilenameType nameType) { try { if (addressLink == null || path == null) { return null; } List<Link> validLinks = new ArrayList<>(); URL url = addressLink.getUrl(); Link coverLink = Link.create().setUrl(url).setAddress(url.toString()).setName("0000_" + path.getName()).setTitle(path.getName()); coverLink.setIndex(0).setFile(new File(coverLink.filename(path, nameType)).getAbsolutePath()); validLinks.add(coverLink); String html = addressLink.getHtml(); if (html == null) { html = TextFileTools.readTexts(task, new File(addressLink.getFile())); } List<Link> links = HtmlReadTools.links(url, html); for (Link link : links) { if (task != null && !task.isWorking()) { return null; } if (link.getAddress() == null) { continue; } String filename = link.filename(path, nameType); if (filename == null) { continue; } link.setFile(new File(filename).getAbsolutePath()); link.setIndex(validLinks.size()); validLinks.add(link); } return validLinks; } catch (Exception e) { MyBoxLog.error(e.toString()); return null; } } public static List<StringTable> Tables(String html, String name) { try { if (html == null || html.isBlank()) { return null; } List<StringTable> tables = new ArrayList<>(); Document doc = Jsoup.parse(html); Elements tablesList = doc.getElementsByTag("table"); String titlePrefix = name != null ? name + "_t_" : "t_"; int count = 0; if (tablesList != null) { for (org.jsoup.nodes.Element table : tablesList) { StringTable stringTable = new StringTable(); stringTable.setTitle(titlePrefix + (++count)); List<List<String>> data = new ArrayList<>(); List<String> names = null; Elements trList = table.getElementsByTag("tr"); if (trList != null) { for (org.jsoup.nodes.Element tr : trList) { if (names == null) { Elements thList = tr.getElementsByTag("th"); if (thList != null) { names = new ArrayList<>(); for (org.jsoup.nodes.Element th : thList) { names.add(th.text()); } if (!names.isEmpty()) { stringTable.setNames(names); } } } Elements tdList = tr.getElementsByTag("td"); if (tdList != null) { List<String> row = new ArrayList<>(); for (org.jsoup.nodes.Element td : tdList) { row.add(td.text()); } if (!row.isEmpty()) { data.add(row); } } } } stringTable.setData(data); tables.add(stringTable); } } return tables; } catch (Exception e) { MyBoxLog.error(e.toString()); return null; } } public static String removeNode(String html, String id) { try { if (html == null || id == null || id.isBlank()) { return html; } Document doc = Jsoup.parse(html); org.jsoup.nodes.Element element = doc.getElementById(id); if (element != null) { element.remove(); return doc.outerHtml(); } else { return html; } } catch (Exception e) { MyBoxLog.debug(e); return html; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/tools/FileDeleteTools.java
alpha/MyBox/src/main/java/mara/mybox/tools/FileDeleteTools.java
package mara.mybox.tools; import java.awt.Desktop; import java.io.File; import java.nio.file.Files; import java.nio.file.Paths; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; /** * @Author Mara * @CreateDate 2021-8-1 * @License Apache License Version 2.0 */ public class FileDeleteTools { public static boolean delete(String fileName) { return delete(null, fileName); } public static boolean delete(FxTask currentTask, String fileName) { if (fileName == null || fileName.isBlank()) { return false; } return delete(currentTask, new File(fileName)); } public static boolean delete(File file) { return delete(null, file); } public static boolean delete(FxTask currentTask, File file) { try { if (file == null || !file.exists()) { return true; } System.gc(); if (file.isDirectory()) { return deleteDir(currentTask, file); } else { return file.delete(); } } catch (Exception e) { MyBoxLog.error(e); return false; } } public static boolean deleteDir(File file) { return delete(null, file); } public static boolean deleteDir(FxTask currentTask, File file) { if (file == null || (currentTask != null && !currentTask.isWorking())) { return false; } if (file.exists() && file.isDirectory()) { File[] children = file.listFiles(); if (children != null) { for (File child : children) { if ((currentTask != null && !currentTask.isWorking()) || !deleteDir(currentTask, child)) { return false; } } } } return file.delete(); // FileUtils.deleteQuietly(dir); // return true; } public static boolean clearDir(FxTask currentTask, File file) { if (file == null || (currentTask != null && !currentTask.isWorking())) { return false; } if (file.exists() && file.isDirectory()) { File[] children = file.listFiles(); if (children != null) { for (File child : children) { if ((currentTask != null && !currentTask.isWorking())) { return false; } if (child.isDirectory()) { if (clearDir(currentTask, child)) { child.delete(); } else { return false; } } else { child.delete(); } } } } return true; // try { // FileUtils.cleanDirectory(dir); // return true; // } catch (Exception e) { // MyBoxLog.error(e); // return false; // } } public static boolean deleteDirExcept(FxTask currentTask, File dir, File except) { if (dir.isDirectory()) { File[] children = dir.listFiles(); if (children != null) { for (File child : children) { if ((currentTask != null && !currentTask.isWorking())) { return false; } if (child.equals(except)) { continue; } if (!deleteDirExcept(currentTask, child, except)) { return false; } } } } return delete(currentTask, dir); } public static void deleteNestedDir(FxTask currentTask, File sourceDir) { try { if ((currentTask != null && !currentTask.isWorking()) || sourceDir == null || !sourceDir.exists() || !sourceDir.isDirectory()) { return; } System.gc(); File targetTmpDir = FileTmpTools.getTempDirectory(); deleteNestedDir(currentTask, sourceDir, targetTmpDir); deleteDir(currentTask, targetTmpDir); deleteDir(currentTask, sourceDir); } catch (Exception e) { MyBoxLog.error(e.toString()); } } public static void deleteNestedDir(FxTask currentTask, File sourceDir, File tmpDir) { try { if ((currentTask != null && !currentTask.isWorking()) || sourceDir == null || !sourceDir.exists()) { return; } if (sourceDir.isDirectory()) { File[] files = sourceDir.listFiles(); if (files == null || files.length == 0) { return; } for (File file : files) { if ((currentTask != null && !currentTask.isWorking())) { return; } if (file.isDirectory()) { File[] subfiles = file.listFiles(); if (subfiles != null) { for (File subfile : subfiles) { if ((currentTask != null && !currentTask.isWorking())) { return; } if (subfile.isDirectory()) { String target = tmpDir.getAbsolutePath() + File.separator + subfile.getName(); new File(target).getParentFile().mkdirs(); Files.move(Paths.get(subfile.getAbsolutePath()), Paths.get(target)); } else { delete(currentTask, subfile); } } } file.delete(); } else { delete(currentTask, file); } } if ((currentTask != null && !currentTask.isWorking())) { return; } deleteNestedDir(currentTask, tmpDir, sourceDir); } } catch (Exception e) { MyBoxLog.error(e.toString()); } } public static int deleteEmptyDir(FxTask currentTask, File dir, boolean trash) { return deleteEmptyDir(currentTask, dir, 0, trash); } public static int deleteEmptyDir(FxTask currentTask, File dir, int count, boolean trash) { if ((currentTask != null && !currentTask.isWorking())) { return count; } if (dir != null && dir.exists() && dir.isDirectory()) { File[] children = dir.listFiles(); if (children == null || children.length == 0) { boolean ok; if (trash) { ok = Desktop.getDesktop().moveToTrash(dir); } else { ok = deleteDir(currentTask, dir); } if (ok) { return ++count; } else { return count; } } for (File child : children) { if ((currentTask != null && !currentTask.isWorking())) { return count; } if (child.isDirectory()) { count = deleteEmptyDir(currentTask, child, count, trash); } } children = dir.listFiles(); if (children == null || children.length == 0) { boolean ok; if (trash) { ok = Desktop.getDesktop().moveToTrash(dir); } else { ok = deleteDir(currentTask, dir); } if (ok) { return ++count; } else { return count; } } } return count; } public static void clearJavaIOTmpPath(FxTask currentTask) { try { System.gc(); clearDir(currentTask, FileTools.javaIOTmpPath()); } catch (Exception e) { // MyBoxLog.debug(e); } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/tools/XmlTools.java
alpha/MyBox/src/main/java/mara/mybox/tools/XmlTools.java
package mara.mybox.tools; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileReader; import java.io.StringReader; import java.sql.Connection; import java.util.ArrayList; import java.util.List; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import mara.mybox.controller.BaseController; import mara.mybox.data.XmlTreeNode; import static mara.mybox.data.XmlTreeNode.NodeType.CDATA; import static mara.mybox.data.XmlTreeNode.NodeType.Comment; import static mara.mybox.data.XmlTreeNode.NodeType.ProcessingInstruction; import static mara.mybox.data.XmlTreeNode.NodeType.Text; import mara.mybox.db.DerbyBase; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.fxml.PopTools; import static mara.mybox.value.Languages.message; import mara.mybox.value.UserConfig; import org.w3c.dom.Document; import org.w3c.dom.DocumentType; import org.w3c.dom.Element; import org.w3c.dom.Entity; import org.w3c.dom.EntityReference; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.Notation; import org.xml.sax.ErrorHandler; import org.xml.sax.InputSource; import org.xml.sax.SAXParseException; /** * @Author Mara * @CreateDate 2023-2-12 * @License Apache License Version 2.0 */ public class XmlTools { public static Transformer transformer; public static DocumentBuilder builder; public static boolean ignoreBlankInstrution; public static boolean ignoreBlankComment; public static boolean ignoreBlankText; public static boolean ignoreComment; public static boolean ignoreBlankCDATA; /* encode */ public static String xmlTag(String tag) { return message(tag).replaceAll(" ", "_"); } public static boolean matchXmlTag(String matchTo, String s) { try { if (matchTo == null || s == null) { return false; } return message("en", matchTo).replaceAll(" ", "_").equalsIgnoreCase(s) || message("zh", matchTo).replaceAll(" ", "_").equalsIgnoreCase(s) || message(matchTo).replaceAll(" ", "_").equalsIgnoreCase(s) || matchTo.replaceAll(" ", "_").equalsIgnoreCase(s); } catch (Exception e) { return false; } } public static String cdata(Node node) { if (node == null) { return null; } try { NodeList fNodes = node.getChildNodes(); if (fNodes != null) { for (int f = 0; f < fNodes.getLength(); f++) { Node c = fNodes.item(f); if (c.getNodeType() == Node.CDATA_SECTION_NODE) { return c.getNodeValue(); } } } } catch (Exception ex) { } return node.getTextContent(); } /* parse */ public static Document textToDoc(FxTask task, BaseController controller, String xml) { try { return readSource(task, controller, new InputSource(new StringReader(xml))); } catch (Exception e) { PopTools.showError(controller, e.toString()); return null; } } public static Document fileToDoc(FxTask task, BaseController controller, File file) { try { return readSource(task, controller, new InputSource(new FileReader(file))); } catch (Exception e) { PopTools.showError(controller, e.toString()); return null; } } public static Document readSource(FxTask task, BaseController controller, InputSource inputSource) { try { Document doc = builder(controller).parse(inputSource); if (doc == null) { return null; } Strip(task, controller, doc); return doc; } catch (Exception e) { PopTools.showError(controller, e.toString()); return null; } } public static Element toElement(FxTask task, BaseController controller, String xml) { try { Document doc = textToDoc(task, controller, xml); if (doc == null || (task != null && !task.isWorking())) { return null; } return doc.getDocumentElement(); } catch (Exception e) { PopTools.showError(controller, e.toString()); return null; } } public static DocumentBuilder builder(BaseController controller) { try (Connection conn = DerbyBase.getConnection()) { ignoreComment = UserConfig.getBoolean(conn, "XmlIgnoreComments", false); ignoreBlankComment = UserConfig.getBoolean(conn, "XmlIgnoreBlankComment", false); ignoreBlankText = UserConfig.getBoolean(conn, "XmlIgnoreBlankText", false); ignoreBlankCDATA = UserConfig.getBoolean(conn, "XmlIgnoreBlankCDATA", false); ignoreBlankInstrution = UserConfig.getBoolean(conn, "XmlIgnoreBlankInstruction", false); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(UserConfig.getBoolean(conn, "XmlDTDValidation", false)); factory.setNamespaceAware(UserConfig.getBoolean(conn, "XmlSupportNamespaces", false)); factory.setCoalescing(false); factory.setIgnoringElementContentWhitespace(false); factory.setIgnoringComments(ignoreComment); builder = factory.newDocumentBuilder(); } catch (Exception e) { PopTools.showError(controller, e.toString()); return null; } builder.setErrorHandler(new ErrorHandler() { @Override public void error(SAXParseException e) { // PopTools.showError(controller, e.toString()); } @Override public void fatalError(SAXParseException e) { // PopTools.showError(controller, e.toString()); } @Override public void warning(SAXParseException e) { // PopTools.showError(controller, e.toString()); } }); return builder; } public static Node Strip(FxTask task, BaseController controller, Node node) { try { if (node == null || (task != null && !task.isWorking())) { return node; } NodeList nodeList = node.getChildNodes(); if (nodeList == null) { return node; } List<Node> children = new ArrayList<>(); for (int i = 0; i < nodeList.getLength(); i++) { if (task != null && !task.isWorking()) { return node; } children.add(nodeList.item(i)); } for (Node child : children) { if (task != null && !task.isWorking()) { return node; } XmlTreeNode.NodeType t = type(child); if (ignoreComment && t == XmlTreeNode.NodeType.Comment) { node.removeChild(child); continue; } String value = child.getNodeValue(); if (value == null || value.isBlank()) { switch (t) { case Comment: if (ignoreBlankComment) { node.removeChild(child); } continue; case Text: if (ignoreBlankText) { node.removeChild(child); } continue; case CDATA: if (ignoreBlankCDATA) { node.removeChild(child); } continue; case ProcessingInstruction: if (ignoreBlankInstrution) { node.removeChild(child); continue; } break; } } Strip(task, controller, child); } } catch (Exception e) { PopTools.showError(controller, e.toString()); } return node; } public static String name(Node node) { return node == null ? null : node.getNodeName(); } public static String value(Node node) { if (node == null) { return null; } switch (node.getNodeType()) { case Node.TEXT_NODE: case Node.CDATA_SECTION_NODE: case Node.COMMENT_NODE: case Node.ATTRIBUTE_NODE: case Node.PROCESSING_INSTRUCTION_NODE: case Node.DOCUMENT_FRAGMENT_NODE: return node.getNodeValue(); case Node.ELEMENT_NODE: return elementInfo((Element) node); case Node.DOCUMENT_NODE: return docInfo((Document) node); case Node.DOCUMENT_TYPE_NODE: return docTypeInfo((DocumentType) node); case Node.ENTITY_NODE: return entityInfo((Entity) node, ""); case Node.ENTITY_REFERENCE_NODE: return entityReferenceInfo((EntityReference) node); case Node.NOTATION_NODE: return notationInfo((Notation) node, ""); default: return null; } } public static String docInfo(Document document) { if (document == null) { return null; } String info = ""; String v = document.getXmlVersion(); if (v != null && !v.isBlank()) { info += "version=\"" + v + "\"\n"; } v = document.getXmlEncoding(); if (v != null && !v.isBlank()) { info += "encoding=\"" + v + "\"\n"; } v = document.getDocumentURI(); if (v != null && !v.isBlank()) { info += "uri=\"" + v + "\"\n"; } return info; } public static XmlTreeNode.NodeType type(Node node) { if (node == null) { return null; } switch (node.getNodeType()) { case Node.ELEMENT_NODE: return XmlTreeNode.NodeType.Element; case Node.ATTRIBUTE_NODE: return XmlTreeNode.NodeType.Attribute; case Node.TEXT_NODE: return XmlTreeNode.NodeType.Text; case Node.CDATA_SECTION_NODE: return XmlTreeNode.NodeType.CDATA; case Node.ENTITY_REFERENCE_NODE: return XmlTreeNode.NodeType.EntityRefrence; case Node.ENTITY_NODE: return XmlTreeNode.NodeType.Entity; case Node.PROCESSING_INSTRUCTION_NODE: return XmlTreeNode.NodeType.ProcessingInstruction; case Node.COMMENT_NODE: return XmlTreeNode.NodeType.Comment; case Node.DOCUMENT_NODE: return XmlTreeNode.NodeType.Document; case Node.DOCUMENT_TYPE_NODE: return XmlTreeNode.NodeType.DocumentType; case Node.DOCUMENT_FRAGMENT_NODE: return XmlTreeNode.NodeType.DocumentFragment; case Node.NOTATION_NODE: return XmlTreeNode.NodeType.Notation; default: return XmlTreeNode.NodeType.Unknown; } } public static String entityReferenceInfo(EntityReference ref) { if (ref == null) { return null; } String info = "\t" + ref.getNodeName() + "=\"" + ref.getNodeValue() + "\""; return info; } public static String docTypeInfo(DocumentType documentType) { if (documentType == null) { return null; } String info = ""; String v = documentType.getName(); if (v != null && !v.isBlank()) { info += "name=\"" + v + "\"\n"; } v = documentType.getPublicId(); if (v != null && !v.isBlank()) { info += "Public Id=\"" + v + "\"\n"; } v = documentType.getSystemId(); if (v != null && !v.isBlank()) { info += "System Id=\"" + v + "\"\n"; } v = documentType.getInternalSubset(); if (v != null && !v.isBlank()) { info += "Internal subset=\"" + v + "\"\n"; } NamedNodeMap entities = documentType.getEntities(); if (entities != null && entities.getLength() > 0) { info += "Entities: \n"; for (int i = 0; i < entities.getLength(); i++) { info += entityInfo((Entity) entities.item(i), "\t"); } } NamedNodeMap notations = documentType.getNotations(); if (notations != null && notations.getLength() > 0) { info += "Notations: \n"; for (int i = 0; i < notations.getLength(); i++) { info += notationInfo((Notation) notations.item(i), "\t"); } } return info; } public static String notationInfo(Notation notation, String indent) { if (notation == null) { return null; } String info = indent + notation.getNodeName() + "=" + notation.getNodeValue() + "\n"; String v = notation.getPublicId(); if (v != null && !v.isBlank()) { info += indent + "\t" + "Public Id=" + v + "\n"; } v = notation.getSystemId(); if (v != null && !v.isBlank()) { info += indent + "\t" + "System Id=" + v + "\n"; } return info; } public static String elementInfo(Element element) { if (element == null) { return null; } String info = ""; NamedNodeMap attributes = element.getAttributes(); if (attributes != null) { for (int i = 0; i < attributes.getLength(); i++) { Node attr = attributes.item(i); info += attr.getNodeName() + "=\"" + attr.getNodeValue() + "\"\n"; } } return info; } public static String entityInfo(Entity entity, String indent) { if (entity == null) { return null; } String info = indent + entity.getNodeName() + "=" + entity.getNodeValue(); String v = entity.getNotationName(); if (v != null && !v.isBlank()) { info += indent + "\t" + "Notation name=\"" + v + "\"\n"; } v = entity.getXmlVersion(); if (v != null && !v.isBlank()) { info += indent + "\t" + "version=\"" + v + "\"\n"; } v = entity.getXmlEncoding(); if (v != null && !v.isBlank()) { info += indent + "\t" + "encoding=\"" + v + "\"\n"; } v = entity.getPublicId(); if (v != null && !v.isBlank()) { info += indent + "\t" + "Public Id=\"" + v + "\"\n"; } v = entity.getSystemId(); if (v != null && !v.isBlank()) { info += indent + "\t" + "System Id=\"" + v + "\"\n"; } return info; } public static Element findName(Document doc, String name, int index) { try { if (doc == null || name == null || name.isBlank() || index < 0) { return null; } NodeList svglist = doc.getElementsByTagName(name); if (svglist == null || svglist.getLength() <= index) { return null; } return (Element) svglist.item(index); } catch (Exception e) { MyBoxLog.error(e); return null; } } /* tree */ public static int index(Node node) { if (node == null) { return -1; } Node parent = node.getParentNode(); if (parent == null) { return -2; } NodeList nodeList = parent.getChildNodes(); if (nodeList == null) { return -3; } for (int i = 0; i < nodeList.getLength(); i++) { if (node.equals(nodeList.item(i))) { return i; } } return -4; } public static String hierarchyNumber(Node node) { if (node == null) { return ""; } String h = ""; Node parent = node.getParentNode(); Node cnode = node; while (parent != null) { int index = index(cnode); if (index < 0) { return ""; } h = "." + (index + 1) + h; cnode = parent; parent = parent.getParentNode(); } if (h.startsWith(".")) { h = h.substring(1, h.length()); } return h; } public static Node find(Node doc, String hierarchyNumber) { try { if (doc == null || hierarchyNumber == null || hierarchyNumber.isBlank()) { return null; } String[] numbers = hierarchyNumber.split("\\.", -1); if (numbers == null || numbers.length == 0) { return null; } int index; Node current = doc; for (String n : numbers) { index = Integer.parseInt(n); NodeList nodeList = current.getChildNodes(); if (nodeList == null || index < 1 || index > nodeList.getLength()) { return null; } current = nodeList.item(index - 1); } return current; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static void remove(Node doc, Node targetNode) { try { if (doc == null || targetNode == null) { return; } Node child = find(doc, hierarchyNumber(targetNode)); if (child == null) { return; } Node parent = child.getParentNode(); if (parent == null) { return; } parent.removeChild(child); } catch (Exception e) { MyBoxLog.error(e); } } public static void remove(Node targetNode) { try { if (targetNode == null) { return; } Node parent = targetNode.getParentNode(); if (parent == null) { return; } parent.removeChild(targetNode); } catch (Exception e) { MyBoxLog.error(e); } } /* transform */ public static String transform(Node node) { if (node == null) { return null; } return transform(node, UserConfig.getBoolean("XmlTransformerIndent", true)); } public static String transform(Node node, boolean indent) { if (node == null) { return null; } String encoding = node instanceof Document ? ((Document) node).getXmlEncoding() : node.getOwnerDocument().getXmlEncoding(); return transform(node, encoding, indent); } public static String transform(Node node, String encoding, boolean indent) { if (node == null) { return null; } if (encoding == null) { encoding = "utf-8"; } try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { if (XmlTools.transformer == null) { XmlTools.transformer = TransformerFactory.newInstance().newTransformer(); } XmlTools.transformer.setOutputProperty(OutputKeys.METHOD, "xml"); XmlTools.transformer.setOutputProperty(OutputKeys.STANDALONE, "yes"); XmlTools.transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, node instanceof Document ? "no" : "yes"); XmlTools.transformer.setOutputProperty(OutputKeys.ENCODING, encoding); XmlTools.transformer.setOutputProperty(OutputKeys.INDENT, indent ? "yes" : "no"); StreamResult streamResult = new StreamResult(); streamResult.setOutputStream(os); XmlTools.transformer.transform(new DOMSource(node), streamResult); os.flush(); os.close(); String s = os.toString(encoding); if (indent) { s = s.replaceAll("><", ">\n<"); } return s; } catch (Exception e) { MyBoxLog.error(e); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/tools/PdfTools.java
alpha/MyBox/src/main/java/mara/mybox/tools/PdfTools.java
package mara.mybox.tools; import com.vladsch.flexmark.ext.toc.TocExtension; import com.vladsch.flexmark.pdf.converter.PdfConverterExtension; import com.vladsch.flexmark.profile.pegdown.Extensions; import com.vladsch.flexmark.profile.pegdown.PegdownOptionsAdapter; import com.vladsch.flexmark.util.data.DataHolder; import java.awt.image.BufferedImage; import java.io.File; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import javafx.embed.swing.SwingFXUtils; import javafx.scene.image.Image; import mara.mybox.image.tools.AlphaTools; import mara.mybox.image.data.ImageBinary; import mara.mybox.controller.ControlPdfWriteOptions; import mara.mybox.data.WeiboSnapParameters; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.image.FxImageTools; import mara.mybox.fxml.FxFileTools; import mara.mybox.fxml.FxTask; import mara.mybox.image.file.ImageFileReaders; import mara.mybox.value.AppValues; import static mara.mybox.value.Languages.message; import mara.mybox.value.UserConfig; import org.apache.pdfbox.cos.COSName; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDDocumentInformation; import org.apache.pdfbox.pdmodel.PDPage; import org.apache.pdfbox.pdmodel.PDPageContentStream; import org.apache.pdfbox.pdmodel.PDPageTree; import org.apache.pdfbox.pdmodel.common.PDRectangle; import org.apache.pdfbox.pdmodel.font.PDFont; import org.apache.pdfbox.pdmodel.font.PDType0Font; import org.apache.pdfbox.pdmodel.font.PDType1Font; import org.apache.pdfbox.pdmodel.font.Standard14Fonts; import org.apache.pdfbox.pdmodel.graphics.blend.BlendMode; import org.apache.pdfbox.pdmodel.graphics.image.CCITTFactory; import org.apache.pdfbox.pdmodel.graphics.image.JPEGFactory; import org.apache.pdfbox.pdmodel.graphics.image.LosslessFactory; import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject; import org.apache.pdfbox.pdmodel.graphics.state.PDExtendedGraphicsState; import org.apache.pdfbox.pdmodel.interactive.action.PDActionGoTo; import org.apache.pdfbox.pdmodel.interactive.documentnavigation.destination.PDPageXYZDestination; /** * @Author Mara * @CreateDate 2018-6-17 9:13:00 * @License Apache License Version 2.0 */ public class PdfTools { public static int PDF_dpi = 72; // pixels per inch public static int DefaultMargin = 20; public static enum PdfImageFormat { Original, Tiff, Jpeg } public static float pixels2mm(float pixels) { return FloatTools.roundFloat2(pixels * 25.4f / 72f); } public static float pixels2inch(float pixels) { return FloatTools.roundFloat2(pixels / 72f); } public static int mm2pixels(float mm) { return Math.round(mm * 72f / 25.4f); } public static int inch2pixels(float inch) { return Math.round(inch * 72f); } public static boolean isPDF(String filename) { String suffix = FileNameTools.ext(filename); if (suffix == null) { return false; } return "PDF".equals(suffix.toUpperCase()); } public static PDDocument createPDF(File file) { return createPDF(file, UserConfig.getString("AuthorKey", System.getProperty("user.name"))); } public static PDDocument createPDF(File file, String author) { PDDocument targetDoc = null; try { PDDocument document = new PDDocument(); setAttributes(document, author, -1); document.save(file); targetDoc = document; } catch (Exception e) { MyBoxLog.error(e.toString()); } return targetDoc; } public static boolean createPdfFile(File file, String author) { try { PDDocument targetDoc = createPDF(file, author); if (targetDoc != null) { targetDoc.close(); } return true; } catch (Exception e) { MyBoxLog.error(e.toString()); return false; } } public static PDImageXObject imageObject(FxTask task, PDDocument document, String format, BufferedImage bufferedImage) { try { PDImageXObject imageObject; bufferedImage = AlphaTools.checkAlpha(task, bufferedImage, format); if (bufferedImage == null || (task != null && !task.isWorking())) { return null; } switch (format) { case "tif": case "tiff": imageObject = CCITTFactory.createFromImage(document, bufferedImage); break; case "jpg": case "jpeg": imageObject = JPEGFactory.createFromImage(document, bufferedImage, 1f); break; default: imageObject = LosslessFactory.createFromImage(document, bufferedImage); break; } return imageObject; } catch (Exception e) { return null; } } public static boolean writePage(FxTask task, PDDocument document, String sourceFormat, BufferedImage bufferedImage, int pageNumber, int total, ControlPdfWriteOptions options) { try { PDFont font = PdfTools.getFont(document, options.getTtfFile()); return writePage(task, document, font, options.getFontSize(), sourceFormat, bufferedImage, pageNumber, total, options.getImageFormat(), options.getThreshold(), options.getJpegQuality(), options.isIsImageSize(), options.isShowPageNumber(), options.getPageWidth(), options.getPageHeight(), options.getMarginSize(), options.getHeader(), options.getFooter(), options.isDithering()); } catch (Exception e) { MyBoxLog.error(e.toString()); return false; } } public static boolean writePage(FxTask task, PDDocument document, PDFont font, int fontSize, String sourceFormat, BufferedImage bufferedImage, int pageNumber, int total, PdfImageFormat targetFormat, int threshold, int jpegQuality, boolean isImageSize, boolean showPageNumber, int pageWidth, int pageHeight, int marginSize, String header, String footer, boolean dithering) { try { PDImageXObject imageObject; switch (targetFormat) { case Tiff: ImageBinary imageBinary = new ImageBinary(); imageBinary.setAlgorithm(ImageBinary.BinaryAlgorithm.Threshold) .setImage(bufferedImage) .setIntPara1(threshold) .setIsDithering(dithering) .setTask(task); bufferedImage = imageBinary.start(); if (bufferedImage == null || (task != null && !task.isWorking())) { return false; } bufferedImage = ImageBinary.byteBinary(task, bufferedImage); if (bufferedImage == null || (task != null && !task.isWorking())) { return false; } imageObject = CCITTFactory.createFromImage(document, bufferedImage); break; case Jpeg: bufferedImage = AlphaTools.checkAlpha(task, bufferedImage, "jpg"); if (bufferedImage == null || (task != null && !task.isWorking())) { return false; } imageObject = JPEGFactory.createFromImage(document, bufferedImage, jpegQuality / 100f); break; default: if (sourceFormat != null) { bufferedImage = AlphaTools.checkAlpha(task, bufferedImage, sourceFormat); } if (bufferedImage == null || (task != null && !task.isWorking())) { return false; } imageObject = LosslessFactory.createFromImage(document, bufferedImage); break; } PDRectangle pageSize; if (isImageSize) { pageSize = new PDRectangle(imageObject.getWidth() + marginSize * 2, imageObject.getHeight() + marginSize * 2); } else { pageSize = new PDRectangle(pageWidth, pageHeight); } PDPage page = new PDPage(pageSize); document.addPage(page); try (PDPageContentStream content = new PDPageContentStream(document, page)) { float w, h; if (isImageSize) { w = imageObject.getWidth(); h = imageObject.getHeight(); } else { if (imageObject.getWidth() > imageObject.getHeight()) { w = page.getTrimBox().getWidth() - marginSize * 2; h = imageObject.getHeight() * w / imageObject.getWidth(); } else { h = page.getTrimBox().getHeight() - marginSize * 2; w = imageObject.getWidth() * h / imageObject.getHeight(); } } content.drawImage(imageObject, marginSize, page.getTrimBox().getHeight() - marginSize - h, w, h); if (showPageNumber) { content.beginText(); if (font != null) { content.setFont(font, fontSize); } content.newLineAtOffset(w + marginSize - 80, 5); content.showText(pageNumber + " / " + total); content.endText(); } if (header != null && !header.trim().isEmpty()) { try { content.beginText(); if (font != null) { content.setFont(font, fontSize); } content.newLineAtOffset(marginSize, page.getTrimBox().getHeight() - marginSize + 2); content.showText(header.trim()); content.endText(); } catch (Exception e) { MyBoxLog.error(e.toString()); } } if (footer != null && !footer.trim().isEmpty()) { try { content.beginText(); if (font != null) { content.setFont(font, fontSize); } content.newLineAtOffset(marginSize, marginSize + 2); content.showText(footer.trim()); content.endText(); } catch (Exception e) { MyBoxLog.error(e.toString()); } } PDExtendedGraphicsState gs = new PDExtendedGraphicsState(); gs.setNonStrokingAlphaConstant(0.2f); gs.setAlphaSourceFlag(true); gs.setBlendMode(BlendMode.NORMAL); } return true; } catch (Exception e) { MyBoxLog.error(e.toString()); return false; } } public static List<BlendMode> pdfBlendModes() { try { List<BlendMode> modes = new ArrayList<>(); modes.add(BlendMode.NORMAL); // modes.add(BlendMode.COMPATIBLE); modes.add(BlendMode.MULTIPLY); modes.add(BlendMode.SCREEN); modes.add(BlendMode.OVERLAY); modes.add(BlendMode.DARKEN); modes.add(BlendMode.LIGHTEN); modes.add(BlendMode.COLOR_DODGE); modes.add(BlendMode.COLOR_BURN); modes.add(BlendMode.HARD_LIGHT); modes.add(BlendMode.SOFT_LIGHT); modes.add(BlendMode.DIFFERENCE); modes.add(BlendMode.EXCLUSION); modes.add(BlendMode.HUE); modes.add(BlendMode.SATURATION); modes.add(BlendMode.LUMINOSITY); modes.add(BlendMode.COLOR); return modes; } catch (Exception e) { MyBoxLog.error(e.toString()); return null; } // BlendMode m = BlendMode.getInstance(COSName.A); // Field xbar = m.getClass().getDeclaredField("BLEND_MODE_NAMES"); // xbar.setAccessible(true); // Map<BlendMode, COSName> maps = (Map<BlendMode, COSName>) xbar.get(reader); // return maps.keySet(); } public static boolean imageInPdf(FxTask task, PDDocument document, BufferedImage bufferedImage, WeiboSnapParameters p, int showPageNumber, int totalPage, PDFont font) { return writePage(task, document, font, p.getFontSize(), "png", bufferedImage, showPageNumber, totalPage, p.getFormat(), p.getThreshold(), p.getJpegQuality(), p.isIsImageSize(), p.isAddPageNumber(), p.getPageWidth(), p.getPageHeight(), p.getMarginSize(), p.getTitle(), null, p.isDithering()); } public static boolean images2Pdf(FxTask task, List<Image> images, File targetFile, WeiboSnapParameters p) { try { if (images == null || images.isEmpty()) { return false; } int count = 0, total = images.size(); try (PDDocument document = new PDDocument()) { PDFont font = getFont(document, p.getFontFile()); BufferedImage bufferedImage; for (Image image : images) { if (task != null && !task.isWorking()) { return false; } if (null == p.getFormat()) { bufferedImage = SwingFXUtils.fromFXImage(image, null); } else { switch (p.getFormat()) { case Tiff: bufferedImage = SwingFXUtils.fromFXImage(image, null); break; case Jpeg: bufferedImage = FxImageTools.checkAlpha(task, image, "jpg"); break; default: bufferedImage = SwingFXUtils.fromFXImage(image, null); break; } } imageInPdf(task, document, bufferedImage, p, ++count, total, font); } setAttributes(document, p.getAuthor(), p.getPdfScale()); document.save(targetFile); document.close(); return true; } } catch (Exception e) { MyBoxLog.error(e.toString()); return false; } } public static boolean imagesFiles2Pdf(FxTask task, List<String> files, File targetFile, WeiboSnapParameters p, boolean deleteFiles) { try { if (files == null || files.isEmpty()) { return false; } int count = 0, total = files.size(); try (PDDocument document = new PDDocument()) { PDFont font = getFont(document, p.getFontFile()); BufferedImage bufferedImage; File file; for (String filename : files) { if (task != null && !task.isWorking()) { return false; } file = new File(filename); bufferedImage = ImageFileReaders.readImage(task, file); if (bufferedImage == null || (task != null && !task.isWorking())) { return false; } imageInPdf(task, document, bufferedImage, p, ++count, total, font); if (task != null && !task.isWorking()) { return false; } if (deleteFiles) { FileDeleteTools.delete(file); } } setAttributes(document, p.getAuthor(), p.getPdfScale()); document.save(targetFile); document.close(); return true; } } catch (Exception e) { MyBoxLog.error(e.toString()); return false; } } public static void setPageSize(PDPage page, PDRectangle pageSize) { page.setTrimBox(pageSize); page.setCropBox(pageSize); page.setArtBox(pageSize); page.setBleedBox(new PDRectangle(pageSize.getWidth() + mm2pixels(5), pageSize.getHeight() + mm2pixels(5))); page.setMediaBox(page.getBleedBox()); // pageSize.setLowerLeftX(20); // pageSize.setLowerLeftY(20); // pageSize.setUpperRightX(page.getTrimBox().getWidth() - 20); // pageSize.setUpperRightY(page.getTrimBox().getHeight() - 20); } public static PDFont HELVETICA() { return new PDType1Font(Standard14Fonts.getMappedFontName(Standard14Fonts.FontName.HELVETICA.getName())); } public static PDFont getFont(PDDocument document, String fontFile) { PDFont font = HELVETICA(); try { if (fontFile != null) { font = PDType0Font.load(document, new File(TTFTools.ttf(fontFile))); } } catch (Exception e) { } return font; } public static PDFont defaultFont(PDDocument document) { PDFont font = HELVETICA(); try { List<String> ttfList = TTFTools.ttfList(); if (ttfList != null && !ttfList.isEmpty()) { font = getFont(document, ttfList.get(0)); } } catch (Exception e) { } return font; } public static float fontWidth(PDFont font, String text, int fontSize) { try { if (font == null || text == null || fontSize <= 0) { return -1; } return fontSize * font.getStringWidth(text) / 1000; } catch (Exception e) { return -2; } } public static float fontHeight(PDFont font, int fontSize) { try { if (font == null || fontSize <= 0) { return -1; } return fontSize * font.getFontDescriptor().getFontBoundingBox().getHeight() / 1000; } catch (Exception e) { return -2; } } public static List<PDImageXObject> getImageListFromPDF(FxTask task, PDDocument document, Integer startPage) throws Exception { List<PDImageXObject> imageList = new ArrayList<>(); if (null != document) { PDPageTree pages = document.getPages(); startPage = startPage == null ? 0 : startPage; int len = pages.getCount(); if (startPage < len) { for (int i = startPage; i < len; ++i) { if (task != null && !task.isWorking()) { return null; } PDPage page = pages.get(i); Iterable<COSName> objectNames = page.getResources().getXObjectNames(); for (COSName imageObjectName : objectNames) { if (task != null && !task.isWorking()) { return null; } if (page.getResources().isImageXObject(imageObjectName)) { imageList.add((PDImageXObject) page.getResources().getXObject(imageObjectName)); } } } } } return imageList; } public static void setAttributes(PDDocument doc, String author, int defaultZoom) { setAttributes(doc, author, "MyBox v" + AppValues.AppVersion, defaultZoom, 1.0f); } public static void setAttributes(PDDocument doc, String author, String producer, int defaultZoom, float version) { try { if (doc == null) { return; } PDDocumentInformation info = new PDDocumentInformation(); info.setCreationDate(Calendar.getInstance()); info.setModificationDate(Calendar.getInstance()); info.setProducer(producer); info.setAuthor(author); doc.setDocumentInformation(info); doc.setVersion(version); if (defaultZoom > 0 && doc.getNumberOfPages() > 0) { PDPage page = doc.getPage(0); PDPageXYZDestination dest = new PDPageXYZDestination(); dest.setPage(page); dest.setZoom(defaultZoom / 100.0f); dest.setTop((int) page.getCropBox().getHeight()); PDActionGoTo action = new PDActionGoTo(); action.setDestination(dest); doc.getDocumentCatalog().setOpenAction(action); } } catch (Exception e) { MyBoxLog.error(e); } } public static String html2pdf(FxTask task, File target, String html, String css, boolean ignoreHead, DataHolder pdfOptions) { try { if (html == null || html.isBlank()) { return null; } if (ignoreHead) { html = HtmlWriteTools.ignoreHead(task, html); if (html == null || (task != null && !task.isWorking())) { return message("Canceled"); } } if (!css.isBlank()) { try { html = PdfConverterExtension.embedCss(html, css); } catch (Exception e) { MyBoxLog.error(e.toString()); } } try { PdfConverterExtension.exportToPdf(target.getAbsolutePath(), html, "", pdfOptions); if (!target.exists()) { return message("Failed"); } else if (target.length() == 0) { FileDeleteTools.delete(target); return message("Failed"); } return message("Successful"); } catch (Exception e) { return e.toString(); } } catch (Exception e) { MyBoxLog.error(e); return e.toString(); } } public static File html2pdf(FxTask task, String html) { try { if (html == null || html.isBlank()) { return null; } File pdfFile = FileTmpTools.generateFile("pdf"); File wqy_microhei = FxFileTools.getInternalFile("/data/wqy-microhei.ttf", "data", "wqy-microhei.ttf"); String css = "@font-face {\n" + " font-family: 'myFont';\n" + " src: url('file:///" + wqy_microhei.getAbsolutePath().replaceAll("\\\\", "/") + "');\n" + " font-weight: normal;\n" + " font-style: normal;\n" + "}\n" + " body { font-family: 'myFont';}"; DataHolder pdfOptions = PegdownOptionsAdapter.flexmarkOptions(Extensions.ALL & ~(Extensions.ANCHORLINKS | Extensions.EXTANCHORLINKS_WRAP), TocExtension.create()) .toMutable() .set(TocExtension.LIST_CLASS, PdfConverterExtension.DEFAULT_TOC_LIST_CLASS) .toImmutable(); html2pdf(task, pdfFile, html, css, true, pdfOptions); return pdfFile; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static File text2pdf(FxTask task, String text) { try { if (text == null || text.isBlank()) { return null; } return html2pdf(task, HtmlWriteTools.textToHtml(text)); } catch (Exception e) { MyBoxLog.error(e); return null; } } public static File md2pdf(FxTask task, String md) { try { if (md == null || md.isBlank()) { return null; } return html2pdf(task, HtmlWriteTools.md2html(md)); } catch (Exception e) { MyBoxLog.error(e); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/tools/NumberTools.java
alpha/MyBox/src/main/java/mara/mybox/tools/NumberTools.java
package mara.mybox.tools; import java.math.RoundingMode; import java.text.DecimalFormat; import javafx.scene.control.IndexRange; import mara.mybox.db.data.ColumnDefinition.InvalidAs; import mara.mybox.value.Languages; /** * @Author Mara * @CreateDate 2022-10-4 * @License Apache License Version 2.0 */ public class NumberTools { public static String format(Number data, String format) { return format(data, format, -1); } public static String format(Number data, String inFormat, int scale) { try { if (data == null) { return null; } String format = inFormat; if (format == null || format.isBlank() || Languages.matchIgnoreCase("None", format)) { return noFormat(data, scale); } else if (Languages.matchIgnoreCase("ScientificNotation", format)) { return scientificNotation(data, scale); } else if (Languages.matchIgnoreCase("GroupInThousands", format)) { return format(data, 3, scale); } else if (Languages.matchIgnoreCase("GroupInTenThousands", format)) { return format(data, 4, scale); } else { DecimalFormat df = new DecimalFormat(format); df.setMaximumFractionDigits(scale >= 0 ? scale : 340); df.setRoundingMode(RoundingMode.HALF_UP); return df.format(data); } } catch (Exception e) { return new DecimalFormat().format(data); } } public static String noFormat(Number data, int scale) { return format(data, -1, scale); } public static String scientificNotation(Number data, int scale) { try { if (data == null) { return null; } double d = DoubleTools.scale(data.toString(), InvalidAs.Empty, scale); return d + ""; } catch (Exception e) { return null; } } public static String format(Number data) { return format(data, 3, -1); } public static String format(Number data, int scale) { return format(data, -1, scale); } public static String format(Number data, int groupSize, int scale) { try { if (data == null) { return null; } DecimalFormat df = new DecimalFormat(); if (groupSize >= 0) { df.setGroupingUsed(true); df.setGroupingSize(groupSize); } else { df.setGroupingUsed(false); } df.setMaximumFractionDigits(scale >= 0 ? scale : 340); df.setRoundingMode(RoundingMode.HALF_UP); return df.format(data); } catch (Exception e) { return null; } } // 0-based, exclude to and end public static IndexRange scrollRange(int scrollSize, int total, int from, int to, int currentIndex) { if (total < 1) { return null; } int start = Math.max(from, currentIndex - scrollSize / 2); if (start < 0 || start >= total) { start = 0; } int end = Math.min(to, start + scrollSize); if (end < 0 || end > total) { end = total; } if (start >= end) { return null; } return new IndexRange(start, end); } public static IndexRange scrollRange(int scrollSize, int total, int currentIndex) { return scrollRange(scrollSize, total, 0, total, currentIndex); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/tools/ConfigTools.java
alpha/MyBox/src/main/java/mara/mybox/tools/ConfigTools.java
package mara.mybox.tools; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.HashMap; import java.util.Map; import java.util.Properties; import mara.mybox.dev.MyBoxLog; import mara.mybox.value.AppValues; import mara.mybox.value.AppVariables; /** * @Author Mara * @CreateDate 2018-6-9 7:46:58 * @Description Read data outside database * @License Apache License Version 2.0 */ public class ConfigTools { /* MyBox config */ public static String defaultDataPath() { return defaultDataPathFile().getAbsolutePath(); } public static File defaultDataPathFile() { File defaultPath = new File(System.getProperty("user.home") + File.separator + "mybox"); if (!defaultPath.exists()) { defaultPath.mkdirs(); } else if (!defaultPath.isDirectory()) { FileDeleteTools.delete(defaultPath); defaultPath.mkdirs(); } return defaultPath; } public static File defaultConfigFile() { File defaultPath = defaultDataPathFile(); File configFile = new File(defaultPath.getAbsolutePath() + File.separator + "MyBox_v" + AppValues.AppVersion + (AppValues.Alpha ? "a" : "") + ".ini"); return configFile; } public static Map<String, String> readValues() { return ConfigTools.readValues(AppVariables.MyboxConfigFile); } public static String readValue(String key) { return ConfigTools.readValue(AppVariables.MyboxConfigFile, key); } public static int readInt(String key, int defaultValue) { try { String v = ConfigTools.readValue(key); return Integer.parseInt(v); } catch (Exception e) { return defaultValue; } } public static boolean writeConfigValue(String key, String value) { try { if (!AppVariables.MyboxConfigFile.exists()) { if (!AppVariables.MyboxConfigFile.createNewFile()) { return false; } } return writeValue(AppVariables.MyboxConfigFile, key, value); } catch (Exception e) { MyBoxLog.error(e.toString()); return false; } } /* General config */ public static Map<String, String> readValues(File file) { Map<String, String> values = new HashMap<>(); try { if (file == null || !file.exists()) { return values; } try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(file))) { Properties conf = new Properties(); conf.load(in); for (String key : conf.stringPropertyNames()) { values.put(key, conf.getProperty(key)); } } } catch (Exception e) { MyBoxLog.error(e.toString()); } return values; } public static String readValue(File file, String key) { try { if (!file.exists() || !file.isFile()) { return null; } String value; try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(file))) { Properties conf = new Properties(); conf.load(in); value = conf.getProperty(key); } return value; } catch (Exception e) { MyBoxLog.error(e.toString()); return null; } } public static boolean writeConfigValue(File file, String key, String value) { Properties conf = new Properties(); try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(file))) { conf.load(in); } catch (Exception e) { MyBoxLog.error(e.toString()); return false; } try (BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file))) { if (value == null) { conf.remove(key); } else { conf.setProperty(key, value); } conf.store(out, "Update " + key); } catch (Exception e) { MyBoxLog.error(e.toString()); return false; } return true; } public static boolean writeValue(File file, String key, String value) { Properties conf = new Properties(); try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(file))) { conf.load(in); } catch (Exception e) { MyBoxLog.error(e.toString()); return false; } try (BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file))) { if (value == null) { conf.remove(key); } else { conf.setProperty(key, value); } conf.store(out, "Update " + key); } catch (Exception e) { MyBoxLog.error(e.toString()); return false; } return true; } public static boolean writeValues(File file, Map<String, String> values) { if (file == null || values == null) { return false; } Properties conf = new Properties(); try (BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file))) { for (String key : values.keySet()) { conf.setProperty(key, values.get(key)); } conf.store(out, "Update "); } catch (Exception e) { MyBoxLog.error(e.toString()); return false; } return true; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/tools/DoubleMatrixTools.java
alpha/MyBox/src/main/java/mara/mybox/tools/DoubleMatrixTools.java
package mara.mybox.tools; import java.util.ArrayList; import java.util.List; import java.util.Random; import mara.mybox.data.StringTable; import mara.mybox.dev.MyBoxLog; import mara.mybox.value.Languages; /** * @Author Mara * @CreateDate 2019-5-18 10:37:15 * @Version 1.0 * @Description * @License Apache License Version 2.0 */ public class DoubleMatrixTools { // columnNumber is 0-based public static double[] columnValues(double[][] m, int columnNumber) { if (m == null || m.length == 0 || m[0].length <= columnNumber) { return null; } double[] column = new double[m.length]; for (int i = 0; i < m.length; ++i) { column[i] = m[i][columnNumber]; } return column; } public static double[][] columnVector(double x, double y, double z) { double[][] rv = new double[3][1]; rv[0][0] = x; rv[1][0] = y; rv[2][0] = z; return rv; } public static double[][] columnVector(double[] v) { double[][] rv = new double[v.length][1]; for (int i = 0; i < v.length; ++i) { rv[i][0] = v[i]; } return rv; } public static double[] matrix2Array(double[][] m) { if (m == null || m.length == 0 || m[0].length == 0) { return null; } int h = m.length; int w = m[0].length; double[] a = new double[w * h]; for (int j = 0; j < h; ++j) { System.arraycopy(m[j], 0, a, j * w, w); } return a; } public static double[][] array2Matrix(double[] a, int w) { if (a == null || a.length == 0 || w < 1) { return null; } int h = a.length / w; if (h < 1) { return null; } double[][] m = new double[h][w]; for (int j = 0; j < h; ++j) { for (int i = 0; i < w; ++i) { m[j][i] = a[j * w + i]; } } return m; } public static double[][] clone(double[][] matrix) { try { if (matrix == null) { return null; } int rowA = matrix.length, columnA = matrix[0].length; double[][] result = new double[rowA][columnA]; for (int i = 0; i < rowA; ++i) { System.arraycopy(matrix[i], 0, result[i], 0, columnA); } return result; } catch (Exception e) { return null; } } public static Number[][] clone(Number[][] matrix) { try { if (matrix == null) { return null; } int rowA = matrix.length, columnA = matrix[0].length; Number[][] result = new Number[rowA][columnA]; for (int i = 0; i < rowA; ++i) { System.arraycopy(matrix[i], 0, result[i], 0, columnA); } return result; } catch (Exception e) { return null; } } public static String print(double[][] matrix, int prefix, int scale) { try { if (matrix == null) { return ""; } String s = "", p = "", t = " "; for (int b = 0; b < prefix; b++) { p += " "; } int row = matrix.length, column = matrix[0].length; for (int i = 0; i < row; ++i) { s += p; for (int j = 0; j < column; ++j) { double d = DoubleTools.scale(matrix[i][j], scale); s += d + t; } s += "\n"; } return s; } catch (Exception e) { return null; } } public static String html(double[][] matrix, int scale) { try { if (matrix == null) { return ""; } String s = "", t = "&nbsp;&nbsp;"; int row = matrix.length, column = matrix[0].length; for (int i = 0; i < row; ++i) { for (int j = 0; j < column; ++j) { double d = DoubleTools.scale(matrix[i][j], scale); s += d + t; } s += "<BR>\n"; } return s; } catch (Exception e) { return null; } } public static boolean same(double[][] matrixA, double[][] matrixB, int scale) { try { if (matrixA == null || matrixB == null || matrixA.length != matrixB.length || matrixA[0].length != matrixB[0].length) { return false; } int rows = matrixA.length; int columns = matrixA[0].length; for (int i = 0; i < rows; ++i) { for (int j = 0; j < columns; ++j) { if (scale < 0) { if (matrixA[i][j] != matrixB[i][j]) { return false; } } else { double a = DoubleTools.scale(matrixA[i][j], scale); double b = DoubleTools.scale(matrixB[i][j], scale); if (a != b) { return false; } } } } return true; } catch (Exception e) { return false; } } public static int[][] identityInt(int n) { try { if (n < 1) { return null; } int[][] result = new int[n][n]; for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { if (i == j) { result[i][j] = 1; } } } return result; } catch (Exception e) { return null; } } public static double[][] identityDouble(int n) { try { if (n < 1) { return null; } double[][] result = new double[n][n]; for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { if (i == j) { result[i][j] = 1; } } } return result; } catch (Exception e) { return null; } } public static double[][] randomMatrix(int n) { return randomMatrix(n, n); } public static double[][] randomMatrix(int m, int n) { try { if (n < 1) { return null; } double[][] result = new double[m][n]; Random r = new Random(); for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { result[i][j] = r.nextDouble(); } } return result; } catch (Exception e) { return null; } } public static double[][] vertivalMerge(double[][] matrixA, double[][] matrixB) { try { if (matrixA == null || matrixB == null || matrixA[0].length != matrixB[0].length) { return null; } int rowsA = matrixA.length, rowsB = matrixB.length; int columns = matrixA[0].length; double[][] result = new double[rowsA + rowsB][columns]; for (int i = 0; i < rowsA; ++i) { System.arraycopy(matrixA[i], 0, result[i], 0, columns); } for (int i = 0; i < rowsB; ++i) { System.arraycopy(matrixB[i], 0, result[i + rowsA], 0, columns); } return result; } catch (Exception e) { return null; } } public static double[][] horizontalMerge(double[][] matrixA, double[][] matrixB) { try { if (matrixA == null || matrixB == null || matrixA.length != matrixB.length) { return null; } int rows = matrixA.length; int columnsA = matrixA[0].length, columnsB = matrixB[0].length; int columns = columnsA + columnsB; double[][] result = new double[rows][columns]; for (int i = 0; i < rows; ++i) { System.arraycopy(matrixA[i], 0, result[i], 0, columnsA); System.arraycopy(matrixB[i], 0, result[i], columnsA, columnsB); } return result; } catch (Exception e) { return null; } } public static double[][] add(double[][] matrixA, double[][] matrixB) { try { if (matrixA == null || matrixB == null || matrixA.length != matrixB.length || matrixA[0].length != matrixB[0].length) { return null; } double[][] result = new double[matrixA.length][matrixA[0].length]; for (int i = 0; i < matrixA.length; ++i) { double[] rowA = matrixA[i]; double[] rowB = matrixB[i]; for (int j = 0; j < rowA.length; ++j) { result[i][j] = rowA[j] + rowB[j]; } } return result; } catch (Exception e) { return null; } } public static double[][] subtract(double[][] matrixA, double[][] matrixB) { try { if (matrixA == null || matrixB == null || matrixA.length != matrixB.length || matrixA[0].length != matrixB[0].length) { return null; } double[][] result = new double[matrixA.length][matrixA[0].length]; for (int i = 0; i < matrixA.length; ++i) { double[] rowA = matrixA[i]; double[] rowB = matrixB[i]; for (int j = 0; j < rowA.length; ++j) { result[i][j] = rowA[j] - rowB[j]; } } return result; } catch (Exception e) { return null; } } public static double[][] multiply(double[][] matrixA, double[][] matrixB) { try { int rowA = matrixA.length, columnA = matrixA[0].length; int rowB = matrixB.length, columnB = matrixB[0].length; if (columnA != rowB) { return null; } double[][] result = new double[rowA][columnB]; for (int i = 0; i < rowA; ++i) { for (int j = 0; j < columnB; ++j) { result[i][j] = 0; for (int k = 0; k < columnA; k++) { result[i][j] += matrixA[i][k] * matrixB[k][j]; } } } return result; } catch (Exception e) { MyBoxLog.debug(e); return null; } } public static double[] multiply(double[][] matrix, double[] columnVector) { if (matrix == null || columnVector == null) { return null; } double[] outputs = new double[matrix.length]; for (int i = 0; i < matrix.length; ++i) { double[] row = matrix[i]; outputs[i] = 0d; for (int j = 0; j < Math.min(row.length, columnVector.length); ++j) { outputs[i] += row[j] * columnVector[j]; } } return outputs; } public static double[][] transpose(double[][] matrix) { try { if (matrix == null) { return null; } int rowsNumber = matrix.length, columnsNumber = matrix[0].length; double[][] result = new double[columnsNumber][rowsNumber]; for (int row = 0; row < rowsNumber; ++row) { for (int col = 0; col < columnsNumber; ++col) { result[col][row] = matrix[row][col]; } } return result; } catch (Exception e) { return null; } } public static double[][] integer(double[][] matrix) { try { if (matrix == null) { return null; } int rowA = matrix.length, columnA = matrix[0].length; double[][] result = new double[rowA][columnA]; for (int i = 0; i < rowA; ++i) { for (int j = 0; j < columnA; ++j) { result[i][j] = Math.round(matrix[i][j]); } } return result; } catch (Exception e) { return null; } } public static double[][] scale(double[][] matrix, int scale) { try { if (matrix == null) { return null; } int rowA = matrix.length, columnA = matrix[0].length; double[][] result = new double[rowA][columnA]; for (int i = 0; i < rowA; ++i) { for (int j = 0; j < columnA; ++j) { result[i][j] = DoubleTools.scale(matrix[i][j], scale); } } return result; } catch (Exception e) { return null; } } public static double[][] multiply(double[][] matrix, double p) { try { if (matrix == null) { return null; } int rowA = matrix.length, columnA = matrix[0].length; double[][] result = new double[rowA][columnA]; for (int i = 0; i < rowA; ++i) { for (int j = 0; j < columnA; ++j) { result[i][j] = matrix[i][j] * p; } } return result; } catch (Exception e) { return null; } } public static double[][] divide(double[][] matrix, double p) { try { if (matrix == null || p == 0) { return null; } int rowA = matrix.length, columnA = matrix[0].length; double[][] result = new double[rowA][columnA]; for (int i = 0; i < rowA; ++i) { for (int j = 0; j < columnA; ++j) { result[i][j] = matrix[i][j] / p; } } return result; } catch (Exception e) { return null; } } public static double[][] power(double[][] matrix, int n) { try { if (matrix == null || n < 0) { return null; } int row = matrix.length, column = matrix[0].length; if (row != column) { return null; } double[][] tmp = clone(matrix); double[][] result = identityDouble(row); while (n > 0) { if (n % 2 > 0) { result = multiply(result, tmp); } tmp = multiply(tmp, tmp); n = n / 2; } return result; } catch (Exception e) { return null; } } public static double[][] inverseByAdjoint(double[][] matrix) { try { if (matrix == null) { return null; } int row = matrix.length, column = matrix[0].length; if (row != column) { return null; } double det = determinantByComplementMinor(matrix); if (det == 0) { return null; } double[][] inverse = new double[row][column]; double[][] adjoint = adjoint(matrix); for (int i = 0; i < row; ++i) { for (int j = 0; j < column; ++j) { inverse[i][j] = adjoint[i][j] / det; } } return inverse; } catch (Exception e) { return null; } } public static double[][] inverse(double[][] matrix) { return inverseByElimination(matrix); } public static double[][] inverseByElimination(double[][] matrix) { try { if (matrix == null) { return null; } int rows = matrix.length, columns = matrix[0].length; if (rows != columns) { return null; } double[][] augmented = new double[rows][columns * 2]; for (int i = 0; i < rows; ++i) { System.arraycopy(matrix[i], 0, augmented[i], 0, columns); augmented[i][i + columns] = 1; } augmented = reducedRowEchelonForm(augmented); double[][] inverse = new double[rows][columns]; for (int i = 0; i < rows; ++i) { for (int j = 0; j < columns; ++j) { inverse[i][j] = augmented[i][j + columns]; } } return inverse; } catch (Exception e) { return null; } } // rowIndex, columnIndex are 0-based. public static double[][] complementMinor(double[][] matrix, int rowIndex, int columnIndex) { try { if (matrix == null || rowIndex < 0 || columnIndex < 0) { return null; } int rows = matrix.length, columns = matrix[0].length; if (rowIndex >= rows || columnIndex >= columns) { return null; } double[][] minor = new double[rows - 1][columns - 1]; int minorRow = 0, minorColumn; for (int i = 0; i < rows; ++i) { if (i == rowIndex) { continue; } minorColumn = 0; for (int j = 0; j < columns; ++j) { if (j == columnIndex) { continue; } minor[minorRow][minorColumn++] = matrix[i][j]; } minorRow++; } return minor; } catch (Exception e) { MyBoxLog.debug(e); return null; } } public static double[][] adjoint(double[][] matrix) { try { if (matrix == null) { return null; } int row = matrix.length, column = matrix[0].length; if (row != column) { return null; } double[][] adjoint = new double[row][column]; if (row == 1) { adjoint[0][0] = matrix[0][0]; return adjoint; } for (int i = 0; i < row; ++i) { for (int j = 0; j < column; ++j) { adjoint[j][i] = Math.pow(-1, i + j) * determinantByComplementMinor(complementMinor(matrix, i, j)); } } return adjoint; } catch (Exception e) { MyBoxLog.debug(e); return null; } } public static double determinant(double[][] matrix) throws Exception { return determinantByElimination(matrix); } public static double determinantByComplementMinor(double[][] matrix) throws Exception { try { if (matrix == null) { throw new Exception("InvalidValue"); } int row = matrix.length, column = matrix[0].length; if (row != column) { throw new Exception("InvalidValue"); } if (row == 1) { return matrix[0][0]; } if (row == 2) { return matrix[0][0] * matrix[1][1] - matrix[1][0] * matrix[0][1]; } double v = 0; for (int j = 0; j < column; ++j) { double[][] minor = complementMinor(matrix, 0, j); v += matrix[0][j] * Math.pow(-1, j) * determinantByComplementMinor(minor); } return v; } catch (Exception e) { // MyBoxLog.debug(e); throw e; } } public static double determinantByElimination(double[][] matrix) throws Exception { try { if (matrix == null) { throw new Exception("InvalidValue"); } int rows = matrix.length, columns = matrix[0].length; if (rows != columns) { throw new Exception("InvalidValue"); } double[][] ref = rowEchelonForm(matrix); if (ref[rows - 1][columns - 1] == 0) { return 0; } double det = 1; for (int i = 0; i < rows; ++i) { det *= ref[i][i]; } return det; } catch (Exception e) { MyBoxLog.debug(e); throw e; } } public static double[][] hadamardProduct(double[][] matrixA, double[][] matrixB) { try { int rowA = matrixA.length, columnA = matrixA[0].length; int rowB = matrixB.length, columnB = matrixB[0].length; if (rowA != rowB || columnA != columnB) { return null; } double[][] result = new double[rowA][columnA]; for (int i = 0; i < rowA; ++i) { for (int j = 0; j < columnA; ++j) { result[i][j] = matrixA[i][j] * matrixB[i][j]; } } return result; } catch (Exception e) { MyBoxLog.debug(e); return null; } } public static double[][] kroneckerProduct(double[][] matrixA, double[][] matrixB) { try { int rowsA = matrixA.length, columnsA = matrixA[0].length; int rowsB = matrixB.length, columnsB = matrixB[0].length; double[][] result = new double[rowsA * rowsB][columnsA * columnsB]; for (int i = 0; i < rowsA; ++i) { for (int j = 0; j < columnsA; ++j) { for (int m = 0; m < rowsB; m++) { for (int n = 0; n < columnsB; n++) { result[i * rowsB + m][j * columnsB + n] = matrixA[i][j] * matrixB[m][n]; } } } } return result; } catch (Exception e) { MyBoxLog.debug(e); return null; } } public static double[][] rowEchelonForm(double[][] matrix) { try { int rows = matrix.length, columns = matrix[0].length; double[][] result = clone(matrix); for (int i = 0; i < Math.min(rows, columns); ++i) { if (result[i][i] == 0) { int row = -1; for (int k = i + 1; k < rows; k++) { if (result[k][i] != 0) { row = k; break; } } if (row < 0) { break; } for (int j = i; j < columns; ++j) { double temp = result[row][j]; result[row][j] = result[i][j]; result[i][j] = temp; } } for (int k = i + 1; k < rows; k++) { if (result[i][i] == 0) { continue; } double ratio = result[k][i] / result[i][i]; for (int j = i; j < columns; ++j) { result[k][j] -= ratio * result[i][j]; } } } return result; } catch (Exception e) { MyBoxLog.debug(e); return null; } } public static double[][] reducedRowEchelonForm(double[][] matrix) { try { int rows = matrix.length, columns = matrix[0].length; double[][] result = rowEchelonForm(matrix); for (int i = Math.min(rows - 1, columns - 1); i >= 0; --i) { double dd = result[i][i]; if (dd == 0) { continue; } for (int k = i - 1; k >= 0; k--) { double ratio = result[k][i] / dd; for (int j = k; j < columns; ++j) { result[k][j] -= ratio * result[i][j]; } } for (int j = i; j < columns; ++j) { result[i][j] = result[i][j] / dd; } } return result; } catch (Exception e) { MyBoxLog.debug(e); return null; } } public static double rank(double[][] matrix) throws Exception { try { if (matrix == null) { throw new Exception("InvalidValue"); } int rows = matrix.length, columns = matrix[0].length; double[][] d = clone(matrix); int i = 0; for (i = 0; i < Math.min(rows, columns); ++i) { if (d[i][i] == 0) { int row = -1; for (int k = i + 1; k < rows; k++) { if (d[k][i] != 0) { row = k; break; } } if (row < 0) { break; } for (int j = i; j < columns; ++j) { double temp = d[row][j]; d[row][j] = d[i][j]; d[i][j] = temp; } } for (int k = i + 1; k < rows; k++) { if (d[i][i] == 0) { continue; } double ratio = d[k][i] / d[i][i]; for (int j = i; j < columns; ++j) { d[k][j] -= ratio * d[i][j]; } } } return i; } catch (Exception e) { MyBoxLog.debug(e); throw e; } } public static double[][] swapRow(double matrix[][], int a, int b) { try { for (int j = 0; j < matrix[0].length; ++j) { double temp = matrix[a][j]; matrix[a][j] = matrix[b][j]; matrix[b][j] = temp; } } catch (Exception e) { } return matrix; } public static double[][] swapColumn(double matrix[][], int columnA, int columnB) { try { for (double[] matrix1 : matrix) { double temp = matrix1[columnA]; matrix1[columnA] = matrix1[columnB]; matrix1[columnB] = temp; } } catch (Exception e) { } return matrix; } public static String dataText(double[][] data, String delimiterName) { if (data == null || data.length == 0 || delimiterName == null) { return null; } StringBuilder s = new StringBuilder(); String delimiter = TextTools.delimiterValue(delimiterName); int rowsNumber = data.length; int colsNumber = data[0].length; for (int i = 0; i < rowsNumber; i++) { for (int j = 0; j < colsNumber; j++) { s.append(data[i][j]); if (j < colsNumber - 1) { s.append(delimiter); } } s.append("\n"); } return s.toString(); } public static String dataHtml(double[][] data, String title) { if (data == null || data.length == 0) { return null; } int rowsNumber = data.length; int colsNumber = data[0].length; StringTable table = new StringTable(null, title == null ? Languages.message("Data") : title); for (int i = 0; i < rowsNumber; i++) { List<String> row = new ArrayList<>(); for (int j = 0; j < colsNumber; j++) { row.add(data[i][j] + ""); } table.add(row); } return table.html(); } public static double[][] toArray(List<List<String>> data) { try { int rowsNumber = data.size(); int colsNumber = data.get(0).size(); if (rowsNumber <= 0 || colsNumber <= 0) { return null; } double[][] array = new double[rowsNumber][colsNumber]; for (int r = 0; r < rowsNumber; r++) { List<String> row = data.get(r); for (int c = 0; c < row.size(); c++) { double d = 0; try { d = Double.parseDouble(row.get(c)); } catch (Exception e) { } array[r][c] = d; } } return array; } catch (Exception e) { return null; } } public static List<List<String>> toList(double[][] array) { try { int rowsNumber = array.length; int colsNumber = array[0].length; List<List<String>> data = new ArrayList<>(); for (int i = 0; i < rowsNumber; i++) { List<String> row = new ArrayList<>(); for (int j = 0; j < colsNumber; j++) { row.add(array[i][j] + ""); } data.add(row); } return data; } catch (Exception e) { return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/tools/TTFTools.java
alpha/MyBox/src/main/java/mara/mybox/tools/TTFTools.java
package mara.mybox.tools; import java.io.File; import java.util.ArrayList; import java.util.List; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxFileTools; import mara.mybox.value.Languages; /** * @Author Mara * @CreateDate 2021-8-1 * @License Apache License Version 2.0 */ public class TTFTools { public static List<String> ttfList() { List<String> names = new ArrayList<>(); try { String os = SystemTools.os(); File ttfPath; switch (os) { case "win": ttfPath = new File("C:/Windows/Fonts/"); names.addAll(ttfList(ttfPath)); break; case "linux": ttfPath = new File("/usr/share/fonts/"); names.addAll(ttfList(ttfPath)); ttfPath = new File("/usr/lib/kbd/consolefonts/"); names.addAll(ttfList(ttfPath)); break; case "mac": ttfPath = new File("/Library/Fonts/"); names.addAll(ttfList(ttfPath)); ttfPath = new File("/System/Library/Fonts/"); names.addAll(ttfList(ttfPath)); break; } // http://wenq.org/wqy2/ File wqy_microhei = FxFileTools.getInternalFile("/data/wqy-microhei.ttf", "data", "wqy-microhei.ttf"); String wqy_microhei_name = wqy_microhei.getAbsolutePath() + " " + Languages.message("wqy_microhei"); if (!names.isEmpty() && names.get(0).contains(" ")) { names.add(1, wqy_microhei_name); } else { names.add(0, wqy_microhei_name); } } catch (Exception e) { MyBoxLog.error(e.toString()); } return names; } public static List<String> ttfList(File path) { List<String> names = new ArrayList<>(); try { if (path == null || !path.exists() || !path.isDirectory()) { return names; } File[] fontFiles = path.listFiles(); if (fontFiles == null || fontFiles.length == 0) { return names; } for (File file : fontFiles) { String filename = file.getAbsolutePath(); if (!filename.toLowerCase().endsWith(".ttf")) { continue; } names.add(filename); } String pathname = path.getAbsolutePath() + File.separator; List<String> cnames = new ArrayList<>(); if (names.contains(pathname + "STSONG.TTF")) { cnames.add(pathname + "STSONG.TTF" + " \u534e\u6587\u5b8b\u4f53"); } if (names.contains(pathname + "simfang.ttf")) { cnames.add(pathname + "simfang.ttf" + " \u4eff\u5b8b"); } if (names.contains(pathname + "simkai.ttf")) { cnames.add(pathname + "simkai.ttf" + " \u6977\u4f53"); } if (names.contains(pathname + "STKAITI.TTF")) { cnames.add(pathname + "STKAITI.TTF" + " \u534e\u6587\u6977\u4f53"); } if (names.contains(pathname + "SIMLI.TTF")) { cnames.add(pathname + "SIMLI.TTF" + " \u96b6\u4e66"); } if (names.contains(pathname + "STXINWEI.TTF")) { cnames.add(pathname + "STXINWEI.TTF" + " \u534e\u6587\u65b0\u9b4f"); } if (names.contains(pathname + "SIMYOU.TTF")) { cnames.add(pathname + "SIMYOU.TTF" + " \u5e7c\u5706"); } if (names.contains(pathname + "FZSTK.TTF")) { cnames.add(pathname + "FZSTK.TTF" + " \u65b9\u6b63\u8212\u4f53"); } if (names.contains(pathname + "STXIHEI.TTF")) { cnames.add(pathname + "STXIHEI.TTF" + " \u534e\u6587\u7ec6\u9ed1"); } if (names.contains(pathname + "simhei.ttf")) { cnames.add(pathname + "simhei.ttf" + " \u9ed1\u4f53"); } for (String name : names) { if (name.contains(pathname + "\u534e\u6587")) { cnames.add(name); } } names.addAll(0, cnames); } catch (Exception e) { MyBoxLog.error(e.toString()); } return names; } public static String ttf(String item) { if (item == null) { return null; } int pos = item.indexOf(" "); if (pos > 0) { return item.substring(0, pos); } return item; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/tools/TextFileTools.java
alpha/MyBox/src/main/java/mara/mybox/tools/TextFileTools.java
package mara.mybox.tools; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.nio.charset.Charset; import java.util.List; import mara.mybox.data.TextEditInformation; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; /** * @Author Mara * @CreateDate 2021-8-1 * @License Apache License Version 2.0 */ public class TextFileTools { public static String readTexts(FxTask task, File file) { return readTexts(task, file, charset(file)); } public static String readTexts(FxTask task, File file, Charset charset) { if (file == null || charset == null) { return null; } StringBuilder s = new StringBuilder(); File validFile = FileTools.removeBOM(task, file); if (validFile == null || (task != null && !task.isWorking())) { return null; } try (final BufferedReader reader = new BufferedReader(new FileReader(validFile, charset))) { String line = reader.readLine(); if (line != null) { s.append(line); while ((line = reader.readLine()) != null) { if (task != null && !task.isWorking()) { break; } s.append(System.lineSeparator()).append(line); } } } catch (Exception e) { return null; } return s.toString(); } public static File writeFile(File file, String data) { return writeFile(file, data, Charset.forName("utf-8")); } public static File writeFile(File file, String data, Charset charset) { if (file == null || data == null) { return null; } file.getParentFile().mkdirs(); Charset fileCharset = charset != null ? charset : Charset.forName("utf-8"); try (BufferedWriter writer = new BufferedWriter(new FileWriter(file, fileCharset, false))) { writer.write(data); writer.flush(); } catch (Exception e) { MyBoxLog.error(e.toString()); return null; } return file; } public static File writeFile(String data) { return writeFile(FileTmpTools.getTempFile(), data); } public static Charset charset(File file) { try { if (file == null || !file.exists()) { return Charset.forName("utf-8"); } TextEditInformation info = new TextEditInformation(file); if (TextTools.checkCharset(info)) { return info.getCharset(); } else { return Charset.forName("utf-8"); } } catch (Exception e) { return Charset.forName("utf-8"); } } public static boolean isUTF8(File file) { Charset charset = charset(file); return charset.equals(Charset.forName("utf-8")); } public static boolean mergeTextFiles(FxTask task, List<File> files, File targetFile) { if (files == null || files.isEmpty() || targetFile == null) { return false; } targetFile.getParentFile().mkdirs(); String line; try (final FileWriter writer = new FileWriter(targetFile, Charset.forName("utf-8"))) { for (File file : files) { File validFile = FileTools.removeBOM(task, file); try (final BufferedReader reader = new BufferedReader(new FileReader(validFile, charset(validFile)))) { while ((line = reader.readLine()) != null) { if (task != null && !task.isWorking()) { return false; } writer.write(line + System.lineSeparator()); } } } writer.flush(); } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e); } return false; } return true; } public static void writeLine(FxTask task, BufferedWriter writer, List<String> values, String delimiter) { try { if (writer == null || values == null || values.isEmpty() || delimiter == null) { return; } String delimiterValue = TextTools.delimiterValue(delimiter); int end = values.size() - 1; String line = ""; for (int c = 0; c <= end; c++) { if (task != null && !task.isWorking()) { return; } String value = values.get(c); if (value != null) { line += value; } if (c < end) { line += delimiterValue; } } writer.write(line + "\n"); } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e); } } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/tools/DownloadTools.java
alpha/MyBox/src/main/java/mara/mybox/tools/DownloadTools.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.tools; /** * * @author mara */ public class DownloadTools { }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/tools/FileTmpTools.java
alpha/MyBox/src/main/java/mara/mybox/tools/FileTmpTools.java
package mara.mybox.tools; import java.io.File; import mara.mybox.value.AppPaths; import mara.mybox.value.AppVariables; /** * @Author Mara * @CreateDate 2021-8-1 * @License Apache License Version 2.0 */ public class FileTmpTools { public static String tmpFilename(String path) { return path + File.separator + DateTools.nowFileString() + "_" + IntTools.random(100); } public static String tmpFilename(String path, String prefix) { if (path == null) { return null; } if (prefix == null) { return FileTmpTools.tmpFilename(path); } return path + File.separator + FileNameTools.filter(prefix) + "_" + DateTools.nowFileString() + "_" + IntTools.random(100); } public static File getTempFile() { return getPathTempFile(AppVariables.MyBoxTempPath.getAbsolutePath()); } public static File getTempFile(String suffix) { return getPathTempFile(AppVariables.MyBoxTempPath.getAbsolutePath(), suffix); } public static File tmpFile(String prefix, String ext) { return getPathTempFile(AppVariables.MyBoxTempPath.getAbsolutePath(), prefix, ext == null || ext.isBlank() ? null : "." + ext); } public static File getPathTempFile(String path) { if (path == null) { return null; } new File(path).mkdirs(); File file = new File(FileTmpTools.tmpFilename(path)); while (file.exists()) { file = new File(FileTmpTools.tmpFilename(path)); } return file; } public static File getPathTempFile(String path, String suffix) { if (path == null) { return null; } new File(path).mkdirs(); String s = FileNameTools.filter(suffix); s = s == null || s.isBlank() ? "" : s; File file = new File(FileTmpTools.tmpFilename(path) + s); while (file.exists()) { file = new File(FileTmpTools.tmpFilename(path) + s); } return file; } public static File getPathTempFile(String path, String prefix, String suffix) { if (path == null) { return null; } new File(path).mkdirs(); String p = FileNameTools.filter(prefix); String s = FileNameTools.filter(suffix); s = s == null || s.isBlank() ? "" : s; if (p != null && !p.isBlank()) { File tFile = new File(path + File.separator + p + s); while (tFile.exists()) { tFile = new File(tmpFilename(path, p) + s); } return tFile; } return getPathTempFile(path, s); } public static File getTempDirectory() { return getPathTempDirectory(AppVariables.MyBoxTempPath.getAbsolutePath()); } public static File getPathTempDirectory(String path) { if (path == null) { return null; } new File(path).mkdirs(); File file = new File(FileTmpTools.tmpFilename(path) + File.separator); while (file.exists()) { file = new File(FileTmpTools.tmpFilename(path) + File.separator); } file.mkdirs(); return file; } public static boolean isTmpFile(File file) { return file != null && file.getAbsolutePath().startsWith( AppVariables.MyBoxTempPath.getAbsolutePath() + File.separator); } public static String generatePath(String type) { String path = AppPaths.getGeneratedPath() + File.separator + (type == null || type.isBlank() ? "x" : FileNameTools.filter(type)); new File(path).mkdirs(); return path; } public static File generateFile(String ext) { return getPathTempFile(generatePath(ext), ext == null || ext.isBlank() ? null : "." + ext); } public static File generateFile(String prefix, String ext) { return getPathTempFile(generatePath(ext), prefix, ext == null || ext.isBlank() ? null : "." + ext); } public static boolean isGenerateFile(File file) { return file != null && file.getAbsolutePath().startsWith( AppPaths.getGeneratedPath() + File.separator); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/tools/CsvTools.java
alpha/MyBox/src/main/java/mara/mybox/tools/CsvTools.java
package mara.mybox.tools; import java.io.File; import java.io.FileWriter; import java.nio.charset.Charset; import mara.mybox.dev.MyBoxLog; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVFormat.Builder; import org.apache.commons.csv.CSVParser; import org.apache.commons.csv.CSVPrinter; import org.apache.commons.csv.DuplicateHeaderMode; /** * @Author Mara * @CreateDate 2022-5 * @License Apache License Version 2.0 */ public class CsvTools { public static final char CommentsMarker = '#'; public static Builder builder(String delimiter) { String d = TextTools.delimiterValue(delimiter); if (d == null) { return null; } return CSVFormat.Builder.create() .setDelimiter(d) .setIgnoreEmptyLines(true) .setTrim(true) .setNullString("") .setCommentMarker(d.equals(CommentsMarker + "") ? null : CommentsMarker) .setDuplicateHeaderMode(DuplicateHeaderMode.ALLOW_ALL); } public static CSVFormat csvFormat(String delimiter, boolean hasHeader) { Builder builder = builder(delimiter); if (hasHeader) { builder.setHeader().setSkipHeaderRecord(true); } else { builder.setSkipHeaderRecord(false); } return builder.get(); } public static CSVFormat csvFormat(String delimiter) { return csvFormat(delimiter, true); } public static CSVFormat csvFormat() { return csvFormat(",", true); } public static CSVPrinter csvPrinter(File csvFile) { try { return new CSVPrinter(new FileWriter(csvFile, Charset.forName("UTF-8")), csvFormat()); } catch (Exception e) { return null; } } public static CSVPrinter csvPrinter(File csvFile, String delimiter, boolean hasHeader) { try { return new CSVPrinter(new FileWriter(csvFile, Charset.forName("UTF-8")), csvFormat(delimiter, hasHeader)); } catch (Exception e) { MyBoxLog.console(e); return null; } } public static CSVParser csvParser(File csvFile, String delimiter, boolean hasHeader) { try { return CSVParser.parse(csvFile, Charset.forName("UTF-8"), csvFormat(delimiter, hasHeader)); } catch (Exception e) { MyBoxLog.console(e); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/tools/SvgTools.java
alpha/MyBox/src/main/java/mara/mybox/tools/SvgTools.java
package mara.mybox.tools; import java.awt.Rectangle; import java.awt.image.BufferedImage; import java.io.BufferedOutputStream; import java.io.BufferedWriter; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.InputStream; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import javafx.scene.paint.Color; import mara.mybox.image.tools.AlphaTools; import mara.mybox.image.data.ImageQuantization; import mara.mybox.image.data.ImageRegionKMeans; import mara.mybox.image.data.PixelsOperation; import mara.mybox.controller.BaseController; import mara.mybox.controller.ControlImageQuantization; import mara.mybox.controller.ControlSvgFromImage; import mara.mybox.controller.ControlSvgFromImage.Algorithm; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.image.FxColorTools; import mara.mybox.fxml.FxTask; import mara.mybox.fxml.PopTools; import mara.mybox.image.file.ImageFileReaders; import static mara.mybox.value.Languages.message; import org.apache.batik.anim.dom.SVGDOMImplementation; import org.apache.batik.dom.GenericDOMImplementation; import org.apache.batik.svggen.SVGGraphics2D; import org.apache.batik.transcoder.TranscoderInput; import org.apache.batik.transcoder.TranscoderOutput; import org.apache.batik.transcoder.image.PNGTranscoder; import org.apache.fop.svg.PDFTranscoder; import org.w3c.dom.*; import thridparty.miguelemosreverte.ImageTracer; import static thridparty.miguelemosreverte.ImageTracer.bytetrans; import thridparty.miguelemosreverte.SVGUtils; import thridparty.miguelemosreverte.VectorizingUtils; import static mara.mybox.image.data.ImageQuantization.QuantizationAlgorithm.RegionKMeansClustering; /** * @Author Mara * @CreateDate 2023-2-12 * @License Apache License Version 2.0 */ public class SvgTools { /* to image */ public static File docToImage(FxTask task, BaseController controller, Document doc, float width, float height, Rectangle area) { if (doc == null) { return null; } return textToImage(task, controller, XmlTools.transform(doc), width, height, area); } public static File textToImage(FxTask task, BaseController controller, String svg, float width, float height, Rectangle area) { if (svg == null || svg.isBlank()) { return null; } String handled = handleAlpha(task, controller, svg); // Looks batik does not supper color formats with alpha try (ByteArrayInputStream inputStream = new ByteArrayInputStream(handled.getBytes("utf-8"))) { return toImage(task, controller, inputStream, width, height, area); } catch (Exception e) { PopTools.showError(controller, e.toString()); return null; } } public static File fileToImage(FxTask task, BaseController controller, File file, float width, float height, Rectangle area) { if (file == null || !file.exists()) { return null; } return textToImage(task, controller, TextFileTools.readTexts(task, file), width, height, area); } public static BufferedImage pathToImage(FxTask task, BaseController controller, String path) { if (path == null || path.isBlank()) { return null; } String svg = "<svg xmlns=\"http://www.w3.org/2000/svg\" ><path d=\"" + path + "\"></path></svg>"; File tmpFile = textToImage(task, controller, svg, -1, -1, null); if (tmpFile == null || !tmpFile.exists()) { return null; } if (tmpFile.length() <= 0) { FileDeleteTools.delete(tmpFile); return null; } return ImageFileReaders.readImage(task, tmpFile); } public static File toImage(FxTask task, BaseController controller, InputStream inputStream, float width, float height, Rectangle area) { if (inputStream == null) { return null; } File tmpFile = FileTmpTools.generateFile("png"); try (BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(tmpFile))) { PNGTranscoder transcoder = new PNGTranscoder(); if (width > 0) { transcoder.addTranscodingHint(PNGTranscoder.KEY_WIDTH, width); } if (height > 0) { transcoder.addTranscodingHint(PNGTranscoder.KEY_HEIGHT, height); } if (area != null) { transcoder.addTranscodingHint(PNGTranscoder.KEY_AOI, area); } TranscoderInput input = new TranscoderInput(inputStream); TranscoderOutput output = new TranscoderOutput(outputStream); transcoder.transcode(input, output); outputStream.flush(); outputStream.close(); } catch (Exception e) { PopTools.showError(controller, e.toString()); } if (tmpFile.exists() && tmpFile.length() > 0) { return tmpFile; } FileDeleteTools.delete(tmpFile); return null; } /* to pdf */ public static File docToPDF(FxTask task, BaseController controller, Document doc, float width, float height, Rectangle area) { if (doc == null) { return null; } return textToPDF(task, controller, XmlTools.transform(doc), width, height, area); } public static File textToPDF(FxTask task, BaseController controller, String svg, float width, float height, Rectangle area) { if (svg == null || svg.isBlank()) { return null; } String handled = handleAlpha(task, controller, svg); // Looks batik does not supper color formats with alpha if (handled == null || (task != null && !task.isWorking())) { return null; } try (ByteArrayInputStream inputStream = new ByteArrayInputStream(handled.getBytes("utf-8"))) { return toPDF(task, controller, inputStream, width, height, area); } catch (Exception e) { PopTools.showError(controller, e.toString()); return null; } } public static File fileToPDF(FxTask task, BaseController controller, File file, float width, float height, Rectangle area) { if (file == null || !file.exists()) { return null; } return textToPDF(task, controller, TextFileTools.readTexts(task, file), width, height, area); } public static File toPDF(FxTask task, BaseController controller, InputStream inputStream, float width, float height, Rectangle area) { if (inputStream == null) { return null; } File tmpFile = FileTmpTools.generateFile("pdf"); try (BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(tmpFile))) { PDFTranscoder transcoder = new PDFTranscoder(); if (width > 0) { transcoder.addTranscodingHint(PDFTranscoder.KEY_WIDTH, width); } if (height > 0) { transcoder.addTranscodingHint(PDFTranscoder.KEY_HEIGHT, height); } if (area != null) { transcoder.addTranscodingHint(PDFTranscoder.KEY_AOI, area); } TranscoderInput input = new TranscoderInput(inputStream); TranscoderOutput output = new TranscoderOutput(outputStream); transcoder.transcode(input, output); outputStream.flush(); outputStream.close(); } catch (Exception e) { PopTools.showError(controller, e.toString()); } if (tmpFile.exists() && tmpFile.length() > 0) { return tmpFile; } FileDeleteTools.delete(tmpFile); return null; } /* color */ public static String handleAlpha(FxTask task, BaseController controller, String svg) { if (svg == null || svg.isBlank()) { return svg; } try { Document doc = XmlTools.textToDoc(task, controller, svg); if (doc == null || (task != null && !task.isWorking())) { return svg; } handleAlpha(task, controller, doc); return XmlTools.transform(doc); } catch (Exception e) { PopTools.showError(controller, e.toString()); return null; } } public static boolean handleAlpha(FxTask task, BaseController controller, Node node) { if (node == null) { return false; } try { if (node instanceof Element) { Element element = (Element) node; try { Color c = Color.web(element.getAttribute("stroke")); String opacity = element.getAttribute("stroke-opacity"); if (c != null) { element.setAttribute("stroke", FxColorTools.color2rgb(c)); if (c.getOpacity() < 1 && (opacity == null || opacity.isBlank())) { element.setAttribute("stroke-opacity", c.getOpacity() + ""); } } } catch (Exception e) { } try { Color c = Color.web(element.getAttribute("fill")); String opacity = element.getAttribute("fill-opacity"); if (c != null) { element.setAttribute("fill", FxColorTools.color2rgb(c)); if (c.getOpacity() < 1 && (opacity == null || opacity.isBlank())) { element.setAttribute("fill-opacity", c.getOpacity() + ""); } } } catch (Exception e) { } try { Color c = Color.web(element.getAttribute("color")); String opacity = element.getAttribute("opacity"); if (c != null) { element.setAttribute("color", FxColorTools.color2rgb(c)); if (c.getOpacity() < 1 && (opacity == null || opacity.isBlank())) { element.setAttribute("opacity", c.getOpacity() + ""); } } } catch (Exception e) { } } NodeList children = node.getChildNodes(); if (children != null) { for (int i = 0; i < children.getLength(); i++) { if (task != null && !task.isWorking()) { return false; } Node child = children.item(i); handleAlpha(task, controller, child); } } return true; } catch (Exception e) { PopTools.showError(controller, e.toString()); return false; } } /* values */ public static Rectangle viewBox(String value) { Rectangle rect = null; try { String[] v = value.trim().split("\\s+"); if (v != null && v.length >= 4) { rect = new Rectangle(Integer.parseInt(v[0]), Integer.parseInt(v[1]), Integer.parseInt(v[2]), Integer.parseInt(v[3])); } } catch (Exception e) { } return rect; } public static String viewBoxString(Rectangle rect) { if (rect == null) { return null; } return (int) rect.getX() + " " + (int) rect.getY() + " " + (int) rect.getWidth() + " " + (int) rect.getHeight(); } /* generate */ public static String blankSVG(float width, float height) { String svg = "<svg xmlns=\"http://www.w3.org/2000/svg\" "; if (width > 0) { svg += " width=\"" + width + "\" "; } if (height > 0) { svg += " height=\"" + height + "\" "; } return svg += " ></svg>"; } public static Document blankDoc(float width, float height) { return XmlTools.textToDoc(null, null, blankSVG(width, height)); } public static Document blankDoc() { return blankDoc(500.0f, 500.0f); } public static Document focus(FxTask task, Document doc, Node node, float bgOpacity) { if (doc == null) { return doc; } Document clonedDoc = (Document) doc.cloneNode(true); if (node == null || !(node instanceof Element) || "svg".equalsIgnoreCase(node.getNodeName())) { return clonedDoc; } String hierarchyNumber = XmlTools.hierarchyNumber(node); if (hierarchyNumber == null) { return clonedDoc; } Node targetNode = XmlTools.find(clonedDoc, hierarchyNumber); Node cnode = targetNode; while (cnode != null) { if (task != null && !task.isWorking()) { return doc; } Node parent = cnode.getParentNode(); if (parent == null) { break; } NodeList nodes = parent.getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { if (task != null && !task.isWorking()) { return doc; } Node child = nodes.item(i); if (child.equals(cnode) || !(child instanceof Element)) { continue; } ((Element) child).setAttribute("opacity", bgOpacity + ""); } cnode = parent; } return clonedDoc; } public static Document removeSize(Document doc) { if (doc == null) { return doc; } Document clonedDoc = (Document) doc.cloneNode(true); Element svgNode = XmlTools.findName(clonedDoc, "svg", 0); svgNode.removeAttribute("width"); svgNode.removeAttribute("height"); svgNode.removeAttribute("viewBox"); return clonedDoc; } public static File toFile(SVGGraphics2D g, File file) { if (g == null || file == null) { return null; } try (BufferedWriter writer = new BufferedWriter(new FileWriter(file, Charset.forName("utf-8"), false))) { g.stream(writer, true); writer.flush(); return file; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static File toFile(SVGGraphics2D g) { if (g == null) { return null; } File tmpFile = FileTmpTools.getTempFile(".svg"); try (BufferedWriter writer = new BufferedWriter(new FileWriter(tmpFile, Charset.forName("utf-8"), false))) { g.stream(writer, true); writer.flush(); return tmpFile; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static String toText(FxTask task, SVGGraphics2D g) { String s = TextFileTools.readTexts(task, toFile(g), Charset.forName("utf-8")); return s; // if (s == null) { // return null; // } // return s.replaceAll("><", ">\n<"); } /* SVGGraphics2D */ public static Document document() { return GenericDOMImplementation.getDOMImplementation().createDocument(SVGDOMImplementation.SVG_NAMESPACE_URI, "svg", null); } /* image to svg */ public static String imagefileToSvg(FxTask task, BaseController controller, File imageFile, ControlSvgFromImage optionsController) { try { if (imageFile == null || !imageFile.exists()) { return null; } BufferedImage image = ImageFileReaders.readImage(task, imageFile); if (image == null || (task != null && !task.isWorking())) { return null; } return imageToSvg(task, controller, image, optionsController); } catch (Exception e) { PopTools.showError(controller, e.toString()); return null; } } // https://github.com/miguelemosreverte/imagetracerjava public static String imageToSvg(FxTask task, BaseController controller, BufferedImage inImage, ControlSvgFromImage optionsController) { try { if (optionsController == null || inImage == null) { PopTools.showError(controller, message("InvalidData")); return null; } BufferedImage image = AlphaTools.removeAlpha(task, inImage); switch (optionsController.getQuantization()) { case jankovicsandras: return jankovicsandras(task, controller, image, optionsController); case mybox: return mybox(task, controller, image, optionsController); default: return miguelemosreverte(task, controller, image, optionsController); } } catch (Exception e) { PopTools.showError(controller, e.toString()); return null; } } public static String miguelemosreverte(FxTask task, BaseController controller, BufferedImage image, ControlSvgFromImage optionsController) { try { if (image == null || optionsController == null) { return null; } HashMap<String, Float> options = optionsController.getOptions(); options = ImageTracer.checkoptions(options); if (options == null || (task != null && !task.isWorking())) { return null; } ImageTracer.IndexedImage ii = miguelemosreverteQuantization(task, controller, image, options); if (ii == null || (task != null && !task.isWorking())) { return null; } return miguelemosreverteSVG(task, controller, ii, options); } catch (Exception e) { PopTools.showError(controller, e.toString()); return null; } } public static ImageTracer.IndexedImage miguelemosreverteQuantization(FxTask task, BaseController controller, BufferedImage image, HashMap<String, Float> options) { try { if (image == null) { PopTools.showError(controller, message("InvalidData")); return null; } if (options == null || (task != null && !task.isWorking())) { return null; } ImageTracer.ImageData imgd = ImageTracer.loadImageData(image); if (imgd == null || (task != null && !task.isWorking())) { return null; } byte[][] palette = ImageTracer.getPalette(image, options); if (palette == null || (task != null && !task.isWorking())) { return null; } return VectorizingUtils.colorquantization(imgd, palette, options); } catch (Exception e) { PopTools.showError(controller, e.toString()); return null; } } public static String miguelemosreverteSVG(FxTask task, BaseController controller, ImageTracer.IndexedImage ii, HashMap<String, Float> options) { try { if (ii == null || (task != null && !task.isWorking())) { return null; } // 2. Layer separation and edge detection int[][][] rawlayers = VectorizingUtils.layering(ii); if (rawlayers == null || (task != null && !task.isWorking())) { return null; } // 3. Batch pathscan ArrayList<ArrayList<ArrayList<Integer[]>>> bps = VectorizingUtils.batchpathscan(rawlayers, (int) (Math.floor(options.get("pathomit")))); if (bps == null || (task != null && !task.isWorking())) { return null; } // 4. Batch interpollation ArrayList<ArrayList<ArrayList<Double[]>>> bis = VectorizingUtils.batchinternodes(bps); if (bis == null || (task != null && !task.isWorking())) { return null; } // 5. Batch tracing ii.layers = VectorizingUtils.batchtracelayers(bis, options.get("ltres"), options.get("qtres")); if (ii.layers == null || (task != null && !task.isWorking())) { return null; } return SVGUtils.getsvgstring(ii, options); } catch (Exception e) { PopTools.showError(controller, e.toString()); return null; } } public static String jankovicsandras(FxTask task, BaseController controller, BufferedImage image, ControlSvgFromImage optionsController) { try { if (image == null || optionsController == null) { return null; } HashMap<String, Float> options = optionsController.getOptions(); options = thridparty.jankovicsandras.ImageTracer.checkoptions(options); if (options == null || (task != null && !task.isWorking())) { return null; } thridparty.jankovicsandras.ImageTracer.IndexedImage ii = jankovicsandrasQuantization(task, controller, image, options); if (ii == null || (task != null && !task.isWorking())) { return null; } return jankovicsandrasSVG(task, controller, ii, options); } catch (Exception e) { PopTools.showError(controller, e.toString()); return null; } } // https://github.com/jankovicsandras/imagetracerjava public static thridparty.jankovicsandras.ImageTracer.IndexedImage jankovicsandrasQuantization(FxTask task, BaseController controller, BufferedImage image, HashMap<String, Float> options) { try { if (image == null || options == null) { return null; } thridparty.jankovicsandras.ImageTracer.ImageData imgd = thridparty.jankovicsandras.ImageTracer.loadImageData(image); if (imgd == null || (task != null && !task.isWorking())) { return null; } return thridparty.jankovicsandras.ImageTracer.colorquantization(imgd, null, options); } catch (Exception e) { PopTools.showError(controller, e.toString()); return null; } } public static String jankovicsandrasSVG(FxTask task, BaseController controller, thridparty.jankovicsandras.ImageTracer.IndexedImage ii, HashMap<String, Float> options) { try { if (ii == null || (task != null && !task.isWorking())) { return null; } // 2. Layer separation and edge detection int[][][] rawlayers = thridparty.jankovicsandras.ImageTracer.layering(ii); if (rawlayers == null || (task != null && !task.isWorking())) { return null; } // 3. Batch pathscan ArrayList<ArrayList<ArrayList<Integer[]>>> bps = thridparty.jankovicsandras.ImageTracer.batchpathscan(rawlayers, (int) (Math.floor(options.get("pathomit")))); if (bps == null || (task != null && !task.isWorking())) { return null; } // 4. Batch interpollation ArrayList<ArrayList<ArrayList<Double[]>>> bis = thridparty.jankovicsandras.ImageTracer.batchinternodes(bps); if (bis == null || (task != null && !task.isWorking())) { return null; } // 5. Batch tracing ii.layers = thridparty.jankovicsandras.ImageTracer.batchtracelayers(bis, options.get("ltres"), options.get("qtres")); if (ii.layers == null || (task != null && !task.isWorking())) { return null; } return thridparty.jankovicsandras.ImageTracer.getsvgstring(ii, options); } catch (Exception e) { PopTools.showError(controller, e.toString()); return null; } } public static ImageKMeans myboxQuantization(FxTask task, BaseController controller, BufferedImage image, ControlImageQuantization quantization) { try { ImageKMeans kmeans = ImageKMeans.create(); kmeans.setAlgorithm(RegionKMeansClustering). setQuantizationSize(quantization.getQuanColors()) .setRegionSize(quantization.getRegionSize()) .setWeight1(quantization.getRgbWeight1()) .setWeight2(quantization.getRgbWeight2()) .setWeight3(quantization.getRgbWeight3()) .setRecordCount(false) .setFirstColor(quantization.getFirstColorCheck().isSelected()) .setOperationType(PixelsOperation.OperationType.Quantization) .setImage(image).setScope(null) .setIsDithering(quantization.getQuanDitherCheck().isSelected()) .setTask(task); kmeans.makePalette().start(); return kmeans; } catch (Exception e) { PopTools.showError(controller, e.toString()); return null; } } public static String mybox(FxTask task, BaseController controller, BufferedImage image, ControlSvgFromImage optionsController) { try { if (image == null || optionsController == null) { return null; } ImageKMeans kmeans = myboxQuantization(task, controller, image, optionsController.getQuantizationController()); if (kmeans == null || kmeans.paletteBytes == null || kmeans.getColorIndice() == null || (task != null && !task.isWorking())) { return null; } HashMap<String, Float> options = optionsController.getOptions(); MyBoxLog.console(optionsController.getLayer().name()); if (optionsController.getLayer() == Algorithm.jankovicsandras) { options = thridparty.jankovicsandras.ImageTracer.checkoptions(options); if (options == null || (task != null && !task.isWorking())) { return null; } thridparty.jankovicsandras.ImageTracer.IndexedImage ii = new thridparty.jankovicsandras.ImageTracer.IndexedImage( kmeans.getColorIndice(), kmeans.paletteBytes); return jankovicsandrasSVG(task, controller, ii, options); } else { options = ImageTracer.checkoptions(options); if (options == null || (task != null && !task.isWorking())) { return null; } ImageTracer.IndexedImage ii = new ImageTracer.IndexedImage( kmeans.getColorIndice(), kmeans.paletteBytes); return miguelemosreverteSVG(task, controller, ii, options); } } catch (Exception e) { PopTools.showError(controller, e.toString()); return null; } } public static class ImageKMeans extends ImageQuantization { public int[][] colorIndice; public byte[][] paletteBytes; protected ImageRegionKMeans kmeans; protected List<java.awt.Color> paletteColors; public static ImageKMeans create() { return new ImageKMeans(); } public ImageKMeans makePalette() { try { kmeans = imageRegionKMeans(); paletteColors = kmeans.getCenters(); int size = paletteColors.size(); paletteBytes = new byte[size + 1][4]; for (int i = 0; i < size; i++) { if (task != null && !task.isWorking()) { return null; } int value = paletteColors.get(i).getRGB(); paletteBytes[i][3] = bytetrans((byte) (value >>> 24)); paletteBytes[i][0] = bytetrans((byte) (value >>> 16)); paletteBytes[i][1] = bytetrans((byte) (value >>> 8)); paletteBytes[i][2] = bytetrans((byte) (value)); } int transparent = 0; paletteBytes[size][3] = bytetrans((byte) (transparent >>> 24)); paletteBytes[size][0] = bytetrans((byte) (transparent >>> 16)); paletteBytes[size][1] = bytetrans((byte) (transparent >>> 8)); paletteBytes[size][2] = bytetrans((byte) (transparent)); int width = image.getWidth(); int height = image.getHeight(); colorIndice = new int[height + 2][width + 2]; for (int j = 0; j < (height + 2); j++) { if (task != null && !task.isWorking()) { return null; } colorIndice[j][0] = -1; colorIndice[j][width + 1] = -1; } for (int i = 0; i < (width + 2); i++) { if (task != null && !task.isWorking()) { return null; } colorIndice[0][i] = -1; colorIndice[height + 1][i] = -1; } } catch (Exception e) { MyBoxLog.debug(e); } return this; } @Override public java.awt.Color operateColor(java.awt.Color color) { try { java.awt.Color mappedColor = kmeans.map(color); int index = paletteColors.indexOf(mappedColor); colorIndice[currentY + 1][currentX + 1] = index; return mappedColor; } catch (Exception e) { return color; } } /* get/set */ public int[][] getColorIndice() { return colorIndice; } public byte[][] getPaletteBytes() { return paletteBytes; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/tools/MarkdownTools.java
alpha/MyBox/src/main/java/mara/mybox/tools/MarkdownTools.java
package mara.mybox.tools; import com.vladsch.flexmark.ast.Heading; import com.vladsch.flexmark.ast.Image; import com.vladsch.flexmark.ast.ImageRef; import com.vladsch.flexmark.ext.abbreviation.AbbreviationExtension; import com.vladsch.flexmark.ext.definition.DefinitionExtension; import com.vladsch.flexmark.ext.footnotes.FootnoteExtension; import com.vladsch.flexmark.ext.tables.TablesExtension; import com.vladsch.flexmark.ext.typographic.TypographicExtension; import com.vladsch.flexmark.html.HtmlRenderer; import com.vladsch.flexmark.parser.Parser; import com.vladsch.flexmark.parser.ParserEmulationProfile; import com.vladsch.flexmark.util.ast.Block; import com.vladsch.flexmark.util.ast.Node; import com.vladsch.flexmark.util.data.MutableDataHolder; import com.vladsch.flexmark.util.data.MutableDataSet; import com.vladsch.flexmark.util.sequence.BasedSequence; import java.io.File; import java.net.URLDecoder; import java.nio.charset.Charset; import java.sql.Connection; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import mara.mybox.data.Link; import mara.mybox.db.DerbyBase; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.value.UserConfig; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; /** * @Author Mara * @CreateDate 2020-10-21 * @License Apache License Version 2.0 */ public class MarkdownTools { public static String string(BasedSequence string) { if (string == null) { return null; } try { return URLDecoder.decode(string.toStringOrNull(), "UTF-8"); } catch (Exception e) { return null; } } // https://github.com/vsch/flexmark-java/blob/master/flexmark-java-samples/src/com/vladsch/flexmark/java/samples/TitleExtract.java public static void links(Node node, List<Link> links) { if (node == null || links == null) { return; } if (node instanceof com.vladsch.flexmark.ast.Link) { com.vladsch.flexmark.ast.Link mdLink = (com.vladsch.flexmark.ast.Link) node; try { Link link = Link.create() .setAddress(string(mdLink.getUrl())) .setName(string(mdLink.getText())) .setTitle(string(mdLink.getTitle())) .setIndex(links.size()); links.add(link); } catch (Exception e) { } } if (node instanceof Block && node.hasChildren()) { Node child = node.getFirstChild(); while (child != null) { links(child, links); child = child.getNext(); } } } public static void heads(Node node, List<Heading> heads) { if (node == null || heads == null) { return; } if (node instanceof Heading) { Heading head = (Heading) node; heads.add(head); } if (node instanceof Block && node.hasChildren()) { Node child = node.getFirstChild(); while (child != null) { heads(child, heads); child = child.getNext(); } } } public static String toc(Node node, int indentSize) { if (node == null) { return null; } List<Heading> heads = new ArrayList<>(); heads(node, heads); String toc = ""; for (Heading head : heads) { for (int i = 0; i < head.getLevel() * indentSize; i++) { toc += " "; } toc += head.getText() + "\n"; } return toc; } public static void images(Node node, List<Image> images) { if (node == null || images == null) { return; } if (node instanceof Image) { Image image = (Image) node; images.add(image); } if (node instanceof Block && node.hasChildren()) { Node child = node.getFirstChild(); while (child != null) { images(child, images); child = child.getNext(); } } } public static void imageRefs(Node node, List<ImageRef> imageRefs) { if (node == null || imageRefs == null) { return; } if (node instanceof ImageRef) { ImageRef imageRef = (ImageRef) node; imageRefs.add(imageRef); } if (node instanceof Block && node.hasChildren()) { Node child = node.getFirstChild(); while (child != null) { imageRefs(child, imageRefs); child = child.getNext(); } } } public static MutableDataHolder htmlOptions(String emulation, int indentSize, boolean trim, boolean discard, boolean append) { try { MutableDataHolder htmlOptions = new MutableDataSet(); htmlOptions.setFrom(ParserEmulationProfile.valueOf(emulation)); htmlOptions.set(Parser.EXTENSIONS, Arrays.asList( AbbreviationExtension.create(), DefinitionExtension.create(), FootnoteExtension.create(), TypographicExtension.create(), TablesExtension.create() )); htmlOptions.set(HtmlRenderer.INDENT_SIZE, indentSize) // .set(HtmlRenderer.PERCENT_ENCODE_URLS, true) // .set(TablesExtension.COLUMN_SPANS, false) .set(TablesExtension.TRIM_CELL_WHITESPACE, trim) .set(TablesExtension.DISCARD_EXTRA_COLUMNS, discard) .set(TablesExtension.APPEND_MISSING_COLUMNS, append); return htmlOptions; } catch (Exception e) { MyBoxLog.error(e.toString()); return null; } } public static MutableDataHolder htmlOptions() { try (Connection conn = DerbyBase.getConnection()) { return htmlOptions(UserConfig.getString(conn, "MarkdownEmulation", "PEGDOWN"), UserConfig.getInt(conn, "MarkdownIndent", 4), UserConfig.getBoolean(conn, "MarkdownTrim", false), UserConfig.getBoolean(conn, "MarkdownDiscard", false), UserConfig.getBoolean(conn, "MarkdownAppend", false)); } catch (Exception e) { MyBoxLog.error(e); return null; } } public static String md2html(FxTask task, MutableDataHolder htmlOptions, File mdFile, String style) { try { if (mdFile == null || !mdFile.exists()) { return null; } Parser htmlParser = Parser.builder(htmlOptions).build(); HtmlRenderer htmlRender = HtmlRenderer.builder(htmlOptions).build(); Node document = htmlParser.parse(TextFileTools.readTexts(task, mdFile)); String html = htmlRender.render(document); Document doc = Jsoup.parse(html); if (doc == null) { return null; } HtmlWriteTools.setCharset(task, doc, Charset.forName("UTF-8")); if (task != null && !task.isWorking()) { return null; } doc.head().appendChild(new Element("style").text(style)); return doc.outerHtml(); } catch (Exception e) { MyBoxLog.error(e); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/tools/NetworkTools.java
alpha/MyBox/src/main/java/mara/mybox/tools/NetworkTools.java
package mara.mybox.tools; import java.net.HttpURLConnection; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.ServerSocket; import java.net.Socket; import java.net.URL; import java.util.Enumeration; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.value.AppValues; /** * @Author Mara * @CreateDate 2018-6-9 7:46:58 * @License Apache License Version 2.0 */ public class NetworkTools { public static int findFreePort(int port) { int p; try { Socket socket = new Socket(InetAddress.getLocalHost(), port); socket.close(); p = port; } catch (Exception e) { try { try (ServerSocket serverSocket = new ServerSocket(0)) { p = serverSocket.getLocalPort(); } } catch (Exception ex) { p = -1; } } return p; } public static boolean isPortUsed(int port) { try { Socket socket = new Socket(InetAddress.getLocalHost(), port); socket.close(); return true; } catch (Exception e) { return false; } } // https://www.cnblogs.com/starcrm/p/7071227.html public static InetAddress localHost() { try { InetAddress candidateAddress = null; MyBoxLog.debug("InetAddress.getLocalHost():" + InetAddress.getLocalHost()); for (Enumeration ifaces = NetworkInterface.getNetworkInterfaces(); ifaces.hasMoreElements();) { NetworkInterface iface = (NetworkInterface) ifaces.nextElement(); for (Enumeration inetAddrs = iface.getInetAddresses(); inetAddrs.hasMoreElements();) { InetAddress inetAddr = (InetAddress) inetAddrs.nextElement(); MyBoxLog.debug("inetAddr.getHostAddress:" + inetAddr.getHostAddress()); if (!inetAddr.isLoopbackAddress()) { if (inetAddr.isSiteLocalAddress()) { return inetAddr; } else if (candidateAddress == null) { candidateAddress = inetAddr; } } } } if (candidateAddress != null) { return candidateAddress; } InetAddress jdkSuppliedAddress = InetAddress.getLocalHost(); if (jdkSuppliedAddress == null) { return InetAddress.getByName("localhost"); } return jdkSuppliedAddress; } catch (Exception e) { return null; } } public static SSLContext sslContext() { try { SSLContext context = SSLContext.getInstance(AppValues.HttpsProtocal); context.init(null, null, null); return context; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static SSLSocketFactory sslSocketFactory() { try { return sslContext().getSocketFactory(); } catch (Exception e) { MyBoxLog.error(e); return null; } } public static SSLSocket sslSocket(String host, int port) { try { return (SSLSocket) sslSocketFactory().createSocket(host, port); } catch (Exception e) { MyBoxLog.error(e); return null; } } public static HttpURLConnection httpConnection(URL url) { try { if ("https".equals(url.getProtocol())) { HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setSSLSocketFactory(sslSocketFactory()); return conn; } else { return (HttpURLConnection) url.openConnection(); } } catch (Exception e) { MyBoxLog.error(e); return null; } } public static String host2ipv4(FxTask task, String host) { try { if (host == null) { return null; } String ip = host2ipv4ByIpaddress(task, host); if (ip != null && !ip.isBlank()) { return ip; } InetAddress a = InetAddress.getByName(host); return a.getHostAddress(); } catch (Exception e) { // MyBoxLog.debug(e); return host; } } // https://fastly.net.ipaddress.com/github.global.ssl.fastly.net public static String host2ipv4ByIpaddress(FxTask task, String host) { try { if (host == null) { return null; } String[] nodes = host.split("\\."); if (nodes.length < 2) { return null; } String domain = nodes[nodes.length - 2] + "." + nodes[nodes.length - 1]; String address = "https://" + domain + ".ipaddress.com/" + (nodes.length == 2 ? "" : host); String data = HtmlReadTools.url2html(task, address); if (data == null) { return null; } String flag = "<tr><th>IP Address</th><td><ul class=\"comma-separated\"><li>"; int start = data.indexOf(flag); if (start < 0) { return null; } data = data.substring(start + flag.length()); int end = data.indexOf("</li>"); if (end < 0) { return null; } return data.substring(0, end); } catch (Exception e) { MyBoxLog.debug(e); return null; } } public static String ip2host(String ip) { try { if (ip == null) { return null; } InetAddress a = InetAddress.getByName(ip); return a.getHostName(); } catch (Exception e) { MyBoxLog.debug(e); return null; } } public static boolean isIPv4(String ip) { try { if (ip == null) { return false; } String[] nodes = ip.split("\\."); if (nodes.length != 4) { return false; } for (String node : nodes) { int v = Integer.parseInt(node); if (v < 0 || v > 255) { return false; } } return true; } catch (Exception e) { return false; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/tools/ByteFileTools.java
alpha/MyBox/src/main/java/mara/mybox/tools/ByteFileTools.java
package mara.mybox.tools; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.ArrayList; import java.util.List; import mara.mybox.dev.MyBoxLog; import mara.mybox.value.AppValues; /** * @Author Mara * @CreateDate 2021-8-1 * @License Apache License Version 2.0 */ public class ByteFileTools { // Can not handle file larger than 2g public static byte[] readBytes(File file) { byte[] data = null; try (final BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file))) { int bufSize = (int) file.length(); data = new byte[bufSize]; int readLen = inputStream.read(data); if (readLen > 0 && readLen < bufSize) { data = ByteTools.subBytes(data, 0, readLen); } } catch (Exception e) { MyBoxLog.debug(e); } return data; } public static byte[] readBytes(File file, long offset, int length) { if (file == null || offset < 0 || length <= 0) { return null; } byte[] data; try (final BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file))) { data = new byte[length]; inputStream.skip(offset); int readLen = inputStream.read(data); if (readLen > 0 && readLen < length) { data = ByteTools.subBytes(data, 0, readLen); } } catch (Exception e) { MyBoxLog.debug(e); return null; } return data; } public static File writeFile(File file, byte[] data) { if (file == null || data == null) { return null; } file.getParentFile().mkdirs(); try (final BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(file))) { outputStream.write(data); outputStream.flush(); } catch (Exception e) { MyBoxLog.error(e.toString()); return null; } return file; } public static boolean mergeBytesFiles(File file1, File file2, File targetFile) { try { List<File> files = new ArrayList(); files.add(file1); files.add(file2); return mergeBytesFiles(files, targetFile); } catch (Exception e) { MyBoxLog.debug(e); return false; } } public static boolean mergeBytesFiles(List<File> files, File targetFile) { if (files == null || files.isEmpty() || targetFile == null) { return false; } targetFile.getParentFile().mkdirs(); try (final BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(targetFile))) { byte[] buf = new byte[AppValues.IOBufferLength]; int bufLen; for (File file : files) { try (final BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file))) { while ((bufLen = inputStream.read(buf)) > 0) { outputStream.write(buf, 0, bufLen); } } } } catch (Exception e) { MyBoxLog.debug(e); return false; } return true; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/tools/MicrosoftDocumentTools.java
alpha/MyBox/src/main/java/mara/mybox/tools/MicrosoftDocumentTools.java
package mara.mybox.tools; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.OutputStream; import java.nio.charset.Charset; import java.util.List; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import org.apache.poi.extractor.ExtractorFactory; import org.apache.poi.extractor.MainExtractorFactory; import org.apache.poi.extractor.POITextExtractor; import org.apache.poi.extractor.ole2.OLE2ScratchpadExtractorFactory; import org.apache.poi.hslf.usermodel.HSLFPictureData; import org.apache.poi.hslf.usermodel.HSLFPictureShape; import org.apache.poi.hslf.usermodel.HSLFSlideShow; import org.apache.poi.hslf.usermodel.HSLFSlideShowFactory; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.usermodel.HSSFWorkbookFactory; import org.apache.poi.hwpf.HWPFDocument; import org.apache.poi.hwpf.converter.WordToHtmlConverter; import org.apache.poi.ooxml.extractor.POIXMLExtractorFactory; import org.apache.poi.sl.usermodel.PictureData.PictureType; import org.apache.poi.sl.usermodel.SlideShowFactory; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellType; import org.apache.poi.ss.usermodel.HorizontalAlignment; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.WorkbookFactory; import org.apache.poi.xslf.usermodel.XSLFSlideShowFactory; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFCellStyle; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.apache.poi.xssf.usermodel.XSSFWorkbookFactory; import org.w3c.dom.Document; /** * @Author Mara * @CreateDate 2020-2-22 * @License Apache License Version 2.0 */ public class MicrosoftDocumentTools { public static String cellString(Cell cell) { if (cell == null) { return null; } switch (cell.getCellType()) { case STRING: return cell.getStringCellValue(); case NUMERIC: return cell.getNumericCellValue() + ""; case BOOLEAN: return cell.getBooleanCellValue() + ""; } return null; } public static void copyRow(Row sourceRow, Row targetRow) { if (sourceRow == null || targetRow == null) { return; } for (int col = sourceRow.getFirstCellNum(); col < sourceRow.getLastCellNum(); col++) { Cell sourceCell = sourceRow.getCell(col); if (sourceCell == null) { continue; } CellType type = sourceCell.getCellType(); if (type == null) { type = CellType.STRING; } Cell targetCell = targetRow.createCell(col, type); copyCell(sourceCell, targetCell, type); } } public static void copyCell(Cell sourceCell, Cell targetCell, CellType type) { if (sourceCell == null || targetCell == null || type == null) { return; } try { switch (type) { case STRING: targetCell.setCellValue(sourceCell.getStringCellValue()); break; case NUMERIC: targetCell.setCellValue(sourceCell.getNumericCellValue()); break; case BLANK: targetCell.setCellValue(""); break; case BOOLEAN: targetCell.setCellValue(sourceCell.getBooleanCellValue()); break; case ERROR: targetCell.setCellErrorValue(sourceCell.getErrorCellValue()); break; case FORMULA: targetCell.setCellFormula(sourceCell.getCellFormula()); break; } } catch (Exception e) { MyBoxLog.debug(e); } } public static void setCell(Cell targetCell, CellType type, String value) { if (value == null || targetCell == null || type == null) { return; } try { if (type == CellType.NUMERIC) { try { long v = Long.parseLong(value); targetCell.setCellValue(v); return; } catch (Exception e) { } try { double v = Double.parseDouble(value); targetCell.setCellValue(v); return; } catch (Exception e) { } } targetCell.setCellValue(value); } catch (Exception e) { MyBoxLog.debug(e); } } public static boolean createXLSX(File file, List<String> columns, List<List<String>> rows) { try { if (file == null || columns == null || rows == null || columns.isEmpty()) { return false; } XSSFWorkbook wb = new XSSFWorkbook(); XSSFSheet sheet = wb.createSheet("sheet1"); // sheet.setDefaultColumnWidth(20); XSSFRow titleRow = sheet.createRow(0); XSSFCellStyle horizontalCenter = wb.createCellStyle(); horizontalCenter.setAlignment(HorizontalAlignment.CENTER); for (int i = 0; i < columns.size(); i++) { XSSFCell cell = titleRow.createCell(i); cell.setCellValue(columns.get(i)); cell.setCellStyle(horizontalCenter); } for (int i = 0; i < rows.size(); i++) { XSSFRow row = sheet.createRow(i + 1); List<String> values = rows.get(i); for (int j = 0; j < values.size(); j++) { XSSFCell cell = row.createCell(j); cell.setCellValue(values.get(j)); } } for (int i = 0; i < columns.size(); i++) { sheet.autoSizeColumn(i); } try (OutputStream fileOut = new FileOutputStream(file)) { wb.write(fileOut); } return true; } catch (Exception e) { MyBoxLog.debug(e); return false; } } public static boolean createXLS(File file, List<String> columns, List<List<String>> rows) { try { if (file == null || columns == null || rows == null || columns.isEmpty()) { return false; } HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet sheet = wb.createSheet("sheet1"); // sheet.setDefaultColumnWidth(40); HSSFRow titleRow = sheet.createRow(0); HSSFCellStyle horizontalCenter = wb.createCellStyle(); horizontalCenter.setAlignment(HorizontalAlignment.CENTER); for (int i = 0; i < columns.size(); i++) { HSSFCell cell = titleRow.createCell(i); cell.setCellValue(columns.get(i)); cell.setCellStyle(horizontalCenter); } for (int i = 1; i <= rows.size(); i++) { HSSFRow row = sheet.createRow(0); List<String> values = rows.get(i); for (int j = 0; j < values.size(); j++) { HSSFCell cell = row.createCell(j); cell.setCellValue(values.get(j)); } } try (OutputStream fileOut = new FileOutputStream(file)) { wb.write(fileOut); } return true; } catch (Exception e) { MyBoxLog.debug(e); return false; } } public static Document word97ToDoc(File srcFile) { Document doc = null; try (HWPFDocument wordDocument = new HWPFDocument(new FileInputStream(srcFile))) { doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); WordToHtmlConverter converter = new WordToHtmlConverter(doc); converter.processDocument(wordDocument); doc = converter.getDocument(); } catch (Exception e) { MyBoxLog.console(e); } return doc; } public static String word97Tohtml(File srcFile, Charset charset) { try { Document doc = word97ToDoc(srcFile); if (doc == null) { return null; } Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.METHOD, "html"); transformer.setOutputProperty(OutputKeys.ENCODING, charset == null ? "UTF-8" : charset.name()); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); transformer.transform(new DOMSource(doc), new StreamResult(baos)); baos.flush(); baos.close(); return baos.toString(charset); } catch (Exception e) { MyBoxLog.error(e); return null; } } public static File word2HtmlFile(File srcFile, Charset charset) { try { String suffix = FileNameTools.ext(srcFile.getName()); String html; if ("doc".equalsIgnoreCase(suffix)) { html = word97Tohtml(srcFile, charset); } else if ("docx".equalsIgnoreCase(suffix)) { String text = extractText(srcFile); if (text == null) { return null; } html = HtmlWriteTools.textToHtml(text); } else { return null; } return HtmlWriteTools.writeHtml(html); } catch (Exception e) { MyBoxLog.error(e); return null; } } public static String word2Html(FxTask task, File srcFile, Charset charset) { try { File htmlFile = word2HtmlFile(srcFile, charset); return TextFileTools.readTexts(task, htmlFile, charset); } catch (Exception e) { MyBoxLog.error(e); return null; } } public static HSLFPictureShape imageShape(FxTask task, HSLFSlideShow ppt, BufferedImage image, String format) { try { byte[] bytes = ByteTools.imageToBytes(task, image, format); PictureType type; if ("png".equalsIgnoreCase(format)) { type = PictureType.PNG; } else if ("jpg".equalsIgnoreCase(format) || "jpeg".equalsIgnoreCase(format)) { type = PictureType.JPEG; } else if ("bmp".equalsIgnoreCase(format)) { type = PictureType.BMP; } else if ("gif".equalsIgnoreCase(format)) { type = PictureType.GIF; } else if ("tif".equalsIgnoreCase(format) || "tiff".equalsIgnoreCase(format)) { type = PictureType.TIFF; } else { type = PictureType.PNG; } HSLFPictureData pd = ppt.addPicture(bytes, type); return new HSLFPictureShape(pd); } catch (Exception e) { MyBoxLog.error(e); return null; } } public static String extractText(File srcFile) { String text = null; try (POITextExtractor extractor = ExtractorFactory.createExtractor(srcFile)) { text = extractor.getText(); } catch (Exception e) { MyBoxLog.error(e); } return text; } // https://github.com/Mararsh/MyBox/issues/1100 public static void registryFactories() { SlideShowFactory.addProvider(new HSLFSlideShowFactory()); SlideShowFactory.addProvider(new XSLFSlideShowFactory()); ExtractorFactory.addProvider(new MainExtractorFactory()); ExtractorFactory.addProvider(new OLE2ScratchpadExtractorFactory()); ExtractorFactory.addProvider(new POIXMLExtractorFactory()); WorkbookFactory.addProvider(new HSSFWorkbookFactory()); WorkbookFactory.addProvider(new XSSFWorkbookFactory()); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/tools/ByteTools.java
alpha/MyBox/src/main/java/mara/mybox/tools/ByteTools.java
package mara.mybox.tools; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.util.zip.DeflaterOutputStream; import java.util.zip.InflaterOutputStream; import javafx.scene.control.IndexRange; import mara.mybox.image.tools.BufferedImageTools; import mara.mybox.data.FileEditInformation.Line_Break; import mara.mybox.data.FindReplaceString; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.value.AppValues; /** * @Author Mara * @CreateDate 2018-6-11 17:43:53 * @Description * @License Apache License Version 2.0 */ public class ByteTools { public static int Invalid_Byte = AppValues.InvalidShort; // https://stackoverflow.com/questions/4485128/how-do-i-convert-long-to-byte-and-back-in-java public static int bytesToInt(byte[] b) { return ByteBuffer.allocate(Integer.BYTES).put(b).flip().getInt(); } public static long bytesToUInt(byte[] b) { return bytesToLong(mergeBytes(new byte[4], b)); } public static long bytesToLong(byte[] b) { return ByteBuffer.allocate(Long.BYTES).put(b).flip().getLong(); } public static int bytesToUshort(byte[] b) { return bytesToInt(mergeBytes(new byte[2], b)); } // https://stackoverflow.com/questions/6374915/java-convert-int-to-byte-array-of-4-bytes?r=SearchResults public static byte[] intToBytes(int a) { return ByteBuffer.allocate(Integer.BYTES).putInt(a).array(); } public static byte intSmallByte(int a) { byte[] bytes = intToBytes(a); return bytes[3]; } public static byte intBigByte(int a) { byte[] bytes = intToBytes(a); return bytes[0]; } public static byte[] longToBytes(long a) { return ByteBuffer.allocate(Long.BYTES).putLong(a).array(); } public static byte[] uIntToBytes(long a) { return subBytes(longToBytes(a), 4, 4); } public static byte[] uShortToBytes(int a) { return subBytes(intToBytes(a), 2, 2); } public static byte[] shortToBytes(short a) { return ByteBuffer.allocate(Short.BYTES).putShort(a).array(); } public static String byteToHex(byte b) { String hex = Integer.toHexString(b & 0xFF); if (hex.length() < 2) { hex = "0" + hex; } return hex; } public static String bytesToHex(byte[] bytes) { if (bytes == null) { return null; } StringBuilder sb = new StringBuilder(); for (int i = 0; i < bytes.length; ++i) { String hex = Integer.toHexString(bytes[i] & 0xFF); if (hex.length() < 2) { sb.append(0); } sb.append(hex); } return sb.toString(); } public static String bytesToHexFormat(byte[] bytes) { if (bytes == null) { return null; } StringBuilder sb = new StringBuilder(); for (int i = 0; i < bytes.length; ++i) { String hex = Integer.toHexString(bytes[i] & 0xFF); if (hex.length() < 2) { sb.append(0); } sb.append(hex).append(" "); } String s = sb.toString(); return s.toUpperCase(); } public static String stringToHexFormat(String text) { return bytesToHexFormatWithCF(text.getBytes()); } public static String bytesToHexFormatWithCF(byte[] bytes) { return bytesToHexFormatWithCF(bytes, bytesToHex("\n".getBytes())); } public static String bytesToHexFormatWithCF(byte[] bytes, String newLineHex) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < bytes.length; ++i) { String hex = Integer.toHexString(bytes[i] & 0xFF); if (hex.length() < 2) { sb.append(0); } sb.append(hex).append(" "); } String s = sb.toString(); s = s.replace(newLineHex + " ", newLineHex + "\n"); s = s.toUpperCase(); return s; } public static String bytesToHexFormat(byte[] bytes, int newLineWidth) { StringBuilder sb = new StringBuilder(); int count = 1; for (int i = 0; i < bytes.length; ++i) { String hex = Integer.toHexString(bytes[i] & 0xFF); if (hex.length() < 2) { sb.append(0); } sb.append(hex).append(" "); if (count % newLineWidth == 0) { sb.append("\n"); } count++; } String s = sb.toString(); s = s.toUpperCase(); return s; } public static byte[] hexToBytes(String inHex) { try { int hexlen = inHex.length(); byte[] result; if (hexlen % 2 == 1) { hexlen++; result = new byte[(hexlen / 2)]; inHex = "0" + inHex; } else { result = new byte[(hexlen / 2)]; } int j = 0; for (int i = 0; i < hexlen; i += 2) { result[j] = hexToByte(inHex.substring(i, i + 2)); j++; } return result; } catch (Exception e) { return null; } } public static byte hexToByte(String inHex) { try { return (byte) Integer.parseInt(inHex, 16); } catch (Exception e) { return 0; } } public static byte hexToByteAnyway(String inHex) { try { return (byte) Integer.parseInt(inHex, 16); } catch (Exception e) { return Byte.valueOf("63");// "?" } } public static int hexToInt(String inHex) { try { if (inHex.length() == 0 || inHex.length() > 2) { return Invalid_Byte; } String hex = inHex; if (inHex.length() == 1) { hex = "0" + hex; } return Integer.parseInt(hex, 16); } catch (Exception e) { return Invalid_Byte; } } public static String validateByteHex(String inHex) { try { if (inHex.length() == 0 || inHex.length() > 2) { return null; } String hex = inHex; if (inHex.length() == 1) { hex = "0" + hex; } Integer.parseInt(hex, 16); return hex; } catch (Exception e) { return null; } } public static boolean isByteHex(String inHex) { try { if (inHex.length() != 2) { return false; } Integer.parseInt(inHex, 16); return true; } catch (Exception e) { return false; } } public static boolean isBytesHex(String inHex) { try { String hex = inHex.replaceAll("\\s+|\n", "").toUpperCase(); int hexlen = hex.length(); if (hexlen % 2 == 1) { return false; } for (int i = 0; i < hexlen; i += 2) { Integer.parseInt(hex.substring(i, i + 2), 16); } return true; } catch (Exception e) { return false; } } public static boolean validateTextHex(String text) { try { String inHex = text.replaceAll("\\s+|\n", "").toUpperCase(); int hexlen = inHex.length(); if (hexlen % 2 == 1) { return false; } String b; for (int i = 0; i < hexlen; i += 2) { b = inHex.substring(i, i + 2); Integer.parseInt(b, 16); } return true; } catch (Exception e) { return false; } } public static String formatTextHex(String text) { try { String inHex = text.replaceAll("\\s+|\n", "").toUpperCase(); int hexlen = inHex.length(); if (hexlen % 2 == 1) { return null; } StringBuilder sb = new StringBuilder(); String b; for (int i = 0; i < hexlen; i += 2) { b = inHex.substring(i, i + 2); Integer.parseInt(b, 16); sb.append(b).append(" "); } return sb.toString(); } catch (Exception e) { return null; } } public static byte[] hexFormatToBytes(String hexFormat) { try { String hex = hexFormat.replaceAll("\\s+|\n", ""); int hexlen = hex.length(); byte[] result; if (hexlen % 2 == 1) { hexlen++; result = new byte[(hexlen / 2)]; hex = "0" + hex; } else { result = new byte[(hexlen / 2)]; } int j = 0; for (int i = 0; i < hexlen; i += 2) { result[j] = hexToByteAnyway(hex.substring(i, i + 2)); j++; } return result; } catch (Exception e) { return null; } } public static byte[] subBytes(byte[] bytes, int off, int length) { try { byte[] newBytes = new byte[length]; System.arraycopy(bytes, off, newBytes, 0, length); return newBytes; } catch (Exception e) { MyBoxLog.error(e, bytes.length + " " + off + " " + length); return null; } } public static byte[] mergeBytes(byte[] bytes1, byte[] bytes2) { try { byte[] bytes3 = new byte[bytes1.length + bytes2.length]; System.arraycopy(bytes1, 0, bytes3, 0, bytes1.length); System.arraycopy(bytes2, 0, bytes3, bytes1.length, bytes2.length); return bytes3; } catch (Exception e) { MyBoxLog.error(e.toString()); return null; } } public static int countNumber(FxTask currentTask, byte[] bytes, byte[] subBytes) { return FindReplaceString.count(currentTask, bytesToHex(bytes), bytesToHex(subBytes)); } public static int countNumber(FxTask currentTask, byte[] bytes, byte c) { return FindReplaceString.count(currentTask, bytesToHex(bytes), byteToHex(c)); } public static int countNumber(FxTask currentTask, byte[] bytes, String hex) { return FindReplaceString.count(currentTask, bytesToHex(bytes), hex); } public static int lineIndex(String lineText, Charset charset, int offset) { int hIndex = 0; byte[] cBytes; for (int i = 0; i < lineText.length(); ++i) { char c = lineText.charAt(i); cBytes = String.valueOf(c).getBytes(charset); int clen = cBytes.length * 3; if (offset <= hIndex + clen) { return i; } hIndex += clen; } return -1; } public static IndexRange textIndex(String hex, Charset charset, IndexRange hexRange) { int hIndex = 0, cindex = 0; int cBegin = 0; int cEnd = 0; int hexBegin = hexRange.getStart(); int hexEnd = hexRange.getEnd(); if (hexBegin == 0 && hexEnd <= 0) { return new IndexRange(0, 0); } boolean gotStart = false, gotEnd = false; String[] lines = hex.split("\n"); StringBuilder text = new StringBuilder(); String lineText; for (String lineHex : lines) { lineText = new String(ByteTools.hexFormatToBytes(lineHex), charset); lineText = StringTools.replaceLineBreak(lineText); if (!gotStart && hexBegin >= hIndex && hexBegin <= (hIndex + lineHex.length())) { cBegin = cindex + lineIndex(lineText, charset, hexBegin - hIndex); gotStart = true; } if (hexEnd >= hIndex && hexEnd <= (hIndex + lineHex.length())) { cEnd = cindex + lineIndex(lineText, charset, hexEnd - hIndex) + 1; gotEnd = true; break; } hIndex += lineHex.length() + 1; cindex += lineText.length() + 1; } if (!gotStart) { cBegin = text.length() - 1; } if (!gotEnd) { cEnd = text.length(); } if (cBegin > cEnd) { cEnd = cBegin; } return new IndexRange(cBegin, cEnd); } public static int indexOf(String hexString, String hexSubString, int initFrom) { if (hexString == null || hexSubString == null || hexString.length() < hexSubString.length()) { return -1; } int from = initFrom, pos = 0; while (pos >= 0) { pos = hexString.indexOf(hexSubString, from); if (pos % 2 == 0) { return pos; } from = pos + 1; } return -1; } public static String formatHex(String hexString, Line_Break lineBreak, int lineBreakWidth, String lineBreakValue) { String text = hexString; if (lineBreak == Line_Break.Width && lineBreakWidth > 0) { int step = 3 * lineBreakWidth; StringBuilder sb = new StringBuilder(); for (int i = 0; i < text.length(); i += step) { if (i + step < text.length()) { sb.append(text.substring(i, i + step - 1)).append("\n"); } else { sb.append(text.substring(i, text.length() - 1)); } } text = sb.toString(); } else if (lineBreakValue != null) { if (text.endsWith(lineBreakValue)) { text = text.replaceAll(lineBreakValue, lineBreakValue.trim() + "\n"); text = text.substring(0, text.length() - 1); } else { text = text.replaceAll(lineBreakValue, lineBreakValue.trim() + "\n"); } } return text; } public static long checkBytesValue(String string) { try { String strV = string.trim().toLowerCase(); long unit = 1; if (strV.endsWith("b")) { unit = 1; strV = strV.substring(0, strV.length() - 1); } else if (strV.endsWith("k")) { unit = 1024; strV = strV.substring(0, strV.length() - 1); } else if (strV.endsWith("m")) { unit = 1024 * 1024; strV = strV.substring(0, strV.length() - 1); } else if (strV.endsWith("g")) { unit = 1024 * 1024 * 1024L; strV = strV.substring(0, strV.length() - 1); } double v = Double.parseDouble(strV.trim()); if (v >= 0) { return Math.round(v * unit); } else { return -1; } } catch (Exception e) { return -1; } } public static byte[] deflate(Object object) { return deflate(toBytes(object)); } public static byte[] deflate(byte[] bytes) { try { ByteArrayOutputStream a = new ByteArrayOutputStream(); try (DeflaterOutputStream out = new DeflaterOutputStream(a)) { out.write(bytes); out.flush(); } return a.toByteArray(); } catch (Exception e) { return null; } } public static byte[] inflate(Object object) { return inflate(toBytes(object)); } public static byte[] inflate(byte[] bytes) { try { ByteArrayOutputStream a = new ByteArrayOutputStream(); try (InflaterOutputStream out = new InflaterOutputStream(a)) { out.write(bytes); out.flush(); } return a.toByteArray(); } catch (Exception e) { return null; } } public static byte[] toBytes(Object object) { try { ByteArrayOutputStream a = new ByteArrayOutputStream(); try (ObjectOutputStream out = new ObjectOutputStream(a)) { out.writeObject(object); out.flush(); } return a.toByteArray(); } catch (Exception e) { return null; } } public static Object toObject(byte[] bytes) { try { ByteArrayInputStream a = new ByteArrayInputStream(bytes); try (ObjectInputStream in = new ObjectInputStream(a)) { return in.readObject(); } } catch (Exception e) { return null; } } public static byte[] imageToBytes(FxTask task, BufferedImage image, String format) { return BufferedImageTools.bytes(task, image, format); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/tools/FileSplitTools.java
alpha/MyBox/src/main/java/mara/mybox/tools/FileSplitTools.java
package mara.mybox.tools; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.ArrayList; import java.util.List; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; /** * @Author Mara * @CreateDate 2021-8-1 * @License Apache License Version 2.0 */ public class FileSplitTools { public static List<File> splitFileByFilesNumber(FxTask currentTask, File file, String filename, long filesNumber) { try { if (file == null || filesNumber <= 0) { return null; } long bytesNumber = file.length() / filesNumber; List<File> splittedFiles = new ArrayList<>(); try (final BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file))) { String newFilename; int digit = (filesNumber + "").length(); byte[] buf = new byte[(int) bytesNumber]; int bufLen; int fileIndex = 1; int startIndex = 0; int endIndex = 0; while ((fileIndex < filesNumber) && (bufLen = inputStream.read(buf)) > 0) { if (currentTask == null || !currentTask.isWorking()) { return null; } endIndex += bufLen; newFilename = filename + "-cut-f" + StringTools.fillLeftZero(fileIndex, digit) + "-b" + (startIndex + 1) + "-b" + endIndex; try (final BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(newFilename))) { if (bytesNumber > bufLen) { buf = ByteTools.subBytes(buf, 0, bufLen); } outputStream.write(buf); } splittedFiles.add(new File(newFilename)); fileIndex++; startIndex = endIndex; } if (currentTask == null || !currentTask.isWorking()) { return null; } buf = new byte[(int) (file.length() - endIndex)]; bufLen = inputStream.read(buf); if (bufLen > 0) { endIndex += bufLen; newFilename = filename + "-cut-f" + StringTools.fillLeftZero(fileIndex, digit) + "-b" + (startIndex + 1) + "-b" + endIndex; try (final BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(newFilename))) { outputStream.write(buf); } splittedFiles.add(new File(newFilename)); } } return splittedFiles; } catch (Exception e) { MyBoxLog.debug(e); return null; } } public static List<File> splitFileByStartEndList(FxTask currentTask, File file, String filename, List<Long> startEndList) { try { if (file == null || startEndList == null || startEndList.isEmpty() || startEndList.size() % 2 > 0) { return null; } List<File> splittedFiles = new ArrayList<>(); for (int i = 0; i < startEndList.size(); i += 2) { if (currentTask == null || !currentTask.isWorking()) { return null; } File f = cutFile(file, filename, startEndList.get(i), startEndList.get(i + 1)); if (f != null) { splittedFiles.add(f); } } return splittedFiles; } catch (Exception e) { MyBoxLog.debug(e); return null; } } public static List<File> splitFileByBytesNumber(FxTask currentTask, File file, String filename, long bytesNumber) { try { if (file == null || bytesNumber <= 0) { return null; } List<File> splittedFiles = new ArrayList<>(); try (final BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file))) { String newFilename; long fnumber = file.length() / bytesNumber; if (file.length() % bytesNumber > 0) { fnumber++; } int digit = (fnumber + "").length(); byte[] buf = new byte[(int) bytesNumber]; int bufLen; int fileIndex = 1; int startIndex = 0; int endIndex = 0; while ((bufLen = inputStream.read(buf)) > 0) { if (currentTask == null || !currentTask.isWorking()) { return null; } endIndex += bufLen; newFilename = filename + "-cut-f" + StringTools.fillLeftZero(fileIndex, digit) + "-b" + (startIndex + 1) + "-b" + endIndex; try (final BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(newFilename))) { if (bytesNumber > bufLen) { buf = ByteTools.subBytes(buf, 0, bufLen); } outputStream.write(buf); } splittedFiles.add(new File(newFilename)); fileIndex++; startIndex = endIndex; } } return splittedFiles; } catch (Exception e) { MyBoxLog.debug(e); return null; } } // 1-based start, that is: from (start - 1) to ( end - 1) actually public static File cutFile(File file, String filename, long startIndex, long endIndex) { try { if (file == null || startIndex < 1 || startIndex > endIndex) { return null; } File tempFile = FileTmpTools.getTempFile(); String newFilename = filename + "-cut-b" + startIndex + "-b" + endIndex; try (final BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file))) { if (startIndex > 1) { inputStream.skip(startIndex - 1); } int cutLength = (int) (endIndex - startIndex + 1); byte[] buf = new byte[cutLength]; int bufLen; bufLen = inputStream.read(buf); if (bufLen <= 0) { return null; } try (final BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(tempFile))) { if (cutLength > bufLen) { buf = ByteTools.subBytes(buf, 0, bufLen); newFilename = filename + "-cut-b" + startIndex + "-b" + bufLen; } outputStream.write(buf); } } File actualFile = new File(newFilename); if (FileTools.override(tempFile, actualFile)) { return actualFile; } else { return null; } } 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/alpha/MyBox/src/main/java/mara/mybox/tools/IconTools.java
alpha/MyBox/src/main/java/mara/mybox/tools/IconTools.java
package mara.mybox.tools; import java.awt.image.BufferedImage; import java.io.File; import java.net.URL; import java.util.regex.Matcher; import java.util.regex.Pattern; import mara.mybox.image.data.ImageAttributes; import mara.mybox.image.tools.ImageConvertTools; import mara.mybox.fxml.FxFileTools; import mara.mybox.fxml.FxTask; import mara.mybox.image.file.ImageFileReaders; import static mara.mybox.value.AppVariables.MyboxDataPath; /** * @Author Mara * @CreateDate 2021-8-1 * @License Apache License Version 2.0 */ public class IconTools { public static File readIcon(FxTask task, String address, boolean download) { try { if (address == null) { return null; } URL url = UrlTools.url(address); if (url == null) { return null; } String host = url.getHost(); if (host == null || host.isBlank()) { return null; } File file = FxFileTools.getInternalFile("/icons/" + host + ".png", "icons", host + ".png"); if (file == null || !file.exists()) { file = FxFileTools.getInternalFile("/icons/" + host + ".ico", "icons", host + ".ico"); if ((file == null || !file.exists()) && download) { file = new File(MyboxDataPath + File.separator + "icons" + File.separator + host + ".ico"); file = readIcon(task, address, file); } } return file != null && file.exists() ? file : null; } catch (Exception e) { // MyBoxLog.debug(e); return null; } } // https://www.cnblogs.com/luguo3000/p/3767380.html public static File readIcon(FxTask task, String address, File targetFile) { File actualTarget = readHostIcon(task, address, targetFile); if (actualTarget == null) { actualTarget = readHtmlIcon(task, address, targetFile); } if (actualTarget != null) { BufferedImage image = ImageFileReaders.readImage(task, actualTarget); if (image != null) { String name = actualTarget.getAbsolutePath(); if (name.endsWith(".ico")) { ImageAttributes attributes = new ImageAttributes() .setImageFormat("png").setColorSpaceName("sRGB") .setAlpha(ImageAttributes.Alpha.Keep).setQuality(100); File png = new File(name.substring(0, name.lastIndexOf(".")) + ".png"); ImageConvertTools.convertColorSpace(task, actualTarget, attributes, png); if (png.exists()) { FileDeleteTools.delete(actualTarget); actualTarget = png; } } return actualTarget; } else { FileDeleteTools.delete(actualTarget); } } return null; } public static File readHostIcon(FxTask task, String address, File targetFile) { try { if (address == null || targetFile == null) { return null; } URL url = UrlTools.url(address); if (url == null) { return null; } String iconUrl = "https://" + url.getHost() + "/favicon.ico"; File actualTarget = downloadIcon(task, iconUrl, targetFile); // if (actualTarget == null) { // iconUrl = "http://" + url.getHost() + "/favicon.ico"; // actualTarget = downloadIcon(task, iconUrl, targetFile); // } return actualTarget; } catch (Exception e) { // MyBoxLog.debug(e); return null; } } public static File readHtmlIcon(FxTask task, String address, File targetFile) { try { if (address == null) { return null; } String iconUrl = htmlIconAddress(task, address); if (iconUrl == null) { return null; } return downloadIcon(task, iconUrl, targetFile); } catch (Exception e) { // MyBoxLog.debug(e); return null; } } public static File downloadIcon(FxTask task, String address, File targetFile) { try { if (address == null || targetFile == null) { return null; } File iconFile = HtmlReadTools.download(task, address, 1000, 1000); if (iconFile == null || !iconFile.exists()) { return null; } String suffix = FileNameTools.ext(address); File actualTarget = targetFile; if (suffix != null && !suffix.isBlank()) { actualTarget = new File(FileNameTools.replaceExt(targetFile.getAbsolutePath(), suffix)); } if (FileTools.override(iconFile, actualTarget, true) && actualTarget.exists()) { return actualTarget; } else { return null; } } catch (Exception e) { // MyBoxLog.debug(e); return null; } } public static String htmlIconAddress(FxTask task, String address) { try { if (address == null) { return null; } String html = HtmlReadTools.url2html(task, address); Pattern[] ICON_PATTERNS = new Pattern[]{ Pattern.compile("rel=[\"']shortcut icon[\"'][^\r\n>]+?((?<=href=[\"']).+?(?=[\"']))"), Pattern.compile("((?<=href=[\"']).+?(?=[\"']))[^\r\n<]+?rel=[\"']shortcut icon[\"']")}; for (Pattern iconPattern : ICON_PATTERNS) { Matcher matcher = iconPattern.matcher(html); if (matcher.find()) { String iconUrl = matcher.group(1); if (iconUrl.contains("http")) { return iconUrl; } if (iconUrl.charAt(0) == '/') { URL url = UrlTools.url(address); if (url == null) { return null; } iconUrl = url.getProtocol() + "://" + url.getHost() + iconUrl; } else { iconUrl = address + "/" + iconUrl; } return iconUrl; } } return null; } 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/alpha/MyBox/src/main/java/mara/mybox/tools/FileSortTools.java
alpha/MyBox/src/main/java/mara/mybox/tools/FileSortTools.java
package mara.mybox.tools; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import javafx.stage.FileChooser; import mara.mybox.data.FileInformation; import mara.mybox.db.data.VisitHistoryTools; import mara.mybox.dev.MyBoxLog; import mara.mybox.value.FileFilters; import mara.mybox.value.Languages; /** * @Author Mara * @CreateDate 2021-8-1 * @License Apache License Version 2.0 */ public class FileSortTools { public static enum FileSortMode { ModifyTimeDesc, ModifyTimeAsc, CreateTimeDesc, CreateTimeAsc, SizeDesc, SizeAsc, NameDesc, NameAsc, FormatDesc, FormatAsc } public static FileSortMode sortMode(String mode) { for (FileSortMode v : FileSortMode.values()) { if (Languages.matchIgnoreCase(v.name(), mode)) { return v; } } return null; } public static boolean hasNextFile(File file, int fileType, FileSortMode sortMode) { try { List<File> files = siblingFiles(file, fileType, sortMode); if (files == null) { return false; } int index = files.indexOf(file); return index >= 0 && index < files.size() - 1; } catch (Exception e) { return false; } } public static boolean hasPreviousFile(File file, int fileType, FileSortMode sortMode) { try { List<File> files = siblingFiles(file, fileType, sortMode); if (files == null) { return false; } int index = files.indexOf(file); return index > 0 && index <= files.size() - 1; } catch (Exception e) { return false; } } public static File nextFile(File file, int fileType, FileSortMode sortMode) { try { List<File> files = siblingFiles(file, fileType, sortMode); if (files == null) { return null; } int index = files.indexOf(file); if (index < 0 || index >= files.size() - 1) { return null; } return files.get(index + 1); } catch (Exception e) { return null; } } public static File previousFile(File file, int fileType, FileSortMode sortMode) { try { List<File> files = siblingFiles(file, fileType, sortMode); if (files == null) { return null; } int index = files.indexOf(file); if (index <= 0 || index > files.size() - 1) { return null; } return files.get(index - 1); } catch (Exception e) { return null; } } public static List<File> siblingFiles(File file, int fileType, FileSortMode sortMode) { if (file == null) { return null; } List<File> files = validFiles(file.getParentFile(), fileType); sortFiles(files, sortMode); return files; } public static List<File> validFiles(File path, int fileType) { try { if (path == null || !path.isDirectory()) { return null; } File[] pathFiles = path.listFiles(); if (pathFiles == null || pathFiles.length == 0) { return null; } List<FileChooser.ExtensionFilter> filter = VisitHistoryTools.getExtensionFilter(fileType); List<File> files = new ArrayList<>(); for (File file : pathFiles) { if (file.isFile() && FileFilters.accept(filter, file)) { files.add(file); } } return files; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static void sortFiles(List<File> files, FileSortMode sortMode) { if (files == null || files.isEmpty() || sortMode == null) { return; } try { switch (sortMode) { case ModifyTimeDesc: Collections.sort(files, new Comparator<File>() { @Override public int compare(File f1, File f2) { long diff = f2.lastModified() - f1.lastModified(); if (diff == 0) { return 0; } else if (diff > 0) { return 1; } else { return -1; } } }); break; case ModifyTimeAsc: Collections.sort(files, new Comparator<File>() { @Override public int compare(File f1, File f2) { long diff = f1.lastModified() - f2.lastModified(); if (diff == 0) { return 0; } else if (diff > 0) { return 1; } else { return -1; } } }); break; case NameDesc: Collections.sort(files, new Comparator<File>() { @Override public int compare(File f1, File f2) { return FileNameTools.compareName(f2, f1); } }); break; case NameAsc: Collections.sort(files, new Comparator<File>() { @Override public int compare(File f1, File f2) { return FileNameTools.compareName(f1, f2); } }); break; case CreateTimeDesc: Collections.sort(files, new Comparator<File>() { @Override public int compare(File f1, File f2) { long t1 = FileTools.createTime(f1.getAbsolutePath()); long t2 = FileTools.createTime(f2.getAbsolutePath()); long diff = t2 - t1; if (diff == 0) { return 0; } else if (diff > 0) { return 1; } else { return -1; } } }); break; case CreateTimeAsc: Collections.sort(files, new Comparator<File>() { @Override public int compare(File f1, File f2) { long t1 = FileTools.createTime(f1.getAbsolutePath()); long t2 = FileTools.createTime(f2.getAbsolutePath()); long diff = t1 - t2; if (diff == 0) { return 0; } else if (diff > 0) { return 1; } else { return -1; } } }); break; case SizeDesc: Collections.sort(files, new Comparator<File>() { @Override public int compare(File f1, File f2) { long diff = f2.length() - f1.length(); if (diff == 0) { return 0; } else if (diff > 0) { return 1; } else { return -1; } } }); break; case SizeAsc: Collections.sort(files, new Comparator<File>() { @Override public int compare(File f1, File f2) { long diff = f1.length() - f2.length(); if (diff == 0) { return 0; } else if (diff > 0) { return 1; } else { return -1; } } }); break; case FormatDesc: Collections.sort(files, new Comparator<File>() { @Override public int compare(File f1, File f2) { return FileNameTools.ext(f2.getName()).compareTo(FileNameTools.ext(f1.getName())); } }); break; case FormatAsc: Collections.sort(files, new Comparator<File>() { @Override public int compare(File f1, File f2) { return FileNameTools.ext(f1.getName()).compareTo(FileNameTools.ext(f2.getName())); } }); break; } } catch (Exception e) { MyBoxLog.debug(e); } } public static void sortFileInformations(List<FileInformation> files, FileSortMode sortMode) { if (files == null || files.isEmpty() || sortMode == null) { return; } switch (sortMode) { case ModifyTimeDesc: Collections.sort(files, new Comparator<FileInformation>() { @Override public int compare(FileInformation f1, FileInformation f2) { return (int) (f2.getFile().lastModified() - f1.getFile().lastModified()); } }); break; case ModifyTimeAsc: Collections.sort(files, new Comparator<FileInformation>() { @Override public int compare(FileInformation f1, FileInformation f2) { return (int) (f1.getFile().lastModified() - f2.getFile().lastModified()); } }); break; case NameDesc: Collections.sort(files, new Comparator<FileInformation>() { @Override public int compare(FileInformation f1, FileInformation f2) { return FileNameTools.compareName(f2.getFile(), f1.getFile()); } }); break; case NameAsc: Collections.sort(files, new Comparator<FileInformation>() { @Override public int compare(FileInformation f1, FileInformation f2) { return FileNameTools.compareName(f1.getFile(), f2.getFile()); } }); break; case CreateTimeDesc: Collections.sort(files, new Comparator<FileInformation>() { @Override public int compare(FileInformation f1, FileInformation f2) { long t1 = FileTools.createTime(f1.getFile().getAbsolutePath()); long t2 = FileTools.createTime(f2.getFile().getAbsolutePath()); return (int) (t2 - t1); } }); break; case CreateTimeAsc: Collections.sort(files, new Comparator<FileInformation>() { @Override public int compare(FileInformation f1, FileInformation f2) { long t1 = FileTools.createTime(f1.getFile().getAbsolutePath()); long t2 = FileTools.createTime(f2.getFile().getAbsolutePath()); return (int) (t1 - t2); } }); break; case SizeDesc: Collections.sort(files, new Comparator<FileInformation>() { @Override public int compare(FileInformation f1, FileInformation f2) { return (int) (f2.getFile().length() - f1.getFile().length()); } }); break; case SizeAsc: Collections.sort(files, new Comparator<FileInformation>() { @Override public int compare(FileInformation f1, FileInformation f2) { return (int) (f1.getFile().length() - f2.getFile().length()); } }); break; case FormatDesc: Collections.sort(files, new Comparator<FileInformation>() { @Override public int compare(FileInformation f1, FileInformation f2) { return FileNameTools.ext(f2.getFile().getName()).compareTo(FileNameTools.ext(f1.getFile().getName())); } }); break; case FormatAsc: Collections.sort(files, new Comparator<FileInformation>() { @Override public int compare(FileInformation f1, FileInformation f2) { return FileNameTools.ext(f1.getFile().getName()).compareTo(FileNameTools.ext(f2.getFile().getName())); } }); break; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/tools/CertificateTools.java
alpha/MyBox/src/main/java/mara/mybox/tools/CertificateTools.java
package mara.mybox.tools; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.security.KeyStore; import java.security.cert.Certificate; import java.security.cert.CertificateFactory; import java.util.ArrayList; import java.util.Collection; import java.util.List; import javax.net.ssl.SSLServerSocket; import javax.net.ssl.SSLServerSocketFactory; import javax.net.ssl.SSLSocket; import mara.mybox.dev.MyBoxLog; import mara.mybox.value.AppVariables; import mara.mybox.value.Languages; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2021-8-1 * @License Apache License Version 2.0 */ public class CertificateTools { public static String keystore() { String jvm_cacerts = System.getProperty("java.home") + File.separator + "lib" + File.separator + "security" + File.separator + "cacerts"; try { File file = myboxCacerts(); if (!file.exists()) { file.getParentFile().mkdirs(); FileCopyTools.copyFile(new File(jvm_cacerts), file); } if (file.exists()) { return file.getAbsolutePath(); } else { return jvm_cacerts; } } catch (Exception e) { return jvm_cacerts; } } public static String keystorePassword() { return "changeit"; } public static void resetKeystore() { FileDeleteTools.delete(myboxCacerts()); keystore(); } public static File myboxCacerts() { return new File(AppVariables.MyboxDataPath + File.separator + "security" + File.separator + "cacerts_mybox"); } public static void SSLServerSocketInfo() { try { SSLServerSocket sslServerSocket; SSLServerSocketFactory ssl = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault(); sslServerSocket = (SSLServerSocket) ssl.createServerSocket(); String[] cipherSuites = sslServerSocket.getSupportedCipherSuites(); for (String suite : cipherSuites) { MyBoxLog.debug(suite); } String[] protocols = sslServerSocket.getSupportedProtocols(); for (String protocol : protocols) { MyBoxLog.debug(protocol); } } catch (Exception e) { } } public static boolean isHostCertificateInstalled(String host) { try { SSLSocket socket = NetworkTools.sslSocket(host, 443); socket.setSoTimeout(UserConfig.getInt("WebConnectTimeout", 10000)); try { socket.startHandshake(); socket.close(); return true; } catch (Exception e) { return false; } } catch (Exception e) { return false; } } public static String installCertificates(String keyStoreFile, String passwd, Certificate[] certs, String[] names) { try { if (keyStoreFile == null || certs == null || names == null || certs.length != names.length) { return Languages.message("InvalidData"); } char[] passphrase = passwd.toCharArray(); File cacerts = new File(keyStoreFile); KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); try (final BufferedInputStream in = new BufferedInputStream(new FileInputStream(cacerts))) { keyStore.load(in, passphrase); } catch (Exception e) { return e.toString(); } File tmpFile = FileTmpTools.getTempFile(); try (final BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(tmpFile))) { for (int i = 0; i < certs.length; i++) { String alias = names[i].replaceAll(" ", "-"); keyStore.setCertificateEntry(alias, certs[i]); } keyStore.store(out, passphrase); } catch (Exception e) { return e.toString(); } FileTools.override(tmpFile, cacerts); return null; } catch (Exception e) { return e.toString(); } } public static String installCertificates(Certificate[] certs, String[] names) { return installCertificates(CertificateTools.keystore(), CertificateTools.keystorePassword(), certs, names); } public static Certificate[] getCertificatesByFile(File certFile) { try (final FileInputStream inStream = new FileInputStream(certFile)) { CertificateFactory cf = CertificateFactory.getInstance("X.509"); Collection<? extends Certificate> data = cf.generateCertificates(inStream); if (data == null || data.isEmpty()) { return null; } Certificate[] certs = new Certificate[data.size()]; int index = 0; for (Certificate cert : data) { certs[index++] = cert; } return certs; } catch (Exception e) { return null; } } public static String installCertificateByFile(String keyStoreFile, String passwd, File certFile, String alias, boolean wholeChain) { try { if (wholeChain) { Certificate[] certs = getCertificatesByFile(certFile); if (certs == null || certs.length == 0) { return Languages.message("InvalidData"); } String[] names = new String[certs.length]; names[0] = alias; for (int i = 1; i < certs.length; i++) { names[i] = alias + "-chain-" + i; } return installCertificates(keyStoreFile, passwd, certs, names); } else { Certificate cert = getCertificateByFile(certFile); if (cert == null) { return Languages.message("InvalidData"); } return installCertificate(keyStoreFile, passwd, cert, alias); } } catch (Exception e) { return e.toString(); } } public static String installCertificateByFile(File certFile, String alias, boolean wholeChain) { return installCertificateByFile(CertificateTools.keystore(), CertificateTools.keystorePassword(), certFile, alias, wholeChain); } public static String installHostsCertificates(List<String> hosts, boolean wholeChain) { if (hosts == null || hosts.isEmpty()) { return Languages.message("InvalidData"); } try { List<Certificate> certsList = new ArrayList<>(); List<String> namesList = new ArrayList<>(); for (String host : hosts) { if (wholeChain) { Certificate[] hostCerts = getCertificatesByHost(host); if (hostCerts == null) { continue; } for (int i = 0; i < hostCerts.length; i++) { certsList.add(hostCerts[i]); namesList.add(host + (i == 0 ? "" : " chain " + i)); } } else { Certificate hostCert = getCertificateByHost(host); if (hostCert == null) { continue; } certsList.add(hostCert); namesList.add(host); } } if (certsList.isEmpty()) { return Languages.message("InvalidData"); } String keyStoreFile = CertificateTools.keystore(); String passwd = CertificateTools.keystorePassword(); Certificate[] certs = new Certificate[certsList.size()]; String[] names = new String[certsList.size()]; for (int i = 0; i < namesList.size(); i++) { certs[i] = certsList.get(i); names[i] = namesList.get(i); } return installCertificates(keyStoreFile, passwd, certs, names); } catch (Exception e) { return e.toString(); } } // https://github.com/escline/InstallCert/blob/master/InstallCert.java public static String installCertificateByHost(String keyStoreFile, String passwd, String host, String alias, boolean wholeChain) { try { if (wholeChain) { Certificate[] certs = getCertificatesByHost(host); if (certs == null || certs.length == 0) { return Languages.message("InvalidData"); } String[] names = new String[certs.length]; names[0] = alias; for (int i = 1; i < certs.length; i++) { names[i] = alias + "-chain-" + i; } return installCertificates(keyStoreFile, passwd, certs, names); } else { Certificate cert = getCertificateByHost(host); if (cert == null) { return Languages.message("InvalidData"); } return installCertificate(keyStoreFile, passwd, cert, alias); } } catch (Exception e) { return e.toString(); } } public static String installCertificateByHost(String host, String alias, boolean wholeChain) { try { return installCertificateByHost(CertificateTools.keystore(), CertificateTools.keystorePassword(), host, alias, wholeChain); } catch (Exception e) { MyBoxLog.console(e.toString()); return e.toString(); } } public static String installCertificateByHost(String host, boolean wholeChain) { try { return installCertificateByHost(host, host, wholeChain); } catch (Exception e) { MyBoxLog.console(e.toString()); return e.toString(); } } public static String uninstallCertificate(String keyStoreFile, String passwd, List<String> aliases) throws Exception { try { char[] passphrase = passwd.toCharArray(); File cacerts = new File(keyStoreFile); KeyStore keyStore; try (final BufferedInputStream in = new BufferedInputStream(new FileInputStream(cacerts))) { keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(in, passphrase); } catch (Exception e) { return e.toString(); } File tmpFile = FileTmpTools.getTempFile(); try (final BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(tmpFile))) { for (String alias : aliases) { keyStore.deleteEntry(alias); } keyStore.store(out, passphrase); } catch (Exception e) { return e.toString(); } FileTools.override(tmpFile, cacerts); return null; } catch (Exception e) { return e.toString(); } } public static Certificate getCertificateByHost(String host) { try { SSLSocket socket = NetworkTools.sslSocket(host, 443); socket.setSoTimeout(UserConfig.getInt("WebConnectTimeout", 10000)); try { socket.startHandshake(); socket.close(); } catch (Exception e) { } return socket.getSession().getPeerCertificates()[0]; } catch (Exception e) { return null; } } public static Certificate[] getCertificatesByHost(String host) { try { SSLSocket socket = NetworkTools.sslSocket(host, 443); socket.setSoTimeout(UserConfig.getInt("WebConnectTimeout", 10000)); try { socket.startHandshake(); socket.close(); } catch (Exception e) { } return socket.getSession().getPeerCertificates(); } catch (Exception e) { return null; } } public static Certificate getCertificateByFile(File certFile) { try (final FileInputStream inStream = new FileInputStream(certFile)) { CertificateFactory cf = CertificateFactory.getInstance("X.509"); return cf.generateCertificate(inStream); } catch (Exception e) { return null; } } public static String installCertificate(String keyStoreFile, String passwd, Certificate cert, String name) { if (cert == null || name == null) { return Languages.message("InvalidData"); } Certificate[] certs = {cert}; String[] names = {name}; return installCertificates(keyStoreFile, passwd, certs, names); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/tools/JsonTools.java
alpha/MyBox/src/main/java/mara/mybox/tools/JsonTools.java
package mara.mybox.tools; import com.fasterxml.jackson.databind.ObjectMapper; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import javafx.scene.control.IndexRange; import mara.mybox.data.FindReplaceString; import static mara.mybox.data.FindReplaceString.create; import mara.mybox.fxml.FxTask; /** * @Author Mara * @CreateDate 2021-3-26 * @License Apache License Version 2.0 */ public class JsonTools { public static LinkedHashMap<String, String> jsonValues(FxTask currentTask, String data, List<String> keys) { try { LinkedHashMap<String, String> values = new LinkedHashMap<>(); String subdata = data; FindReplaceString endFind = create() .setOperation(FindReplaceString.Operation.FindNext) .setFindString("[\\},]").setAnchor(0) .setIsRegex(true).setCaseInsensitive(true).setMultiline(true); for (String key : keys) { if (currentTask != null && !currentTask.isWorking()) { return null; } Map<String, Object> value = jsonValue(currentTask, subdata, key, endFind); if (currentTask != null && !currentTask.isWorking()) { return null; } if (value == null) { continue; } values.put(key, (String) value.get("value")); int start = (int) value.get("end") + 1; if (start >= subdata.length() - 1) { break; } subdata = subdata.substring(start); } return values; } catch (Exception e) { return null; } } public static Map<String, Object> jsonValue(FxTask currentTask, String json, String key, FindReplaceString endFind) { try { String flag = "\"" + key + "\":"; int startPos = json.indexOf(flag); if (startPos < 0) { return null; } String data = json.substring(startPos + flag.length()); endFind.setInputString(data).handleString(currentTask); if (currentTask != null && !currentTask.isWorking()) { return null; } IndexRange end = endFind.getStringRange(); if (end == null) { return null; } int endPos = end.getStart(); Map<String, Object> map = new HashMap<>(); String value = data.substring(0, endPos); if (value.startsWith("\"")) { value = value.substring(1); } if (value.endsWith("\"")) { value = value.substring(0, value.length() - 1); } map.put("value", value); map.put("start", startPos); map.put("end", endPos); return map; } catch (Exception e) { return null; } } public static String encode(String value) { try { return new ObjectMapper().writeValueAsString(value); } catch (Exception e) { return value; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/tools/ShortTools.java
alpha/MyBox/src/main/java/mara/mybox/tools/ShortTools.java
package mara.mybox.tools; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Random; import mara.mybox.value.AppValues; /** * @Author Mara * @CreateDate 2021-10-4 * @License Apache License Version 2.0 */ public class ShortTools { public static boolean invalidShort(Short value) { return value == null || value == AppValues.InvalidShort; } // invalid values are always in the end public static int compare(String s1, String s2, boolean desc) { float f1, f2; try { f1 = Short.parseShort(s1.replaceAll(",", "")); } catch (Exception e) { f1 = Float.NaN; } try { f2 = Short.parseShort(s2.replaceAll(",", "")); } catch (Exception e) { f2 = Float.NaN; } if (Float.isNaN(f1)) { if (Float.isNaN(f2)) { return 0; } else { return 1; } } else { if (Float.isNaN(f2)) { return -1; } else { float diff = f1 - f2; if (diff == 0) { return 0; } else if (diff > 0) { return desc ? -1 : 1; } else { return desc ? 1 : -1; } } } } public static short random(short max) { Random r = new Random(); return (short) r.nextInt(max); } public static String format(short v, String format, int scale) { if (invalidShort(v)) { return null; } return NumberTools.format(v, format, scale); } public static short[] sortArray(short[] numbers) { List<Short> list = new ArrayList<>(); for (short i : numbers) { list.add(i); } Collections.sort(list, new Comparator<Short>() { @Override public int compare(Short p1, Short p2) { if (p1 > p2) { return 1; } else if (p1 < p2) { return -1; } else { return 0; } } }); short[] sorted = new short[numbers.length]; for (int i = 0; i < list.size(); ++i) { sorted[i] = list.get(i); } return sorted; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/tools/StringTools.java
alpha/MyBox/src/main/java/mara/mybox/tools/StringTools.java
package mara.mybox.tools; import java.math.BigDecimal; import java.nio.charset.Charset; import java.text.Collator; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; import mara.mybox.dev.MyBoxLog; import mara.mybox.value.AppValues; import mara.mybox.value.AppVariables; import mara.mybox.value.Languages; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2018-6-11 17:43:53 * @License Apache License Version 2.0 */ public class StringTools { public static String start(String string, int maxLen) { if (string == null) { return string; } return string.length() > maxLen ? string.substring(0, maxLen) + "..." : string; } public static String end(String string, int maxLen) { if (string == null) { return string; } int len = string.length(); return len > maxLen ? "..." + string.substring(len - maxLen, len) : string; } public static String abbreviate(String string, int maxLen) { if (string == null) { return string; } return start(replaceLineBreak(string, " ").strip(), maxLen); } // https://github.com/Mararsh/MyBox/issues/1266 // Error popped when menu name includes "_". Not sure whether this is a bug of javafx public static String menuSuffix(String name) { if (name == null) { return null; } return end(name.replaceAll("_|\r\n|\r|\n", " ").strip(), AppVariables.menuMaxLen); } public static String menuPrefix(String name) { if (name == null) { return null; } return start(name.replaceAll("_|\r\n|\r|\n", " ").strip(), AppVariables.menuMaxLen); } public static String replaceLineBreak(String string) { return replaceLineBreak(string, " "); } public static String replaceHtmlLineBreak(String string) { return replaceLineBreak(string, "</BR>"); } public static String replaceLineBreak(String string, String replaceAs) { if (string == null) { return string; } if (replaceAs == null) { replaceAs = ""; } return string.replaceAll("\r\n|\n|\r", replaceAs); } public static String trimBlanks(String string) { if (string == null) { return string; } return string.replaceAll("\\s+", " ").trim(); } public static String[] separatedBySpace(String string) { String[] ss = new String[2]; String s = string.trim(); int pos1 = s.indexOf(' '); if (pos1 < 0) { ss[0] = s; ss[1] = ""; return ss; } ss[0] = s.substring(0, pos1); ss[1] = s.substring(pos1).trim(); return ss; } public static String[] splitBySpace(String string) { if (string == null) { return null; } return string.trim().split("\\s+"); } public static String[] splitByComma(String string) { String[] splitted = string.split(","); return splitted; } public static String fillLeftZero(Number value, int digit) { String v = value + ""; for (int i = v.length(); i < digit; ++i) { v = "0" + v; } return v; } public static String fillRightZero(Number value, int digit) { String v = value + ""; for (int i = v.length(); i < digit; ++i) { v += "0"; } return v; } public static String fillRightBlank(Number value, int digit) { String v = value + ""; for (int i = v.length(); i < digit; ++i) { v += " "; } return v; } public static String fillLeftBlank(Number value, int digit) { String v = new BigDecimal(value + "").toString() + ""; for (int i = v.length(); i < digit; ++i) { v = " " + v; } return v; } public static String fillRightBlank(String value, int digit) { String v = value; for (int i = v.length(); i < digit; ++i) { v += " "; } return v; } public static int numberPrefix(String string) { if (string == null) { return AppValues.InvalidInteger; } try { String s = string.trim(); int sign = 1; if (s.startsWith("-")) { if (s.length() == 1) { return AppValues.InvalidInteger; } sign = -1; s = s.substring(1); } String prefix = ""; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (isNumber(c)) { prefix += c; } else { break; } } if (prefix.isBlank()) { return AppValues.InvalidInteger; } return Integer.parseInt(prefix) * sign; } catch (Exception e) { return AppValues.InvalidInteger; } } public static boolean isNumber(char c) { return c >= '0' && c <= '9'; } public static int compareWithNumber(String string1, String string2) { try { if (string1 == null) { return string2 == null ? 0 : -1; } if (string2 == null) { return 1; } int len = Math.min(string1.length(), string2.length()); String number1 = "", number2 = ""; boolean numberEnd1 = false, numberEnd2 = false; for (int i = 0; i < len; i++) { char c1 = string1.charAt(i); char c2 = string2.charAt(i); if (c1 == c2) { continue; } if (isNumber(c1)) { if (!numberEnd1) { number1 += c1; } } else { numberEnd1 = true; } if (isNumber(c2)) { if (!numberEnd2) { number2 += c2; } } else { numberEnd2 = true; } if (numberEnd1 && numberEnd2) { break; } } if (!number1.isBlank() && !number2.isBlank()) { return compareNumber(number1, number2); } return compare(string1, string2); } catch (Exception e) { MyBoxLog.debug(e); return 1; } } public static int compareNumber(String number1, String number2) { if (number1 == null) { return number2 == null ? 0 : -1; } if (number2 == null) { return 1; } int len1 = number1.length(); int len2 = number2.length(); if (len1 > len2) { return 1; } else if (len1 < len2) { return -1; } for (int i = 0; i < len1; i++) { char c1 = number1.charAt(i); char c2 = number2.charAt(i); if (c1 > c2) { return 1; } else if (c1 < c2) { return -1; } } return 0; } public static int compare(String s1, String s2) { if (s1 == null) { return s2 == null ? 0 : -1; } if (s2 == null) { return 1; } Collator compare = Collator.getInstance(Locale.getDefault()); return compare.compare(s1, s2); } public static void sort(List<String> strings, Locale locale) { if (strings == null || strings.isEmpty()) { return; } Collections.sort(strings, new Comparator<String>() { private final Collator compare = Collator.getInstance(locale); @Override public int compare(String f1, String f2) { return compare.compare(f1, f2); } }); } public static void sort(List<String> strings) { sort(strings, Locale.getDefault()); } public static void sortDesc(List<String> strings, Locale locale) { if (strings == null || strings.isEmpty()) { return; } Collections.sort(strings, new Comparator<String>() { private final Collator compare = Collator.getInstance(Locale.getDefault()); @Override public int compare(String f1, String f2) { return compare.compare(f2, f1); } }); } public static void sortDesc(List<String> strings) { sortDesc(strings, Locale.getDefault()); } public static String format(long data) { try { DecimalFormat df = new DecimalFormat("#,###"); return df.format(data); } catch (Exception e) { return message("Invalid"); } } public static String format(double data) { return format(Math.round(data)); } public static String leftAlgin(String name, String value, int nameLength) { return String.format("%-" + nameLength + "s:" + value, name); } public static boolean match(String string, String find, boolean caseInsensitive) { if (string == null || find == null || find.isEmpty()) { return false; } try { int mode = (caseInsensitive ? Pattern.CASE_INSENSITIVE : 0x00) | Pattern.MULTILINE; Pattern pattern = Pattern.compile(find, mode); Matcher matcher = pattern.matcher(string); return matcher.matches(); } catch (Exception e) { MyBoxLog.debug(e); return false; } } public static boolean match(String string, String find, boolean isRegex, boolean dotAll, boolean multiline, boolean caseInsensitive) { if (string == null || find == null || find.isEmpty()) { return false; } try { int mode = (isRegex ? 0x00 : Pattern.LITERAL) | (caseInsensitive ? Pattern.CASE_INSENSITIVE : 0x00) | (dotAll ? Pattern.DOTALL : 0x00) | (multiline ? Pattern.MULTILINE : 0x00); Pattern pattern = Pattern.compile(find, mode); Matcher matcher = pattern.matcher(string); return matcher.matches(); } catch (Exception e) { MyBoxLog.debug(e); return false; } } public static boolean include(String string, String find, boolean caseInsensitive) { if (string == null || find == null || find.isEmpty()) { return false; } try { int mode = (caseInsensitive ? Pattern.CASE_INSENSITIVE : 0x00) | Pattern.MULTILINE; Pattern pattern = Pattern.compile(find, mode); Matcher matcher = pattern.matcher(string); return matcher.find(); } catch (Exception e) { MyBoxLog.debug(e); return false; } } // https://blog.csdn.net/zx1749623383/article/details/79540748 public static String decodeUnicode(String unicode) { if (unicode == null || "".equals(unicode)) { return null; } StringBuilder sb = new StringBuilder(); int i, pos = 0; while ((i = unicode.indexOf("\\u", pos)) > 0) { sb.append(unicode.substring(pos, i)); if (i + 5 < unicode.length()) { pos = i + 6; sb.append((char) Integer.parseInt(unicode.substring(i + 2, i + 6), 16)); } else { break; } } return sb.toString(); } public static String encodeUnicode(String string) { if (string == null || "".equals(string)) { return null; } StringBuilder unicode = new StringBuilder(); for (int i = 0; i < string.length(); i++) { char c = string.charAt(i); unicode.append("\\u").append(Integer.toHexString(c)); } return unicode.toString(); } public static String convertCharset(String source, String sourceCharset, String targetCharset) { try { if (sourceCharset.equals(targetCharset)) { return source; } return new String(source.getBytes(sourceCharset), targetCharset); } catch (Exception e) { return source; } } public static String convertCharset(String source, Charset sourceCharset, Charset targetCharset) { try { if (sourceCharset.equals(targetCharset)) { return source; } return new String(source.getBytes(sourceCharset), targetCharset); } catch (Exception e) { return source; } } public static String discardBlankLines(String text) { if (text == null) { return null; } String[] lines = text.split("\n"); StringBuilder s = new StringBuilder(); for (String line : lines) { if (line.isBlank()) { continue; } s.append(line).append("\n"); } return s.toString(); } public static String[][] transpose(String[][] matrix) { try { if (matrix == null) { return null; } int rowsNumber = matrix.length, columnsNumber = matrix[0].length; String[][] result = new String[columnsNumber][rowsNumber]; for (int row = 0; row < rowsNumber; ++row) { for (int col = 0; col < columnsNumber; ++col) { result[col][row] = matrix[row][col]; } } return result; } catch (Exception e) { return null; } } public static String[] matrix2Array(String[][] m) { if (m == null || m.length == 0 || m[0].length == 0) { return null; } int h = m.length; int w = m[0].length; String[] a = new String[w * h]; for (int j = 0; j < h; ++j) { System.arraycopy(m[j], 0, a, j * w, w); } return a; } public static String[][] array2Matrix(String[] a, int w) { if (a == null || a.length == 0 || w < 1) { return null; } int h = a.length / w; if (h < 1) { return null; } String[][] m = new String[h][w]; for (int j = 0; j < h; ++j) { for (int i = 0; i < w; ++i) { m[j][i] = a[j * w + i]; } } return m; } public static String[][] toString(double[][] dMatrix) { try { if (dMatrix == null) { return null; } int rsize = dMatrix.length, csize = dMatrix[0].length; String[][] sMatrix = new String[rsize][csize]; for (int i = 0; i < rsize; i++) { for (int j = 0; j < csize; j++) { sMatrix[i][j] = dMatrix[i][j] + ""; } } return sMatrix; } catch (Exception e) { return null; } } public static List<String> toList(String value, String separater) { try { if (value == null || value.isBlank()) { return null; } String[] a = value.split(separater, 0); if (a == null || a.length == 0) { return null; } List<String> values = new ArrayList<>(); values.addAll(Arrays.asList(a)); if (values.isEmpty()) { return null; } else { return values; } } catch (Exception e) { return null; } } public static String toString(List<String> values, String separater) { try { if (values == null || values.isEmpty()) { return null; } String s = null; for (String v : values) { if (v != null && !v.isBlank()) { if (s == null) { s = v; } else { s += separater + v; } } } if (s == null || s.isBlank()) { return null; } else { return s; } } catch (Exception e) { return null; } } public static boolean isTrue(String string) { if (string == null || string.isBlank()) { return false; } return "1".equals(string) || Languages.matchIgnoreCase("true", string) || Languages.matchIgnoreCase("yes", string); } public static boolean isFalse(String string) { if (string == null || string.isBlank()) { return false; } return "0".equals(string) || Languages.matchIgnoreCase("false", string) || Languages.matchIgnoreCase("no", string); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/tools/FileNameTools.java
alpha/MyBox/src/main/java/mara/mybox/tools/FileNameTools.java
package mara.mybox.tools; import java.io.File; import java.text.Collator; import java.util.Locale; import java.util.regex.Pattern; import mara.mybox.dev.MyBoxLog; import mara.mybox.value.AppValues; /** * @Author Mara * @CreateDate 2021-8-1 * @License Apache License Version 2.0 */ public class FileNameTools { public static String filter(String name) { if (name == null || name.isBlank()) { return name; } Pattern pattern = Pattern.compile(AppValues.FileNameSpecialChars); return pattern.matcher(name).replaceAll("_"); } public static String name(String filename) { return name(filename, File.separator); } public static String name(String filename, String separator) { if (filename == null) { return null; } String fname = filename; int pos = fname.lastIndexOf(separator); if (pos >= 0) { fname = (pos < fname.length() - 1) ? fname.substring(pos + 1) : ""; } return fname; } public static String append(String filename, String append) { if (filename == null) { return null; } if (append == null || append.isEmpty()) { return filename; } String path; String name; int pos = filename.lastIndexOf(File.separator); if (pos >= 0) { path = filename.substring(0, pos + 1); name = pos < filename.length() - 1 ? filename.substring(pos + 1) : ""; } else { path = ""; name = filename; } pos = name.lastIndexOf('.'); if (pos >= 0) { return path + name.substring(0, pos) + append + name.substring(pos); } else { return path + name + append; } } // not include path, only filename's prefix public static String prefix(String filename) { if (filename == null) { return null; } String name = name(filename); int pos = name.lastIndexOf('.'); if (pos >= 0) { name = name.substring(0, pos); } return name; } public static String ext(String filename) { return ext(filename, File.separator); } // not include "." public static String ext(String filename, String separator) { if (filename == null || filename.endsWith(separator)) { return null; } String name = name(filename, separator); int pos = name.lastIndexOf('.'); return (pos >= 0 && pos < name.length() - 1) ? name.substring(pos + 1) : ""; } public static String replaceExt(String file, String newSuffix) { if (file == null || newSuffix == null) { return null; } String path; String name; int pos = file.lastIndexOf(File.separator); if (pos >= 0) { path = file.substring(0, pos + 1); name = pos < file.length() - 1 ? file.substring(pos + 1) : ""; } else { path = ""; name = file; } pos = name.lastIndexOf('.'); if (pos >= 0) { return path + name.substring(0, pos + 1) + newSuffix; } else { return path + name + "." + newSuffix; } } // include "." public static String suffix(String filename) { if (filename == null || filename.endsWith(File.separator)) { return null; } String name = name(filename); int pos = name.lastIndexOf('.'); return (pos >= 0 && pos < name.length() - 1) ? name.substring(pos) : ""; } public static int compareName(File f1, File f2) { try { if (f1 == null) { return f2 == null ? 0 : -1; } if (f2 == null) { return 1; } if (f1.isFile() && f2.isFile() && f1.getParent().equals(f2.getParent())) { return StringTools.compareWithNumber(f1.getName(), f2.getName()); } else { Collator compare = Collator.getInstance(Locale.getDefault()); return compare.compare(f1.getAbsolutePath(), f2.getAbsolutePath()); } } catch (Exception e) { MyBoxLog.debug(e); return 1; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/tools/FFmpegTools.java
alpha/MyBox/src/main/java/mara/mybox/tools/FFmpegTools.java
package mara.mybox.tools; /** * @Author Mara * @CreateDate 2018-7-12 * @Description * @License Apache License Version 2.0 */ public class FFmpegTools { // public static FFprobeResult FFprobleFrames(File FFprobleExcuatble, File mediaFile, // String streams, String intervals) throws Exception { // FFprobe probe = FFprobe.atPath(FFprobleExcuatble.toPath().getParent()) // .setShowFrames(true) // .setInput(Paths.get(mediaFile.getAbsolutePath())); // if (streams != null && !streams.trim().isEmpty()) { // probe.setSelectStreams(streams.trim()); // } // if (intervals != null && !intervals.trim().isEmpty()) { // probe.setReadIntervals(intervals.trim()); // } // return probe.execute(); // } // // public static FFprobeResult FFproblePackets(File FFprobleExcuatble, File mediaFile, // String streams, String intervals) throws Exception { // FFprobe probe = FFprobe.atPath(FFprobleExcuatble.toPath().getParent()) // .setShowPackets(true) // .setInput(Paths.get(mediaFile.getAbsolutePath())); // if (streams != null && !streams.trim().isEmpty()) { // probe.setSelectStreams(streams.trim()); // } // if (intervals != null && !intervals.trim().isEmpty()) { // probe.setReadIntervals(intervals.trim()); // } // return probe.execute(); // } // // public static void convert(File FFmpegExcuatble, File sourceFile, File targetFile) { // // The most reliable way to get video duration // // ffprobe for some formats can't detect duration // final AtomicLong duration = new AtomicLong(); // final FFmpegResult nullResult = FFmpeg.atPath(FFmpegExcuatble.toPath()) // .addInput(UrlInput.fromPath(sourceFile.toPath())) // .addOutput(new NullOutput()) // .setOverwriteOutput(true) // .setProgressListener(new ProgressListener() { // @Override // public void onProgress(FFmpegProgress progress) { // duration.set(progress.getTimeMillis()); // } // }) // .execute(); // // ProgressListener listener = new ProgressListener() { // private final long lastReportTs = System.currentTimeMillis(); // // @Override // public void onProgress(FFmpegProgress progress) { // long now = System.currentTimeMillis(); // if (lastReportTs + 1000 < now) { // long percent = 100 * progress.getTimeMillis() / duration.get(); // MyBoxLog.debug("Progress: " + percent + "%"); // } // } // }; // // FFmpegResult result = FFmpeg.atPath(FFmpegExcuatble.toPath()) // .addInput(UrlInput.fromPath(sourceFile.toPath())) // .addOutput(UrlOutput.toPath(targetFile.toPath())) // .setProgressListener(listener) // .setOverwriteOutput(true) // .execute(); // } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/tools/TextTools.java
alpha/MyBox/src/main/java/mara/mybox/tools/TextTools.java
package mara.mybox.tools; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import javafx.scene.control.IndexRange; import mara.mybox.data.FileEditInformation; import mara.mybox.data.FileEditInformation.Line_Break; import mara.mybox.data.TextEditInformation; import static mara.mybox.data2d.DataFileText.CommentsMarker; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import static mara.mybox.value.Languages.message; import thridparty.EncodingDetect; /** * @Author Mara * @CreateDate 2018-12-10 13:06:33 * @Version 1.0 * @Description * @License Apache License Version 2.0 */ public class TextTools { public final static String BlankName = "Blank"; public final static String Blank4Name = "Blank4"; public final static String Blank8Name = "Blank8"; public final static String BlanksName = "Blanks"; public final static String TabName = "Tab"; public static List<Charset> getCharsets() { List<Charset> sets = new ArrayList<>(); sets.addAll(Arrays.asList(Charset.forName("UTF-8"), Charset.forName("GBK"), Charset.forName("GB2312"), Charset.forName("GB18030"), Charset.forName("BIG5"), Charset.forName("ASCII"), Charset.forName("ISO-8859-1"), Charset.forName("UTF-16"), Charset.forName("UTF-16BE"), Charset.forName("UTF-16LE"), Charset.forName("UTF-32"), Charset.forName("UTF-32BE"), Charset.forName("UTF-32LE") )); if (sets.contains(Charset.defaultCharset())) { sets.remove(Charset.defaultCharset()); } sets.add(0, Charset.defaultCharset()); Map<String, Charset> all = Charset.availableCharsets(); for (Charset set : all.values()) { if (Charset.isSupported(set.name()) && !sets.contains(set)) { sets.add(set); } } return sets; } public static List<String> getCharsetNames() { try { List<Charset> sets = getCharsets(); List<String> setNames = new ArrayList<>(); for (Charset set : sets) { setNames.add(set.name()); } return setNames; } catch (Exception e) { return null; } } public static String checkCharsetByBom(byte[] bytes) { if (bytes.length < 2) { return null; } if ((bytes[0] == (byte) 0xFE) && (bytes[1] == (byte) 0xFF)) { return "UTF-16BE"; } if ((bytes[0] == (byte) 0xFF) && (bytes[1] == (byte) 0xFE)) { return "UTF-16LE"; } if (bytes.length < 3) { return null; } if ((bytes[0] == (byte) 0xEF) && (bytes[1] == (byte) 0xBB) && (bytes[2] == (byte) 0xBF)) { return "UTF-8"; } if (bytes.length < 4) { return null; } if ((bytes[0] == (byte) 0x00) && (bytes[1] == (byte) 0x00) && (bytes[2] == (byte) 0xFE) && (bytes[3] == (byte) 0xFF)) { return "UTF-32BE"; } if ((bytes[0] == (byte) 0xFF) && (bytes[1] == (byte) 0xFE) && (bytes[2] == (byte) 0x00) && (bytes[3] == (byte) 0x00)) { return "UTF-32LE"; } return null; } public static boolean checkCharset(FileEditInformation info) { try { if (info == null || info.getFile() == null) { return false; } String setName; info.setWithBom(false); try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(info.getFile()))) { byte[] header = new byte[4]; int bufLen; if ((bufLen = inputStream.read(header, 0, 4)) > 0) { header = ByteTools.subBytes(header, 0, bufLen); setName = checkCharsetByBom(header); if (setName != null) { info.setCharset(Charset.forName(setName)); info.setWithBom(true); return true; } } } setName = EncodingDetect.detect(info.getFile()); info.setCharset(Charset.forName(setName)); return true; } catch (Exception e) { // MyBoxLog.debug(e); return false; } } public static int bomSize(String charset) { switch (charset) { case "UTF-16": case "UTF-16BE": return 2; case "UTF-16LE": return 2; case "UTF-8": return 3; case "UTF-32": case "UTF-32BE": return 4; case "UTF-32LE": return 4; } return 0; } public static String bomHex(String charset) { switch (charset) { case "UTF-16": case "UTF-16BE": return "FE FF"; case "UTF-16LE": return "FF FE"; case "UTF-8": return "EF BB BF"; case "UTF-32": case "UTF-32BE": return "00 00 FE FF"; case "UTF-32LE": return "FF FE 00 00"; } return null; } public static byte[] bomBytes(String charset) { switch (charset) { case "UTF-16": case "UTF-16BE": return new byte[]{(byte) 0xFE, (byte) 0xFF}; case "UTF-16LE": return new byte[]{(byte) 0xFF, (byte) 0xFE}; case "UTF-8": return new byte[]{(byte) 0xEF, (byte) 0xBB, (byte) 0xBF}; case "UTF-32": case "UTF-32BE": return new byte[]{(byte) 0x00, (byte) 0x00, (byte) 0xFE, (byte) 0xFF}; case "UTF-32LE": return new byte[]{(byte) 0xFF, (byte) 0xFE, (byte) 0x00, (byte) 0x00}; } return null; } public static String readText(FxTask task, File file) { return readText(task, new TextEditInformation(file)); } public static String readText(FxTask task, FileEditInformation info) { try { if (info == null || info.getFile() == null) { return null; } StringBuilder text = new StringBuilder(); try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(info.getFile())); InputStreamReader reader = new InputStreamReader(inputStream, info.getCharset())) { if (info.isWithBom()) { inputStream.skip(bomSize(info.getCharset().name())); } char[] buf = new char[512]; int len; while ((len = reader.read(buf)) > 0) { if (task != null && !task.isWorking()) { return text.toString(); } text.append(buf, 0, len); } } return text.toString(); } catch (Exception e) { MyBoxLog.debug(e); return null; } } public static boolean writeText(FileEditInformation info, String text) { try (BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(info.getFile())); OutputStreamWriter writer = new OutputStreamWriter(outputStream, info.getCharset())) { if (info.isWithBom()) { byte[] bytes = bomBytes(info.getCharset().name()); outputStream.write(bytes); } writer.write(text); return true; } catch (Exception e) { MyBoxLog.debug(e); return false; } } public static boolean convertCharset(FxTask task, FileEditInformation source, FileEditInformation target) { try { if (source == null || source.getFile() == null || source.getCharset() == null || target == null || target.getFile() == null || target.getCharset() == null) { return false; } try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(source.getFile())); InputStreamReader reader = new InputStreamReader(inputStream, source.getCharset()); BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(target.getFile())); OutputStreamWriter writer = new OutputStreamWriter(outputStream, target.getCharset())) { if (source.isWithBom()) { inputStream.skip(bomSize(source.getCharset().name())); } if (target.isWithBom()) { byte[] bytes = bomBytes(target.getCharset().name()); outputStream.write(bytes); } char[] buf = new char[512]; int count; while ((count = reader.read(buf)) > 0) { if (task != null && !task.isWorking()) { return false; } String text = new String(buf, 0, count); writer.write(text); } } return true; } catch (Exception e) { MyBoxLog.debug(e); return false; } } public static boolean convertLineBreak(FxTask task, FileEditInformation source, FileEditInformation target) { try { if (source == null || source.getFile() == null || source.getCharset() == null || target == null || target.getFile() == null || target.getCharset() == null) { return false; } String sourceLineBreak = TextTools.lineBreakValue(source.getLineBreak()); String taregtLineBreak = TextTools.lineBreakValue(target.getLineBreak()); if (sourceLineBreak == null || taregtLineBreak == null) { return false; } if (source.getLineBreak() == target.getLineBreak()) { return FileCopyTools.copyFile(source.getFile(), target.getFile(), true, true); } try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(source.getFile())); InputStreamReader reader = new InputStreamReader(inputStream, source.getCharset()); BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(target.getFile())); OutputStreamWriter writer = new OutputStreamWriter(outputStream, target.getCharset())) { char[] buf = new char[4096]; int count; while ((count = reader.read(buf)) > 0) { if (task != null && !task.isWorking()) { return false; } String text = new String(buf, 0, count); text = text.replaceAll(sourceLineBreak, taregtLineBreak); writer.write(text); } } return true; } catch (Exception e) { MyBoxLog.debug(e); return false; } } public static long checkCharsNumber(String string) { try { String strV = string.trim().toLowerCase(); long unit = 1; if (strV.endsWith("k")) { unit = 1024; strV = strV.substring(0, strV.length() - 1); } else if (strV.endsWith("m")) { unit = 1024 * 1024; strV = strV.substring(0, strV.length() - 1); } else if (strV.endsWith("g")) { unit = 1024 * 1024 * 1024L; strV = strV.substring(0, strV.length() - 1); } double v = Double.parseDouble(strV.trim()); if (v >= 0) { return Math.round(v * unit); } else { return -1; } } catch (Exception e) { return -1; } } public static List<File> convert(FxTask task, FileEditInformation source, FileEditInformation target, int maxLines) { try { if (source == null || source.getFile() == null || source.getCharset() == null || target == null || target.getFile() == null || target.getCharset() == null) { return null; } String sourceLineBreak = TextTools.lineBreakValue(source.getLineBreak()); String taregtLineBreak = TextTools.lineBreakValue(target.getLineBreak()); if (sourceLineBreak == null || taregtLineBreak == null) { return null; } List<File> files = new ArrayList<>(); try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(source.getFile())); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, source.getCharset()))) { if (source.isWithBom()) { inputStream.skip(bomSize(source.getCharset().name())); } if (maxLines > 0) { int fileIndex = 0; while (true) { if (task != null && !task.isWorking()) { return null; } int linesNumber = 0; String line = null; File file = new File(FileNameTools.append(target.getFile().getAbsolutePath(), "-" + (++fileIndex))); try (BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(file)); OutputStreamWriter writer = new OutputStreamWriter(outputStream, target.getCharset())) { if (target.isWithBom()) { byte[] bytes = bomBytes(target.getCharset().name()); outputStream.write(bytes); } while ((line = bufferedReader.readLine()) != null) { if (task != null && !task.isWorking()) { return null; } if (linesNumber++ > 0) { writer.write(taregtLineBreak + line); } else { writer.write(line); } if (linesNumber >= maxLines) { break; } } } catch (Exception e) { MyBoxLog.error(e.toString()); return null; } if (file.exists() && file.length() > 0) { files.add(file); } if (line == null) { break; } } } else { File file = target.getFile(); try (BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(file)); OutputStreamWriter writer = new OutputStreamWriter(outputStream, target.getCharset())) { if (target.isWithBom()) { byte[] bytes = bomBytes(target.getCharset().name()); outputStream.write(bytes); } String line; if ((line = bufferedReader.readLine()) != null) { writer.write(line); } while ((line = bufferedReader.readLine()) != null) { if (task != null && !task.isWorking()) { return null; } writer.write(taregtLineBreak + line); } } catch (Exception e) { MyBoxLog.debug(e); return null; } if (file.exists() && file.length() > 0) { files.add(file); } } } catch (Exception e) { MyBoxLog.debug(e); return null; } return files; } catch (Exception e) { MyBoxLog.debug(e); return null; } } public static IndexRange hexIndex(FxTask task, String text, Charset charset, String lineBreakValue, IndexRange textRange) { int hIndex = 0; int hBegin = 0; int hEnd = 0; int cBegin = textRange.getStart(); int cEnd = textRange.getEnd(); if (cBegin == 0 && cEnd == 0) { return new IndexRange(0, 0); } int lbLen = lineBreakValue.getBytes(charset).length * 3 + 1; for (int i = 0; i < text.length(); ++i) { if (cBegin == i) { hBegin = hIndex; } if (cEnd == i) { hEnd = hIndex; } char c = text.charAt(i); if (c == '\n') { hIndex += lbLen; } else { hIndex += String.valueOf(c).getBytes(charset).length * 3; } } if (cBegin == text.length()) { hBegin = hIndex; } if (cEnd == text.length()) { hEnd = hIndex; } return new IndexRange(hBegin, hEnd); } public static Line_Break checkLineBreak(FxTask task, File file) { if (file == null) { return Line_Break.LF; } try (InputStreamReader reader = new InputStreamReader( new BufferedInputStream(new FileInputStream(file)))) { int c; boolean cr = false; while ((c = reader.read()) > 0) { if (task != null && !task.isWorking()) { return Line_Break.LF; } if ((char) c == '\r') { cr = true; } else if ((char) c == '\n') { if (cr) { return Line_Break.CRLF; } else { return Line_Break.LF; } } else if (c != 0 && cr) { return Line_Break.CR; } } } catch (Exception e) { MyBoxLog.error(e); } return Line_Break.LF; } public static String lineBreakValue(Line_Break lb) { switch (lb) { case LF: return "\n"; case CRLF: return "\r\n"; case CR: return "\r"; default: return "\n"; } } public static byte[] lineBreakBytes(Line_Break lb, Charset charset) { switch (lb) { case LF: return "\n".getBytes(charset); case CRLF: return "\r\n".getBytes(charset); case CR: return "\r".getBytes(charset); default: return "\n".getBytes(charset); } } public static String lineBreakHex(Line_Break lb, Charset charset) { return ByteTools.bytesToHex(lineBreakBytes(lb, charset)); } public static String lineBreakHexFormat(Line_Break lb, Charset charset) { return ByteTools.bytesToHexFormat(lineBreakBytes(lb, charset)); } public static String delimiterValue(String delimiterName) { if (delimiterName == null) { return ","; } String delimiter; switch (delimiterName) { case TabName: case "tab": delimiter = "\t"; break; case BlankName: case "blank": delimiter = " "; break; case Blank4Name: case "blank4": delimiter = " "; break; case Blank8Name: case "blank8": delimiter = " "; break; case BlanksName: case "blanks": delimiter = " "; break; default: delimiter = delimiterName; break; } return delimiter; } public static String delimiterMessage(String delimiterName) { if (delimiterName == null || delimiterName.isEmpty()) { return message("Unknown"); } String msg; switch (delimiterName) { case TabName: case "tab": case "\t": msg = message("Tab"); break; case BlankName: case "blank": case " ": msg = message("Blank"); break; case Blank4Name: case "blank4": case " ": msg = message("Blank4"); break; case Blank8Name: case "blank8": case " ": msg = message("Blank8"); break; case BlanksName: case "blanks": msg = message("BlankCharacters"); break; default: if (delimiterName.isBlank()) { msg = message("BlankCharacters"); } else { msg = delimiterName; } break; } return msg; } public static String arrayText(FxTask task, Object[][] data, String delimiterName, List<String> colsNames, List<String> rowsNames) { if (data == null || data.length == 0 || delimiterName == null) { return ""; } try { StringBuilder s = new StringBuilder(); String delimiter = delimiterValue(delimiterName); int rowsNumber = data.length; int colsNumber = data[0].length; int colEnd; if (colsNames != null && colsNames.size() >= colsNumber) { if (rowsNames != null && !rowsNames.isEmpty()) { s.append(delimiter); } colEnd = colsNumber - 1; for (int c = 0; c <= colEnd; c++) { if (task != null && !task.isWorking()) { return null; } s.append(colsNames.get(c)); if (c < colEnd) { s.append(delimiter); } } s.append("\n"); } Object v; int rowEnd = rowsNumber - 1; for (int i = 0; i <= rowEnd; i++) { if (task != null && !task.isWorking()) { return null; } if (rowsNames != null && !rowsNames.isEmpty()) { s.append(rowsNames.get(i)).append(delimiter); } colEnd = colsNumber - 1; for (int c = 0; c <= colEnd; c++) { if (task != null && !task.isWorking()) { return null; } v = data[i][c]; s.append(v == null ? "" : v); if (c < colEnd) { s.append(delimiter); } } if (i < rowEnd) { s.append("\n"); } } return s.toString(); } catch (Exception e) { MyBoxLog.console(e); return ""; } } public static String rowsText(FxTask task, List<List<String>> rows, String delimiterName) { return arrayText(task, toArray(task, rows), delimiterName, null, null); } public static String rowsText(FxTask task, List<List<String>> rows, String delimiterName, List<String> colsNames, List<String> rowsNames) { return arrayText(task, toArray(task, rows), delimiterName, colsNames, rowsNames); } public static boolean validLine(String line) { return line != null && !line.isBlank() && !line.startsWith(CommentsMarker); } public static List<String> parseLine(String line, String delimiterName) { try { if (!validLine(line) || delimiterName == null) { return null; } String[] values; switch (delimiterName) { case TabName: case "tab": case "\t": values = line.split("\t", -1); break; case BlankName: case "blank": case " ": values = line.split("\\s", -1); break; case Blank4Name: case "blank4": case " ": values = line.split("\\s{4}", -1); break; case Blank8Name: case "blank8": case " ": values = line.split("\\s{8}", -1); break; case BlanksName: case "blanks": values = line.split("\\s+", -1); break; case "|": values = line.split("\\|", -1); break; case "*": values = line.split("\\*", -1); break; case ".": values = line.split("\\.", -1); break; case "?": values = line.split("\\?", -1); break; case "\\": values = line.split("\\\\", -1); break; default: if (delimiterName.isBlank()) { values = line.split("\\s+", -1); } else { values = line.split(delimiterName, -1); } break; } if (values == null || values.length == 0) { return null; } List<String> row = new ArrayList<>(); row.addAll(Arrays.asList(values)); return row; } catch (Exception e) { MyBoxLog.console(e.toString()); return null; } } public static String[][] toArray(FxTask task, List<List<String>> rows) { try { if (rows == null || rows.isEmpty()) { return null; } int rowSize = rows.size(); int colSize = -1; for (List<String> row : rows) { int len = row.size(); if (len > colSize) { colSize = len; } } String[][] data = new String[rowSize][colSize]; for (int r = 0; r < rows.size(); r++) { List<String> row = rows.get(r); for (int c = 0; c < row.size(); c++) { data[r][c] = row.get(c); } } return data; } catch (Exception e) { MyBoxLog.console(e); return null; } } public static List<List<String>> toList(FxTask task, String[][] array) { try { int rowsNumber = array.length; int colsNumber = array[0].length; List<List<String>> data = new ArrayList<>(); for (int i = 0; i < rowsNumber; i++) { List<String> row = new ArrayList<>(); for (int j = 0; j < colsNumber; j++) { row.add(array[i][j]); } data.add(row); } return data; } catch (Exception e) { return null; } } public static String vertical(FxTask task, String text, boolean leftToRight) { try { if (text == null) { return null; } StringBuilder s = new StringBuilder(); String[] lines = text.split("\n", -1); int maxLen = 0; for (String line : lines) { int lineLen = line.length(); if (lineLen > maxLen) { maxLen = lineLen; } } int end = lines.length - 1; if (leftToRight) { for (int r = 0; r < maxLen; r++) { for (int i = 0; i <= end; i++) { String line = lines[i]; int lineLen = line.length(); if (lineLen > r) { s.append(line.charAt(r)); } else { s.append(" "); } } s.append("\n"); } } else { for (int r = 0; r < maxLen; r++) { for (int i = end; i >= 0; i--) { String line = lines[i]; int lineLen = line.length(); if (lineLen > r) { s.append(line.charAt(r)); } else { s.append(" "); } } s.append("\n"); } } return s.toString(); } catch (Exception e) { MyBoxLog.error(e); return text; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/tools/CompressTools.java
alpha/MyBox/src/main/java/mara/mybox/tools/CompressTools.java
/* * Apache License Version 2.0 */ package mara.mybox.tools; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import mara.mybox.controller.BaseTaskController; import mara.mybox.data.FileInformation.FileType; import mara.mybox.data.FileNode; import mara.mybox.dev.MyBoxLog; import static mara.mybox.value.Languages.message; import mara.mybox.value.UserConfig; import org.apache.commons.compress.archivers.ArchiveEntry; import org.apache.commons.compress.archivers.ArchiveInputStream; import org.apache.commons.compress.archivers.ArchiveStreamFactory; import org.apache.commons.compress.archivers.sevenz.SevenZArchiveEntry; import org.apache.commons.compress.archivers.sevenz.SevenZFile; import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipFile; import org.apache.commons.compress.compressors.CompressorInputStream; import org.apache.commons.compress.compressors.CompressorStreamFactory; import org.apache.commons.compress.compressors.lz4.BlockLZ4CompressorInputStream; import org.apache.commons.io.IOUtils; /** * * @author mara */ public class CompressTools { public static Map<String, String> CompressExtension; public static Map<String, String> ExtensionCompress; public static Map<String, String> ArchiveExtension; public static Map<String, String> ExtensionArchive; public static Map<String, String> compressExtension() { if (CompressExtension != null) { return CompressExtension; } CompressExtension = new HashMap<>(); CompressExtension.put("gz", "gz"); CompressExtension.put("bzip2", "bz2"); CompressExtension.put("pack200", "pack"); CompressExtension.put("xz", "xz"); CompressExtension.put("lzma", "lzma"); CompressExtension.put("snappy-framed", "sz"); CompressExtension.put("snappy-raw", "sz"); CompressExtension.put("z", "z"); CompressExtension.put("deflate", "deflate"); CompressExtension.put("deflate64", "deflate"); CompressExtension.put("lz4-block", "lz4"); CompressExtension.put("lz4-framed", "lz4"); // CompressExtension.put("zstandard", "zstd"); // CompressExtension.put("brotli", "br"); return CompressExtension; } public static Map<String, String> extensionCompress() { if (ExtensionCompress != null) { return ExtensionCompress; } Map<String, String> formats = compressExtension(); ExtensionCompress = new HashMap<>(); for (String format : formats.keySet()) { ExtensionCompress.put(formats.get(format), format); } return ExtensionCompress; } public static Map<String, String> archiveExtension() { if (ArchiveExtension != null) { return ArchiveExtension; } ArchiveExtension = new HashMap<>(); ArchiveExtension.put("zip", "zip"); ArchiveExtension.put("7z", "7z"); ArchiveExtension.put("jar", "jar"); ArchiveExtension.put("tar", "tar"); ArchiveExtension.put("ar", "ar"); ArchiveExtension.put("arj", "arj"); ArchiveExtension.put("cpio", "cpio"); ArchiveExtension.put("dump", "dump"); return ArchiveExtension; } public static Map<String, String> extensionArchive() { if (ExtensionArchive != null) { return ExtensionArchive; } Map<String, String> formats = archiveExtension(); ExtensionArchive = new HashMap<>(); for (String format : formats.keySet()) { ExtensionArchive.put(formats.get(format), format); } return ExtensionArchive; } public static String extensionByCompressor(String compressor) { if (compressor == null) { return null; } return compressExtension().get(compressor.toLowerCase()); } public static String compressorByExtension(String ext) { if (ext == null) { return null; } return extensionCompress().get(ext.toLowerCase()); } public static Set<String> compressFormats() { return compressExtension().keySet(); } public static Set<String> archiveFormats() { return archiveExtension().keySet(); } public static String decompressedName(BaseTaskController taskController, File srcFile) { return decompressedName(taskController, srcFile, detectCompressor(taskController, srcFile)); } public static String decompressedName(BaseTaskController taskController, File srcFile, String compressor) { try { if (srcFile == null || compressor == null) { return null; } String ext = CompressTools.extensionByCompressor(compressor); if (ext == null) { return null; } String fname = srcFile.getName(); if (fname.toLowerCase().endsWith("." + ext)) { return fname.substring(0, fname.length() - ext.length() - 1); } else { return fname + "." + ext; } } catch (Exception e) { taskController.updateLogs(e.toString()); return null; } } public static String detectCompressor(BaseTaskController taskController, File srcFile) { if (srcFile == null) { return null; } String ext = FileNameTools.ext(srcFile.getName()).toLowerCase(); return detectCompressor(taskController, srcFile, compressorByExtension(ext)); } public static String detectCompressor(BaseTaskController taskController, File srcFile, String extIn) { if (srcFile == null || "none".equals(extIn)) { return null; } String compressor = null; String ext = (extIn != null) ? extIn.toLowerCase() : null; try (BufferedInputStream fileIn = new BufferedInputStream(new FileInputStream(srcFile))) { CompressorStreamFactory cFactory = new CompressorStreamFactory(); if (ext != null && cFactory.getInputStreamCompressorNames().contains(ext)) { try (CompressorInputStream in = cFactory.createCompressorInputStream(ext, fileIn)) { compressor = ext; } catch (Exception e) { compressor = detectCompressor(taskController, fileIn, ext); } } else { compressor = detectCompressor(taskController, fileIn, ext); } } catch (Exception e) { taskController.updateLogs(e.toString()); } return compressor; } public static String detectCompressor(BaseTaskController taskController, BufferedInputStream fileIn, String extIn) { String compressor = null; try { compressor = CompressorStreamFactory.detect(fileIn); } catch (Exception ex) { if ("lz4".equals(extIn)) { try (CompressorInputStream in = new BlockLZ4CompressorInputStream(fileIn)) { compressor = "lz4-block"; } catch (Exception e) { taskController.updateLogs(message("NotCompressFormat")); } } else { taskController.updateLogs(message("NotCompressFormat")); } } return compressor; } public static Map<String, Object> decompress(BaseTaskController taskController, File srcFile, File targetFile) { String ext = FileNameTools.ext(srcFile.getName()).toLowerCase(); return CompressTools.decompress(taskController, srcFile, CompressTools.compressorByExtension(ext), targetFile); } public static Map<String, Object> decompress(BaseTaskController taskController, File srcFile, String extIn, File targetFile) { Map<String, Object> decompress = null; try { File decompressedFile = null; String compressor = null; boolean detect = false; String ext = (extIn != null) ? extIn.toLowerCase() : null; try (BufferedInputStream fileIn = new BufferedInputStream(new FileInputStream(srcFile))) { CompressorStreamFactory cFactory = new CompressorStreamFactory(); if (ext != null && cFactory.getInputStreamCompressorNames().contains(ext)) { try (CompressorInputStream in = cFactory.createCompressorInputStream(ext, fileIn)) { decompressedFile = decompress(taskController, in, targetFile); if (decompressedFile != null) { compressor = ext; detect = false; } } catch (Exception e) { // taskController.updateLogs(e.toString()); try { String defectValue = CompressorStreamFactory.detect(fileIn); try (CompressorInputStream in = cFactory.createCompressorInputStream(defectValue, fileIn)) { decompressedFile = decompress(taskController, in, targetFile); if (decompressedFile != null) { compressor = defectValue; detect = true; } } catch (Exception ex) { // taskController.updateLogs(ex.toString()); } } catch (Exception ex) { // taskController.updateLogs(ex.toString()); } } } else { try { String defectValue = CompressorStreamFactory.detect(fileIn); try (CompressorInputStream in = cFactory.createCompressorInputStream(defectValue, fileIn)) { decompressedFile = decompress(taskController, in, targetFile); if (decompressedFile != null) { compressor = defectValue; detect = true; } } catch (Exception ex) { // taskController.updateLogs(ex.toString()); } } catch (Exception ex) { // taskController.updateLogs(ex.toString()); } } } if (compressor != null && decompressedFile != null && decompressedFile.exists()) { decompress = new HashMap<>(); decompress.put("compressor", compressor); decompress.put("decompressedFile", decompressedFile); decompress.put("detect", detect); } else { taskController.updateLogs(message("NotCompressFormat")); } } catch (Exception e) { taskController.updateLogs(e.toString()); } return decompress; } public static File decompress(BaseTaskController taskController, CompressorInputStream compressorInputStream, File targetFile) { if (compressorInputStream == null) { return null; } File file = FileTmpTools.getTempFile(); try (BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file))) { IOUtils.copy(compressorInputStream, out); } catch (Exception e) { taskController.updateLogs(e.toString()); return null; } if (targetFile == null) { return file; } else if (FileTools.override(file, targetFile)) { return targetFile; } else { return null; } } public static String detectArchiver(BaseTaskController taskController, File srcFile) { if (srcFile == null) { return null; } String ext = FileNameTools.ext(srcFile.getName()).toLowerCase(); return detectArchiver(taskController, srcFile, ext); } public static String detectArchiver(BaseTaskController taskController, File srcFile, String extIn) { if (srcFile == null || "none".equals(extIn)) { return null; } String archiver = null; String ext = (extIn != null) ? extIn.toLowerCase() : null; try (BufferedInputStream fileIn = new BufferedInputStream(new FileInputStream(srcFile))) { ArchiveStreamFactory aFactory = new ArchiveStreamFactory(); if (ext != null && aFactory.getInputStreamArchiveNames().contains(ext)) { try (ArchiveInputStream in = aFactory.createArchiveInputStream(ext, fileIn)) { archiver = ext; } catch (Exception e) { try { archiver = ArchiveStreamFactory.detect(fileIn); } catch (Exception ex) { taskController.updateLogs(ex.toString()); } } } else { try { archiver = ArchiveStreamFactory.detect(fileIn); } catch (Exception ex) { taskController.updateLogs(ex.toString()); } } } catch (Exception e) { taskController.updateLogs(e.toString()); } return archiver; } public static Map<String, Object> readEntries(BaseTaskController taskController, File srcFile, String encoding) { if (srcFile == null) { return null; } String ext = FileNameTools.ext(srcFile.getName()).toLowerCase(); return readEntries(taskController, srcFile, ext, encoding); } public static Map<String, Object> readEntries(BaseTaskController taskController, File srcFile, String extIn, String encodingIn) { Map<String, Object> unarchive = new HashMap<>(); try { String encoding = (encodingIn != null) ? encodingIn : UserConfig.getString("FilesUnarchiveEncoding", Charset.defaultCharset().name()); if (srcFile == null || "none".equals(extIn) || encoding == null) { return null; } String ext = extIn; if (ArchiveStreamFactory.SEVEN_Z.equals(ext)) { return readEntries7z(taskController, srcFile, encoding); } else if (ArchiveStreamFactory.ZIP.equals(ext)) { return readEntriesZip(taskController, srcFile, encoding); } try (BufferedInputStream fileIn = new BufferedInputStream(new FileInputStream(srcFile));) { if (ext == null) { ext = ArchiveStreamFactory.detect(fileIn); } if (ext != null && !ArchiveStreamFactory.SEVEN_Z.equals(ext) && !ArchiveStreamFactory.ZIP.equals(ext)) { ArchiveStreamFactory aFactory = new ArchiveStreamFactory(); if (aFactory.getInputStreamArchiveNames().contains(ext)) { try (ArchiveInputStream in = aFactory.createArchiveInputStream(ext, fileIn, encoding)) { List<FileNode> entires = readEntries(taskController, in); if (entires != null && !entires.isEmpty()) { unarchive.put("archiver", ext); unarchive.put("entries", entires); } } catch (Exception e) { unarchive.put("error", e.toString()); taskController.updateLogs(e.toString()); } } } } catch (Exception e) { unarchive.put("error", e.toString()); taskController.updateLogs(e.toString()); } if (ext != null && unarchive.get("entries") == null) { if (ArchiveStreamFactory.SEVEN_Z.equals(ext)) { return readEntries7z(taskController, srcFile, encoding); } else if (ArchiveStreamFactory.ZIP.equals(ext)) { return readEntriesZip(taskController, srcFile, encoding); } } } catch (Exception e) { unarchive.put("error", e.toString()); taskController.updateLogs(e.toString()); } return unarchive; } public static List<FileNode> readEntries(BaseTaskController taskController, ArchiveInputStream archiveInputStream) { List<FileNode> entries = new ArrayList(); try { if (archiveInputStream == null) { return null; } ArchiveEntry entry; while ((entry = archiveInputStream.getNextEntry()) != null) { if (!archiveInputStream.canReadEntryData(entry)) { MyBoxLog.debug("Can not Read entry Data:" + entry.getName()); continue; } try { FileNode file = new FileNode().setSeparator("/"); file.setData(entry.getName()); file.setModifyTime(entry.getLastModifiedDate().getTime()); file.setFileSize(entry.getSize()); file.setFileType(entry.isDirectory() ? FileType.Directory : FileType.File); entries.add(file); } catch (Exception e) { MyBoxLog.debug(e); } } } catch (Exception e) { MyBoxLog.error(e.toString()); } return entries; } public static Map<String, Object> readEntriesZip(BaseTaskController taskController, File srcFile, String encoding) { Map<String, Object> unarchive = new HashMap<>(); try (ZipFile zipFile = ZipFile.builder().setFile(srcFile).setCharset(encoding).get()) { List<FileNode> fileEntries = new ArrayList(); Enumeration<ZipArchiveEntry> entries = zipFile.getEntries(); while (entries.hasMoreElements()) { ZipArchiveEntry entry = entries.nextElement(); FileNode file = new FileNode().setSeparator("/"); file.setData(entry.getName()); file.setModifyTime(entry.getLastModifiedDate().getTime()); file.setFileSize(entry.getSize()); file.setFileType(entry.isDirectory() ? FileType.Directory : FileType.File); fileEntries.add(file); } unarchive.put("archiver", ArchiveStreamFactory.ZIP); unarchive.put("entries", fileEntries); } catch (Exception e) { unarchive.put("error", e.toString()); } return unarchive; } public static Map<String, Object> readEntries7z(BaseTaskController taskController, File srcFile, String encoding) { Map<String, Object> unarchive = new HashMap<>(); try (SevenZFile sevenZFile = SevenZFile.builder().setFile(srcFile).get()) { SevenZArchiveEntry entry; List<FileNode> entries = new ArrayList(); while ((entry = sevenZFile.getNextEntry()) != null) { FileNode file = new FileNode().setSeparator("/"); file.setData(entry.getName()); file.setModifyTime(entry.getLastModifiedDate().getTime()); file.setFileSize(entry.getSize()); file.setFileType(entry.isDirectory() ? FileType.Directory : FileType.File); entries.add(file); } unarchive.put("archiver", ArchiveStreamFactory.SEVEN_Z); unarchive.put("entries", entries); } catch (Exception e) { unarchive.put("error", e.toString()); } return unarchive; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/tools/ScheduleTools.java
alpha/MyBox/src/main/java/mara/mybox/tools/ScheduleTools.java
package mara.mybox.tools; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; /** * @Author Mara * @CreateDate 2022-11-2 * @License Apache License Version 2.0 */ public class ScheduleTools { public final static ScheduledExecutorService service = Executors.newScheduledThreadPool(2); }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/tools/UrlTools.java
alpha/MyBox/src/main/java/mara/mybox/tools/UrlTools.java
package mara.mybox.tools; import java.io.File; import java.net.URI; import java.net.URL; import java.net.URLDecoder; import java.net.URLEncoder; import java.nio.charset.Charset; import mara.mybox.dev.MyBoxLog; /** * @Author Mara * @CreateDate 2021-8-1 * @License Apache License Version 2.0 */ public class UrlTools { public static URL url(String address) { try { // some address may pop syntax error when run new URI(address).toURL() // So still use the deprecated api return new URL(address); } catch (Exception e) { return null; } } public static URL url(URL base, String address) { try { return new URL(base, address); } catch (Exception e) { return null; } } public static String checkURL(String value, Charset charset) { try { if (value == null || value.isBlank()) { return null; } String address = value; String addressS = address.toLowerCase(); if (addressS.startsWith("file:/") || addressS.startsWith("http://") || addressS.startsWith("https://")) { } else if (address.startsWith("//")) { address = "http:" + value; } else { File file = new File(address); if (file.exists()) { address = file.toURI().toString(); } else { address = "https://" + value; } } address = decodeURL(address, charset); return address; } catch (Exception e) { MyBoxLog.debug(e); return value; } } public static String decodeURL(String value, Charset charset) { try { if (value == null) { return null; } return URLDecoder.decode(value, charset); } catch (Exception e) { MyBoxLog.debug(e); return value; } } public static String decodeURL(File file, Charset charset) { try { if (file == null) { return null; } return decodeURL(file.toURI().toString(), charset); } catch (Exception e) { MyBoxLog.debug(e); return null; } } public static String encodeURL(String value, Charset charset) { try { if (value == null) { return null; } return URLEncoder.encode(value, charset); } catch (Exception e) { MyBoxLog.debug(e); return value; } } public static String encodeURL(File file, Charset charset) { try { if (file == null) { return null; } return encodeURL(file.toURI().toString(), charset); } catch (Exception e) { MyBoxLog.debug(e); return null; } } public static String fullAddress(String baseAddress, String address) { try { URL baseUrl = UrlTools.url(baseAddress); if (baseUrl == null) { return address; } URL url = fullUrl(baseUrl, address); return url.toString(); } catch (Exception e) { // MyBoxLog.debug(e); return address; } } public static URL fullUrl(URL baseURL, String address) { URL url = UrlTools.url(baseURL, address); if (url != null) { return url; } return UrlTools.url(address); } public static String filePrefix(URL url) { if (url == null) { return ""; } String file = file(url); if (file == null) { return ""; } int pos = file.lastIndexOf("."); file = pos < 0 ? file : file.substring(0, pos); return file; } public static URI uri(String address) { try { URI u; if (address.startsWith("file:")) { u = new URI(address); } else if (!address.startsWith("http")) { u = new URI("http://" + address); } else { u = new URI(address); } return u; } catch (Exception e) { // MyBoxLog.error(e.toString()); return null; } } public static String path(URL url) { if (url == null) { return null; } String urlPath = url.getPath(); int pos = urlPath.lastIndexOf("/"); String path = pos < 0 ? "" : urlPath.substring(0, pos + 1); return path; } public static String fullPath(URL url) { if (url == null) { return null; } String fullPath = url.getProtocol() + "://" + url.getHost() + path(url); return fullPath; } public static String fullPath(String address) { try { URL url = UrlTools.url(address); if (url == null) { return address; } String path = fullPath(url); return path == null ? address : path; } catch (Exception e) { return address; } } public static String fileSuffix(URL url) { if (url == null) { return ""; } String name = file(url); if (name == null) { return ""; } int pos = name.lastIndexOf("."); name = pos < 0 ? "" : name.substring(pos); return name; } public static String file(URL url) { if (url == null) { return null; } try { String urlPath = url.getPath(); int pos = urlPath.lastIndexOf("/"); if (pos >= 0) { return pos < urlPath.length() - 1 ? urlPath.substring(pos + 1) : null; } else { return urlPath; } } catch (Exception e) { return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/tools/JShellTools.java
alpha/MyBox/src/main/java/mara/mybox/tools/JShellTools.java
package mara.mybox.tools; import java.util.List; import jdk.jshell.JShell; import jdk.jshell.SnippetEvent; import jdk.jshell.SourceCodeAnalysis; import mara.mybox.data.JShellSnippet; import mara.mybox.dev.MyBoxLog; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2022-6-1 * @License Apache License Version 2.0 */ public class JShellTools { public static String runSnippet(JShell jShell, String orignalSource, String source) { try { if (source == null || source.isBlank()) { return source; } String snippet = source.trim(); List<SnippetEvent> events = jShell.eval(snippet); String results = ""; for (int i = 0; i < events.size(); i++) { SnippetEvent e = events.get(i); JShellSnippet jShellSnippet = new JShellSnippet(jShell, e.snippet()); if (i > 0) { results += "\n"; } results += "id: " + jShellSnippet.getId() + "\n"; if (jShellSnippet.getStatus() != null) { results += message("Status") + ": " + jShellSnippet.getStatus() + "\n"; } if (jShellSnippet.getType() != null) { results += message("Type") + ": " + jShellSnippet.getType() + "\n"; } if (jShellSnippet.getName() != null) { results += message("Name") + ": " + jShellSnippet.getName() + "\n"; } if (jShellSnippet.getValue() != null) { results += message("Value") + ": " + jShellSnippet.getValue() + "\n"; } } return results; } catch (Exception e) { return e.toString(); } } public static String runSnippet(JShell jShell, String source) { return runSnippet(jShell, source, source); } public static boolean runScript(JShell jShell, String script) { try { if (script == null || script.isBlank()) { return false; } String leftCodes = script; while (leftCodes != null && !leftCodes.isBlank()) { SourceCodeAnalysis.CompletionInfo info = jShell.sourceCodeAnalysis().analyzeCompletion(leftCodes); String snippet = info.source().trim(); jShell.eval(snippet); leftCodes = info.remaining(); } return true; } catch (Exception e) { MyBoxLog.error(e); return false; } } public static String expValue(JShell jShell, String exp) { try { return new JShellSnippet(jShell, jShell.eval(exp).get(0).snippet()).getValue(); } catch (Exception e) { MyBoxLog.error(e, exp); return null; } } public static String classPath(JShell jShell) { try { String paths = expValue(jShell, "System.getProperty(\"java.class.path\")"); if (paths.startsWith("\"") && paths.endsWith("\"")) { paths = paths.substring(1, paths.length() - 1); } return paths; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static JShell initWithClassPath() { try { JShell jShell = JShell.create(); jShell.addToClasspath(System.getProperty("java.class.path")); return jShell; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static JShell initJEXL() { try { JShell jShell = JShell.create(); jShell.addToClasspath(System.getProperty("java.class.path")); String initCodes = "import org.apache.commons.jexl3.JexlBuilder;\n" + "import org.apache.commons.jexl3.JexlEngine;\n" + "import org.apache.commons.jexl3.JexlScript;\n" + "import org.apache.commons.jexl3.MapContext;\n" + "JexlEngine jexlEngine = new JexlBuilder().cache(512).strict(true).silent(false).create();\n" + "MapContext jexlContext = new MapContext();" + "JexlScript jexlScript;"; runScript(jShell, initCodes); return jShell; } catch (Exception e) { MyBoxLog.error(e); return null; } } // public static void clearSnippets(JShell jShell) { // try { // jShell.snippets().dropWhile(predicate) // return new JShellSnippet(jShell, jShell.eval(exp).get(0).snippet()).getValue(); // } catch (Exception e) { // MyBoxLog.error(e, exp); // return null; // } // } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/image/tools/ColorBlendTools.java
alpha/MyBox/src/main/java/mara/mybox/image/tools/ColorBlendTools.java
package mara.mybox.image.tools; import java.awt.Color; /** * @Author Mara * @CreateDate 2018-6-4 16:07:27 * @License Apache License Version 2.0 */ public class ColorBlendTools { // https://www.cnblogs.com/xiaonanxia/p/9448444.html public static Color blendColor(Color foreColor, float opacity, Color backColor, boolean keepAlpha) { int red = (int) (foreColor.getRed() * opacity + backColor.getRed() * (1.0f - opacity)); int green = (int) (foreColor.getGreen() * opacity + backColor.getGreen() * (1.0f - opacity)); int blue = (int) (foreColor.getBlue() * opacity + backColor.getBlue() * (1.0f - opacity)); int alpha = keepAlpha ? (int) (foreColor.getAlpha() * opacity + backColor.getAlpha() * (1.0f - opacity)) : 255; return new Color( Math.min(Math.max(red, 0), 255), Math.min(Math.max(green, 0), 255), Math.min(Math.max(blue, 0), 255), Math.min(Math.max(alpha, 0), 255)); } public static Color blendColor(Color color, int opocity, Color bgColor, boolean keepAlpha) { return blendColor(color, opocity / 255.0F, bgColor, keepAlpha); } public static Color blendColor(Color color, float opocity, Color bgColor) { return blendColor(color, opocity, bgColor, false); } public static int blendPixel(int forePixel, int backPixel, float opacity, boolean orderReversed, boolean ignoreTransparency) { if (ignoreTransparency && forePixel == 0) { return backPixel; } if (ignoreTransparency && backPixel == 0) { return forePixel; } Color foreColor, backColor; if (orderReversed) { foreColor = new Color(backPixel, true); backColor = new Color(forePixel, true); } else { foreColor = new Color(forePixel, true); backColor = new Color(backPixel, true); } Color newColor = blendColor(foreColor, opacity, backColor, true); return newColor.getRGB(); } public static int blendPixel(int forePixel, int backPixel, float opacity) { return blendPixel(forePixel, backPixel, opacity, false, false); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/image/tools/ColorMatchTools.java
alpha/MyBox/src/main/java/mara/mybox/image/tools/ColorMatchTools.java
package mara.mybox.image.tools; import java.awt.Color; /** * @Author Mara * @CreateDate 2018-6-4 16:07:27 * @License Apache License Version 2.0 */ public class ColorMatchTools { // distanceSquare = Math.pow(distance, 2) public static boolean isColorMatchSquare2(Color color1, Color color2, int distanceSquare) { if (color1 == null || color2 == null) { return false; } if (color1.getRGB() == color2.getRGB()) { return true; } else if (distanceSquare == 0 || color1.getRGB() == 0 || color2.getRGB() == 0) { return false; } return calculateColorDistanceSquare2(color1, color2) <= distanceSquare; } // https://en.wikipedia.org/wiki/Color_difference public static int calculateColorDistanceSquare2(Color color1, Color color2) { if (color1 == null || color2 == null) { return Integer.MAX_VALUE; } int redDiff = color1.getRed() - color2.getRed(); int greenDiff = color1.getGreen() - color2.getGreen(); int blueDiff = color1.getBlue() - color2.getBlue(); return 2 * redDiff * redDiff + 4 * greenDiff * greenDiff + 3 * blueDiff * blueDiff; } // Generally not use this value. Use distance square instead. public static int calculateColorDistance2(Color color1, Color color2) { if (color1 == null || color2 == null) { return Integer.MAX_VALUE; } int v = calculateColorDistanceSquare2(color1, color2); return (int) Math.round(Math.sqrt(v)); } // distance: 0-255 }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/image/tools/ShapeTools.java
alpha/MyBox/src/main/java/mara/mybox/image/tools/ShapeTools.java
package mara.mybox.image.tools; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Polygon; import java.awt.Rectangle; import java.awt.Shape; import java.awt.geom.Path2D; import java.awt.image.BufferedImage; import java.util.List; import java.util.Random; import javafx.scene.shape.Line; import mara.mybox.data.DoublePoint; import mara.mybox.data.DoublePolylines; import mara.mybox.data.DoubleShape; import mara.mybox.data.ShapeStyle; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.image.data.ImageMosaic; import mara.mybox.image.data.PixelsBlend; import mara.mybox.value.AppVariables; /** * @Author Mara * @CreateDate 2018-6-27 18:58:57 * @License Apache License Version 2.0 */ public class ShapeTools { public static BasicStroke stroke(ShapeStyle style) { if (style == null) { return new BasicStroke(); } else { return new BasicStroke(style.getStrokeWidth(), style.getStrokeLineCapAwt(), style.getStrokeLineJoinAwt(), style.getStrokeLineLimit(), style.isIsStrokeDash() ? style.getStrokeDashAwt() : null, 0.0F); } } public static BufferedImage drawShape(FxTask task, BufferedImage srcImage, DoubleShape doubleShape, ShapeStyle style, PixelsBlend blender) { try { if (srcImage == null || doubleShape == null || doubleShape.isEmpty() || style == null || blender == null) { return srcImage; } float strokeWidth = style.getStrokeWidth(); boolean showStroke = strokeWidth > 0; boolean fill = style.isIsFillColor(); if (!fill && !showStroke) { return srcImage; } int width = srcImage.getWidth(); int height = srcImage.getHeight(); int imageType = BufferedImage.TYPE_INT_ARGB; Color strokeColor = Color.WHITE; Color fillColor = Color.BLACK; Color backgroundColor = Color.RED; BufferedImage shapeImage = new BufferedImage(width, height, imageType); Graphics2D g = shapeImage.createGraphics(); if (AppVariables.ImageHints != null) { g.addRenderingHints(AppVariables.ImageHints); } g.setStroke(stroke(style)); g.setBackground(backgroundColor); Shape shape = doubleShape.getShape(); if (fill) { g.setColor(fillColor); g.fill(shape); } if (showStroke) { g.setColor(strokeColor); g.draw(shape); } g.dispose(); if (task != null && !task.isWorking()) { return null; } BufferedImage target = new BufferedImage(width, height, imageType); int strokePixel = strokeColor.getRGB(); int fillPixel = fillColor.getRGB(); int realStrokePixel = style.getStrokeColorAwt().getRGB(); int realFillPixel = style.getFillColorAwt().getRGB(); for (int j = 0; j < height; ++j) { if (task != null && !task.isWorking()) { return null; } for (int i = 0; i < width; ++i) { if (task != null && !task.isWorking()) { return null; } int srcPixel = srcImage.getRGB(i, j); int shapePixel = shapeImage.getRGB(i, j); if (shapePixel == strokePixel) { target.setRGB(i, j, blender.blend(realStrokePixel, srcPixel)); } else if (shapePixel == fillPixel) { target.setRGB(i, j, blender.blend(realFillPixel, srcPixel)); } else { target.setRGB(i, j, srcPixel); } } } return target; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static BufferedImage drawErase(FxTask task, BufferedImage srcImage, DoublePolylines linesData, ShapeStyle style) { try { if (linesData == null || linesData.getLinesSize() == 0 || style == null) { return srcImage; } int width = srcImage.getWidth(); int height = srcImage.getHeight(); int imageType = BufferedImage.TYPE_INT_ARGB; BufferedImage linesImage = new BufferedImage(width, height, imageType); Graphics2D linesg = linesImage.createGraphics(); if (AppVariables.ImageHints != null) { linesg.addRenderingHints(AppVariables.ImageHints); } linesg.setStroke(stroke(style)); linesg.setBackground(Color.WHITE); linesg.setColor(Color.BLACK); for (List<DoublePoint> line : linesData.getLines()) { if (task != null && !task.isWorking()) { return null; } Path2D.Double path = new Path2D.Double(); DoublePoint p = line.get(0); path.moveTo(p.getX(), p.getY()); for (int i = 1; i < line.size(); i++) { p = line.get(i); path.lineTo(p.getX(), p.getY()); } linesg.draw(path); } if (task != null && !task.isWorking()) { return null; } linesg.dispose(); BufferedImage target = new BufferedImage(width, height, imageType); int black = Color.BLACK.getRGB(); for (int j = 0; j < height; ++j) { if (task != null && !task.isWorking()) { return null; } for (int i = 0; i < width; ++i) { if (task != null && !task.isWorking()) { return null; } if (linesImage.getRGB(i, j) == black) { target.setRGB(i, j, 0); } else { target.setRGB(i, j, srcImage.getRGB(i, j)); } } } return target; } catch (Exception e) { MyBoxLog.error(e); return srcImage; } } public static boolean inLine(Line line, int x, int y) { double d = (x - line.getStartX()) * (line.getStartY() - line.getEndY()) - ((line.getStartX() - line.getEndX()) * (y - line.getStartY())); return Math.abs(d) < 1.0E-4 && (x >= Math.min(line.getStartX(), line.getEndX()) && x <= Math.max(line.getStartX(), line.getEndX())) && (y >= Math.min(line.getStartY(), line.getEndY())) && (y <= Math.max(line.getStartY(), line.getEndY())); } public static int mosaic(BufferedImage source, int imageWidth, int imageHeight, int x, int y, ImageMosaic.MosaicType type, int intensity) { int newColor; if (type == ImageMosaic.MosaicType.Mosaic) { int mx = Math.max(0, Math.min(imageWidth - 1, x - x % intensity)); int my = Math.max(0, Math.min(imageHeight - 1, y - y % intensity)); newColor = source.getRGB(mx, my); } else { int fx = Math.max(0, Math.min(imageWidth - 1, x - new Random().nextInt(intensity))); int fy = Math.max(0, Math.min(imageHeight - 1, y - new Random().nextInt(intensity))); newColor = source.getRGB(fx, fy); } return newColor; } public static BufferedImage drawMosaic(FxTask task, BufferedImage source, DoublePolylines linesData, ImageMosaic.MosaicType mosaicType, int strokeWidth, int intensity) { try { if (linesData == null || mosaicType == null || linesData.getLinesSize() == 0 || strokeWidth < 1 || intensity < 1) { return source; } int width = source.getWidth(); int height = source.getHeight(); int imageType = BufferedImage.TYPE_INT_ARGB; BufferedImage target = new BufferedImage(width, height, imageType); Graphics2D gt = target.createGraphics(); if (AppVariables.ImageHints != null) { gt.addRenderingHints(AppVariables.ImageHints); } gt.drawImage(source, 0, 0, width, height, null); gt.dispose(); if (task != null && !task.isWorking()) { return null; } int pixel; int w = strokeWidth / 2; for (Line line : linesData.getLineList()) { if (task != null && !task.isWorking()) { return null; } int x1 = Math.min(width, Math.max(0, (int) line.getStartX())); int y1 = Math.min(height, Math.max(0, (int) line.getStartY())); int x2 = Math.min(width, Math.max(0, (int) line.getEndX())); int y2 = Math.min(height, Math.max(0, (int) line.getEndY())); Polygon polygon = new Polygon(); polygon.addPoint(x1 - w, y1); polygon.addPoint(x1, y1 - w); polygon.addPoint(x1 + w, y1); polygon.addPoint(x2 - w, y2); polygon.addPoint(x2, y2 + w); polygon.addPoint(x2 + w, y2); Rectangle rect = polygon.getBounds(); int bx = (int) rect.getX(); int by = (int) rect.getY(); int bw = (int) rect.getWidth(); int bh = (int) rect.getHeight(); for (int x = bx; x < bx + bw; x++) { if (task != null && !task.isWorking()) { return null; } for (int y = by; y < by + bh; y++) { if (task != null && !task.isWorking()) { return null; } if (polygon.contains(x, y)) { pixel = mosaic(source, width, height, x, y, mosaicType, intensity); target.setRGB(x, y, pixel); } } } } return target; } catch (Exception e) { MyBoxLog.error(e); return source; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/image/tools/ColorComponentTools.java
alpha/MyBox/src/main/java/mara/mybox/image/tools/ColorComponentTools.java
package mara.mybox.image.tools; import java.awt.Color; import java.util.HashMap; import java.util.Map; import mara.mybox.value.Languages; /** * @Author Mara * @CreateDate 2018-6-4 16:07:27 * @License Apache License Version 2.0 */ public class ColorComponentTools { public static enum ColorComponent { Gray, RedChannel, GreenChannel, BlueChannel, Hue, Saturation, Brightness, AlphaChannel } public static Map<ColorComponent, Color> ComponentColor; public static Color color(ColorComponent c) { if (ComponentColor == null) { ComponentColor = new HashMap<>(); ComponentColor.put(ColorComponent.RedChannel, Color.RED); ComponentColor.put(ColorComponent.GreenChannel, Color.GREEN); ComponentColor.put(ColorComponent.BlueChannel, Color.BLUE); ComponentColor.put(ColorComponent.Hue, Color.PINK); ComponentColor.put(ColorComponent.Brightness, Color.ORANGE); ComponentColor.put(ColorComponent.Saturation, Color.CYAN); ComponentColor.put(ColorComponent.AlphaChannel, Color.YELLOW); ComponentColor.put(ColorComponent.Gray, Color.GRAY); } if (c == null) { return null; } return ComponentColor.get(c); } public static Color color(ColorComponent component, int value) { switch (component) { case RedChannel: return new Color(value, 0, 0, 255); case GreenChannel: return new Color(0, value, 0, 255); case BlueChannel: return new Color(0, 0, value, 255); case AlphaChannel: Color aColor = ColorComponentTools.color(component); return new Color(aColor.getRed(), aColor.getGreen(), aColor.getBlue(), value); case Gray: return new Color(value, value, value, 255); case Hue: return ColorConvertTools.hsb2rgb(value / 360.0F, 1.0F, 1.0F); case Saturation: float h1 = ColorConvertTools.getHue(ColorComponentTools.color(component)); return ColorConvertTools.hsb2rgb(h1, value / 100.0F, 1.0F); case Brightness: float h2 = ColorConvertTools.getHue(ColorComponentTools.color(component)); return ColorConvertTools.hsb2rgb(h2, 1.0F, value / 100.0F); } return null; } public static float percentage(ColorComponent component, int value) { switch (component) { case RedChannel: case GreenChannel: case BlueChannel: case AlphaChannel: case Gray: return value / 255f; case Hue: return value / 360f; case Saturation: case Brightness: return value / 100f; } return 0; } public static Color color(String name, int index) { return color(ColorComponentTools.component(name), index); } public static Color componentColor(String name) { return color(component(name)); } public static ColorComponent component(String name) { for (ColorComponent c : ColorComponent.values()) { if (c.name().equals(name) || Languages.message(c.name()).equals(name)) { return c; } } return null; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/image/tools/TransformTools.java
alpha/MyBox/src/main/java/mara/mybox/image/tools/TransformTools.java
package mara.mybox.image.tools; import java.awt.Color; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.value.AppVariables; import mara.mybox.value.Colors; /** * @Author Mara * @CreateDate 2018-6-27 18:58:57 * @License Apache License Version 2.0 */ public class TransformTools { public static BufferedImage rotateImage(FxTask task, BufferedImage source, int inAngle, boolean cutMargins) { int angle = inAngle % 360; if (angle == 0) { return source; } if (angle < 0) { angle = 360 + angle; } double radians = Math.toRadians(angle); double cos = Math.abs(Math.cos(radians)); double sin = Math.abs(Math.sin(radians)); int width = source.getWidth(); int height = source.getHeight(); int newWidth = (int) (width * cos + height * sin) + 2; int newHeight = (int) (height * cos + width * sin) + 2; int imageType = BufferedImage.TYPE_INT_ARGB; BufferedImage target = new BufferedImage(newWidth, newHeight, imageType); Graphics2D g = target.createGraphics(); if (AppVariables.ImageHints != null) { g.addRenderingHints(AppVariables.ImageHints); } Color bgColor = Colors.TRANSPARENT; g.setBackground(bgColor); g.translate((newWidth - width) / 2, (newHeight - height) / 2); if (task != null && !task.isWorking()) { return null; } g.rotate(radians, width / 2, height / 2); if (task != null && !task.isWorking()) { return null; } g.drawImage(source, null, null); g.dispose(); if (cutMargins) { target = MarginTools.cutMarginsByColor(task, target, bgColor, true, true, true, true); } return target; } public static BufferedImage shearImage(FxTask task, BufferedImage source, float shearX, float shearY, boolean cutMargins) { try { int width = source.getWidth(); int height = source.getHeight(); int offsetX = (int) (height * Math.abs(shearX)) + 1; int newWidth = width + offsetX + 1; if (shearX >= 0) { offsetX = 0; } int offsetY = (int) (width * Math.abs(shearY)) + 1; int newHeight = height + offsetY + 1; if (shearY >= 0) { offsetY = 0; } int imageType = BufferedImage.TYPE_INT_ARGB; BufferedImage target = new BufferedImage(newWidth, newHeight, imageType); Graphics2D g = target.createGraphics(); if (AppVariables.ImageHints != null) { g.addRenderingHints(AppVariables.ImageHints); } Color bgColor = Colors.TRANSPARENT; g.setBackground(bgColor); g.translate(offsetX, offsetY); g.shear(shearX, shearY); if (task != null && !task.isWorking()) { return null; } g.drawImage(source, null, null); if (task != null && !task.isWorking()) { return null; } g.dispose(); if (cutMargins) { target = MarginTools.cutMarginsByColor(task, target, bgColor, true, true, true, true); } return target; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static BufferedImage horizontalMirrorImage(FxTask task, BufferedImage source) { try { int width = source.getWidth(); int height = source.getHeight(); int imageType = BufferedImage.TYPE_INT_ARGB; BufferedImage target = new BufferedImage(width, height, imageType); 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; } int pl = source.getRGB(l, j); int pr = source.getRGB(r, j); target.setRGB(l, j, pr); target.setRGB(r, j, pl); l++; r--; } } return target; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static BufferedImage verticalMirrorImage(FxTask task, BufferedImage source) { try { int width = source.getWidth(); int height = source.getHeight(); int imageType = BufferedImage.TYPE_INT_ARGB; BufferedImage target = new BufferedImage(width, height, imageType); 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; } int pt = source.getRGB(i, t); int pb = source.getRGB(i, b); target.setRGB(i, t, pb); target.setRGB(i, b, pt); t++; b--; } } return target; } catch (Exception e) { MyBoxLog.error(e); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/image/tools/ColorConvertTools.java
alpha/MyBox/src/main/java/mara/mybox/image/tools/ColorConvertTools.java
package mara.mybox.image.tools; import java.awt.Color; import mara.mybox.db.data.ColorData; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2018-6-4 16:07:27 * @License Apache License Version 2.0 */ public class ColorConvertTools { /* rgba */ public static Color pixel2rgba(int pixel) { return new Color(pixel, true); } public static Color rgba2color(String rgba) { javafx.scene.paint.Color c = javafx.scene.paint.Color.web(rgba); return converColor(c); } public static int rgba2Pixel(int r, int g, int b, int a) { return color2Pixel(new Color(r, g, b, a)); } public static int color2Pixel(Color color) { if (color == null) { return 0; } return color.getRGB(); } public static int setAlpha(int pixel, int a) { Color c = new Color(pixel); return new Color(c.getRed(), c.getGreen(), c.getBlue(), a).getRGB(); } public static String color2css(Color color) { return "rgba(" + color.getRed() + "," + color.getGreen() + "," + color.getBlue() + "," + color.getTransparency() + ")"; } /* rgb */ public static Color rgb(Color color) { return new Color(color.getRed(), color.getGreen(), color.getBlue()); } public static Color pixel2rgb(int pixel) { return new Color(pixel); } public static int rgb2Pixel(int r, int g, int b) { return rgba2Pixel(r, g, b, 255); } /* hsb */ public static float[] color2hsb(Color color) { if (color == null) { return null; } return Color.RGBtoHSB(color.getRed(), color.getGreen(), color.getBlue(), null); } public static float[] pixel2hsb(int pixel) { Color rgb = pixel2rgba(pixel); return Color.RGBtoHSB(rgb.getRed(), rgb.getGreen(), rgb.getBlue(), null); } public static Color hsb2rgb(float h, float s, float b) { return new Color(Color.HSBtoRGB(h, s, b)); } // 0.0-1.0 public static float getHue(Color color) { if (color == null) { return 0; } float[] hsb = Color.RGBtoHSB(color.getRed(), color.getGreen(), color.getBlue(), null); return hsb[0]; } // 0.0-1.0 public static float getBrightness(Color color) { if (color == null) { return 0; } float[] hsb = Color.RGBtoHSB(color.getRed(), color.getGreen(), color.getBlue(), null); return hsb[2]; } public static float getBrightness(int pixel) { Color color = new Color(pixel); float[] hsb = Color.RGBtoHSB(color.getRed(), color.getGreen(), color.getBlue(), null); return hsb[2]; } // 0.0-1.0 public static float getSaturation(Color color) { if (color == null) { return 0; } float[] hsb = Color.RGBtoHSB(color.getRed(), color.getGreen(), color.getBlue(), null); return hsb[1]; } /* grey */ public static Color color2gray(Color color) { if (color == null) { return null; } int gray = color2grayValue(color); return new Color(gray, gray, gray, color.getAlpha()); } public static int color2grayValue(Color color) { if (color == null) { return 0; } return rgb2grayValue(color.getRed(), color.getGreen(), color.getBlue()); } public static int rgba2grayPixel(int r, int g, int b, int a) { int gray = rgb2grayValue(r, g, b); return rgba2Pixel(gray, gray, gray, a); } // https://en.wikipedia.org/wiki/HSL_and_HSV#Lightness // https://en.wikipedia.org/wiki/Grayscale // Simplest:I = ( R + G + B ) / 3 // PAL和NTSC(Video) Y'UV and Y'IQ primaries Rec.601 : Y ′ = 0.299 R ′ + 0.587 G ′ + 0.114 B ′ // HDTV(High Definiton TV) ITU-R primaries Rec.709: Y ′ = 0.2126 R ′ + 0.7152 G ′ + 0.0722 B ′ // JDK internal: javafx.scene.paint.Color.grayscale() = 0.21 * red + 0.71 * green + 0.07 * blue public static int rgb2grayValue(int r, int g, int b) { int gray = (2126 * r + 7152 * g + 722 * b) / 10000; return gray; } public static int pixel2GrayPixel(int pixel) { Color c = pixel2rgb(pixel); return rgba2grayPixel(c.getRed(), c.getGreen(), c.getBlue(), c.getAlpha()); } public static int pixel2grayValue(int pixel) { Color c = new Color(pixel); return rgb2grayValue(c.getRed(), c.getGreen(), c.getBlue()); } /* others */ public static javafx.scene.paint.Color converColor(Color color) { return new javafx.scene.paint.Color(color.getRed() / 255.0, color.getGreen() / 255.0, color.getBlue() / 255.0, color.getAlpha() / 255.0); } public static Color converColor(javafx.scene.paint.Color color) { return new Color((int) (color.getRed() * 255), (int) (color.getGreen() * 255), (int) (color.getBlue() * 255), (int) (color.getOpacity() * 255)); } // https://stackoverflow.com/questions/21899824/java-convert-a-greyscale-and-sepia-version-of-an-image-with-bufferedimage/21900125#21900125 public static Color pixel2Sepia(int pixel, int sepiaIntensity) { return pixel2Sepia(pixel2rgb(pixel), sepiaIntensity); } public static Color pixel2Sepia(Color color, int sepiaIntensity) { int sepiaDepth = 20; int gray = color2grayValue(color); int r = gray; int g = gray; int b = gray; r = Math.min(r + (sepiaDepth * 2), 255); g = Math.min(g + sepiaDepth, 255); b = Math.min(Math.max(b - sepiaIntensity, 0), 255); Color newColor = new Color(r, g, b, color.getAlpha()); return newColor; } public static String pixel2hex(int pixel) { Color c = new Color(pixel); return String.format("#%02X%02X%02X", c.getRed(), c.getGreen(), c.getBlue()); } public static float[] color2srgb(Color color) { if (color == null) { return null; } float[] srgb = new float[3]; srgb[0] = color.getRed() / 255.0F; srgb[1] = color.getGreen() / 255.0F; srgb[2] = color.getBlue() / 255.0F; return srgb; } public static Color alphaColor() { return converColor(UserConfig.alphaColor()); } public static Color thresholdingColor(Color inColor, int threshold, int smallValue, int bigValue) { int red; int green; int blue; if (inColor.getRed() < threshold) { red = smallValue; } else { red = bigValue; } if (inColor.getGreen() < threshold) { green = smallValue; } else { green = bigValue; } if (inColor.getBlue() < threshold) { blue = smallValue; } else { blue = bigValue; } Color newColor = new Color(red, green, blue, inColor.getAlpha()); return newColor; } public static Color scaleSaturate(Color color, float scale) { float[] hsb = Color.RGBtoHSB(color.getRed(), color.getGreen(), color.getBlue(), null); return Color.getHSBColor(hsb[0], hsb[1] * scale, hsb[2]); } // https://blog.csdn.net/weixin_44938037/article/details/90599711 public static Color ryb2rgb(float angle) { float hue = ryb2hue(angle); float brightness = ryb2brightness(angle); return Color.getHSBColor(hue / 360, 1, brightness / 100); } public static Color rybComplementary(ColorData data) { if (data == null) { return null; } javafx.scene.paint.Color originalColor = data.getColor(); if (originalColor == null) { return null; } float colorRyb = data.getRyb(); if (colorRyb < 0) { return null; } float complementaryRyb = colorRyb + 180; float complementaryHue = ryb2hue(complementaryRyb) / 360; float complementaryRybBrightness = ryb2brightness(complementaryRyb); float colorRybBrightness = ryb2brightness(colorRyb); float colorBrightness = (float) data.getColor().getBrightness(); float complementaryBrightness = Math.min(1f, complementaryRybBrightness * colorBrightness / colorRybBrightness); Color c = Color.getHSBColor(complementaryHue, (float) originalColor.getSaturation(), complementaryBrightness); return new Color(c.getRed(), c.getGreen(), c.getBlue(), (int) (originalColor.getOpacity() * 255)); } public static float ryb2hue(float angle) { float a = angle % 360; float hue; if (a < 30) { hue = 2 * a / 3; } else if (a < 90) { hue = a / 3 + 10; } else if (a < 120) { hue = 2 * a / 3 - 20; } else if (a < 180) { hue = a - 60; } else if (a < 210) { hue = 2 * a - 240; } else if (a < 270) { hue = a - 30; } else if (a < 300) { hue = 2 * a - 300; } else { hue = a; } return hue; } // b = maxB - (maxB -minB) * (a - minA)/(maxA - minA) // b = minB + (maxB -minB) * (a - minA) /(maxA - minA) public static float ryb2brightness(float angle) { float a = angle % 360; float b; if (a <= 13) { b = 100 - 10 * a / 13; } else if (a <= 60) { b = 90 + 10 * (a - 13) / 47; } else if (a <= 120) { b = 100; } else if (a <= 180) { b = 100 - 5 * (a - 120) / 6; } else if (a <= 240) { b = 50 + 5 * (a - 180) / 6; } else if (a <= 300) { b = 100 - 5 * (a - 240) / 6; } else { b = 50 + 5 * (a - 300) / 6; } return b; } public static float hue2ryb(double hue) { return hue2ryb((float) hue); } public static float hue2ryb(float hue) { float h = hue % 360; float a; if (h < 20) { a = 1.5f * h; } else if (h < 40) { a = 3 * h - 30; } else if (h < 60) { a = 1.5f * h + 30; } else if (h < 120) { a = h + 60; } else if (h < 180) { a = h / 2 + 120; } else if (h < 240) { a = h + 30; } else if (h < 300) { a = h / 2 + 150; } else { a = h; } return a; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/image/tools/ImageScopeTools.java
alpha/MyBox/src/main/java/mara/mybox/image/tools/ImageScopeTools.java
package mara.mybox.image.tools; import java.awt.Color; import java.awt.image.BufferedImage; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.Random; import javafx.embed.swing.SwingFXUtils; import javafx.scene.image.Image; import mara.mybox.controller.BaseController; import mara.mybox.data.DoubleCircle; import mara.mybox.data.DoubleEllipse; import mara.mybox.data.DoublePolygon; import mara.mybox.data.DoubleRectangle; import mara.mybox.data.DoubleShape; import mara.mybox.data.ImageItem; import mara.mybox.data.IntPoint; import mara.mybox.data.StringTable; import mara.mybox.db.data.DataNode; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.fxml.image.FxImageTools; import mara.mybox.fxml.image.ScopeTools; import mara.mybox.image.data.ImageScope; import mara.mybox.image.data.ImageScope.ShapeType; import static mara.mybox.image.data.ImageScope.ShapeType.Matting4; import mara.mybox.image.file.ImageFileWriters; import mara.mybox.tools.HtmlWriteTools; import mara.mybox.value.AppPaths; import mara.mybox.value.InternalImages; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2018-8-1 16:22:41 * @License Apache License Version 2.0 */ public class ImageScopeTools { public static void cloneValues(ImageScope targetScope, ImageScope sourceScope) { try { targetScope.setBackground(sourceScope.getBackground()); targetScope.setName(sourceScope.getName()); targetScope.setShapeData(sourceScope.getShapeData()); targetScope.setColorData(sourceScope.getColorData()); targetScope.setOutlineName(sourceScope.getOutlineName()); List<IntPoint> npoints = new ArrayList<>(); if (sourceScope.getPoints() != null) { npoints.addAll(sourceScope.getPoints()); } targetScope.setPoints(npoints); targetScope.setRectangle(sourceScope.getRectangle() != null ? sourceScope.getRectangle().copy() : null); targetScope.setCircle(sourceScope.getCircle() != null ? sourceScope.getCircle().copy() : null); targetScope.setEllipse(sourceScope.getEllipse() != null ? sourceScope.getEllipse().copy() : null); targetScope.setPolygon(sourceScope.getPolygon() != null ? sourceScope.getPolygon().copy() : null); targetScope.setShapeExcluded(sourceScope.isShapeExcluded()); targetScope.setColors(sourceScope.getColors()); targetScope.setColorExcluded(sourceScope.isColorExcluded()); sourceScope.getColorMatch().copyTo(targetScope.getColorMatch()); targetScope.setMaskOpacity(sourceScope.getMaskOpacity()); targetScope.setOutlineSource(sourceScope.getOutlineSource()); targetScope.setOutline(sourceScope.getOutline()); targetScope.setOutlineName(sourceScope.getOutlineName()); targetScope.setClip(sourceScope.getClip()); targetScope.setMaskColor(sourceScope.getMaskColor()); targetScope.setMaskOpacity(sourceScope.getMaskOpacity()); } catch (Exception e) { // MyBoxLog.debug(e); } } public static ImageScope cloneAll(ImageScope sourceScope) { ImageScope targetScope = new ImageScope(); ImageScopeTools.cloneAll(targetScope, sourceScope); return targetScope; } public static void cloneAll(ImageScope targetScope, ImageScope sourceScope) { try { targetScope.setImage(sourceScope.getImage()); targetScope.setShapeType(sourceScope.getShapeType()); cloneValues(targetScope, sourceScope); } catch (Exception e) { } } public static boolean inShape(DoubleShape shape, boolean areaExcluded, int x, int y) { if (areaExcluded) { return !DoubleShape.contains(shape, x, y); } else { return DoubleShape.contains(shape, x, y); } } /* make scope from */ public static ImageScope fromDataNode(FxTask task, BaseController controller, DataNode node) { try { if (node == null) { return null; } ImageScope scope = new ImageScope(); scope.setName(node.getTitle()); scope.setShapeType(node.getStringValue("shape_type")); scope.setShapeData(node.getStringValue("shape_data")); scope.setShapeExcluded(node.getBooleanValue("shape_excluded")); scope.setColorAlgorithm(node.getStringValue("color_algorithm")); scope.setColorData(node.getStringValue("color_data")); scope.setColorThreshold(node.getDoubleValue("color_threshold")); scope.setColorWeights(node.getStringValue("color_weights")); scope.setColorExcluded(node.getBooleanValue("color_excluded")); scope.setBackground(node.getStringValue("background_file")); scope.setOutlineName(node.getStringValue("outline_file")); scope.decode(task); return scope; } catch (Exception e) { // MyBoxLog.error(e); return null; } } /* convert scope to */ public static DataNode toDataNode(DataNode inNode, ImageScope scope) { try { if (scope == null) { return null; } ShapeType type = scope.getShapeType(); if (type == null) { type = ShapeType.Whole; } DataNode node = inNode; if (node == null) { node = DataNode.create(); } node.setValue("shape_type", type.name()); node.setValue("shape_data", encodeShapeData(scope)); node.setValue("shape_excluded", scope.isShapeExcluded()); node.setValue("color_algorithm", scope.getColorAlgorithm().name()); node.setValue("color_data", encodeColorData(scope)); node.setValue("color_excluded", scope.isColorExcluded()); node.setValue("color_threshold", scope.getColorThreshold()); node.setValue("color_weights", scope.getColorWeights()); node.setValue("background_file", scope.getBackground()); node.setValue("outline_file", encodeOutline(null, scope)); return node; } catch (Exception e) { MyBoxLog.error(e); return null; } } // scope should have been decoded public static String toHtml(FxTask task, ImageScope scope) { try { if (scope == null || scope.isWhole()) { return null; } String html = ""; StringTable htmlTable = new StringTable(); List<String> row; try { ImageItem item = new ImageItem(scope.getBackground()); Image image = item.readImage(); if (image == null) { image = new Image(InternalImages.exampleImageName()); } if (task != null && !task.isWorking()) { return null; } if (scope.getShapeType() == ShapeType.Outline) { makeOutline(task, scope, image, scope.getRectangle(), true); } image = ScopeTools.maskScope(task, image, scope, false, true); if (task != null && !task.isWorking()) { return null; } if (image != null) { File imgFile = FxImageTools.writeImage(task, image); if (imgFile != null) { html = "<P align=\"center\"><Img src='" + imgFile.toURI().toString() + "' width=500></P><BR>"; } } String v = scope.getName(); if (v != null && !v.isBlank()) { row = new ArrayList<>(); row.addAll(Arrays.asList(message("Name"), HtmlWriteTools.codeToHtml(v))); htmlTable.add(row); } row = new ArrayList<>(); row.addAll(Arrays.asList(message("ShapeType"), message(scope.getShapeType().name()))); htmlTable.add(row); v = scope.getBackground(); if (v != null && !v.isBlank()) { row = new ArrayList<>(); row.addAll(Arrays.asList(message("Background"), HtmlWriteTools.codeToHtml(v))); htmlTable.add(row); } v = scope.getOutlineName(); if (v != null && !v.isBlank()) { row = new ArrayList<>(); row.addAll(Arrays.asList(message("Outline"), HtmlWriteTools.codeToHtml(v))); htmlTable.add(row); } row = new ArrayList<>(); row.addAll(Arrays.asList(message("ColorMatchAlgorithm"), message(scope.getColorAlgorithm().name()))); htmlTable.add(row); v = scope.getShapeData(); if (v != null && !v.isBlank()) { row = new ArrayList<>(); row.addAll(Arrays.asList(message("Shape"), v)); htmlTable.add(row); } v = scope.getColorData(); if (v != null && !v.isBlank()) { row = new ArrayList<>(); row.addAll(Arrays.asList(message("Colors"), v)); htmlTable.add(row); } row = new ArrayList<>(); row.addAll(Arrays.asList(message("ColorMatchThreshold"), scope.getColorThreshold() + "")); htmlTable.add(row); row = new ArrayList<>(); row.addAll(Arrays.asList(message("ShapeExcluded"), scope.isShapeExcluded() ? message("Yes") : "")); htmlTable.add(row); row = new ArrayList<>(); row.addAll(Arrays.asList(message("ColorExcluded"), scope.isColorExcluded() ? message("Yes") : "")); htmlTable.add(row); } catch (Exception e) { } return html + htmlTable.div(); } catch (Exception e) { MyBoxLog.error(e); return null; } } public static DoubleRectangle makeOutline(FxTask task, ImageScope scope, Image bgImage, DoubleRectangle reck, boolean keepRatio) { try { if (scope.getOutlineSource() == null) { if (scope.getOutlineName() != null) { Image image = new ImageItem(scope.getOutlineName()).readImage(); if (image != null) { scope.setOutlineSource(SwingFXUtils.fromFXImage(image, null)); } } } if (scope.getOutlineSource() == null) { return null; } BufferedImage[] outline = AlphaTools.outline(task, scope.getOutlineSource(), reck, (int) bgImage.getWidth(), (int) bgImage.getHeight(), keepRatio); if (outline == null || (task != null && !task.isWorking())) { return null; } DoubleRectangle outlineReck = DoubleRectangle.xywh( reck.getX(), reck.getY(), outline[0].getWidth(), outline[0].getHeight()); scope.setOutline(outline[1]); scope.setRectangle(outlineReck.copy()); return outlineReck; } catch (Exception e) { MyBoxLog.error(e); return null; } } /* extract value from scope */ public static Image encodeBackground(FxTask task, String address) { try { String background = address; ImageItem item = new ImageItem(background); Image image = item.readImage(); if (image == null) { background = InternalImages.exampleImageName(); image = new Image(background); } return image; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static boolean decodeColorData(ImageScope scope) { if (scope == null) { return false; } return decodeColorData(scope.getColorData(), scope); } public static boolean decodeColorData(String colorData, ImageScope scope) { if (colorData == null || scope == null) { return false; } try { List<Color> colors = new ArrayList<>(); if (!colorData.isBlank()) { String[] items = colorData.split(ImageScope.ValueSeparator); for (String item : items) { try { colors.add(new Color(Integer.parseInt(item), true)); } catch (Exception e) { MyBoxLog.error(e); } } } scope.setColors(colors); scope.setColorData(colorData); return true; } catch (Exception e) { MyBoxLog.error(e); return false; } } public static String encodeColorData(ImageScope scope) { if (scope == null) { return ""; } String s = ""; try { List<Color> colors = scope.getColors(); if (colors != null) { for (Color color : colors) { s += color.getRGB() + ImageScope.ValueSeparator; } if (s.endsWith(ImageScope.ValueSeparator)) { s = s.substring(0, s.length() - ImageScope.ValueSeparator.length()); } } scope.setColorData(s); } catch (Exception e) { MyBoxLog.error(e); s = ""; } return s; } public static String encodeShapeData(ImageScope scope) { if (scope == null) { return ""; } String s = ""; try { switch (scope.getShapeType()) { case Matting4: case Matting8: { List<IntPoint> points = scope.getPoints(); if (points != null) { for (IntPoint p : points) { s += p.getX() + ImageScope.ValueSeparator + p.getY() + ImageScope.ValueSeparator; } if (s.endsWith(ImageScope.ValueSeparator)) { s = s.substring(0, s.length() - ImageScope.ValueSeparator.length()); } } } break; case Rectangle: case Outline: DoubleRectangle rect = scope.getRectangle(); if (rect != null) { s = (int) rect.getX() + ImageScope.ValueSeparator + (int) rect.getY() + ImageScope.ValueSeparator + (int) rect.getMaxX() + ImageScope.ValueSeparator + (int) rect.getMaxY(); } break; case Circle: DoubleCircle circle = scope.getCircle(); if (circle != null) { s = (int) circle.getCenterX() + ImageScope.ValueSeparator + (int) circle.getCenterY() + ImageScope.ValueSeparator + (int) circle.getRadius(); } break; case Ellipse: DoubleEllipse ellipse = scope.getEllipse(); if (ellipse != null) { s = (int) ellipse.getX() + ImageScope.ValueSeparator + (int) ellipse.getY() + ImageScope.ValueSeparator + (int) ellipse.getMaxX() + ImageScope.ValueSeparator + (int) ellipse.getMaxY(); } break; case Polygon: DoublePolygon polygon = scope.getPolygon(); if (polygon != null) { for (Double d : polygon.getData()) { s += Math.round(d) + ImageScope.ValueSeparator; } if (s.endsWith(ImageScope.ValueSeparator)) { s = s.substring(0, s.length() - ImageScope.ValueSeparator.length()); } } break; } scope.setShapeData(s); } catch (Exception e) { MyBoxLog.error(e); s = ""; } return s; } public static boolean decodeShapeData(ImageScope scope) { try { if (scope == null) { return false; } ShapeType type = scope.getShapeType(); String shapeData = scope.getShapeData(); if (shapeData == null) { return false; } switch (type) { case Matting4: case Matting8: { String[] items = shapeData.split(ImageScope.ValueSeparator); for (int i = 0; i < items.length / 2; ++i) { int x = (int) Double.parseDouble(items[i * 2]); int y = (int) Double.parseDouble(items[i * 2 + 1]); scope.addPoint(x, y); } } break; case Rectangle: case Outline: { String[] items = shapeData.split(ImageScope.ValueSeparator); if (items.length == 4) { DoubleRectangle rect = DoubleRectangle.xy12(Double.parseDouble(items[0]), Double.parseDouble(items[1]), Double.parseDouble(items[2]), Double.parseDouble(items[3])); scope.setRectangle(rect); } else { return false; } } break; case Circle: { String[] items = shapeData.split(ImageScope.ValueSeparator); if (items.length == 3) { DoubleCircle circle = new DoubleCircle(Double.parseDouble(items[0]), Double.parseDouble(items[1]), Double.parseDouble(items[2])); scope.setCircle(circle); } else { return false; } } break; case Ellipse: { String[] items = shapeData.split(ImageScope.ValueSeparator); if (items.length == 4) { DoubleEllipse ellipse = DoubleEllipse.xy12(Double.parseDouble(items[0]), Double.parseDouble(items[1]), Double.parseDouble(items[2]), Double.parseDouble(items[3])); scope.setEllipse(ellipse); } else { return false; } } break; case Polygon: { String[] items = shapeData.split(ImageScope.ValueSeparator); DoublePolygon polygon = new DoublePolygon(); for (int i = 0; i < items.length / 2; ++i) { int x = (int) Double.parseDouble(items[i * 2]); int y = (int) Double.parseDouble(items[i * 2 + 1]); polygon.add(x, y); } scope.setPolygon(polygon); } break; } return true; } catch (Exception e) { MyBoxLog.error(e); return false; } } public static String encodeOutline(FxTask task, ImageScope scope) { if (scope == null || scope.getShapeType() != ImageScope.ShapeType.Outline) { return ""; } String outlineName = scope.getOutlineName(); try { if (outlineName != null && (outlineName.startsWith("img/") || outlineName.startsWith("buttons/"))) { return outlineName; } BufferedImage outlineSource = scope.getOutlineSource(); if (outlineSource == null) { return ""; } String prefix = AppPaths.getImageScopePath() + File.separator + scope.getShapeType() + "_"; String name = prefix + (new Date().getTime()) + "_" + new Random().nextInt(1000) + ".png"; while (new File(name).exists()) { name = prefix + (new Date().getTime()) + "_" + new Random().nextInt(1000) + ".png"; } if (ImageFileWriters.writeImageFile(task, outlineSource, "png", name)) { outlineName = name; } scope.setOutlineName(outlineName); } catch (Exception e) { // MyBoxLog.error(e); outlineName = ""; } return outlineName; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/image/tools/ImageTextTools.java
alpha/MyBox/src/main/java/mara/mybox/image/tools/ImageTextTools.java
package mara.mybox.image.tools; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics2D; import java.awt.Shape; import java.awt.font.FontRenderContext; import java.awt.font.TextLayout; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import mara.mybox.image.data.PixelsBlend; import static mara.mybox.image.tools.ShapeTools.stroke; import mara.mybox.controller.ControlImageText; import mara.mybox.data.DoubleRectangle; import mara.mybox.data.ShapeStyle; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.value.AppVariables; /** * @Author Mara * @CreateDate 2018-6-27 18:58:57 * @License Apache License Version 2.0 */ public class ImageTextTools { public static BufferedImage addText(FxTask task, BufferedImage sourceImage, ControlImageText optionsController) { try { String text = optionsController.text(); if (text == null || text.isEmpty()) { return sourceImage; } int width = sourceImage.getWidth(); int height = sourceImage.getHeight(); int imageType = BufferedImage.TYPE_INT_ARGB; Font font = optionsController.font(); BufferedImage shapeImage = new BufferedImage(width, height, imageType); Graphics2D g = shapeImage.createGraphics(); if (AppVariables.ImageHints != null) { g.addRenderingHints(AppVariables.ImageHints); } FontMetrics metrics = g.getFontMetrics(font); optionsController.countValues(g, metrics, width, height); PixelsBlend blend = optionsController.getBlend(); if (blend == null || (task != null && !task.isWorking())) { return null; } int textBaseX = optionsController.getBaseX(); int textBaseY = optionsController.getTextY(); int shadowSize = optionsController.getShadow(); g.rotate(Math.toRadians(optionsController.getAngle()), textBaseX, textBaseY); Color textColor = Color.BLACK; Color shadowColor = Color.GRAY; Color borderColor = Color.GREEN; Color fillColor = Color.RED; Color backgroundColor = Color.BLUE; g.setBackground(backgroundColor); if (optionsController.showBorders()) { ShapeStyle style = optionsController.getBorderStyle(); if (style == null || (task != null && !task.isWorking())) { return null; } g.setStroke(stroke(style)); int m = optionsController.getBordersMargin(); DoubleRectangle border = DoubleRectangle.xywh( optionsController.getBaseX() - m, optionsController.getBaseY() - m, optionsController.getTextWidth() + 2 * m, optionsController.getTextHeight() + 2 * m); border.setRoundx(optionsController.getBordersArc()); border.setRoundy(optionsController.getBordersArc()); Shape shape = border.getShape(); if (style == null || (task != null && !task.isWorking())) { return null; } if (optionsController.bordersFilled()) { g.setColor(fillColor); g.fill(shape); } if (optionsController.getBordersStrokeWidth() > 0) { g.setColor(borderColor); g.draw(shape); } } if (blend == null || (task != null && !task.isWorking())) { return null; } g.setStroke(new BasicStroke()); g.setFont(font); if (shadowSize > 0) { g.setColor(shadowColor); drawText(g, optionsController, text, shadowSize); } g.setColor(textColor); drawText(g, optionsController, text, 0); g.dispose(); if (blend == null || (task != null && !task.isWorking())) { return null; } BufferedImage target = new BufferedImage(width, height, imageType); int textPixel = textColor.getRGB(); int shadowPixel = shadowColor.getRGB(); int borderPixel = borderColor.getRGB(); int fillPixel = fillColor.getRGB(); int realTextPixel = optionsController.textColor().getRGB(); int realShadowPixel = optionsController.shadowColor().getRGB(); int realBorderPixel = optionsController.bordersStrokeColor().getRGB(); int realFillPixel = optionsController.bordersFillColor().getRGB(); for (int j = 0; j < height; ++j) { if (task != null && !task.isWorking()) { return null; } for (int i = 0; i < width; ++i) { if (task != null && !task.isWorking()) { return null; } int srcPixel = sourceImage.getRGB(i, j); int shapePixel = shapeImage.getRGB(i, j); if (shapePixel == textPixel) { target.setRGB(i, j, blend.blend(realTextPixel, srcPixel)); } else if (shapePixel == shadowPixel) { target.setRGB(i, j, blend.blend(realShadowPixel, srcPixel)); } else if (shapePixel == borderPixel) { target.setRGB(i, j, blend.blend(realBorderPixel, srcPixel)); } else if (shapePixel == fillPixel) { target.setRGB(i, j, blend.blend(realFillPixel, srcPixel)); } else { target.setRGB(i, j, srcPixel); } } } return target; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static boolean drawText(Graphics2D g, ControlImageText optionsController, String text, int shadow) { try { if (g == null) { return false; } int textBaseX = optionsController.getBaseX(); int textBaseY = optionsController.getTextY(); int rowx = textBaseX, rowy = textBaseY, rowHeight = optionsController.getRowHeight(); String[] lines = text.split("\n", -1); int lend = lines.length - 1; boolean isOutline = optionsController.isOutline(); boolean leftToRight = optionsController.isLeftToRight(); Font font = optionsController.font(); FontMetrics metrics = g.getFontMetrics(font); if (optionsController.isVertical()) { for (int r = (leftToRight ? 0 : lend); (leftToRight ? r <= lend : r >= 0);) { String line = lines[r]; rowy = textBaseY; double cWidthMax = 0; for (int i = 0; i < line.length(); i++) { String c = line.charAt(i) + ""; drawText(g, c, font, rowx, rowy, shadow, isOutline); Rectangle2D cBound = metrics.getStringBounds(c, g); rowy += cBound.getHeight(); if (rowHeight <= 0) { double cWidth = cBound.getWidth(); if (cWidth > cWidthMax) { cWidthMax = cWidth; } } } if (rowHeight > 0) { rowx += rowHeight; } else { rowx += cWidthMax; } if (leftToRight) { r++; } else { r--; } } } else { for (String line : lines) { drawText(g, line, font, rowx, rowy, shadow, isOutline); if (rowHeight > 0) { rowy += rowHeight; } else { rowy += g.getFontMetrics(font).getStringBounds(line, g).getHeight(); } } } return true; } catch (Exception e) { MyBoxLog.error(e.toString()); return false; } } public static void drawText(Graphics2D g, String text, Font font, int x, int y, int shadow, boolean isOutline) { try { if (text == null || text.isEmpty()) { return; } if (shadow > 0) { // Not blurred. Can improve g.drawString(text, x + shadow, y + shadow); } else { if (isOutline) { FontRenderContext frc = g.getFontRenderContext(); TextLayout textTl = new TextLayout(text, font, frc); Shape outline = textTl.getOutline(null); g.translate(x, y); g.draw(outline); g.translate(-x, -y); } else { g.drawString(text, x, y); } } } 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/alpha/MyBox/src/main/java/mara/mybox/image/tools/ScaleTools.java
alpha/MyBox/src/main/java/mara/mybox/image/tools/ScaleTools.java
package mara.mybox.image.tools; import java.awt.Color; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import mara.mybox.value.AppVariables; import mara.mybox.value.Colors; /** * @Author Mara * @CreateDate 2018-6-27 18:58:57 * @License Apache License Version 2.0 */ public class ScaleTools { public static BufferedImage scaleImage(BufferedImage source, int width, int height, Color bgColor) { if (width <= 0 || height <= 0 || (width == source.getWidth() && height == source.getHeight())) { return source; } int imageType = BufferedImage.TYPE_INT_ARGB; BufferedImage target = new BufferedImage(width, height, imageType); Graphics2D g = target.createGraphics(); if (AppVariables.ImageHints != null) { g.addRenderingHints(AppVariables.ImageHints); } g.setBackground(bgColor); g.drawImage(source, 0, 0, width, height, null); g.dispose(); return target; } public static BufferedImage scaleImage(BufferedImage source, int width, int height) { return scaleImage(source, width, height, Colors.TRANSPARENT); } public static BufferedImage scaleImage(BufferedImage source, int targetW, int targetH, boolean keepRatio, int keepType) { int finalW = targetW; int finalH = targetH; if (keepRatio) { int[] wh = ScaleTools.scaleValues(source.getWidth(), source.getHeight(), targetW, targetH, keepType); finalW = wh[0]; finalH = wh[1]; } return scaleImageBySize(source, finalW, finalH); } public static int[] scaleValues(int sourceX, int sourceY, int newWidth, int newHeight, int keepRatioType) { int finalW = newWidth; int finalH = newHeight; if (keepRatioType != BufferedImageTools.KeepRatioType.None) { double ratioW = (double) newWidth / sourceX; double ratioH = (double) newHeight / sourceY; if (ratioW != ratioH) { switch (keepRatioType) { case BufferedImageTools.KeepRatioType.BaseOnWidth: finalH = (int) (ratioW * sourceY); break; case BufferedImageTools.KeepRatioType.BaseOnHeight: finalW = (int) (ratioH * sourceX); break; case BufferedImageTools.KeepRatioType.BaseOnLarger: if (ratioW > ratioH) { finalH = (int) (ratioW * sourceY); } else { finalW = (int) (ratioH * sourceX); } break; case BufferedImageTools.KeepRatioType.BaseOnSmaller: if (ratioW < ratioH) { finalH = (int) (ratioW * sourceY); } else { finalW = (int) (ratioH * sourceX); } break; } } } int[] d = new int[2]; d[0] = finalW; d[1] = finalH; return d; } public static BufferedImage scaleImageByScale(BufferedImage source, float scale) { return scaleImageByScale(source, scale, scale); } public static BufferedImage scaleImageByScale(BufferedImage source, float xscale, float yscale) { int width = (int) (source.getWidth() * xscale); int height = (int) (source.getHeight() * yscale); return scaleImage(source, width, height); } public static BufferedImage scaleImageHeightKeep(BufferedImage source, int height) { int width = source.getWidth() * height / source.getHeight(); return scaleImage(source, width, height); } public static BufferedImage scaleImageBySize(BufferedImage source, int width, int height) { return scaleImage(source, width, height); } public static BufferedImage scaleImageWidthKeep(BufferedImage source, int width) { if (width <= 0 || width == source.getWidth()) { return source; } int height = source.getHeight() * width / source.getWidth(); return scaleImage(source, width, height); } public static BufferedImage demoImage(BufferedImage source) { return scaleImageLess(source, AppVariables.maxDemoImage); } public static BufferedImage scaleImageLess(BufferedImage source, long size) { if (size <= 0) { return source; } float scale = size * 1f / (source.getWidth() * source.getHeight()); if (scale >= 1) { return source; } return scaleImageByScale(source, scale); } public static BufferedImage fitSize(BufferedImage source, int targetW, int targetH) { try { int[] wh = ScaleTools.scaleValues(source.getWidth(), source.getHeight(), targetW, targetH, BufferedImageTools.KeepRatioType.BaseOnSmaller); int finalW = wh[0]; int finalH = wh[1]; int imageType = BufferedImage.TYPE_INT_ARGB; BufferedImage target = new BufferedImage(targetW, targetH, imageType); Graphics2D g = target.createGraphics(); if (AppVariables.ImageHints != null) { g.addRenderingHints(AppVariables.ImageHints); } g.setBackground(Colors.TRANSPARENT); g.drawImage(source, (targetW - finalW) / 2, (targetH - finalH) / 2, finalW, finalH, null); g.dispose(); return target; } catch (Exception e) { return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/image/tools/ImageConvertTools.java
alpha/MyBox/src/main/java/mara/mybox/image/tools/ImageConvertTools.java
package mara.mybox.image.tools; import java.awt.color.ColorSpace; import java.awt.color.ICC_ColorSpace; import java.awt.color.ICC_Profile; import java.awt.image.BufferedImage; import java.awt.image.ColorConvertOp; import java.awt.image.DataBufferByte; import java.awt.image.Raster; import java.awt.image.WritableRaster; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.imageio.IIOImage; import javax.imageio.ImageIO; import javax.imageio.ImageReader; import javax.imageio.ImageWriteParam; import javax.imageio.ImageWriter; import javax.imageio.metadata.IIOMetadata; import javax.imageio.stream.ImageInputStream; import javax.imageio.stream.ImageOutputStream; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.image.data.ImageAttributes; import mara.mybox.image.data.ImageBinary; import mara.mybox.image.data.ImageColorSpace; import mara.mybox.image.data.ImageInformation; import mara.mybox.image.file.ImageFileReaders; import static mara.mybox.image.file.ImageFileReaders.getReader; import static mara.mybox.image.file.ImageFileReaders.readBrokenImage; import mara.mybox.image.file.ImageFileWriters; import mara.mybox.tools.FileNameTools; import mara.mybox.tools.FileTmpTools; import mara.mybox.tools.FileTools; import mara.mybox.value.FileExtensions; import static mara.mybox.value.Languages.message; import thridparty.image4j.ICODecoder; import thridparty.image4j.ICOEncoder; /** * @Author Mara * @CreateDate 2019-6-22 9:52:02 * @License Apache License Version 2.0 */ public class ImageConvertTools { // dpi(dot per inch) convert to dpm(dot per millimeter) public static int dpi2dpmm(int dpi) { return Math.round(dpi / 25.4f); } // dpi(dot per inch) convert to ppm(dot per meter) public static int dpi2dpm(int dpi) { return Math.round(1000 * dpi / 25.4f); } // ppm(dot Per Meter) convert to dpi(dot per inch) public static int dpm2dpi(int dpm) { return Math.round(dpm * 25.4f / 1000f); } // dpi(dot per inch) convert to dpm(dot per centimeter) public static int dpi2dpcm(int dpi) { return Math.round(dpi / 2.54f); } // dpm(dot per centimeter) convert to dpi(dot per inch) public static int dpcm2dpi(int dpcm) { return Math.round(dpcm * 2.54f); } public static int inch2cm(float inch) { return Math.round(inch / 2.54f); } // "pixel size in millimeters" convert to dpi(dot per inch) public static int pixelSizeMm2dpi(float psmm) { // if (psmm == 0) { return 0; } return Math.round(25.4f / psmm); } // dpi(dot per inch) convert to "pixel size in millimeters" public static float dpi2pixelSizeMm(int dpi) { // if (dpi == 0) { return 0; } return 25.4f / dpi; } public static BufferedImage convert(FxTask task, BufferedImage srcImage, String format) { return convertColorSpace(task, srcImage, new ImageAttributes(srcImage, format)); } public static BufferedImage convertBinary(FxTask task, BufferedImage srcImage, ImageAttributes attributes) { try { if (srcImage == null || attributes == null) { return srcImage; } ImageBinary imageBinary = attributes.getImageBinary(); if (imageBinary == null) { imageBinary = new ImageBinary(); } imageBinary.setImage(srcImage).setTask(task); BufferedImage targetImage = imageBinary.start(); if (targetImage == null) { return null; } targetImage = ImageBinary.byteBinary(task, targetImage); return targetImage; } catch (Exception e) { MyBoxLog.error(e); return srcImage; } } public static BufferedImage convertColorSpace(FxTask task, BufferedImage srcImage, ImageAttributes attributes) { try { if (srcImage == null || attributes == null) { return srcImage; } String targetFormat = attributes.getImageFormat(); if ("ico".equals(targetFormat) || "icon".equals(targetFormat)) { return convertToIcon(task, srcImage, attributes); } BufferedImage tmpImage = srcImage; if (null != attributes.getAlpha()) { switch (attributes.getAlpha()) { case PremultipliedAndKeep: tmpImage = AlphaTools.premultipliedAlpha(task, srcImage, false); break; case PremultipliedAndRemove: tmpImage = AlphaTools.premultipliedAlpha(task, srcImage, true); break; case Remove: tmpImage = AlphaTools.removeAlpha(task, srcImage); break; } } if (tmpImage == null) { return null; } ICC_Profile targetProfile = attributes.getProfile(); String csName = attributes.getColorSpaceName(); if (targetProfile == null) { if (csName == null) { return tmpImage; } if ("BlackOrWhite".equals(csName) || message("BlackOrWhite").equals(csName)) { return convertBinary(task, tmpImage, attributes); } else { if (message("Gray").equals(csName)) { csName = "Gray"; tmpImage = AlphaTools.removeAlpha(task, srcImage); } targetProfile = ImageColorSpace.internalProfileByName(csName); attributes.setProfile(targetProfile); attributes.setProfileName(csName); } } if (tmpImage == null || (task != null && !task.isWorking())) { return null; } ICC_ColorSpace targetColorSpace = new ICC_ColorSpace(targetProfile); ColorConvertOp c = new ColorConvertOp(targetColorSpace, null); BufferedImage targetImage = c.filter(tmpImage, null); return targetImage; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static boolean convertColorSpace(FxTask task, File srcFile, ImageAttributes attributes, File targetFile) { try { if (srcFile == null || targetFile == null || attributes == null) { return false; } String targetFormat = attributes.getImageFormat(); if ("ico".equals(targetFormat) || "icon".equals(targetFormat)) { return convertToIcon(task, srcFile, attributes, targetFile); } String sourceFormat = FileNameTools.ext(srcFile.getName()); if ("ico".equals(sourceFormat) || "icon".equals(sourceFormat)) { return convertFromIcon(task, srcFile, attributes, targetFile); } boolean supportMultiFrames = FileExtensions.MultiFramesImages.contains(targetFormat); ImageWriter writer = ImageFileWriters.getWriter(targetFormat); if (writer == null) { return false; } ImageWriteParam param = ImageFileWriters.getWriterParam(attributes, writer); File tmpFile = FileTmpTools.getTempFile(); try (ImageInputStream iis = ImageIO.createImageInputStream(srcFile); ImageOutputStream out = ImageIO.createImageOutputStream(tmpFile)) { ImageReader reader = ImageFileReaders.getReader(iis, sourceFormat); if (reader == null) { writer.dispose(); return false; } reader.setInput(iis, false); writer.setOutput(out); if (supportMultiFrames) { writer.prepareWriteSequence(null); } BufferedImage bufferedImage; int index = 0; ImageInformation info = new ImageInformation(srcFile); while (true) { if (task != null && !task.isWorking()) { writer.dispose(); reader.dispose(); return false; } try { bufferedImage = reader.read(index); } catch (Exception e) { if (e.toString().contains("java.lang.IndexOutOfBoundsException")) { break; } bufferedImage = readBrokenImage(task, e, info.setIndex(index)); } if (bufferedImage == null) { continue; } bufferedImage = ImageConvertTools.convertColorSpace(task, bufferedImage, attributes); if (bufferedImage == null) { continue; } IIOMetadata metaData = ImageFileWriters.getWriterMetaData(targetFormat, attributes, bufferedImage, writer, param); if (supportMultiFrames) { writer.writeToSequence(new IIOImage(bufferedImage, null, metaData), param); } else { writer.write(metaData, new IIOImage(bufferedImage, null, metaData), param); } index++; } if (task != null && !task.isWorking()) { writer.dispose(); reader.dispose(); return false; } if (supportMultiFrames) { writer.endWriteSequence(); } out.flush(); reader.dispose(); } writer.dispose(); return FileTools.override(tmpFile, targetFile); } catch (Exception e) { MyBoxLog.error(e); return false; } } public static BufferedImage convertToPNG(BufferedImage srcImage) { try { if (srcImage == null || srcImage.getType() == BufferedImage.TYPE_4BYTE_ABGR || srcImage.getType() == BufferedImage.TYPE_4BYTE_ABGR_PRE) { return srcImage; } ICC_Profile targetProfile = ICC_Profile.getInstance(ICC_ColorSpace.CS_sRGB); ICC_ColorSpace targetColorSpace = new ICC_ColorSpace(targetProfile); ColorConvertOp c = new ColorConvertOp(targetColorSpace, null); BufferedImage targetImage = c.filter(srcImage, null); return targetImage; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static boolean convertToIcon(FxTask task, File srcFile, ImageAttributes attributes, File targetFile) { try { if (srcFile == null || targetFile == null) { return false; } List<BufferedImage> images = new ArrayList(); try (ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(srcFile)))) { ImageReader reader = getReader(iis, FileNameTools.ext(srcFile.getName())); if (reader == null) { return false; } reader.setInput(iis, false); BufferedImage bufferedImage; int index = 0; ImageInformation info = new ImageInformation(srcFile); while (true) { if (task != null && !task.isWorking()) { reader.dispose(); return false; } try { bufferedImage = reader.read(index); } catch (Exception e) { if (e.toString().contains("java.lang.IndexOutOfBoundsException")) { break; } bufferedImage = readBrokenImage(task, e, info.setIndex(index)); } if (task != null && !task.isWorking()) { reader.dispose(); return false; } if (bufferedImage != null) { bufferedImage = convertToIcon(task, bufferedImage, attributes); images.add(bufferedImage); index++; } else { break; } } reader.dispose(); } if (images.isEmpty()) { return false; } ICOEncoder.write(images, targetFile); return true; } catch (Exception e) { MyBoxLog.error(e); return false; } } public static boolean convertToIcon(FxTask task, BufferedImage bufferedImage, ImageAttributes attributes, File targetFile) { try { if (bufferedImage == null || targetFile == null) { return false; } BufferedImage icoImage = convertToIcon(task, bufferedImage, attributes); if (icoImage == null || (task != null && !task.isWorking())) { return false; } ICOEncoder.write(icoImage, targetFile); return true; } catch (Exception e) { MyBoxLog.error(e); return false; } } public static BufferedImage convertToIcon(FxTask task, BufferedImage bufferedImage, ImageAttributes attributes) { try { if (bufferedImage == null) { return null; } int width = 0; if (attributes != null) { width = attributes.getWidth(); } if (width <= 0) { width = Math.min(512, bufferedImage.getWidth()); } BufferedImage icoImage = ScaleTools.scaleImageWidthKeep(bufferedImage, width); return icoImage; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static boolean convertFromIcon(FxTask task, File srcFile, ImageAttributes attributes, File targetFile) { try { if (srcFile == null || targetFile == null) { return false; } List<BufferedImage> images = ICODecoder.read(srcFile); if (images == null || images.isEmpty() || (task != null && !task.isWorking())) { return false; } String targetFormat = attributes.getImageFormat(); boolean supportMultiFrames = FileExtensions.MultiFramesImages.contains(targetFormat); ImageWriter writer = ImageFileWriters.getWriter(targetFormat); ImageWriteParam param = ImageFileWriters.getWriterParam(attributes, writer); File tmpFile = FileTmpTools.getTempFile(); try (ImageOutputStream out = ImageIO.createImageOutputStream(tmpFile)) { writer.setOutput(out); int num; if (supportMultiFrames) { num = images.size(); writer.prepareWriteSequence(null); } else { num = 1; } BufferedImage bufferedImage; for (int i = 0; i < num; ++i) { if (task != null && !task.isWorking()) { writer.dispose(); return false; } bufferedImage = images.get(i); bufferedImage = ImageConvertTools.convertColorSpace(task, bufferedImage, attributes); if (task != null && !task.isWorking()) { writer.dispose(); return false; } if (bufferedImage == null) { continue; } IIOMetadata metaData = ImageFileWriters.getWriterMetaData(targetFormat, attributes, bufferedImage, writer, param); if (supportMultiFrames) { writer.writeToSequence(new IIOImage(bufferedImage, null, metaData), param); } else { writer.write(metaData, new IIOImage(bufferedImage, null, metaData), param); } } if (task != null && !task.isWorking()) { writer.dispose(); return false; } if (supportMultiFrames) { writer.endWriteSequence(); } out.flush(); } writer.dispose(); return FileTools.override(tmpFile, targetFile); } catch (Exception e) { MyBoxLog.error(e); return false; } } // https://stackoverflow.com/questions/2408613/unable-to-read-jpeg-image-using-imageio-readfile-file/12132805#12132805 // https://stackoverflow.com/questions/50798014/determining-color-space-for-jpeg/50861048?r=SearchResults#50861048 // https://blog.idrsolutions.com/2011/10/ycck-color-conversion-in-pdf-files/ // https://community.oracle.com/message/10003648?tstart=0 public static void ycck2cmyk(FxTask task, WritableRaster rast, boolean invertedColors) { int w = rast.getWidth(), h = rast.getHeight(); double c, m, y, k; double Y, Cb, Cr, K; int[] pixels = null; for (int row = 0; row < h; row++) { if (task != null && !task.isWorking()) { return; } pixels = rast.getPixels(0, row, w, 1, pixels); for (int i = 0; i < pixels.length; i += 4) { if (task != null && !task.isWorking()) { return; } Y = pixels[i]; Cb = pixels[i + 1]; Cr = pixels[i + 2]; K = pixels[i + 3]; c = Math.min(255, Math.max(0, 255 - (Y + 1.402 * Cr - 179.456))); m = Math.min(255, Math.max(0, 255 - (Y - 0.34414 * Cb - 0.71414 * Cr + 135.45984))); y = Math.min(255, Math.max(0, 255 - (Y + 1.7718d * Cb - 226.816))); k = K; if (invertedColors) { pixels[i] = (byte) (255 - c); pixels[i + 1] = (byte) (255 - m); pixels[i + 2] = (byte) (255 - y); pixels[i + 3] = (byte) (255 - k); } else { pixels[i] = (byte) c; pixels[i + 1] = (byte) m; pixels[i + 2] = (byte) y; pixels[i + 3] = (byte) k; } } rast.setPixels(0, row, w, 1, pixels); } } public static void invertPixelValue(FxTask task, WritableRaster raster) { int height = raster.getHeight(); int width = raster.getWidth(); int stride = width * 4; int[] pixelRow = new int[stride]; for (int h = 0; h < height; h++) { if (task != null && !task.isWorking()) { return; } raster.getPixels(0, h, width, 1, pixelRow); for (int x = 0; x < stride; x++) { if (task != null && !task.isWorking()) { return; } pixelRow[x] = 255 - pixelRow[x]; } raster.setPixels(0, h, width, 1, pixelRow); } } public static Raster ycck2cmyk(FxTask task, final byte[] buffer, final int w, final int h) throws IOException { final int pixelCount = w * h * 4; for (int i = 0; i < pixelCount; i = i + 4) { if (task != null && !task.isWorking()) { return null; } int y = (buffer[i] & 255); int cb = (buffer[i + 1] & 255); int cr = (buffer[i + 2] & 255); // int k = (buffer[i + 3] & 255); int r = Math.max(0, Math.min(255, (int) (y + 1.402 * cr - 179.456))); int g = Math.max(0, Math.min(255, (int) (y - 0.34414 * cb - 0.71414 * cr + 135.95984))); int b = Math.max(0, Math.min(255, (int) (y + 1.772 * cb - 226.316))); buffer[i] = (byte) (255 - r); buffer[i + 1] = (byte) (255 - g); buffer[i + 2] = (byte) (255 - b); } return Raster.createInterleavedRaster(new DataBufferByte(buffer, pixelCount), w, h, w * 4, 4, new int[]{ 0, 1, 2, 3}, null); } public static BufferedImage rgb2cmyk(ICC_Profile cmykProfile, BufferedImage inImage) throws IOException { if (cmykProfile == null) { cmykProfile = ImageColorSpace.eciCmykProfile(); } ICC_ColorSpace cmykCS = new ICC_ColorSpace(cmykProfile); ColorConvertOp rgb2cmyk = new ColorConvertOp(cmykCS, null); return rgb2cmyk.filter(inImage, null); } public static BufferedImage cmyk2rgb(Raster cmykRaster, ICC_Profile cmykProfile) throws IOException { if (cmykProfile == null) { cmykProfile = ImageColorSpace.eciCmykProfile(); } ICC_ColorSpace cmykCS = new ICC_ColorSpace(cmykProfile); BufferedImage rgbImage = new BufferedImage(cmykRaster.getWidth(), cmykRaster.getHeight(), BufferedImage.TYPE_INT_RGB); WritableRaster rgbRaster = rgbImage.getRaster(); ColorSpace rgbCS = rgbImage.getColorModel().getColorSpace(); ColorConvertOp cmykToRgb = new ColorConvertOp(cmykCS, rgbCS, null); cmykToRgb.filter(cmykRaster, rgbRaster); return rgbImage; } // https://bugs.openjdk.java.net/browse/JDK-8041125 public static BufferedImage cmyk2rgb(FxTask task, final byte[] buffer, final int w, final int h) throws IOException { final ColorSpace CMYK = ImageColorSpace.adobeCmykColorSpace(); final int pixelCount = w * h * 4; int C, M, Y, K, lastC = -1, lastM = -1, lastY = -1, lastK = -1; int j = 0; float[] RGB = new float[]{0f, 0f, 0f}; //turn YCC in Buffer to CYM using profile for (int i = 0; i < pixelCount; i = i + 4) { if (task != null && !task.isWorking()) { return null; } C = (buffer[i] & 255); M = (buffer[i + 1] & 255); Y = (buffer[i + 2] & 255); K = (buffer[i + 3] & 255); // System.out.println(C+" "+M+" "+Y+" "+K); if (C == lastC && M == lastM && Y == lastY && K == lastK) { //no change so use last value } else { //new value RGB = CMYK.toRGB(new float[]{C / 255f, M / 255f, Y / 255f, K / 255f}); //flag so we can just reuse if next value the same lastC = C; lastM = M; lastY = Y; lastK = K; } //put back as CMY buffer[j] = (byte) (RGB[0] * 255f); buffer[j + 1] = (byte) (RGB[1] * 255f); buffer[j + 2] = (byte) (RGB[2] * 255f); j = j + 3; } /** * create CMYK raster from buffer */ final Raster raster = Raster.createInterleavedRaster(new DataBufferByte(buffer, j), w, h, w * 3, 3, new int[]{ 0, 1, 2}, null); //data now sRGB so create image final BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); image.setData(raster); return image; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/image/tools/AlphaTools.java
alpha/MyBox/src/main/java/mara/mybox/image/tools/AlphaTools.java
package mara.mybox.image.tools; import java.awt.Color; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import mara.mybox.data.DoubleRectangle; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.value.AppVariables; import mara.mybox.value.Colors; import mara.mybox.value.FileExtensions; /** * @Author Mara * @CreateDate 2018-6-27 18:58:57 * @License Apache License Version 2.0 */ public class AlphaTools { // https://bugs.java.com/bugdatabase/view_bug.do?bug_id=4836466 public static BufferedImage checkAlpha(FxTask task, BufferedImage source, String targetFormat) { if (targetFormat == null) { return source; } BufferedImage checked = source; if (FileExtensions.NoAlphaImages.contains(targetFormat.toLowerCase())) { if (hasAlpha(source)) { checked = AlphaTools.premultipliedAlpha(task, source, true); } } return checked; } public static boolean hasAlpha(BufferedImage source) { switch (source.getType()) { case BufferedImage.TYPE_3BYTE_BGR: case BufferedImage.TYPE_BYTE_BINARY: case BufferedImage.TYPE_BYTE_GRAY: case BufferedImage.TYPE_BYTE_INDEXED: case BufferedImage.TYPE_INT_BGR: case BufferedImage.TYPE_INT_RGB: case BufferedImage.TYPE_USHORT_555_RGB: case BufferedImage.TYPE_USHORT_565_RGB: case BufferedImage.TYPE_USHORT_GRAY: return false; default: if (source.getColorModel() != null) { return source.getColorModel().hasAlpha(); } else { return true; } } } public static BufferedImage removeAlpha(FxTask task, BufferedImage source) { return AlphaTools.removeAlpha(task, source, ColorConvertTools.alphaColor()); } public static BufferedImage removeAlpha(FxTask task, BufferedImage source, Color alphaColor) { try { if (!hasAlpha(source)) { return source; } int width = source.getWidth(); int height = source.getHeight(); int imageType = BufferedImage.TYPE_INT_RGB; BufferedImage target = new BufferedImage(width, height, imageType); int alphaPixel = alphaColor.getRGB(); for (int j = 0; j < height; ++j) { if (task != null && !task.isWorking()) { return null; } for (int i = 0; i < width; ++i) { if (task != null && !task.isWorking()) { return null; } int pixel = source.getRGB(i, j); if (pixel == 0) { target.setRGB(i, j, alphaPixel); } else { target.setRGB(i, j, new Color(pixel, false).getRGB()); } } } return target; } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e); } return null; } } public static BufferedImage[] extractAlpha(FxTask task, BufferedImage source) { try { if (source == null) { return null; } BufferedImage[] bfs = new BufferedImage[2]; int width = source.getWidth(); int height = source.getHeight(); BufferedImage alphaImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); BufferedImage noAlphaImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Color color; Color newColor; int pixel; int alphaPixel = ColorConvertTools.alphaColor().getRGB(); for (int j = 0; j < height; ++j) { if (task != null && !task.isWorking()) { return null; } for (int i = 0; i < width; ++i) { if (task != null && !task.isWorking()) { return null; } pixel = source.getRGB(i, j); if (pixel == 0) { noAlphaImage.setRGB(i, j, alphaPixel); alphaImage.setRGB(i, j, 0); } else { color = new Color(pixel, true); newColor = new Color(color.getRed(), color.getGreen(), color.getBlue()); noAlphaImage.setRGB(i, j, newColor.getRGB()); newColor = new Color(0, 0, 0, color.getAlpha()); alphaImage.setRGB(i, j, newColor.getRGB()); } } } bfs[0] = noAlphaImage; bfs[1] = alphaImage; return bfs; } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e); } return null; } } public static BufferedImage extractAlphaOnly(FxTask task, BufferedImage source) { try { if (source == null) { return null; } int width = source.getWidth(); int height = source.getHeight(); BufferedImage alphaImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Color color; Color newColor; int pixel; for (int j = 0; j < height; ++j) { if (task != null && !task.isWorking()) { return null; } for (int i = 0; i < width; ++i) { if (task != null && !task.isWorking()) { return null; } pixel = source.getRGB(i, j); color = new Color(pixel, true); newColor = new Color(0, 0, 0, color.getAlpha()); alphaImage.setRGB(i, j, newColor.getRGB()); } } return alphaImage; } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e); } return null; } } public static BufferedImage premultipliedAlpha(FxTask task, BufferedImage source, boolean removeAlpha) { try { if (source == null || !AlphaTools.hasAlpha(source) || (source.isAlphaPremultiplied() && !removeAlpha)) { return source; } int sourceWidth = source.getWidth(); int sourceHeight = source.getHeight(); int imageType; if (removeAlpha) { imageType = BufferedImage.TYPE_INT_RGB; } else { imageType = BufferedImage.TYPE_INT_ARGB_PRE; } BufferedImage target = new BufferedImage(sourceWidth, sourceHeight, imageType); Color sourceColor; Color newColor; Color bkColor = ColorConvertTools.alphaColor(); int bkPixel = bkColor.getRGB(); for (int j = 0; j < sourceHeight; ++j) { if (task != null && !task.isWorking()) { return null; } for (int i = 0; i < sourceWidth; ++i) { if (task != null && !task.isWorking()) { return null; } int pixel = source.getRGB(i, j); if (pixel == 0) { target.setRGB(i, j, bkPixel); continue; } sourceColor = new Color(pixel, true); newColor = ColorBlendTools.blendColor(sourceColor, sourceColor.getAlpha(), bkColor, !removeAlpha); target.setRGB(i, j, newColor.getRGB()); } } return target; } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e); } return source; } } public static BufferedImage addAlpha(FxTask task, BufferedImage source, BufferedImage alpha, boolean isPlus) { try { if (source == null || alpha == null || !alpha.getColorModel().hasAlpha()) { return source; } int sourceWidth = source.getWidth(); int sourceHeight = source.getHeight(); int alphaWidth = alpha.getWidth(); int alphaHeight = alpha.getHeight(); boolean addAlpha = isPlus && source.getColorModel().hasAlpha(); BufferedImage target = new BufferedImage(sourceWidth, sourceHeight, BufferedImage.TYPE_INT_ARGB); Color sourceColor; Color alphaColor; Color newColor; int alphaValue; for (int j = 0; j < sourceHeight; ++j) { if (task != null && !task.isWorking()) { return null; } for (int i = 0; i < sourceWidth; ++i) { if (task != null && !task.isWorking()) { return null; } if (i < alphaWidth && j < alphaHeight) { sourceColor = new Color(source.getRGB(i, j), addAlpha); alphaColor = new Color(alpha.getRGB(i, j), true); alphaValue = alphaColor.getAlpha(); if (addAlpha) { alphaValue = Math.min(255, alphaValue + sourceColor.getAlpha()); } newColor = new Color(sourceColor.getRed(), sourceColor.getGreen(), sourceColor.getBlue(), alphaValue); target.setRGB(i, j, newColor.getRGB()); } else { target.setRGB(i, j, source.getRGB(i, j)); } } } return target; } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e); } return null; } } public static BufferedImage addAlpha(FxTask task, BufferedImage source, float opacity, boolean isPlus) { try { if (source == null || opacity < 0) { return source; } int sourceWidth = source.getWidth(); int sourceHeight = source.getHeight(); boolean addAlpha = isPlus && source.getColorModel().hasAlpha(); BufferedImage target = new BufferedImage(sourceWidth, sourceHeight, BufferedImage.TYPE_INT_ARGB); Color sourceColor; Color newColor; int opacityValue = Math.min(255, Math.round(opacity * 255)); for (int j = 0; j < sourceHeight; ++j) { if (task != null && !task.isWorking()) { return null; } for (int i = 0; i < sourceWidth; ++i) { if (task != null && !task.isWorking()) { return null; } sourceColor = new Color(source.getRGB(i, j), addAlpha); if (addAlpha) { opacityValue = Math.min(255, opacityValue + sourceColor.getAlpha()); } newColor = new Color(sourceColor.getRed(), sourceColor.getGreen(), sourceColor.getBlue(), opacityValue); target.setRGB(i, j, newColor.getRGB()); } } return target; } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e); } return null; } } public static BufferedImage premultipliedAlpha2(FxTask task, BufferedImage source, boolean removeAlpha) { try { if (source == null || !AlphaTools.hasAlpha(source) || (source.isAlphaPremultiplied() && !removeAlpha)) { return source; } BufferedImage target = BufferedImageTools.clone(source); target.coerceData(true); if (removeAlpha) { target = AlphaTools.removeAlpha(task, target); } return target; } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e); } return source; } } public static BufferedImage[] outline(FxTask task, BufferedImage alphaImage, DoubleRectangle rect, int bgWidth, int bgHeight, boolean keepRatio) { try { if (alphaImage == null) { return null; } BufferedImage scaledImage = ScaleTools.scaleImage(alphaImage, (int) rect.getWidth(), (int) rect.getHeight(), keepRatio, BufferedImageTools.KeepRatioType.BaseOnWidth); int offsetX = (int) rect.getX(); int offsetY = (int) rect.getY(); int scaledWidth = scaledImage.getWidth(); int scaledHeight = scaledImage.getHeight(); int width = offsetX >= 0 ? Math.max(bgWidth, scaledWidth + offsetX) : Math.max(bgWidth - offsetX, scaledWidth); int height = offsetY >= 0 ? Math.max(bgHeight, scaledHeight + offsetY) : Math.max(bgHeight - offsetY, scaledHeight); int startX = offsetX >= 0 ? offsetX : 0; int startY = offsetY >= 0 ? offsetY : 0; BufferedImage target = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D g = target.createGraphics(); if (AppVariables.ImageHints != null) { g.addRenderingHints(AppVariables.ImageHints); } g.setColor(Colors.TRANSPARENT); g.fillRect(0, 0, width, height); int imagePixel; int inPixel = 64, outPixel = -64; for (int j = 0; j < scaledHeight; ++j) { if (task != null && !task.isWorking()) { return null; } for (int i = 0; i < scaledWidth; ++i) { if (task != null && !task.isWorking()) { return null; } imagePixel = scaledImage.getRGB(i, j); target.setRGB(i + startX, j + startY, imagePixel == 0 ? outPixel : inPixel); } } g.dispose(); BufferedImage[] ret = new BufferedImage[2]; ret[0] = scaledImage; ret[1] = target; return ret; } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e); } return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/image/tools/RepeatTools.java
alpha/MyBox/src/main/java/mara/mybox/image/tools/RepeatTools.java
package mara.mybox.image.tools; import java.awt.AlphaComposite; import java.awt.Color; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import mara.mybox.image.data.CropTools; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.value.AppVariables; /** * @Author Mara * @CreateDate 2022-9-25 * @License Apache License Version 2.0 */ public class RepeatTools { public static BufferedImage repeat(FxTask task, BufferedImage source, int repeatH, int repeatV, int interval, int margin, Color bgColor) { try { if (source == null || repeatH <= 0 || repeatV <= 0) { return source; } int width = source.getWidth(); int height = source.getHeight(); int imageType = BufferedImage.TYPE_INT_ARGB; int stepx = width + interval; int stepy = height + interval; int totalWidth = width + stepx * (repeatH - 1) + margin * 2; int totalHeight = height + stepy * (repeatV - 1) + margin * 2; BufferedImage target = new BufferedImage(totalWidth, totalHeight, imageType); Graphics2D g = target.createGraphics(); if (AppVariables.ImageHints != null) { g.addRenderingHints(AppVariables.ImageHints); } g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER)); g.setColor(bgColor); g.fillRect(0, 0, totalWidth, totalHeight); int x, y = margin; for (int v = 0; v < repeatV; ++v) { if (task != null && !task.isWorking()) { return null; } x = margin; for (int h = 0; h < repeatH; ++h) { if (task != null && !task.isWorking()) { return null; } g.drawImage(source, x, y, width, height, null); x += stepx; } y += stepy; } return target; } catch (Exception e) { MyBoxLog.error(e); return source; } } public static BufferedImage tile(FxTask task, BufferedImage source, int canvasWidth, int canvasHeight, int interval, int margin, Color bgColor) { try { if (source == null || canvasWidth <= 0 || canvasHeight <= 0) { return source; } int width = source.getWidth(); int height = source.getHeight(); int imageType = BufferedImage.TYPE_INT_ARGB; BufferedImage target = new BufferedImage(canvasWidth, canvasHeight, imageType); Graphics2D g = target.createGraphics(); if (AppVariables.ImageHints != null) { g.addRenderingHints(AppVariables.ImageHints); } g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER)); g.setColor(bgColor); g.fillRect(0, 0, canvasWidth, canvasHeight); int x = margin, y = margin; int stepx = width + interval; int stepy = height + interval; for (int v = margin; v < canvasHeight - height - margin; v += stepy) { if (task != null && !task.isWorking()) { return null; } for (int h = margin; h < canvasWidth - width - margin; h += stepx) { if (task != null && !task.isWorking()) { return null; } g.drawImage(source, h, v, width, height, null); x = h + stepx; y = v + stepy; } } int leftWidth = canvasWidth - margin - x; if (leftWidth > 0) { BufferedImage cropped = CropTools.cropOutside(task, source, 0, 0, leftWidth, height); if (cropped == null || (task != null && !task.isWorking())) { return null; } for (int v = margin; v < canvasHeight - height - margin; v += stepy) { if (task != null && !task.isWorking()) { return null; } g.drawImage(cropped, x, v, leftWidth, height, null); } } int leftHeight = canvasHeight - margin - y; if (leftHeight > 0) { BufferedImage cropped = CropTools.cropOutside(task, source, 0, 0, width, leftHeight); if (cropped == null || (task != null && !task.isWorking())) { return null; } for (int h = margin; h < canvasWidth - width - margin; h += stepx) { if (task != null && !task.isWorking()) { return null; } g.drawImage(cropped, h, y, width, leftHeight, null); } } if (leftWidth > 0 && leftHeight > 0) { BufferedImage cropped = CropTools.cropOutside(task, source, 0, 0, leftWidth, leftHeight); if (cropped == null || (task != null && !task.isWorking())) { return null; } g.drawImage(cropped, x, y, leftWidth, leftHeight, null); } return target; } catch (Exception e) { MyBoxLog.error(e); return source; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/image/tools/CombineTools.java
alpha/MyBox/src/main/java/mara/mybox/image/tools/CombineTools.java
package mara.mybox.image.tools; import java.awt.AlphaComposite; import java.awt.Color; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.util.ArrayList; import java.util.List; import javafx.embed.swing.SwingFXUtils; import javafx.scene.image.Image; import mara.mybox.image.data.ImageCombine; import mara.mybox.image.data.ImageInformation; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.image.FxColorTools; import mara.mybox.fxml.FxTask; import mara.mybox.value.AppVariables; /** * @Author Mara * @CreateDate 2018-6-27 18:58:57 * @License Apache License Version 2.0 */ public class CombineTools { public static Image combineSingleRow(FxTask task, ImageCombine imageCombine, List<ImageInformation> images, boolean isPart, boolean careTotal) { if (imageCombine == null || images == null) { return null; } try { int imageWidth; int imageHeight; int totalWidth = 0; int totalHeight = 0; int maxHeight = 0; int minHeight = Integer.MAX_VALUE; int sizeType = imageCombine.getSizeType(); if (sizeType == ImageCombine.CombineSizeType.AlignAsBigger) { for (ImageInformation imageInfo : images) { if (task != null && !task.isWorking()) { return null; } imageHeight = (int) imageInfo.getPickedHeight(); if (imageHeight > maxHeight) { maxHeight = imageHeight; } } } else if (sizeType == ImageCombine.CombineSizeType.AlignAsSmaller) { for (ImageInformation imageInfo : images) { if (task != null && !task.isWorking()) { return null; } imageHeight = (int) imageInfo.getPickedHeight(); if (imageHeight < minHeight) { minHeight = imageHeight; } } } int x = isPart ? 0 : imageCombine.getMarginsValue(); int y = isPart ? 0 : imageCombine.getMarginsValue(); List<Integer> xs = new ArrayList<>(); List<Integer> ys = new ArrayList<>(); List<Integer> widths = new ArrayList<>(); List<Integer> heights = new ArrayList<>(); for (int i = 0; i < images.size(); i++) { if (task != null && !task.isWorking()) { return null; } ImageInformation imageInfo = images.get(i); imageWidth = (int) imageInfo.getPickedWidth(); imageHeight = (int) imageInfo.getPickedHeight(); if (sizeType == ImageCombine.CombineSizeType.KeepSize || sizeType == ImageCombine.CombineSizeType.TotalWidth || sizeType == ImageCombine.CombineSizeType.TotalHeight) { } else if (sizeType == ImageCombine.CombineSizeType.EachWidth) { imageHeight = (imageHeight * imageCombine.getEachWidthValue()) / imageWidth; imageWidth = imageCombine.getEachWidthValue(); } else if (sizeType == ImageCombine.CombineSizeType.EachHeight) { imageWidth = (imageWidth * imageCombine.getEachHeightValue()) / imageHeight; imageHeight = imageCombine.getEachHeightValue(); } else if (sizeType == ImageCombine.CombineSizeType.AlignAsBigger) { imageWidth = (imageWidth * maxHeight) / imageHeight; imageHeight = maxHeight; } else if (sizeType == ImageCombine.CombineSizeType.AlignAsSmaller) { imageWidth = (imageWidth * minHeight) / imageHeight; imageHeight = minHeight; } xs.add(x); ys.add(y); widths.add(imageWidth); heights.add(imageHeight); x += imageWidth + imageCombine.getIntervalValue(); if (imageHeight > totalHeight) { totalHeight = imageHeight; } } totalWidth = x - imageCombine.getIntervalValue(); if (!isPart) { totalWidth += imageCombine.getMarginsValue(); totalHeight += 2 * imageCombine.getMarginsValue(); } Image newImage = combineImages(task, images, (int) totalWidth, (int) totalHeight, FxColorTools.toAwtColor(imageCombine.getBgColor()), xs, ys, widths, heights, imageCombine.getTotalWidthValue(), imageCombine.getTotalHeightValue(), careTotal && (sizeType == ImageCombine.CombineSizeType.TotalWidth), careTotal && (sizeType == ImageCombine.CombineSizeType.TotalHeight)); return newImage; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static Image combineSingleColumn(FxTask task, ImageCombine imageCombine, List<ImageInformation> imageInfos, boolean isPart, boolean careTotal) { if (imageCombine == null || imageInfos == null) { return null; } try { int imageWidth; int imageHeight; int totalWidth = 0; int totalHeight = 0; int maxWidth = 0; int minWidth = Integer.MAX_VALUE; int sizeType = imageCombine.getSizeType(); if (sizeType == ImageCombine.CombineSizeType.AlignAsBigger) { for (ImageInformation imageInfo : imageInfos) { if (task != null && !task.isWorking()) { return null; } imageWidth = (int) imageInfo.getPickedWidth(); if (imageWidth > maxWidth) { maxWidth = imageWidth; } } } else if (sizeType == ImageCombine.CombineSizeType.AlignAsSmaller) { for (ImageInformation imageInfo : imageInfos) { if (task != null && !task.isWorking()) { return null; } imageWidth = (int) imageInfo.getPickedWidth(); if (imageWidth < minWidth) { minWidth = imageWidth; } } } int x = isPart ? 0 : imageCombine.getMarginsValue(); int y = isPart ? 0 : imageCombine.getMarginsValue(); List<Integer> xs = new ArrayList<>(); List<Integer> ys = new ArrayList<>(); List<Integer> widths = new ArrayList<>(); List<Integer> heights = new ArrayList<>(); for (ImageInformation imageInfo : imageInfos) { if (task != null && !task.isWorking()) { return null; } imageWidth = (int) imageInfo.getPickedWidth(); imageHeight = (int) imageInfo.getPickedHeight(); if (sizeType == ImageCombine.CombineSizeType.KeepSize || sizeType == ImageCombine.CombineSizeType.TotalWidth || sizeType == ImageCombine.CombineSizeType.TotalHeight) { } else if (sizeType == ImageCombine.CombineSizeType.EachWidth) { if (!isPart) { imageHeight = (imageHeight * imageCombine.getEachWidthValue()) / imageWidth; imageWidth = imageCombine.getEachWidthValue(); } } else if (sizeType == ImageCombine.CombineSizeType.EachHeight) { if (!isPart) { imageWidth = (imageWidth * imageCombine.getEachHeightValue()) / imageHeight; imageHeight = imageCombine.getEachHeightValue(); } } else if (sizeType == ImageCombine.CombineSizeType.AlignAsBigger) { imageHeight = (imageHeight * maxWidth) / imageWidth; imageWidth = maxWidth; } else if (sizeType == ImageCombine.CombineSizeType.AlignAsSmaller) { imageHeight = (imageHeight * minWidth) / imageWidth; imageWidth = minWidth; } xs.add(x); ys.add(y); widths.add((int) imageWidth); heights.add((int) imageHeight); y += imageHeight + imageCombine.getIntervalValue(); if (imageWidth > totalWidth) { totalWidth = imageWidth; } } totalHeight = y - imageCombine.getIntervalValue(); if (!isPart) { totalWidth += 2 * imageCombine.getMarginsValue(); totalHeight += imageCombine.getMarginsValue(); } Image newImage = combineImages(task, imageInfos, (int) totalWidth, (int) totalHeight, FxColorTools.toAwtColor(imageCombine.getBgColor()), xs, ys, widths, heights, imageCombine.getTotalWidthValue(), imageCombine.getTotalHeightValue(), careTotal && (sizeType == ImageCombine.CombineSizeType.TotalWidth), careTotal && (sizeType == ImageCombine.CombineSizeType.TotalHeight)); return newImage; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static Image combineImages(FxTask task, List<ImageInformation> imageInfos, int totalWidth, int totalHeight, Color bgColor, List<Integer> xs, List<Integer> ys, List<Integer> widths, List<Integer> heights, int trueTotalWidth, int trueTotalHeight, boolean isTotalWidth, boolean isTotalHeight) { if (imageInfos == null || xs == null || ys == null || widths == null || heights == null) { return null; } try { BufferedImage target = new BufferedImage(totalWidth, totalHeight, BufferedImage.TYPE_INT_ARGB); Graphics2D g = target.createGraphics(); if (AppVariables.ImageHints != null) { g.addRenderingHints(AppVariables.ImageHints); } g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER)); g.setColor(bgColor); g.fillRect(0, 0, totalWidth, totalHeight); for (int i = 0; i < imageInfos.size(); ++i) { if (task != null && !task.isWorking()) { return null; } ImageInformation imageInfo = imageInfos.get(i); Image image = imageInfo.loadImage(task); if (image == null || (task != null && !task.isWorking())) { return null; } BufferedImage source = SwingFXUtils.fromFXImage(image, null); g.drawImage(source, xs.get(i), ys.get(i), widths.get(i), heights.get(i), null); } if (isTotalWidth) { target = ScaleTools.scaleImageBySize(target, trueTotalWidth, (trueTotalWidth * totalHeight) / totalWidth); } else if (isTotalHeight) { target = ScaleTools.scaleImageBySize(target, (trueTotalHeight * totalWidth) / totalHeight, trueTotalHeight); } if (target == null || (task != null && !task.isWorking())) { return null; } Image newImage = SwingFXUtils.toFXImage(target, null); return newImage; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static Image combineImagesColumns(FxTask currentTask, ImageCombine imageCombine, List<ImageInformation> imageInfos) { if (imageInfos == null || imageInfos.isEmpty() || imageCombine.getColumnsValue() <= 0) { return null; } try { List<ImageInformation> rowImages = new ArrayList<>(); List<ImageInformation> rows = new ArrayList<>(); for (ImageInformation imageInfo : imageInfos) { if (currentTask != null && !currentTask.isWorking()) { return null; } rowImages.add(imageInfo); if (rowImages.size() == imageCombine.getColumnsValue()) { Image rowImage = CombineTools.combineSingleRow(currentTask, imageCombine, rowImages, true, false); if (rowImage == null || (currentTask != null && !currentTask.isWorking())) { return null; } rows.add(new ImageInformation(rowImage)); rowImages = new ArrayList<>(); } } if (!rowImages.isEmpty()) { Image rowImage = CombineTools.combineSingleRow(currentTask, imageCombine, rowImages, true, false); if (rowImage == null || (currentTask != null && !currentTask.isWorking())) { return null; } rows.add(new ImageInformation(rowImage)); } Image newImage = CombineTools.combineSingleColumn(currentTask, imageCombine, rows, false, true); return newImage; } catch (Exception e) { MyBoxLog.error(e); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/image/tools/MarginTools.java
alpha/MyBox/src/main/java/mara/mybox/image/tools/MarginTools.java
package mara.mybox.image.tools; import java.awt.Color; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import mara.mybox.image.data.CropTools; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.value.AppVariables; import mara.mybox.value.Colors; /** * @Author Mara * @CreateDate 2018-6-27 18:58:57 * @License Apache License Version 2.0 */ public class MarginTools { public static BufferedImage blurMarginsAlpha(FxTask task, BufferedImage source, int blurWidth, boolean blurTop, boolean blurBottom, boolean blurLeft, boolean blurRight) { try { int width = source.getWidth(); int height = source.getHeight(); int imageType = BufferedImage.TYPE_INT_ARGB; BufferedImage target = new BufferedImage(width, height, imageType); float iOpocity; float jOpacity; float opocity; Color newColor; for (int j = 0; j < height; ++j) { if (task != null && !task.isWorking()) { return null; } for (int i = 0; i < width; ++i) { if (task != null && !task.isWorking()) { return null; } int pixel = source.getRGB(i, j); if (pixel == 0) { target.setRGB(i, j, 0); continue; } iOpocity = jOpacity = 1.0F; if (i < blurWidth) { if (blurLeft) { iOpocity = 1.0F * i / blurWidth; } } else if (i > width - blurWidth) { if (blurRight) { iOpocity = 1.0F * (width - i) / blurWidth; } } if (j < blurWidth) { if (blurTop) { jOpacity = 1.0F * j / blurWidth; } } else if (j > height - blurWidth) { if (blurBottom) { jOpacity = 1.0F * (height - j) / blurWidth; } } opocity = iOpocity * jOpacity; if (opocity == 1.0F) { target.setRGB(i, j, pixel); } else { newColor = new Color(pixel); opocity = newColor.getAlpha() * opocity; newColor = new Color(newColor.getRed(), newColor.getGreen(), newColor.getBlue(), (int) opocity); target.setRGB(i, j, newColor.getRGB()); } } } return target; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static BufferedImage cutMarginsByColor(FxTask task, BufferedImage source, Color cutColor, boolean cutTop, boolean cutBottom, boolean cutLeft, boolean cutRight) { try { if (cutColor.getRGB() == Colors.TRANSPARENT.getRGB() && !AlphaTools.hasAlpha(source)) { return source; } int width = source.getWidth(); int height = source.getHeight(); int top, bottom, left, right; int cutValue = cutColor.getRGB(); if (cutTop) { top = -1; toploop: for (int j = 0; j < height; ++j) { if (task != null && !task.isWorking()) { return null; } for (int i = 0; i < width; ++i) { if (task != null && !task.isWorking()) { return null; } if (source.getRGB(i, j) != cutValue) { top = j; break toploop; } } } if (top < 0) { return null; } } else { top = 0; } if (cutBottom) { bottom = -1; bottomploop: for (int j = height - 1; j >= 0; --j) { if (task != null && !task.isWorking()) { return null; } for (int i = 0; i < width; ++i) { if (task != null && !task.isWorking()) { return null; } if (source.getRGB(i, j) != cutValue) { bottom = j + 1; break bottomploop; } } } if (bottom < 0) { return null; } } else { bottom = height; } if (cutLeft) { left = -1; leftloop: for (int i = 0; i < width; ++i) { if (task != null && !task.isWorking()) { return null; } for (int j = 0; j < height; ++j) { if (task != null && !task.isWorking()) { return null; } if (source.getRGB(i, j) != cutValue) { left = i; break leftloop; } } } if (left < 0) { return null; } } else { left = 0; } if (cutRight) { right = -1; rightloop: for (int i = width - 1; i >= 0; --i) { if (task != null && !task.isWorking()) { return null; } for (int j = 0; j < height; ++j) { if (task != null && !task.isWorking()) { return null; } if (source.getRGB(i, j) != cutValue) { right = i + 1; break rightloop; } } } if (right < 0) { return null; } } else { right = width; } BufferedImage target = CropTools.cropOutside(task, source, left, top, right, bottom); return target; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static BufferedImage cutMarginsByWidth(FxTask task, BufferedImage source, int MarginWidth, boolean cutTop, boolean cutBottom, boolean cutLeft, boolean cutRight) { try { if (source == null || MarginWidth <= 0) { return source; } if (!cutTop && !cutBottom && !cutLeft && !cutRight) { return source; } int width = source.getWidth(); int height = source.getHeight(); int x1 = 0; int y1 = 0; int x2 = width; int y2 = height; if (cutLeft) { x1 = MarginWidth; } if (cutRight) { x2 = width - MarginWidth; } if (cutTop) { y1 = MarginWidth; } if (cutBottom) { y2 = height - MarginWidth; } return CropTools.cropOutside(task, source, x1, y1, x2, y2); } catch (Exception e) { MyBoxLog.error(e); return null; } } public static BufferedImage blurMarginsNoAlpha(FxTask task, BufferedImage source, int blurWidth, boolean blurTop, boolean blurBottom, boolean blurLeft, boolean blurRight) { try { int width = source.getWidth(); int height = source.getHeight(); int imageType = BufferedImage.TYPE_INT_RGB; BufferedImage target = new BufferedImage(width, height, imageType); float iOpocity; float jOpacity; float opocity; Color alphaColor = ColorConvertTools.alphaColor(); for (int j = 0; j < height; ++j) { if (task != null && !task.isWorking()) { return null; } for (int i = 0; i < width; ++i) { if (task != null && !task.isWorking()) { return null; } int pixel = source.getRGB(i, j); if (pixel == 0) { target.setRGB(i, j, alphaColor.getRGB()); continue; } iOpocity = jOpacity = 1.0F; if (i < blurWidth) { if (blurLeft) { iOpocity = 1.0F * i / blurWidth; } } else if (i > width - blurWidth) { if (blurRight) { iOpocity = 1.0F * (width - i) / blurWidth; } } if (j < blurWidth) { if (blurTop) { jOpacity = 1.0F * j / blurWidth; } } else if (j > height - blurWidth) { if (blurBottom) { jOpacity = 1.0F * (height - j) / blurWidth; } } opocity = iOpocity * jOpacity; if (opocity == 1.0F) { target.setRGB(i, j, pixel); } else { Color color = ColorBlendTools.blendColor(new Color(pixel), opocity, alphaColor); target.setRGB(i, j, color.getRGB()); } } } return target; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static BufferedImage addMargins(FxTask task, BufferedImage source, Color addColor, int MarginWidth, boolean addTop, boolean addBottom, boolean addLeft, boolean addRight) { try { if (source == null || MarginWidth <= 0) { return source; } if (!addTop && !addBottom && !addLeft && !addRight) { return source; } int width = source.getWidth(); int height = source.getHeight(); int totalWidth = width; int totalHegiht = height; int x = 0; int y = 0; if (addLeft) { totalWidth += MarginWidth; x = MarginWidth; } if (addRight) { totalWidth += MarginWidth; } if (addTop) { totalHegiht += MarginWidth; y = MarginWidth; } if (addBottom) { totalHegiht += MarginWidth; } int imageType = BufferedImage.TYPE_INT_ARGB; BufferedImage target = new BufferedImage(totalWidth, totalHegiht, imageType); Graphics2D g = target.createGraphics(); if (AppVariables.ImageHints != null) { g.addRenderingHints(AppVariables.ImageHints); } g.setColor(addColor); g.fillRect(0, 0, totalWidth, totalHegiht); if (task != null && !task.isWorking()) { return null; } g.drawImage(source, x, y, width, height, null); g.dispose(); return target; } catch (Exception e) { MyBoxLog.error(e); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/image/tools/BufferedImageTools.java
alpha/MyBox/src/main/java/mara/mybox/image/tools/BufferedImageTools.java
package mara.mybox.image.tools; import java.awt.AlphaComposite; import java.awt.Color; import java.awt.Graphics2D; import java.awt.GraphicsConfiguration; import java.awt.GraphicsEnvironment; import java.awt.RenderingHints; import java.awt.Transparency; import java.awt.geom.RoundRectangle2D; import java.awt.image.BufferedImage; import java.awt.image.ColorModel; import java.io.ByteArrayOutputStream; import java.io.File; import java.util.Arrays; import java.util.Base64; import java.util.Hashtable; import java.util.Map; import javax.imageio.ImageIO; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.image.file.ImageFileReaders; import mara.mybox.tools.MessageDigestTools; import mara.mybox.value.AppVariables; import mara.mybox.value.Colors; import mara.mybox.value.FileExtensions; /** * @Author Mara * @CreateDate 2018-6-27 18:58:57 * @License Apache License Version 2.0 */ public class BufferedImageTools { public static enum Direction { Top, Bottom, Left, Right, LeftTop, RightBottom, LeftBottom, RightTop } public static class KeepRatioType { public static final int BaseOnWidth = 0; public static final int BaseOnHeight = 1; public static final int BaseOnLarger = 2; public static final int BaseOnSmaller = 3; public static final int None = 9; } public static BufferedImage addShadow(FxTask task, BufferedImage source, int shadowX, int shadowY, Color shadowColor, boolean isBlur) { try { if (source == null || shadowColor == null || (shadowX == 0 && shadowY == 0)) { return source; } int width = source.getWidth(); int height = source.getHeight(); boolean blend = !AlphaTools.hasAlpha(source); int imageType = blend ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB; BufferedImage shadowImage = new BufferedImage(width, height, imageType); float iOpocity; float jOpacity; float opocity; float shadowRed = shadowColor.getRed() / 255.0F; float shadowGreen = shadowColor.getGreen() / 255.0F; float shadowBlue = shadowColor.getBlue() / 255.0F; Color newColor; Color alphaColor = blend ? ColorConvertTools.alphaColor() : Colors.TRANSPARENT; int alphaPixel = alphaColor.getRGB(); int offsetX = Math.abs(shadowX); int offsetY = Math.abs(shadowY); for (int j = 0; j < height; ++j) { if (task != null && !task.isWorking()) { return null; } for (int i = 0; i < width; ++i) { if (task != null && !task.isWorking()) { return null; } int pixel = source.getRGB(i, j); if (pixel == 0) { shadowImage.setRGB(i, j, alphaPixel); continue; } if (isBlur) { iOpocity = jOpacity = 1.0F; if (i < offsetX) { iOpocity = 1.0F * i / offsetX; } else if (i > width - offsetX) { iOpocity = 1.0F * (width - i) / offsetX; } if (j < offsetY) { jOpacity = 1.0F * j / offsetY; } else if (j > height - offsetY) { jOpacity = 1.0F * (height - j) / offsetY; } opocity = iOpocity * jOpacity; if (opocity == 1.0F) { newColor = shadowColor; } else if (blend) { newColor = ColorBlendTools.blendColor(shadowColor, opocity, alphaColor); } else { newColor = new Color(shadowRed, shadowGreen, shadowBlue, opocity); } } else { newColor = shadowColor; } shadowImage.setRGB(i, j, newColor.getRGB()); } } if (task != null && !task.isWorking()) { return null; } BufferedImage target = new BufferedImage(width + offsetX, height + offsetY, imageType); Graphics2D g = target.createGraphics(); if (AppVariables.ImageHints != null) { g.addRenderingHints(AppVariables.ImageHints); } g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER)); if (task != null && !task.isWorking()) { return null; } int x = shadowX > 0 ? 0 : -shadowX; int y = shadowY > 0 ? 0 : -shadowY; int sx = shadowX > 0 ? shadowX : 0; int sy = shadowY > 0 ? shadowY : 0; g.drawImage(shadowImage, sx, sy, null); if (task != null && !task.isWorking()) { return null; } g.drawImage(source, x, y, null); g.dispose(); return target; } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e); } return null; } } public static BufferedImage setRound(FxTask task, BufferedImage source, int roundX, int roundY, Color bgColor) { try { int width = source.getWidth(); int height = source.getHeight(); int imageType = BufferedImage.TYPE_INT_ARGB; BufferedImage target = new BufferedImage(width, height, imageType); Graphics2D g = target.createGraphics(); if (AppVariables.ImageHints != null) { g.addRenderingHints(AppVariables.ImageHints); } g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER)); g.setColor(bgColor); g.fillRect(0, 0, width, height); if (task != null && !task.isWorking()) { return null; } g.setClip(new RoundRectangle2D.Double(0, 0, width, height, roundX, roundY)); if (task != null && !task.isWorking()) { return null; } g.drawImage(source, 0, 0, null); g.dispose(); return target; } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e); } return null; } } // https://stackoverflow.com/questions/3514158/how-do-you-clone-a-bufferedimage# public static BufferedImage clone(BufferedImage source) { if (source == null) { return null; } try { ColorModel cm = source.getColorModel(); Hashtable<String, Object> properties = null; String[] keys = source.getPropertyNames(); if (keys != null) { properties = new Hashtable<>(); for (String key : keys) { properties.put(key, source.getProperty(key)); } } return new BufferedImage(cm, source.copyData(null), cm.isAlphaPremultiplied(), properties) .getSubimage(0, 0, source.getWidth(), source.getHeight()); } catch (Exception e) { MyBoxLog.error(e); return null; } } // https://stackoverflow.com/questions/24038524/how-to-get-byte-from-javafx-imageview public static byte[] bytes(FxTask task, BufferedImage srcImage, String format) { byte[] bytes = null; try (ByteArrayOutputStream stream = new ByteArrayOutputStream();) { BufferedImage tmpImage = srcImage; if (!FileExtensions.AlphaImages.contains(format)) { tmpImage = AlphaTools.removeAlpha(task, srcImage); if (tmpImage == null) { return null; } } ImageIO.write(tmpImage, format, stream); bytes = stream.toByteArray(); } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e); } } return bytes; } public static String base64(FxTask task, BufferedImage image, String format) { try { if (image == null || format == null) { return null; } Base64.Encoder encoder = Base64.getEncoder(); byte[] bytes = bytes(task, image, format); if (bytes == null) { return null; } return encoder.encodeToString(bytes); } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e); } return null; } } public static String base64(FxTask task, File file, String format) { try { if (file == null) { return null; } return base64(task, ImageFileReaders.readImage(task, file), format == null ? "jpg" : format); } catch (Exception e) { if (task != null) { task.setError(e.toString()); } else { MyBoxLog.error(e); } return null; } } public static boolean sameByMD5(FxTask task, BufferedImage imageA, BufferedImage imageB) { if (imageA == null || imageB == null || imageA.getWidth() != imageB.getWidth() || imageA.getHeight() != imageB.getHeight()) { return false; } byte[] bA = MessageDigestTools.MD5(task, imageA); if (bA == null || (task != null && !task.isWorking())) { return false; } byte[] bB = MessageDigestTools.MD5(task, imageB); if (bB == null || (task != null && !task.isWorking())) { return false; } return Arrays.equals(bA, bB); } // This way may be quicker than comparing digests public static boolean same(FxTask task, BufferedImage imageA, BufferedImage imageB) { try { if (imageA == null || imageB == null || imageA.getWidth() != imageB.getWidth() || imageA.getHeight() != imageB.getHeight()) { return false; } int width = imageA.getWidth(), height = imageA.getHeight(); 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 (imageA.getRGB(x, y) != imageA.getRGB(x, y)) { return false; } } for (int x = width - 1; x >= width / 2; x--) { if (task != null && !task.isWorking()) { return false; } if (imageA.getRGB(x, y) != imageA.getRGB(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 (imageA.getRGB(x, y) != imageA.getRGB(x, y)) { return false; } } for (int x = width - 1; x >= width / 2; x--) { if (task != null && !task.isWorking()) { return false; } if (imageA.getRGB(x, y) != imageA.getRGB(x, y)) { return false; } } } return true; } catch (Exception e) { return false; } } // This way may be quicker than comparing digests public static boolean sameImage(FxTask task, BufferedImage imageA, BufferedImage imageB) { if (imageA == null || imageB == null || imageA.getWidth() != imageB.getWidth() || imageA.getHeight() != imageB.getHeight()) { return false; } for (int y = 0; y < imageA.getHeight(); y++) { if (task != null && !task.isWorking()) { return false; } for (int x = 0; x < imageA.getWidth(); x++) { if (task != null && !task.isWorking()) { return false; } if (imageA.getRGB(x, y) != imageB.getRGB(x, y)) { return false; } } } return true; } public static GraphicsConfiguration getGraphicsConfiguration() { return GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration(); } public static BufferedImage createCompatibleImage(int width, int height) { return createCompatibleImage(width, height, Transparency.TRANSLUCENT); } public static BufferedImage createCompatibleImage(int width, int height, int transparency) { BufferedImage image = getGraphicsConfiguration().createCompatibleImage(width, height, transparency); image.coerceData(true); return image; } public static BufferedImage applyRenderHints(BufferedImage srcImage, Map<RenderingHints.Key, Object> hints) { try { if (srcImage == null || hints == null) { return srcImage; } int width = srcImage.getWidth(); int height = srcImage.getHeight(); BufferedImage target = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D g = target.createGraphics(); g.addRenderingHints(hints); g.drawImage(srcImage, 0, 0, width, height, null); g.dispose(); return target; } catch (Exception e) { MyBoxLog.error(e); return srcImage; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/image/file/ImageGifFile.java
alpha/MyBox/src/main/java/mara/mybox/image/file/ImageGifFile.java
package mara.mybox.image.file; import com.github.jaiimageio.impl.plugins.gif.GIFImageMetadata; import com.github.jaiimageio.impl.plugins.gif.GIFImageWriter; import com.github.jaiimageio.impl.plugins.gif.GIFImageWriterSpi; import java.awt.image.BufferedImage; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.util.List; import java.util.Map; import javax.imageio.IIOImage; import javax.imageio.ImageIO; import javax.imageio.ImageReader; import javax.imageio.ImageTypeSpecifier; import javax.imageio.ImageWriteParam; import javax.imageio.ImageWriter; import javax.imageio.metadata.IIOMetadata; import javax.imageio.metadata.IIOMetadataNode; import javax.imageio.stream.ImageInputStream; import javax.imageio.stream.ImageOutputStream; import mara.mybox.image.data.ImageAttributes; import mara.mybox.image.data.ImageInformation; import mara.mybox.image.tools.ScaleTools; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.tools.FileDeleteTools; import mara.mybox.tools.FileTmpTools; import mara.mybox.tools.FileTools; import thridparty.GifDecoder; import thridparty.GifDecoder.GifImage; /** * @Author Mara * @CreateDate 2018-6-24 * * @Description * @License Apache License Version 2.0 */ public class ImageGifFile { public static GIFImageMetadata getGifMetadata(File file) { try { // ImageReaderSpi readerSpi = new GIFImageReaderSpi(); // GIFImageReader gifReader = (GIFImageReader) readerSpi.createReaderInstance(); try (ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(file)))) { ImageReader reader = ImageIO.getImageReadersByFormatName("gif").next(); reader.setInput(iis, false); GIFImageMetadata metadata = (GIFImageMetadata) reader.getImageMetadata(0); reader.dispose(); return metadata; } } catch (Exception e) { MyBoxLog.error(e.toString()); return null; } } // https://stackoverflow.com/questions/22259714/arrayindexoutofboundsexception-4096-while-reading-gif-file // https://github.com/DhyanB/Open-Imaging public static BufferedImage readBrokenGifFile(FxTask task, ImageInformation imageInfo) { try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(imageInfo.getFile()))) { GifImage gif = GifDecoder.read(in); BufferedImage bufferedImage = gif.getFrame(imageInfo.getIndex()); if (task != null && !task.isWorking()) { return null; } return ImageFileReaders.adjust(task, imageInfo, bufferedImage); } catch (Exception e) { MyBoxLog.error(e.toString()); imageInfo.setError(e.toString()); return null; } } // https://docs.oracle.com/javase/10/docs/api/javax/imageio/metadata/doc-files/gif_metadata.html#image public static ImageWriter getWriter() { GIFImageWriterSpi gifspi = new GIFImageWriterSpi(); GIFImageWriter writer = new GIFImageWriter(gifspi); return writer; } public static ImageWriteParam getPara(ImageAttributes attributes, ImageWriter writer) { try { ImageWriteParam param = writer.getDefaultWriteParam(); if (param.canWriteCompressed()) { param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); if (attributes != null && attributes.getCompressionType() != null) { param.setCompressionType(attributes.getCompressionType()); } if (attributes != null && attributes.getQuality() > 0) { param.setCompressionQuality(attributes.getQuality() / 100.0f); } else { param.setCompressionQuality(1.0f); } } return param; } catch (Exception e) { MyBoxLog.error(e.toString()); return null; } } public static IIOMetadata getWriterMeta(ImageAttributes attributes, BufferedImage image, ImageWriter writer, ImageWriteParam param) { try { GIFImageMetadata metaData; try { metaData = (GIFImageMetadata) writer.getDefaultImageMetadata(new ImageTypeSpecifier(image), param); } catch (Exception e) { MyBoxLog.error(e.toString()); metaData = null; } if (attributes.getDensity() > 0) { // Have not found the way to set density data in meta data of GIF format. } return metaData; } catch (Exception e) { MyBoxLog.error(e.toString()); return null; } } public static void writeGifImageFile(BufferedImage image, ImageAttributes attributes, String outFile) { try { ImageWriter writer = getWriter(); ImageWriteParam param = getPara(attributes, writer); IIOMetadata metaData = getWriterMeta(attributes, image, writer, param); try (ImageOutputStream out = ImageIO.createImageOutputStream(new File(outFile))) { writer.setOutput(out); writer.write(metaData, new IIOImage(image, null, metaData), param); out.flush(); } writer.dispose(); } catch (Exception e) { MyBoxLog.error(e.toString()); } } public static boolean getParaMeta(long duration, boolean loop, ImageWriteParam param, GIFImageMetadata metaData) { try { param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); param.setCompressionType("LZW"); param.setCompressionQuality(1); String durationV; if (duration > 0) { durationV = duration / 10 + ""; } else { durationV = "100"; } String format = metaData.getNativeMetadataFormatName(); IIOMetadataNode tree = (IIOMetadataNode) metaData.getAsTree(format); IIOMetadataNode graphicsControlExtensionNode = new IIOMetadataNode("GraphicControlExtension"); graphicsControlExtensionNode.setAttribute("delayTime", durationV); graphicsControlExtensionNode.setAttribute("disposalMethod", "restoreToBackgroundColor"); graphicsControlExtensionNode.setAttribute("userInputFlag", "false"); graphicsControlExtensionNode.setAttribute("transparentColorFlag", "false"); graphicsControlExtensionNode.setAttribute("delayTime", durationV); graphicsControlExtensionNode.setAttribute("transparentColorIndex", "0"); tree.appendChild(graphicsControlExtensionNode); if (loop) { IIOMetadataNode applicationExtensionsNode = new IIOMetadataNode("ApplicationExtensions"); IIOMetadataNode applicationExtensionNode = new IIOMetadataNode("ApplicationExtension"); applicationExtensionNode.setAttribute("applicationID", "NETSCAPE"); applicationExtensionNode.setAttribute("authenticationCode", "2.0"); byte[] k = {1, 0, 0}; applicationExtensionNode.setUserObject(k); applicationExtensionsNode.appendChild(applicationExtensionNode); tree.appendChild(applicationExtensionsNode); } metaData.mergeTree(format, tree); return true; } catch (Exception e) { MyBoxLog.error(e.toString()); return false; } } // https://www.programcreek.com/java-api-examples/javax.imageio.ImageWriter // http://www.java2s.com/Code/Java/2D-Graphics-GUI/GiffileEncoder.htm // https://programtalk.com/python-examples/com.sun.media.imageioimpl.plugins.gif.GIFImageWriterSpi/ // https://www.jianshu.com/p/df52f1511cf8 // http://giflib.sourceforge.net/whatsinagif/index.html public static String writeImages(FxTask task, List<ImageInformation> imagesInfo, File outFile, boolean loop, boolean keepSize, int width) { try { if (imagesInfo == null || imagesInfo.isEmpty() || outFile == null) { return "InvalidParameters"; } System.gc(); ImageWriter gifWriter = getWriter(); ImageWriteParam param = gifWriter.getDefaultWriteParam(); GIFImageMetadata metaData = (GIFImageMetadata) gifWriter.getDefaultImageMetadata( ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_INT_RGB), param); File tmpFile = FileTmpTools.getTempFile(); try (ImageOutputStream out = ImageIO.createImageOutputStream(tmpFile)) { gifWriter.setOutput(out); gifWriter.prepareWriteSequence(null); for (ImageInformation info : imagesInfo) { if (task != null && !task.isWorking()) { return null; } BufferedImage bufferedImage = ImageInformation.readBufferedImage(task, info); // bufferedImage = ImageManufacture.removeAlpha(bufferedImage); if (bufferedImage != null) { if (!keepSize) { bufferedImage = ScaleTools.scaleImageWidthKeep(bufferedImage, width); } getParaMeta(info.getDuration(), loop, param, metaData); gifWriter.writeToSequence(new IIOImage(bufferedImage, null, metaData), param); } } gifWriter.endWriteSequence(); gifWriter.dispose(); out.flush(); } catch (Exception e) { MyBoxLog.error(e.toString()); return e.toString(); } return FileTools.override(tmpFile, outFile) ? "" : "Failed"; } catch (Exception e) { MyBoxLog.error(e.toString()); return e.toString(); } } public static String writeImageFiles(FxTask task, List<File> srcFiles, File outFile, int duration, boolean deleteSource) { try { if (srcFiles == null || srcFiles.isEmpty() || outFile == null) { return "InvalidParameters"; } ImageWriter gifWriter = getWriter(); ImageWriteParam param = gifWriter.getDefaultWriteParam(); GIFImageMetadata metaData = (GIFImageMetadata) gifWriter.getDefaultImageMetadata( ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_INT_RGB), param); File tmpFile = FileTmpTools.getTempFile(); try (ImageOutputStream out = ImageIO.createImageOutputStream(tmpFile)) { gifWriter.setOutput(out); gifWriter.prepareWriteSequence(null); for (File file : srcFiles) { if (task != null && !task.isWorking()) { return null; } BufferedImage bufferedImage = ImageFileReaders.readImage(task, file); if (bufferedImage != null) { // bufferedImage = ImageManufacture.removeAlpha(bufferedImage); getParaMeta(duration, true, param, metaData); gifWriter.writeToSequence(new IIOImage(bufferedImage, null, metaData), param); } } gifWriter.endWriteSequence(); out.flush(); } gifWriter.dispose(); if (!FileTools.override(tmpFile, outFile)) { return "Failed"; } if (deleteSource) { for (File file : srcFiles) { FileDeleteTools.delete(file); } srcFiles.clear(); } return ""; } catch (Exception e) { MyBoxLog.error(e.toString()); return e.toString(); } } public static String writeImages(FxTask task, List<BufferedImage> images, File outFile, int duration) { try { if (images == null || images.isEmpty() || outFile == null) { return "InvalidParameters"; } ImageWriter gifWriter = getWriter(); ImageWriteParam param = gifWriter.getDefaultWriteParam(); GIFImageMetadata metaData = (GIFImageMetadata) gifWriter.getDefaultImageMetadata( ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_INT_RGB), param); File tmpFile = FileTmpTools.getTempFile(); try (ImageOutputStream out = ImageIO.createImageOutputStream(tmpFile)) { gifWriter.setOutput(out); gifWriter.prepareWriteSequence(null); for (BufferedImage bufferedImage : images) { if (task != null && !task.isWorking()) { return null; } if (bufferedImage != null) { // bufferedImage = ImageManufacture.removeAlpha(bufferedImage); getParaMeta(duration, true, param, metaData); gifWriter.writeToSequence(new IIOImage(bufferedImage, null, metaData), param); } } gifWriter.endWriteSequence(); out.flush(); } gifWriter.dispose(); return FileTools.override(tmpFile, outFile) ? "" : "Failed"; } catch (Exception e) { MyBoxLog.error(e.toString()); return e.toString(); } } public static void explainGifMetaData(Map<String, Map<String, List<Map<String, Object>>>> metaData, ImageInformation info) { try { String format = "javax_imageio_gif_stream_1.0"; if (metaData.containsKey(format)) { Map<String, List<Map<String, Object>>> javax_imageio_gif_stream = metaData.get(format); if (javax_imageio_gif_stream.containsKey("Version")) { Map<String, Object> Version = javax_imageio_gif_stream.get("Version").get(0); if (Version.containsKey("value")) { info.setNativeAttribute("Version", (String) Version.get("value")); } } if (javax_imageio_gif_stream.containsKey("LogicalScreenDescriptor")) { Map<String, Object> LogicalScreenDescriptor = javax_imageio_gif_stream.get("LogicalScreenDescriptor").get(0); if (LogicalScreenDescriptor.containsKey("logicalScreenWidth")) { info.setNativeAttribute("logicalScreenWidth", Integer.valueOf((String) LogicalScreenDescriptor.get("logicalScreenWidth"))); } if (LogicalScreenDescriptor.containsKey("logicalScreenHeight")) { info.setNativeAttribute("logicalScreenHeight", Integer.valueOf((String) LogicalScreenDescriptor.get("logicalScreenHeight"))); } if (LogicalScreenDescriptor.containsKey("colorResolution")) { info.setNativeAttribute("colorResolution", Integer.valueOf((String) LogicalScreenDescriptor.get("colorResolution"))); } if (LogicalScreenDescriptor.containsKey("pixelAspectRatio")) { int v = Integer.parseInt((String) LogicalScreenDescriptor.get("pixelAspectRatio")); if (v == 0) { info.setNativeAttribute("pixelAspectRatio", 1); } else { info.setNativeAttribute("pixelAspectRatio", (v + 15.f) / 64); } } } if (javax_imageio_gif_stream.containsKey("GlobalColorTable")) { Map<String, Object> GlobalColorTable = javax_imageio_gif_stream.get("GlobalColorTable").get(0); if (GlobalColorTable.containsKey("sizeOfGlobalColorTable")) { info.setNativeAttribute("sizeOfGlobalColorTable", Integer.valueOf((String) GlobalColorTable.get("sizeOfGlobalColorTable"))); } if (GlobalColorTable.containsKey("backgroundColorIndex")) { info.setNativeAttribute("backgroundColorIndex", Integer.valueOf((String) GlobalColorTable.get("backgroundColorIndex"))); } if (GlobalColorTable.containsKey("sortFlag")) { info.setNativeAttribute("sortFlag", (String) GlobalColorTable.get("sortFlag")); } } if (javax_imageio_gif_stream.containsKey("stream_ColorTableEntry")) { List<Map<String, Object>> ColorTableEntryList = javax_imageio_gif_stream.get("ColorTableEntry"); if (ColorTableEntryList != null) { info.setNativeAttribute("stream_ColorTableEntryList", ColorTableEntryList.size()); // Extract data if need in future } } } format = "javax_imageio_gif_image_1.0"; if (metaData.containsKey(format)) { Map<String, List<Map<String, Object>>> javax_imageio_gif_image = metaData.get(format); if (javax_imageio_gif_image.containsKey("Version")) { Map<String, Object> ImageDescriptor = javax_imageio_gif_image.get("ImageDescriptor").get(0); if (ImageDescriptor.containsKey("imageLeftPosition")) { info.setNativeAttribute("imageLeftPosition", (String) ImageDescriptor.get("imageLeftPosition")); } if (ImageDescriptor.containsKey("imageTopPosition")) { info.setNativeAttribute("imageTopPosition", (String) ImageDescriptor.get("imageTopPosition")); } if (ImageDescriptor.containsKey("imageWidth")) { info.setNativeAttribute("imageWidth", (String) ImageDescriptor.get("imageWidth")); } if (ImageDescriptor.containsKey("imageHeight")) { info.setNativeAttribute("imageHeight", (String) ImageDescriptor.get("imageHeight")); } if (ImageDescriptor.containsKey("interlaceFlag")) { info.setNativeAttribute("interlaceFlag", (String) ImageDescriptor.get("interlaceFlag")); } } if (javax_imageio_gif_image.containsKey("ColorTableEntry")) { List<Map<String, Object>> ColorTableEntryList = javax_imageio_gif_image.get("ColorTableEntry"); if (ColorTableEntryList != null) { info.setNativeAttribute("ColorTableEntryList", ColorTableEntryList.size()); // Extract data if need in future } } if (javax_imageio_gif_image.containsKey("GraphicControlExtension")) { Map<String, Object> GraphicControlExtension = javax_imageio_gif_image.get("GraphicControlExtension").get(0); if (GraphicControlExtension.containsKey("disposalMethod")) { info.setNativeAttribute("disposalMethod", (String) GraphicControlExtension.get("disposalMethod")); } if (GraphicControlExtension.containsKey("userInputFlag")) { info.setNativeAttribute("userInputFlag", (String) GraphicControlExtension.get("userInputFlag")); } if (GraphicControlExtension.containsKey("transparentColorFlag")) { info.setNativeAttribute("transparentColorFlag", (String) GraphicControlExtension.get("transparentColorFlag")); } if (GraphicControlExtension.containsKey("delayTime")) { // in hundredths of a second info.setNativeAttribute("delayTime", GraphicControlExtension.get("delayTime")); try { int v = Integer.parseInt((String) GraphicControlExtension.get("delayTime")); info.setDuration(v * 10); } catch (Exception e) { } } if (GraphicControlExtension.containsKey("transparentColorIndex")) { info.setNativeAttribute("transparentColorIndex", (String) GraphicControlExtension.get("transparentColorIndex")); } } if (javax_imageio_gif_image.containsKey("PlainTextExtension")) { Map<String, Object> PlainTextExtension = javax_imageio_gif_image.get("PlainTextExtension").get(0); if (PlainTextExtension.containsKey("textGridLeft")) { info.setNativeAttribute("textGridLeft", PlainTextExtension.get("textGridLeft")); } if (PlainTextExtension.containsKey("textGridTop")) { info.setNativeAttribute("textGridTop", PlainTextExtension.get("textGridTop")); } if (PlainTextExtension.containsKey("textGridWidth")) { info.setNativeAttribute("textGridWidth", PlainTextExtension.get("textGridWidth")); } if (PlainTextExtension.containsKey("textGridHeight")) { info.setNativeAttribute("textGridHeight", PlainTextExtension.get("textGridHeight")); } if (PlainTextExtension.containsKey("characterCellWidth")) { info.setNativeAttribute("characterCellWidth", PlainTextExtension.get("characterCellWidth")); } if (PlainTextExtension.containsKey("characterCellHeight")) { info.setNativeAttribute("characterCellHeight", PlainTextExtension.get("characterCellHeight")); } if (PlainTextExtension.containsKey("textForegroundColor")) { info.setNativeAttribute("textForegroundColor", PlainTextExtension.get("textForegroundColor")); } if (PlainTextExtension.containsKey("textBackgroundColor")) { info.setNativeAttribute("textBackgroundColor", PlainTextExtension.get("textBackgroundColor")); } } if (javax_imageio_gif_image.containsKey("ApplicationExtensions")) { Map<String, Object> ApplicationExtensions = javax_imageio_gif_image.get("ApplicationExtensions").get(0); if (ApplicationExtensions.containsKey("applicationID")) { info.setNativeAttribute("applicationID", ApplicationExtensions.get("applicationID")); } if (ApplicationExtensions.containsKey("authenticationCode")) { info.setNativeAttribute("authenticationCode", ApplicationExtensions.get("authenticationCode")); } } if (javax_imageio_gif_image.containsKey("CommentExtensions")) { Map<String, Object> CommentExtensions = javax_imageio_gif_image.get("CommentExtensions").get(0); if (CommentExtensions.containsKey("value")) { info.setNativeAttribute("CommentExtensions", CommentExtensions.get("value")); } } } } catch (Exception e) { } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false