From e12a874a96717f390b26924888b780f0cfa80683 Mon Sep 17 00:00:00 2001 From: Alexdoru <57050655+Alexdoru@users.noreply.github.com> Date: Fri, 18 Oct 2024 00:45:00 +0200 Subject: [PATCH] add util to open files / urls on every OS (#83) --- .../gtnewhorizon/gtnhlib/util/FilesUtil.java | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 src/main/java/com/gtnewhorizon/gtnhlib/util/FilesUtil.java diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/util/FilesUtil.java b/src/main/java/com/gtnewhorizon/gtnhlib/util/FilesUtil.java new file mode 100644 index 0000000..ab76a66 --- /dev/null +++ b/src/main/java/com/gtnewhorizon/gtnhlib/util/FilesUtil.java @@ -0,0 +1,58 @@ +package com.gtnewhorizon.gtnhlib.util; + +import java.io.IOException; +import java.net.URI; + +import org.lwjgl.Sys; + +import com.gtnewhorizon.gtnhlib.GTNHLib; + +public class FilesUtil { + + public static void openUri(URI uri) { + switch (net.minecraft.util.Util.getOSType()) { + case OSX -> { + try { + Runtime.getRuntime().exec(new String[] { "/usr/bin/open", uri.toString() }); + return; + } catch (IOException e) { + e.printStackTrace(); + } + } + case WINDOWS -> { + try { + Runtime.getRuntime() + .exec(new String[] { "rundll32", "url.dll,FileProtocolHandler", uri.toString() }); + return; + } catch (IOException e) { + e.printStackTrace(); + } + } + case LINUX -> { + try { + Runtime.getRuntime().exec(new String[] { "xdg-open", uri.toString() }); + return; + } catch (IOException e) { + e.printStackTrace(); + } + } + default -> {} + } + boolean openViaSystemClass = false; + + try { + final Class aClass = Class.forName("java.awt.Desktop"); + final Object getDesktop = aClass.getMethod("getDesktop").invoke(null); + aClass.getMethod("browse", URI.class).invoke(getDesktop, uri); + } catch (Exception e) { + e.printStackTrace(); + openViaSystemClass = true; + } + + if (openViaSystemClass) { + GTNHLib.LOG.debug("Opening via system class!"); + Sys.openURL("file://" + uri); + } + } + +}