Skip to content

Commit

Permalink
Better file logic.
Browse files Browse the repository at this point in the history
  • Loading branch information
IMB11 committed Jun 29, 2024
1 parent e9963d2 commit e0b2481
Showing 1 changed file with 42 additions and 13 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,11 @@
import org.apache.commons.validator.routines.UrlValidator;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
Expand Down Expand Up @@ -141,9 +145,32 @@ protected void initTabNavigation() {
updateValidity();
}

private boolean isValidFilePath(String path) {
File f = new File(path);
return f.exists() && FilenameUtils.getExtension(path).equals("png");
private boolean isValidPngFilePath(String pathStr) {
// Trim leading and trailing spaces
pathStr = pathStr.trim();

// Remove surrounding quotation marks if present
if (pathStr.startsWith("\"") && pathStr.endsWith("\"")) {
pathStr = pathStr.substring(1, pathStr.length() - 1);
}

// Allow ~ as a shortcut for the user's home directory
if (pathStr.startsWith("~")) {
String home = System.getProperty("user.home");
pathStr = home + pathStr.substring(1);
}

// Resolve the path
Path path = Paths.get(pathStr);

// Check if the file exists, follows symlinks, and is a regular file
if (Files.exists(path) && Files.isRegularFile(path)) {
// Check if the file has a .png extension (case insensitive)
String fileName = path.getFileName().toString().toLowerCase();
return fileName.endsWith(".png");
}

return false;
}

private boolean isValidUUID(String uuid) {
Expand All @@ -169,16 +196,7 @@ public boolean validate() {
return urlValidator.isValid(widget.getText());
}
case FILE -> {
String txt = widget.getText();
if (txt.indexOf(":") == txt.length() - 1) {
return false;
}
if (txt.length() > 1) {
if (txt.substring(0, 1).equals("\"") && txt.substring(txt.length() - 1, txt.length()).equals("\"")) {
widget.setText(txt.substring(1, txt.length() - 1));
}
}
return isValidFilePath(widget.getText());
return isValidPngFilePath(widget.getText());
}
case RESOURCE_LOCATION -> {
if (Identifier.isValid(widget.getText())) {
Expand Down Expand Up @@ -324,6 +342,17 @@ public int getHeight() {
SkinShuffle.id("textures/gui/reload-button-icon.png"),
button -> {
if (currentSourceType != SourceType.UNCHANGED) {
if(currentSourceType == SourceType.FILE) {
// Expand ~ to the user's home directory
String pathStr = textFieldWidget.getText();
if (pathStr.startsWith("~")) {
String home = System.getProperty("user.home");
pathStr = home + pathStr.substring(1);
}

textFieldWidget.setText(pathStr);
}

loadSkin();
}
}
Expand Down

0 comments on commit e0b2481

Please sign in to comment.