Skip to content

Instantly share code, notes, and snippets.

@lgvr123
Created December 19, 2022 08:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lgvr123/cdeb8f432ddfdc0ae56ce23e71f1b177 to your computer and use it in GitHub Desktop.
Save lgvr123/cdeb8f432ddfdc0ae56ce23e71f1b177 to your computer and use it in GitHub Desktop.
/**
* Search for the right program by parsing the desktopfile
*
* @param desktopfile
*
* @return
*/
private String getProgramFromDesktopFile(String desktopfile) {
// -- Identify all the places where the desktop file could be stored
Path userhome = Paths.get(System.getProperty("user.home"));
Path localPlace = userhome.resolve(Paths.get(".local", "share", "applications")); // = /home/myuser/.local/share/applications/
Stream<Path> places = Stream.of(localPlace);
String xdgdatadirs = System.getenv("XDG_DATA_DIRS"); // all the official places for storing a desktop file
if (xdgdatadirs != null)
places = Stream.concat(places, Stream.of(xdgdatadirs.split(":")).map(s -> Paths.get(s)));
logger.trace("Searching for " + desktopfile + " in :");
// -- Find where is located the desktop file we are searching for
Path dfile = places
.peek(f -> logger.trace("\t" + f))
.map(f -> f.resolve(desktopfile))
.filter(p -> Files.exists(p))
.findAny()
.orElse(null);
if (dfile == null) {
logger.warn("Could not find any desktop file name " + desktopfile);
return null;
}
logger.debug("Desktopfile found at " + dfile);
// Read the desktopfile as a regulary Property file
Properties dprop = null;
try {
dprop = new Properties();
InputStream stream = Files.newInputStream(dfile);
dprop.load(stream);
} catch (IOException ex) {
logger.error("Fail to read " + dfile, ex);
return null;
}
logger.debug("Exec >> " + dprop.getOrDefault("Exec", "???"));
String program = dprop.getProperty("Exec");
if (program == null)
return null;
// Strip the %1, %F, ...
if (program.contains("%")) {
program = program.substring(0, program.indexOf('%')).trim();
}
logger.debug("Program >> " + program);
return program;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment