package tools; import java.util.Scanner; import java.io.File; import java.lang.Runtime; import java.io.IOException; /** Helper to get application directories. * @author Louis Royer * @author Flavien Haas * @author JS Auge * @version 1.0 */ public class Directories { private String projectName; private String dataHomeDirectory; private String os; /** Constructor with projectName parameter. * @param projectName name of the project */ public Directories(String projectName) { this.projectName = projectName; os = System.getProperty("os.name"); setDataHomeDirectory(); } /** Setter for dataHomeDirectory. Will create the directory if not already exists. */ private void setDataHomeDirectory() { /* Follow XDG Base Directory Specification * https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html */ if (os.equals("Linux")) { dataHomeDirectory = System.getenv().get("XDG_DATA_HOME"); if (dataHomeDirectory == null || dataHomeDirectory.equals("")) { dataHomeDirectory = System.getProperty("user.home") + "/.local/share"; } } else if (os.equals("Mac")||os.equals("Mac OS X")) { /* Apple MacOS X User Data Directory * https://developer.apple.com/library/archive/qa/qa1170/_index.html */ dataHomeDirectory = System.getProperty("user.home") + "/Library"; } else { dataHomeDirectory = "."; } dataHomeDirectory += "/" + projectName + "/"; // create directory if not already exists new File(dataHomeDirectory).mkdirs(); } /** Create a subdirectory. * @param subdir Name of subdirectory to create */ public void createSubdir(String subdir) { String d = dataHomeDirectory; if (subdir != null) { d += subdir; if (!subdir.endsWith("/")) { d += "/"; } } new File(d).mkdirs(); } /** Getter for dataHomeDirectory. * @return path to the application home directory */ public String getDataHomeDirectory() { return dataHomeDirectory; } /** Opens dataHomeDirectory if supported. */ private void openDataHomeDirectory(String subdir) { String d = dataHomeDirectory; if (subdir != null) { d += subdir; if (!subdir.endsWith("/")) { d += "/"; } } try { if (os.equals("Linux")) { Runtime runtime = Runtime.getRuntime(); runtime.exec(new String[] { "xdg-open", d }); } else if (os.equals("Mac")||os.equals("Mac OS X")) { Runtime runtime = Runtime.getRuntime(); runtime.exec(new String[] { "open", d }); } } catch (IOException e) { System.out.println("Error encountered while trying to open directory"); } } /** Asks the user to choose opening dataHomeDirectory or not. */ public void askOpenDataHomeDirectory(String subdir) { if (os.equals("Linux") || os.equals("Mac") || os.equals("Mac OS X")) { System.out.println("Do you want to open this directory? (y/N)"); Scanner scanner = new Scanner(System.in); String resp = scanner.nextLine(); if (resp.equals("y") || resp.equals("Y")) { System.out.println("Openning"); openDataHomeDirectory(subdir); } } } }