diff --git a/.gitignore b/.gitignore index cd99249298..9bf866d3bc 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,6 @@ .DS_Store .AppleDouble +*.iml ._* *~ /build/shared/reference.zip diff --git a/app/build.xml b/app/build.xml index b6d97218ab..bef3f06b70 100644 --- a/app/build.xml +++ b/app/build.xml @@ -13,14 +13,14 @@ - + - + @@ -30,22 +30,19 @@ + nowarn="true"> - diff --git a/app/lib/jna-platform.jar b/app/lib/jna-platform.jar index d0fd2e4f52..4722681821 100644 Binary files a/app/lib/jna-platform.jar and b/app/lib/jna-platform.jar differ diff --git a/app/lib/jna.jar b/app/lib/jna.jar index 25243176ea..0b5fabdd8b 100644 Binary files a/app/lib/jna.jar and b/app/lib/jna.jar differ diff --git a/app/src/processing/app/Platform.java b/app/src/processing/app/Platform.java index 16a31bf80e..dc3c8c0da1 100644 --- a/app/src/processing/app/Platform.java +++ b/app/src/processing/app/Platform.java @@ -339,10 +339,10 @@ static public File getJavaHome() { File[] plugins = getContentFile("../PlugIns").listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return dir.isDirectory() && - name.endsWith(".jdk") && !name.startsWith("."); + name.contains("jdk") && !name.startsWith("."); } }); - return new File(plugins[0], "Contents/Home/jre"); + return new File(plugins[0], "Contents/Home"); } // On all other platforms, it's the 'java' folder adjacent to Processing return getContentFile("java"); @@ -412,4 +412,4 @@ static public int unsetenv(String variable) { static public int getSystemDPI() { return inst.getSystemDPI(); } -} \ No newline at end of file +} diff --git a/app/src/processing/app/platform/LinuxPlatform.java b/app/src/processing/app/platform/LinuxPlatform.java index fe3d7ce859..56c7859ded 100644 --- a/app/src/processing/app/platform/LinuxPlatform.java +++ b/app/src/processing/app/platform/LinuxPlatform.java @@ -40,20 +40,6 @@ public class LinuxPlatform extends DefaultPlatform { public void initBase(Base base) { super.initBase(base); - String javaVendor = System.getProperty("java.vendor"); - String javaVM = System.getProperty("java.vm.name"); - if (javaVendor == null || - (!javaVendor.contains("Sun") && !javaVendor.contains("Oracle")) || - javaVM == null || !javaVM.contains("Java")) { - Messages.showWarning("Not fond of this Java VM", - "Processing requires Java 8 from Oracle.\n" + - "Other versions such as OpenJDK, IcedTea,\n" + - "and GCJ are strongly discouraged. Among other things, you're\n" + - "likely to run into problems with sketch window size and\n" + - "placement. For more background, please read the wiki:\n" + - "https://github.com/processing/processing/wiki/Supported-Platforms#linux", null); - } - // Set x11 WM_CLASS property which is used as the application // name by Gnome3 and other window managers. // https://github.com/processing/processing/issues/2534 diff --git a/app/src/processing/app/platform/ThinkDifferent.java b/app/src/processing/app/platform/ThinkDifferent.java index dc905c62a3..01c9823bc3 100644 --- a/app/src/processing/app/platform/ThinkDifferent.java +++ b/app/src/processing/app/platform/ThinkDifferent.java @@ -24,11 +24,15 @@ import java.awt.event.*; import java.io.File; +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; +import java.util.List; import javax.swing.*; -import com.apple.eawt.*; -import com.apple.eawt.AppEvent.*; +import com.apple.eawt.Application; import processing.app.*; import processing.app.ui.About; @@ -65,44 +69,40 @@ static protected void init(final Base base) { if (adapter == null) { adapter = new ThinkDifferent(); //base); } - - application.setAboutHandler(new AboutHandler() { - public void handleAbout(AboutEvent ae) { - new About(null); - } + + setHandler(application, "setAboutHandler", (proxy, method, args) -> { + new About(null); + return null; }); - - application.setPreferencesHandler(new PreferencesHandler() { - public void handlePreferences(PreferencesEvent arg0) { - base.handlePrefs(); - } + + setHandler(application, "setPreferencesHandler", (proxy, method, args) -> { + base.handlePrefs(); + return null; }); - application.setOpenFileHandler(new OpenFilesHandler() { - public void openFiles(OpenFilesEvent event) { - for (File file : event.getFiles()) { - base.handleOpen(file.getAbsolutePath()); - } + setHandler(application, "setOpenFileHandler", (proxy, method, args) -> { + Method m = args[0].getClass().getMethod("getFiles"); + for (File file : (List) m.invoke(args[0])) { + base.handleOpen(file.getAbsolutePath()); } + return null; }); - - application.setPrintFileHandler(new PrintFilesHandler() { - public void printFiles(PrintFilesEvent event) { - // TODO not yet implemented - } + + setHandler(application, "setPrintFileHandler", (proxy, method, args) -> { + // TODO not yet implemented + return null; }); - - application.setQuitHandler(new QuitHandler() { - public void handleQuitRequestWith(QuitEvent event, QuitResponse response) { - if (base.handleQuit()) { - response.performQuit(); - } else { - response.cancelQuit(); - } + + setHandler(application, "setQuitHandler", (proxy, method, args) -> { + if (base.handleQuit()) { + args[1].getClass().getMethod("performQuit").invoke(args[1]); + } else { + args[1].getClass().getMethod("cancelQuit").invoke(args[1]); } + return null; }); - // Set the menubar to be used when nothing else is open. + // Set the menubar to be used when nothing else is open. JMenuBar defaultMenuBar = new JMenuBar(); JMenu fileMenu = buildFileMenu(base); defaultMenuBar.add(fileMenu); @@ -117,12 +117,12 @@ public void handleQuitRequestWith(QuitEvent event, QuitResponse response) { e.printStackTrace(); // oh well, never mind } // } else { -// // The douchebags at Oracle didn't feel that a working f*king menubar -// // on OS X was important enough to make it into the 7u40 release. +// // The douchebags at Oracle didn't feel that a working f*king menubar +// // on OS X was important enough to make it into the 7u40 release. // //http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=8007267 // // It languished in the JDK 8 source and has been backported for 7u60: // //http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=8022667 -// +// // JFrame offscreen = new JFrame(); // offscreen.setUndecorated(true); // offscreen.setJMenuBar(defaultMenuBar); @@ -131,12 +131,51 @@ public void handleQuitRequestWith(QuitEvent event, QuitResponse response) { // offscreen.setVisible(true); // } } - + // public ThinkDifferent(Base base) { // this.base = base; // } + /** + * Sets a handler on an instance of {@link Application}, taking into account JVM version + * differences. + * + * @param app an instance of {@link Application} + * @param name the "set handler" method name + * @param handler the handler + */ + private static void setHandler(Application app, String name, InvocationHandler handler) { + // Determine which version of com.apple.eawt.Application to use and pass it a handler of the + // appropriate type + Method[] methods = app.getClass().getMethods(); + for (Method m : methods) { + if (!name.equals(m.getName())) { + continue; + } + if (m.getParameterCount() != 1) { + continue; + } + Class paramType = m.getParameterTypes()[0]; + try { + // Allow a null handler + Object proxy = null; + if (handler != null) { + proxy = Proxy.newProxyInstance( + paramType.getClassLoader(), new Class[] { paramType }, handler); + } + m.invoke(app, proxy); + } catch (IllegalArgumentException ex) { + // TODO: Print error?: method doesn't take an interface, etc. + } catch (IllegalAccessException ex) { + // TODO: Print error?: Other method invocation problem + } catch (InvocationTargetException ex) { + ex.getCause().printStackTrace(); + // TODO: Print ex.getCause() a different way? + } + break; + } + } /** * Gimpy file menu to be used on OS X when no sketches are open. @@ -162,7 +201,7 @@ public void actionPerformed(ActionEvent e) { fileMenu.add(item); item = Toolkit.newJMenuItemShift(Language.text("menu.file.sketchbook"), 'K'); - item.addActionListener(new ActionListener() { + item.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { base.getNextMode().showSketchbookFrame(); diff --git a/app/src/processing/app/platform/WindowsPlatform.java b/app/src/processing/app/platform/WindowsPlatform.java index 3c4759a375..fd29eed58b 100644 --- a/app/src/processing/app/platform/WindowsPlatform.java +++ b/app/src/processing/app/platform/WindowsPlatform.java @@ -64,10 +64,16 @@ public class WindowsPlatform extends DefaultPlatform { "\\" + APP_NAME.toLowerCase() + ".exe \"%1\""; static final String REG_DOC = APP_NAME + ".Document"; + // Starting with Java 9, the scaling is done automatically. If DPI is + // used to scaling within the application, one ends up with 2x the + // expected scale. See JEP 263. + private static final int WINDOWS_NATIVE_DPI = 96; public void initBase(Base base) { super.initBase(base); + checkAssociations(); + //checkQuickTime(); checkPath(); @@ -627,56 +633,9 @@ public int unsetenv(String variable) { // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . - // Need to extend com.sun.jna.platform.win32.User32 to access - // Win32 function GetDpiForSystem() - interface ExtUser32 extends StdCallLibrary, com.sun.jna.platform.win32.User32 { - ExtUser32 INSTANCE = (ExtUser32) Native.loadLibrary("user32", ExtUser32.class, W32APIOptions.DEFAULT_OPTIONS); - - public int GetDpiForSystem(); - - public int SetProcessDpiAwareness(int value); - - public final int DPI_AWARENESS_INVALID = -1; - public final int DPI_AWARENESS_UNAWARE = 0; - public final int DPI_AWARENESS_SYSTEM_AWARE = 1; - public final int DPI_AWARENESS_PER_MONITOR_AWARE = 2; - - public Pointer SetThreadDpiAwarenessContext(Pointer dpiContext); - - public final Pointer DPI_AWARENESS_CONTEXT_UNAWARE = new Pointer(-1); - public final Pointer DPI_AWARENESS_CONTEXT_SYSTEM_AWARE = new Pointer(-2); - public final Pointer DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE = new Pointer(-3); - } - - - static private int detected = detectSystemDPI(); - - public int getSystemDPI() { - if (detected == -1) { - return super.getSystemDPI(); - } - return detected; + // Note that this is supported "natively" within Java - See JEP 263. + return WINDOWS_NATIVE_DPI; } - - public static int detectSystemDPI() { - try { - ExtUser32.INSTANCE.SetProcessDpiAwareness(ExtUser32.DPI_AWARENESS_SYSTEM_AWARE); - } catch (Throwable e) { - // Ignore error - } - try { - ExtUser32.INSTANCE.SetThreadDpiAwarenessContext(ExtUser32.DPI_AWARENESS_CONTEXT_SYSTEM_AWARE); - } catch (Throwable e) { - // Ignore error (call valid only on Windows 10) - } - try { - return ExtUser32.INSTANCE.GetDpiForSystem(); - } catch (Throwable e) { - // DPI detection failed, fall back with default - System.out.println("DPI detection failed, fallback to 96 dpi"); - return -1; - } - } } diff --git a/app/src/processing/app/syntax/JEditTextArea.java b/app/src/processing/app/syntax/JEditTextArea.java index b63084c63a..c3e6c617cb 100644 --- a/app/src/processing/app/syntax/JEditTextArea.java +++ b/app/src/processing/app/syntax/JEditTextArea.java @@ -76,12 +76,17 @@ public class JEditTextArea extends JComponent /** The size of the offset between the leftmost padding and the code */ public static final int leftHandGutter = 6; + private final Segment TEST_SEGMENT; + private InputMethodSupport inputMethodSupport; private TextAreaDefaults defaults; private Brackets bracketHelper = new Brackets(); + private FontMetrics cachedPartialPixelWidthFont; + private float partialPixelWidth; + /** * Creates a new JEditTextArea with the specified settings. @@ -90,6 +95,9 @@ public class JEditTextArea extends JComponent public JEditTextArea(TextAreaDefaults defaults, InputHandler inputHandler) { this.defaults = defaults; + char[] testSegmentContents = {'w'}; + TEST_SEGMENT = new Segment(testSegmentContents, 0, 1); + // Enable the necessary events enableEvents(AWTEvent.KEY_EVENT_MASK); @@ -113,6 +121,8 @@ public void actionPerformed(ActionEvent e) { lineSegment = new Segment(); bracketLine = bracketPosition = -1; blink = true; + cachedPartialPixelWidthFont = null; + partialPixelWidth = 0; // Initialize the GUI setLayout(new ScrollLayout()); @@ -632,7 +642,7 @@ public int _offsetToX(int line, int offset) { // If syntax coloring is disabled, do simple translation if (tokenMarker == null) { lineSegment.count = offset; - return x + Utilities.getTabbedTextWidth(lineSegment, fm, x, painter, 0); + return x + getTabbedTextWidth(lineSegment, fm, x, painter, 0); } else { // If syntax coloring is enabled, we have to do this @@ -664,10 +674,10 @@ public int _offsetToX(int line, int offset) { int length = tokens.length; if (offset + segmentOffset < lineSegment.offset + length) { lineSegment.count = offset - (lineSegment.offset - segmentOffset); - return x + Utilities.getTabbedTextWidth(lineSegment, fm, x, painter, 0); + return x + getTabbedTextWidth(lineSegment, fm, x, painter, 0); } else { lineSegment.count = length; - x += Utilities.getTabbedTextWidth(lineSegment, fm, x, painter, 0); + x += getTabbedTextWidth(lineSegment, fm, x, painter, 0); lineSegment.offset += length; } tokens = tokens.next; @@ -1310,6 +1320,72 @@ else if ( Character.isWhitespace(ch) ) return CharacterKinds.Other; } + /** + * Get the width in pixels of a segment of text within the IDE. + * + *

+ * Fractional-font aware implementation of Utilities.getTabbedTextWidth that determines if there + * are fractional character widths present in a font in order to return a more accurate pixel + * width for an input segment. + *

+ * + * @param s The segment of text for which a pixel width should be returned. + * @param metrics The metrics for the font in which the given segment will be drawn. + * @param x The x origin. + * @param expander The strategy for converting tabs into characters. + * @param startOffset The offset to apply before the text will be drawn. + * @return The width of the input segment in pixels with fractional character widths considered. + */ + private int getTabbedTextWidth(Segment s, FontMetrics metrics, float x, TabExpander expander, + int startOffset) { + + float additionalOffset = getPartialPixelWidth(metrics, x, expander, startOffset) * s.length(); + + return (int) Math.round( + Utilities.getTabbedTextWidth(s, metrics, x, expander, startOffset) + additionalOffset + ); + } + + /** + * Get any partial widths applied within a font. + * + *

+ * Get any partial widths applied within a font, caching results for the latest requested font + * (as identified via a FontMetrics object). Note that this is calculated for a sample character + * and is only valid for extrapolation in a monospaced font (that one might want to use in an + * IDE). + *

+ * + * @param candidateMetrics The FontMetrics for which partial character pixel widths should be + * returned. + * @param x The x origin. + * @param expander The strategy for converting tabs into characters. + * @param startOffset The offset to apply before the text will be drawn. + * @return The partial width of a sample character within a font. + */ + private float getPartialPixelWidth(FontMetrics candidateMetrics, float x, TabExpander expander, + int startOffset) { + + // See https://github.com/sampottinger/processing/issues/103 + // Requires reference not object equality check + if (candidateMetrics != cachedPartialPixelWidthFont) { + float withFractional = Utilities.getTabbedTextWidth​( + TEST_SEGMENT, + candidateMetrics, + x, + expander, + startOffset + ); + + int withoutFractional = (int) withFractional; + + partialPixelWidth = withFractional - withoutFractional; + cachedPartialPixelWidthFont = candidateMetrics; + } + + return partialPixelWidth; + } + protected void setNewSelectionWord( int line, int offset ) { if (getLineLength(line) == 0) { diff --git a/build/build.xml b/build/build.xml index c7061c2c3d..93f2b05415 100644 --- a/build/build.xml +++ b/build/build.xml @@ -1,6 +1,14 @@ + + + + + + + + @@ -27,52 +35,66 @@ - + - + - + - + - - + + - - + + - - + + - + + + + + + + + - - - + + + + + + + + + + @@ -84,71 +106,89 @@ --> - + + + + + + + - - + + + + + + + + + - - + + + - - - + + + + + + + - - - - - - - + + - - + - + + + - - + + + + - + + + + + + - - - - - - + + - - + - + + + - + @@ -210,16 +250,108 @@ --> - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - + + @@ -232,37 +364,47 @@ classpath="jre/downloader.jar" /> - + + - + - - + + - - + + - + component="JDK" + flavor="${jdk.downloader}" + path="${jdk.tgz.path}" /> - - + + + + @@ -271,8 +413,7 @@ - + @@ -307,18 +448,40 @@ - + + + + + + + + + + + + + + + + + + + + + + - + + - + - + @@ -506,27 +669,51 @@
- - - ======================================================= - Processing for Mac OS X can only be built on Mac OS X. - - Bye. - ======================================================= - - + + + + + + ======================================================= + Processing for Mac can only be built on *nix systems. + + Bye. + ======================================================= + + + + + - + + - - + + + + + + + + - + + + + + + + + + + - + @@ -539,20 +726,17 @@ signature="Pde3" icon="macosx/processing.icns" copyright="© The Processing Foundation" - getInfo="${version}, Copyright © The Processing Foundation" shortVersion="${version}" version="${revision}" - javafx="true" - minimumSystem="10.8.5" mainClassName="processing.app.BaseSplash"> + jdk1.7.0_40.jdk, so we'll need to strip that out. --> @@ -599,7 +783,7 @@ - + @@ -777,19 +1005,24 @@ - - - ======================================================= - Processing for Linux can only be built on *nix systems. - - Bye. - ======================================================= - - - + + + + + + ======================================================= + Processing for Linux can only be built on *nix systems. + + Bye. + ======================================================= + + + + + - + @@ -829,6 +1062,25 @@ + + + + + + + + + + + + + + + + + + + @@ -860,7 +1112,7 @@ Cannot use ant version of tar because it doesn't preserve properties. --> @@ -875,37 +1127,52 @@ --> - + - - + + - + + + + + + + + + + + + + + - + + + - + - + - + - + @@ -926,7 +1193,7 @@ - + @@ -985,7 +1252,7 @@ - + @@ -995,10 +1262,10 @@ - + - + @@ -1064,18 +1331,10 @@ - - ======================================================= - Processing for Windows can only be built on windows. - - Bye. - ======================================================= - - - + - + @@ -1088,10 +1347,10 @@ https://github.com/processing/processing/issues/3624 --> - + - + @@ -1109,6 +1368,34 @@ + + + + + + + + + + + + + + + + + + + + + + @@ -1123,12 +1410,31 @@ - - - - - + + + + + + + + + + + + + + + + + + + + + + @@ -1138,6 +1444,14 @@ + + + + + + + + @@ -1145,22 +1459,32 @@ - - + + + + + + + + + + + + + @@ -1168,7 +1492,7 @@ --> - + @@ -1190,7 +1514,7 @@ excludes="java/**" /> --> - + - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + - + - - - + + diff --git a/build/jre/src/AdoptOpenJdkDownloadUrlGenerator.java b/build/jre/src/AdoptOpenJdkDownloadUrlGenerator.java new file mode 100644 index 0000000000..7ede8c52b5 --- /dev/null +++ b/build/jre/src/AdoptOpenJdkDownloadUrlGenerator.java @@ -0,0 +1,85 @@ +/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */ + +/* + Part of the Processing project - http://processing.org + + Copyright (c) 2019 The Processing Foundation + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + version 2, as published by the Free Software Foundation. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software Foundation, + Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +*/ + +/** + * Utility to generate download URLs from AdoptOpenJDK. + */ +public class AdoptOpenJdkDownloadUrlGenerator extends DownloadUrlGenerator { + + private static final String BASE_URL = "https://github.com/AdoptOpenJDK/openjdk%d-binaries/releases/download/jdk-%d.%d.%d%%2B%d/OpenJDK%dU-%s_%d.%d.%d_%d.%s"; + + @Override + public String buildUrl(String platform, String component, int train, int version, int update, + int build, String flavor, String hash) { + + if (!component.equalsIgnoreCase("jdk")) { + throw new RuntimeException("Can only generate JDK download URLs for AdoptOpenJDK."); + } + + String filename = buildDownloadRemoteFilename(platform); + String fileExtension = buildFileExtension(platform); + return String.format( + BASE_URL, + train, + train, + version, + update, + build, + train, + filename, + train, + version, + update, + build, + fileExtension + ); + } + + /** + * Build a the filename (the "flavor") that is expected on AdoptOpenJDK. + * + * @param downloadPlatform The platform for which the download URL is being generated like + * "macos" or "linux64". + * @return The artifact name without extension like "jdk_x64_mac_hotspot". + */ + private String buildDownloadRemoteFilename(String downloadPlatform) { + switch (downloadPlatform.toLowerCase()) { + case "windows32": return "jdk_x86-32_windows_hotspot"; + case "windows64": return "jdk_x64_windows_hotspot"; + case "macosx64": return "jdk_x64_mac_hotspot"; + case "linux32": throw new RuntimeException("Linux32 not supported by AdoptOpenJDK."); + case "linux64": return "jdk_x64_linux_hotspot"; + case "linuxarm": return "jdk_aarch64_linux_hotspot"; + default: throw new RuntimeException("Unknown platform: " + downloadPlatform); + } + } + + /** + * Determine the download file extension. + * + * @param downloadPlatform The platform for which the download URL is being generated like + * "macos" or "linux64". + * @return The file extension without leading period like "zip" or "tar.gz". + */ + private String buildFileExtension(String downloadPlatform) { + return downloadPlatform.startsWith("windows") ? "zip" : "tar.gz"; + } +} diff --git a/build/jre/src/DownloadItem.java b/build/jre/src/DownloadItem.java new file mode 100644 index 0000000000..30e716f435 --- /dev/null +++ b/build/jre/src/DownloadItem.java @@ -0,0 +1,77 @@ +/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */ + +/* + Part of the Processing project - http://processing.org + + Copyright (c) 2014-19 The Processing Foundation + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + version 2, as published by the Free Software Foundation. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software Foundation, + Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +*/ + +import java.util.Optional; + + +/** + * Data structure describing an item to be downloaded as part the Processing build. + */ +public class DownloadItem { + + private String url; + private String localPath; + private Optional cookie; + + /** + * Create a new download item. + * + * @param newUrl The remote URL at which the download can be found (via GET). + * @param newLocalPath The local path to which the file should be written. + * @param newCookie Optional cookie that, if present, should be given to the server along with the + * GET request for the download contents. + */ + public DownloadItem(String newUrl, String newLocalPath, Optional newCookie) { + url = newUrl; + localPath = newLocalPath; + cookie = newCookie; + } + + /** + * Determine where the download can be requested. + * + * @return The remote URL at which the download can be found (via GET). + */ + public String getUrl() { + return url; + } + + /** + * Determine to where the download should be saved. + * + * @return The local path to which the file should be written. + */ + public String getLocalPath() { + return localPath; + } + + /** + * Determine if and what cookie should be given as part of the download request. + * + * @return Optional cookie that, if present, should be given to the server along with the + * GET request for the download contents. Should be ignored otherwise. + */ + public Optional getCookie() { + return cookie; + } + + +} diff --git a/build/jre/src/DownloadUrlGenerator.java b/build/jre/src/DownloadUrlGenerator.java new file mode 100644 index 0000000000..02e0d62c46 --- /dev/null +++ b/build/jre/src/DownloadUrlGenerator.java @@ -0,0 +1,84 @@ +/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */ + +/* + Part of the Processing project - http://processing.org + + Copyright (c) 2014-19 The Processing Foundation + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + version 2, as published by the Free Software Foundation. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software Foundation, + Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +*/ + + +import java.util.Optional; + +/** + * Abstract base class for strategy to generate download URLs. + */ +public abstract class DownloadUrlGenerator { + + /** + * Determine the URL at which the artifact can be downloaded. + * + * @param platform The platform for which the download URL is being generated like "macos" or + * "linux64". + * @param component The component to download like "JDK", "JRE", or "JFX". + * @param train The JDK train (like 1 or 11). + * @param version The JDK version (like 8 or 1). + * @param update The update (like 13). + * @param build The build number (like 133). + * @param flavor The flavor like "macosx-x64.dmg". + * @param hash The hash like "d54c1d3a095b4ff2b6607d096fa80163". + */ + public abstract String buildUrl(String platform, String component, int train, int version, + int update, int build, String flavor, String hash); + + /** + * Get the cookie that should be used in downloading the target component. + * + * @return Optional that is empty if no cookie should be used or optional with the string cookie + * value if one should be used. + */ + public Optional getCookie() { + return Optional.empty(); + } + + /** + * Determine the name of the file to which the remote file should be saved. + * + * @param downloadPlatform The platform for which the download URL is being generated like + * "macos" or "linux64". + * @param component The component to download like "JDK", "JRE", or "JFX". + * @param train The JDK train (like 1 or 11). + * @param version The JDK version (like 8 or 1). + * @param update The update (like 13). + * @param build The build number (like 133). + * @param flavor The flavor like "macosx-x64.dmg". + * @param hash The hash like "d54c1d3a095b4ff2b6607d096fa80163". + */ + public String getLocalFilename(String downloadPlatform, String component, int train, int version, + int update, int build, String flavor, String hash) { + + String baseFilename = component.toLowerCase(); + + String versionStr; + if (update == 0) { + versionStr = String.format("-%d-%s", version, flavor); + } else { + versionStr = String.format("-%du%d-%s", version, update, flavor); + } + + return baseFilename + versionStr; + } + +} diff --git a/build/jre/src/Downloader.java b/build/jre/src/Downloader.java index b25fb58b8d..8828cb595e 100644 --- a/build/jre/src/Downloader.java +++ b/build/jre/src/Downloader.java @@ -1,3 +1,24 @@ +/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */ + +/* + Part of the Processing project - http://processing.org + + Copyright (c) 2014-19 The Processing Foundation + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + version 2, as published by the Free Software Foundation. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software Foundation, + Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +*/ + import java.io.*; import java.net.*; import java.util.*; @@ -7,66 +28,134 @@ /** - * Ant Task for downloading the latest JRE or JDK from Oracle. + * Ant Task for downloading the latest JRE, JDK, or OpenJFX release. */ public class Downloader extends Task { - static final String COOKIE = - "oraclelicense=accept-securebackup-cookie"; + private static final boolean PRINT_LOGGING = true; - private int version; // Java 8 + private boolean openJdk; // If using openJDK. + private String platform; // macos + private int train; // Java 11 (was 1 through Java 8) + private int version; // 0 (was 8 prior to Java 9) private int update; // Update 131 private int build; // Build 11 // https://gist.github.com/P7h/9741922 // http://stackoverflow.com/q/10268583 private String hash; // d54c1d3a095b4ff2b6607d096fa80163 - private boolean jdk; // false if JRE + private String component; // "JRE", "JDK", or "JFX" - private String flavor; + private String flavor; // Like "zip" private String path; // target path + /** + * Create a new downloader without tag attributes filled in. + **/ public Downloader() { } + /** + * Set the platform being used. + * + * @param platform The platfom for which files are being downloaded like macosx. + */ + public void setPlatform(String platform) { + this.platform = platform; + } + + /** + * Indicate if the OpenJDK is being used. + * + * @param openJdk True if OpenJDK is being used. False if Oracle JDK is being used. + */ + public void setOpenJdk(boolean openJdk) { + this.openJdk = openJdk; + } + + /** + * Specify the build train being used. + * + * @param train The build train like 1 (Java 8 and before) or 11 (Java 11). + */ + public void setTrain(int train) { + this.train = train; + } + /** + * Set the version to download within the given build train. + * + * @param version The version within the train to use like 0 for "11.0.1_13". + */ public void setVersion(int version) { this.version = version; } - + /** + * Set the update number to download within the given build train. + * + * @param update The update within the version to use like 1 for "11.0.1_13". + */ public void setUpdate(int update) { this.update = update; } - + /** + * Set the build number to download. + * + * @param build The build number to use within the build train like 13 for "11.0.1_13". + */ public void setBuild(int build) { this.build = build; } - + /** + * Set the expected hash of the download. + * + * @param hash The hash set. + */ public void setHash(String hash) { this.hash = hash; } - - public void setJDK(boolean jdk) { - this.jdk = jdk; + /** + * Indicate what component or release type of Java is being downloaded. + * + * @param component The component to download like "JDK", "JRE", or "OpenJFX". + */ + public void setComponent(String component) { + this.component = component; } - + /** + * Indicate the file flavor to be downloaded. + * + * @param flavor The flavor of file (dependent on platform) to be downloaded. Like "-x64.tar.gz". + */ public void setFlavor(String flavor) { this.flavor = flavor; } - + /** + * Set the path to which the file should be downloaded. + * + * @param path The path to which the file should be downloaded. + */ public void setPath(String path) { this.path = path; } - + /** + * Download the JDK or JRE. + */ public void execute() throws BuildException { - if (version == 0) { + if (train == 0) { + // 1 if prior to Java 9 + throw new BuildException("Train (i.e. 1 or 11) must be set"); + } + + boolean isJava11 = train == 11; + if (!isJava11 && version == 0) { throw new BuildException("Version (i.e. 7 or 8) must be set"); } @@ -90,33 +179,38 @@ public void execute() throws BuildException { } } - + /** + * Download the package from AdoptOpenJDK or Oracle. + */ void download() throws IOException { - String filename = (jdk ? "jdk" : "jre") + - (update == 0 ? - String.format("-%d-%s", version, flavor) : - String.format("-%du%d-%s", version, update, flavor)); + DownloadItem downloadItem; - if (path == null) { - path = filename; + // Determine url generator for task + Optional downloadItemMaybe = getDownloadItem(); + if (downloadItemMaybe.isEmpty()) { + return; // There is nothing to do. + } else { + downloadItem = downloadItemMaybe.get(); } - String url = "http://download.oracle.com/otn-pub/java/jdk/" + - (update == 0 ? - String.format("%d-b%02d/", version, build) : - String.format("%du%d-b%02d/", version, update, build)); - - // URL format changed starting with 8u121 - if (update >= 121) { - url += hash + "/"; + // Build URL and path + if (path == null) { + path = downloadItem.getLocalPath(); } - // Finally, add the filename to the end - url += filename; + String url = downloadItem.getUrl(); + + // Downlaod + println("Attempting download at " + url); HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); - conn.setRequestProperty("Cookie", COOKIE); + + Optional cookieMaybe = downloadItem.getCookie(); + + if (cookieMaybe.isPresent()) { + conn.setRequestProperty("Cookie", cookieMaybe.get()); + } //printHeaders(conn); //conn.connect(); @@ -125,7 +219,7 @@ void download() throws IOException { List location = headers.get("Location"); if (location.size() == 1) { url = location.get(0); - System.out.println("Redirecting to " + url); + println("Redirecting to " + url); } else { throw new BuildException("Got " + location.size() + " locations."); } @@ -136,7 +230,11 @@ void download() throws IOException { conn.setRequestProperty("Cookie", cookie); } } - conn.setRequestProperty("Cookie", COOKIE); + + if (cookieMaybe.isPresent()) { + conn.setRequestProperty("Cookie", cookieMaybe.get()); + } + conn.connect(); } @@ -144,7 +242,10 @@ void download() throws IOException { InputStream input = conn.getInputStream(); BufferedInputStream bis = new BufferedInputStream(input); File outputFile = new File(path); //folder, filename); - System.out.format("Downloading %s from %s%n", outputFile.getAbsolutePath(), url); + + String msg = String.format("Downloading %s from %s%n", outputFile.getAbsolutePath(), url); + println(msg); + // Write to a temp file so that we don't have an incomplete download // masquerading as a good archive. File tempFile = File.createTempFile("download", "", outputFile.getParentFile()); @@ -175,19 +276,107 @@ void download() throws IOException { } } - + /** + * Print the headers used for {URLConnection}. + */ static void printHeaders(URLConnection conn) { Map> headers = conn.getHeaderFields(); Set>> entrySet = headers.entrySet(); for (Map.Entry> entry : entrySet) { String headerName = entry.getKey(); - System.out.println("Header Name:" + headerName); + println("Header Name:" + headerName); List headerValues = entry.getValue(); for (String value : headerValues) { - System.out.print("Header value:" + value); + print("Header value:" + value); } - System.out.println(); - System.out.println(); + printEmptyLine(); + printEmptyLine(); } } + + /** + * Get the item to be downloaded for this task. + * + * @return The to be downloaded or empty if there is no download required. + */ + private Optional getDownloadItem() { + // Determine download type + boolean isJavaDownload = component.equalsIgnoreCase("jdk"); + isJavaDownload = isJavaDownload || component.equalsIgnoreCase("jre"); + + boolean isJfxDownload = component.equalsIgnoreCase("jfx"); + + DownloadUrlGenerator downloadUrlGenerator; + + // Determine url generator + if (isJavaDownload) { + if (openJdk) { + downloadUrlGenerator = new AdoptOpenJdkDownloadUrlGenerator(); + } else { + downloadUrlGenerator = new OracleDownloadUrlGenerator(); + } + } else if (isJfxDownload) { + if (openJdk) { + downloadUrlGenerator = new GluonHqDownloadUrlGenerator(); + } else { + return Optional.empty(); // Nothing to download + } + } else { + throw new RuntimeException("Do not know how to download: " + component); + } + + // Build download item + String path = downloadUrlGenerator.getLocalFilename( + platform, + component, + train, + version, + update, + build, + flavor, + hash + ); + + String url = downloadUrlGenerator.buildUrl( + platform, + component, + train, + version, + update, + build, + flavor, + hash + ); + + return Optional.of(new DownloadItem(url, path, downloadUrlGenerator.getCookie())); + } + + /** + * Print a line out to console if logging is enabled. + * + * @param message The message to be printed. + */ + private static void println(String message) { + if (PRINT_LOGGING) { + System.out.println(message); + } + } + + /** + * Print a line out to console if logging is enabled without a newline. + * + * @param message The message to be printed. + */ + private static void print(String message) { + if (PRINT_LOGGING) { + System.out.print(message); + } + } + + /** + * Print an empty line to the system.out. + */ + private static void printEmptyLine() { + println(""); + } } diff --git a/build/jre/src/GluonHqDownloadUrlGenerator.java b/build/jre/src/GluonHqDownloadUrlGenerator.java new file mode 100644 index 0000000000..d11fc5df3d --- /dev/null +++ b/build/jre/src/GluonHqDownloadUrlGenerator.java @@ -0,0 +1,50 @@ +/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */ + +/* + Part of the Processing project - http://processing.org + + Copyright (c) 2014-19 The Processing Foundation + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + version 2, as published by the Free Software Foundation. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software Foundation, + Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +*/ + + +/** + * URL generator for downloading JFX directly from OpenJFX's sponsor Gluon. + */ +public class GluonHqDownloadUrlGenerator extends DownloadUrlGenerator { + + private static final String TEMPLATE_URL = "http://gluonhq.com/download/javafx-%d-%d-%d-sdk-%s/"; + + @Override + public String buildUrl(String platform, String component, int train, int version, int update, + int build, String flavor, String hash) { + + String platformLower = platform.toLowerCase(); + + String platformShort; + if (platformLower.contains("linux")) { + platformShort = "linux"; + } else if (platformLower.contains("mac")) { + platformShort = "mac"; + } else if (platformLower.contains("windows")) { + platformShort = "windows"; + } else { + throw new RuntimeException("Unsupported platform for JFX: " + platform); + } + + return String.format(TEMPLATE_URL, train, version, update, platformShort); + } + +} diff --git a/build/jre/src/OracleDownloadUrlGenerator.java b/build/jre/src/OracleDownloadUrlGenerator.java new file mode 100644 index 0000000000..2984bfa1c5 --- /dev/null +++ b/build/jre/src/OracleDownloadUrlGenerator.java @@ -0,0 +1,72 @@ +/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */ + +/* + Part of the Processing project - http://processing.org + + Copyright (c) 2014-19 The Processing Foundation + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + version 2, as published by the Free Software Foundation. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software Foundation, + Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +*/ + + +import java.util.Optional; + +/** + * Utility to generate the download URL from Oracle. + */ +public class OracleDownloadUrlGenerator extends DownloadUrlGenerator { + private static final String COOKIE = + "oraclelicense=accept-securebackup-cookie"; + + + @Override + public String buildUrl(String platform, String component, int train, int version, int update, + int build, String flavor, String hash) { + + if (!component.equalsIgnoreCase("jdk")) { + throw new RuntimeException("Can only generate JDK download URLs for Oracle."); + } + + String filename = getLocalFilename( + platform, + component, + train, + version, + update, + build, + flavor, + hash + ); + + String url = "http://download.oracle.com/otn-pub/java/jdk/" + + (update == 0 ? + String.format("%d-b%02d/", version, build) : + String.format("%du%d-b%02d/", version, update, build)); + + // URL format changed starting with 8u121 + if (update >= 121) { + url += hash + "/"; + } + + // Finally, add the filename to the end + url += filename; + + return url; + } + + public Optional getCookie() { + return Optional.of(COOKIE); + } + +} diff --git a/build/jre/test/AdoptOpenJdkDownloadUrlGeneratorTest.java b/build/jre/test/AdoptOpenJdkDownloadUrlGeneratorTest.java new file mode 100644 index 0000000000..4a07fa990d --- /dev/null +++ b/build/jre/test/AdoptOpenJdkDownloadUrlGeneratorTest.java @@ -0,0 +1,128 @@ +/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */ + +/* + Part of the Processing project - http://processing.org + + Copyright (c) 2012-19 The Processing Foundation + Copyright (c) 2004-12 Ben Fry and Casey Reas + Copyright (c) 2001-04 Massachusetts Institute of Technology + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + version 2, as published by the Free Software Foundation. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software Foundation, + Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +*/ + + +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class AdoptOpenJdkDownloadUrlGeneratorTest { + + private static final String EXPECTED_WIN64_URL = "https://github.com/AdoptOpenJDK/openjdk11-binaries/releases/download/jdk-11.0.1%2B13/OpenJDK11U-jdk_x64_windows_hotspot_11.0.1_13.zip"; + private static final String EXPECTED_MAC_URL = "https://github.com/AdoptOpenJDK/openjdk11-binaries/releases/download/jdk-11.0.1%2B13/OpenJDK11U-jdk_x64_mac_hotspot_11.0.1_13.tar.gz"; + private static final String EXPECTED_LINUX_URL = "https://github.com/AdoptOpenJDK/openjdk11-binaries/releases/download/jdk-11.0.1%2B13/OpenJDK11U-jdk_x64_linux_hotspot_11.0.1_13.tar.gz"; + private static final String EXPECTED_LINUX_URL_ARM = "https://github.com/AdoptOpenJDK/openjdk11-binaries/releases/download/jdk-11.0.1%2B13/OpenJDK11U-jdk_aarch64_linux_hotspot_11.0.1_13.tar.gz"; + + private static final String COMPONENT = "jdk"; + private static final int TRAIN = 11; + private static final int VERSION = 0; + private static final int UPDATE = 1; + private static final int BUILD = 13; + private static final String FLAVOR_SUFFIX = "-x64.tar.gz"; + private static final String HASH = ""; + + private AdoptOpenJdkDownloadUrlGenerator urlGenerator; + + @Before + public void setUp() throws Exception { + urlGenerator = new AdoptOpenJdkDownloadUrlGenerator(); + } + + @Test + public void testBuildUrlWindows() { + String url = urlGenerator.buildUrl( + "windows64", + COMPONENT, + TRAIN, + VERSION, + UPDATE, + BUILD, + "windows" + FLAVOR_SUFFIX, + HASH + ); + + assertEquals( + EXPECTED_WIN64_URL, + url + ); + } + + @Test + public void testBuildUrlMac() { + String url = urlGenerator.buildUrl( + "macosx64", + COMPONENT, + TRAIN, + VERSION, + UPDATE, + BUILD, + "mac" + FLAVOR_SUFFIX, + HASH + ); + + assertEquals( + EXPECTED_MAC_URL, + url + ); + } + + @Test + public void testBuildUrlLinux64() { + String url = urlGenerator.buildUrl( + "linux64", + COMPONENT, + TRAIN, + VERSION, + UPDATE, + BUILD, + "linux64" + FLAVOR_SUFFIX, + HASH + ); + + assertEquals( + EXPECTED_LINUX_URL, + url + ); + } + + @Test + public void testBuildUrlLinuxArm() { + String url = urlGenerator.buildUrl( + "linuxArm", + COMPONENT, + TRAIN, + VERSION, + UPDATE, + BUILD, + "linuxArm" + FLAVOR_SUFFIX, + HASH + ); + + assertEquals( + EXPECTED_LINUX_URL_ARM, + url + ); + } + +} diff --git a/build/jre/test/GluonHqDownloadUrlGeneratorTest.java b/build/jre/test/GluonHqDownloadUrlGeneratorTest.java new file mode 100644 index 0000000000..0f1ca2faa2 --- /dev/null +++ b/build/jre/test/GluonHqDownloadUrlGeneratorTest.java @@ -0,0 +1,108 @@ +/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */ + +/* + Part of the Processing project - http://processing.org + + Copyright (c) 2012-19 The Processing Foundation + Copyright (c) 2004-12 Ben Fry and Casey Reas + Copyright (c) 2001-04 Massachusetts Institute of Technology + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + version 2, as published by the Free Software Foundation. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software Foundation, + Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +*/ + + +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class GluonHqDownloadUrlGeneratorTest { + + private static final String EXPECTED_WIN64_URL = "http://gluonhq.com/download/javafx-11-0-2-sdk-windows/"; + private static final String EXPECTED_MAC_URL = "http://gluonhq.com/download/javafx-11-0-2-sdk-mac"; + private static final String EXPECTED_LINUX_URL = "http://gluonhq.com/download/javafx-11-0-2-sdk-linux/"; + + private static final String COMPONENT = "jfx"; + private static final int TRAIN = 11; + private static final int VERSION = 0; + private static final int UPDATE = 2; + private static final int BUILD = 0; + private static final String FLAVOR_SUFFIX = ".zip"; + private static final String HASH = ""; + + private AdoptOpenJdkDownloadUrlGenerator urlGenerator; + + @Before + public void setUp() throws Exception { + urlGenerator = new AdoptOpenJdkDownloadUrlGenerator(); + } + + @Test + public void testBuildUrlWindows() { + String url = urlGenerator.buildUrl( + "windows64", + COMPONENT, + TRAIN, + VERSION, + UPDATE, + BUILD, + "windows" + FLAVOR_SUFFIX, + HASH + ); + + assertEquals( + EXPECTED_WIN64_URL, + url + ); + } + + @Test + public void testBuildUrlMac() { + String url = urlGenerator.buildUrl( + "macosx64", + COMPONENT, + TRAIN, + VERSION, + UPDATE, + BUILD, + "mac" + FLAVOR_SUFFIX, + HASH + ); + + assertEquals( + EXPECTED_MAC_URL, + url + ); + } + + @Test + public void testBuildUrlLinux() { + String url = urlGenerator.buildUrl( + "linux64", + COMPONENT, + TRAIN, + VERSION, + UPDATE, + BUILD, + "linux64" + FLAVOR_SUFFIX, + HASH + ); + + assertEquals( + EXPECTED_LINUX_URL, + url + ); + } + +} diff --git a/build/jre/test/OracleDownloadUrlGeneratorTest.java b/build/jre/test/OracleDownloadUrlGeneratorTest.java new file mode 100644 index 0000000000..2124c210f2 --- /dev/null +++ b/build/jre/test/OracleDownloadUrlGeneratorTest.java @@ -0,0 +1,59 @@ +/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */ + +/* + Part of the Processing project - http://processing.org + + Copyright (c) 2012-19 The Processing Foundation + Copyright (c) 2004-12 Ben Fry and Casey Reas + Copyright (c) 2001-04 Massachusetts Institute of Technology + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + version 2, as published by the Free Software Foundation. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software Foundation, + Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +*/ + +import org.junit.Before; +import org.junit.Test; +import org.junit.Ignore; +import static org.junit.Assert.assertEquals; + +public class OracleDownloadUrlGeneratorTest { + + private static final String EXPECTED_URL = "http://download.oracle.com/otn-pub/java/jdk/8u131-b11/d54c1d3a095b4ff2b6607d096fa80163/jdk-8u131-macosx-x64.dmg"; + + private OracleDownloadUrlGenerator urlGenerator; + + @Before + public void setUp() throws Exception { + urlGenerator = new OracleDownloadUrlGenerator(); + } + + @Test + public void testBuildUrl() { + String url = urlGenerator.buildUrl( + "macos", + "jdk", + 1, + 8, + 131, + 11, + "macosx-x64.dmg", + "d54c1d3a095b4ff2b6607d096fa80163" + ); + + assertEquals( + EXPECTED_URL, + url + ); + } + +} diff --git a/build/library/ant-contrib-0.6.jar b/build/library/ant-contrib-0.6.jar new file mode 100644 index 0000000000..db90b0aae8 Binary files /dev/null and b/build/library/ant-contrib-0.6.jar differ diff --git a/build/library/ant-contrib-LICENSE.txt b/build/library/ant-contrib-LICENSE.txt new file mode 100644 index 0000000000..4d8c2fb7a1 --- /dev/null +++ b/build/library/ant-contrib-LICENSE.txt @@ -0,0 +1,47 @@ +/* + * The Apache Software License, Version 1.1 + * + * Copyright (c) 2001-2003 Ant-Contrib project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, if + * any, must include the following acknowlegement: + * "This product includes software developed by the + * Ant-Contrib project (http://sourceforge.net/projects/ant-contrib)." + * Alternately, this acknowlegement may appear in the software itself, + * if and wherever such third-party acknowlegements normally appear. + * + * 4. The name Ant-Contrib must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact + * ant-contrib-developers@lists.sourceforge.net. + * + * 5. Products derived from this software may not be called "Ant-Contrib" + * nor may "Ant-Contrib" appear in their names without prior written + * permission of the Ant-Contrib project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE ANT-CONTRIB PROJECT OR ITS + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + */ diff --git a/build/linux/processing b/build/linux/processing index 078b2428b5..a7a008e334 100755 --- a/build/linux/processing +++ b/build/linux/processing @@ -1,11 +1,11 @@ #!/bin/sh -# This script runs Processing, using the JRE in the Processing +# This script runs Processing, using the JRE in the Processing # installation directory. # If your system needs a different version of Java than what's included # in the download, replace the 'java' folder with the contents of a new -# Oracle JRE (Java 8 only), or create a symlink named "java" in the +# Oracle JRE (Java 8 only), or create a symlink named "java" in the # Processing installation directory that points to the JRE home directory. # This must be a Sun/Oracle JDK. For more details, see here: # https://github.com/processing/processing/wiki/Supported-Platforms @@ -104,7 +104,7 @@ cmd_name='processing-java' if [ $current_name = $cmd_name ] then - java -Djna.nosys=true -Djava.ext.dirs="$APPDIR"/java/lib/ext -Xmx256m processing.mode.java.Commander "$@" + java -Djna.nosys=true -Xmx256m processing.mode.java.Commander "$@" exit $? else # Start Processing in the same directory as this script @@ -115,5 +115,5 @@ else fi cd "$APPDIR" - java -splash:lib/about-1x.png -Djna.nosys=true -Djava.ext.dirs="$APPDIR"/java/lib/ext -Xmx256m processing.app.Base "$SKETCH" & + java -splash:lib/about-1x.png -Djna.nosys=true -Xmx256m processing.app.Base "$SKETCH" & fi diff --git a/build/macosx/appbundler.jar b/build/macosx/appbundler.jar index 42cc8f18cd..62a658d51e 100644 Binary files a/build/macosx/appbundler.jar and b/build/macosx/appbundler.jar differ diff --git a/build/macosx/appbundler/build.xml b/build/macosx/appbundler/build.xml index 4d02204175..068b41b39a 100644 --- a/build/macosx/appbundler/build.xml +++ b/build/macosx/appbundler/build.xml @@ -73,8 +73,7 @@ questions. - - + @@ -90,7 +89,7 @@ questions. --> - + diff --git a/build/macosx/appbundler/doc/appbundler.html b/build/macosx/appbundler/doc/appbundler.html index aa44684872..5c213e908a 100644 --- a/build/macosx/appbundler/doc/appbundler.html +++ b/build/macosx/appbundler/doc/appbundler.html @@ -73,6 +73,13 @@

Parameters

Corresponds to the CFBundleIconFile key in the Info.plist file. No + + hideDockIcon + Set to true to prevent display of the application icon on the Mac OS X dock. + Corresponds to the LSUIElement key in the Info.plist file. + (Details) + No + shortversion The release version number string for the application. @@ -100,10 +107,86 @@

Parameters

file. No + + privileged + Bool value if the bundled application is to be launched as privileged. + No + mainclassname The name of the bundled application's main class. + Yes, alternative to jnlplaunchername Yes + + + plistClassPaths + A comma-separated list of classpath-elements which are used for the java application. + $APP_ROOT is replaced by the path of the .app-bundle. Required only if not + the libraries specified by the classpath and librarypath should be used. + No + + + jvmRequired + Specifies the required Java virtual machine version. + No (defaults to 1.7) + + + jrePreferred + If set to true, a Java Runtime Edition is required for execution. If both jrePreferred and jdkPreferred are set true, then a JRE is preferred but a JDK ia also accepted. + No + + + jdkPreferred + If set to true, a Java Development Kit is required for execution. If both jrePreferred and jdkPreferred are set true, then a JRE is preferred but a JDK ia also accepted. + No + + + minimumSystemVersion + Indicates the minimum version of OS X required for this app to run. + Corresponds to the LSMinimumSystemVersion key in the Info.plist + file. + (Details) + No + + + jnlplaunchername + The name of the bundled applications's jnlp file. The file has to be be copied to the Contents/Java folder. It has to be present during execution of the application. This serves as option to deliver signed applications based upon JNLP files. The application can then be signed and the signature won't break when modifying the JNLP file. + No, alternative to mainclassname + + + workingdirectory + Specifies the working directory of the application. + $APP_ROOT is replaced by the path of the .app-bundle. + No + + + privileged + If set, the application is started with administrator privileges. + No + + + highResolutionCapable + Sets the High Resolution Capable flag. + Corresponds to the NSHighResolutionCapable key in the Info.plist + file. + No + + + supportsAutomaticGraphicsSwitching + Allow OpenGL applications to utilize the integrated GPU. + Corresponds to the NSSupportsAutomaticGraphicsSwitching key in the Info.plist + No + + + ignorePSN + If set to true, the -psn... arguments passed by the OS + to the application is filtered out. + No + + + isDebug + If set to true, additiona console output will be produced during startup. + No @@ -137,6 +220,23 @@

librarypath

option

Specifies a command-line option to be passed to the JVM at startup.

+

Options may be named, which allows the bundled Java program +itself to override the option (e.g. to adjust heap settings). Changes will take effect upon restart of the +application. Assuming your CFBundleIdentifier (settable via the attribute identifier) +is com.oracle.appbundler. Then you can override a named option by calling +

import java.util.prefs.Preferences; + [...] + Preferences jvmOptions = Preferences.userRoot().node("/com/oracle/appbundler/JVMOptions"); + jvmOptions.put("name", "value"); // use option name and desired value here + jvmOptions.flush(); +The corresponding entries will be stored in a file called +~/Library/Preferences/com.oracle.appbundler.plist. To manipulate the file +without Java's Preferences from the command line, you should use the tool +defaults. +For example, to add an entry via the command line, use: + defaults write com.oracle.appbundler /com/oracle/appbundler/ -dict-add JVMOptions/ '{"name"="value";}' +Of named options, only the value is passed to the JVM, not the name. The name merely serves as identifier. +

@@ -148,6 +248,11 @@

option

+ + + + +
Attribute The option value. Yes
nameThe option name.No

argument

@@ -165,6 +270,218 @@

argument

+

environment

+

Specifies an environment variable set via LSEnvironment entry in the Info.plist file. See the + Apple Documentation for details.

+

The string $APP_ROOT will be replaced by the application bundle path in all environment variables on runtime.

+ + + + + + + + + + + + + + + + +
AttributeDescriptionRequired
nameThe variable name.Yes
valueThe variable value.Yes
+ +

architecture

+

Specifies the elements of the LSArchitecturePriority array in Info.plist. +(Details)

+ + + + + + + + + + + +
AttributeDescriptionRequired
nameThe architecture name.Yes
+ +

plistentry

+

Adds an arbitrary entry to the generated Info.plist.

+ + + + + + + + + + + + + + + + + + + + + +
AttributeDescriptionRequired
keyThe entry's key.Yes
valueThe entry's value.Yes
typeThe entry's type.No (defaults to String)
+ + +

scheme

+

Specifies a protocol for which the bundled application should be registered as a handler.

+ + + + + + + + + + + +
AttributeDescriptionRequired
valueThe protocol scheme.Yes
+ +

bundledocument

+

Describes a document associated with your application.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
AttributeDescriptionCorresponding CFBundleDocumentTypes keyRequired
contentTypesA comma-separated list of Uniform Type Identifiers defining each a supported file type. + If you reference custom filetypes, declare them using a typedeclaration. + If set, extensions and isPackage are ignored. See the UTI reference for a list of default UTIs.LSItemContentTypesYes (or extensions)
extensionsA comma-separated list of filename extensions (minus the leading period) to map to this document type.CFBundleTypeExtensionsYes (or contentTypes)
iconThe name of the icon file (.icns) to associate with this OS X document type.CFBundleTypeIconFileNo (But recommended)
nameThe abstract name for the document type.CFBundleTypeNameNo (But recommended)
roleThis key specifies the app's role with respect to the type. The value can be Editor, Viewer, Shell, or None.CFBundleTypeRoleNo (default: Editor)
handlerRankDetermines how Launch Services ranks this app among the apps that declare themselves editors or viewers of files of this type. The possible values are: Owner (this app is the creator of files of this type), Alternate (this app is a secondary viewer of files of this type), None (this app must never be used to open files of this type, but it accepts drops of files of this type), Default (default; this app doesn't accept drops of files of this type). LSHandlerRankNo
isPackageSpecifies whether the document is distributed as a bundle. If set to true, the bundle directory is treated as a file.LSTypeIsPackageNo (default: false)
exportableTypesA comma-separated list of Uniform Type Identifiers defining a supported file type to which this document can export its content. + If you reference custom filetypes, declare them using a typedeclaration. + See also the Additional Document Type Considerations of the Document-Based App Programming Guide for Mac. + NSExportableTypesNo
+ +

typedeclaration

+

Declares a new Uniform Type Identifier. +Required if you reference non-system UTIs in bundledocument's contentTypes or exportableTypes

. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
AttributeDescriptionCorresponding UT...TypeDeclarations keyRequired
identifierThe unique UTI for the declared type. Following the reverse-DNS format beginning with com.companyName is a simple way to ensure uniqueness.UTTypeIdentifierYes
descriptionA user-visible description of this type.UTTypeDescriptionNo
iconThe name of the icon file (.icns) to associate with this UTI.UTTypeIconFileNo
referenceUrlThe URL of a reference document describing this type.UTTypeReferenceURLNo
conformsToA comma-separated list of UTIs to which this identifier conforms. + Although a custom UTI can conform to any UTI, public.data or com.apple.package must be at the root of the conformance hierarchy.UTTypeConformsToNo (defaults to public.data)
extensionsA comma-separated list of filename extensions (minus the leading period) to map to this UTI.UTTypeTagSpecification -> public.filename-extensionNo (but recommended)
mimeTypesA comma-separated list of mime types which identify this UTI.UTTypeTagSpecification -> public.mime-typeNo
osTypesComma-separated list of four-character codes formerly used to identify types. + Only specify OSTypes if you really know what you're doing.UTTypeTagSpecification -> com.apple.ostypeNo
importedIf set to true, the declaration is listed under the UTImportedTypeDeclarations key. + Otherwise, it is listed under UTExportedTypeDeclarations. + If your code relies on third-party UTI types that may not be present on the system, you should declare those UTIs as imported types.-No
+

Examples

Generate a launcher for the "Swing Set" demo, bundling the JRE defined by the JAVA_HOME environment variable with the resulting executable.

@@ -187,9 +504,57 @@

Examples

<runtime dir="${env.JAVA_HOME}"/> <classpath file="/Library/Java/Demos/JFC/SwingSet2/SwingSet2.jar"/> <option value="-Dapple.laf.useScreenMenuBar=true"/> + <scheme value="mailto"/> </bundleapp> </target> +

Example 2: JNLP Launcher

+

Generate a launcher for a JNLP File, copy it into the package and sign the package. You need to have a Developer ID Profile to sign the application.

+

You can now dynamically modify the zip content (only the JNLP file), deliver it with your web service and the application should directly unpack and can be run

+
+<-- Define the appbundler task -->
+<taskdef name="bundleapp" classname="com.oracle.appbundler.AppBundlerTask"/>
+
+<-- Create the app bundle -->
+<target name="bundle-swingset" depends="package">
+
+    <mkdir dir="./app">
+
+    <bundleapp outputdirectory="./app"
+        name="SwingSet2"
+        displayname="SwingSet 2"
+        identifier="com.oracle.javax.swing.SwingSet2"
+        shortversion="1.0"
+        icon="icon.icns"
+        applicationCategory="public.app-category.developer-tools"
+        jnlplaunchername="Contents/_CodeSignature/SwingSet2.jnlp">
+        
+        <value="-Xdock:icon=Contents/Resources/icon.icns" />
+        <option value="-Dapple.laf.useScreenMenuBar=true"/>
+    </bundleapp>
+
+    <!-- Optionally copy an original file -->
+    <copy todir="./SwingSet2.app/Contents/_CodeSignature" includeemptydirs="true" overwrite="false">
+        <fileset dir=".">
+            <include name="**/*.jnlp" />
+        </fileset>
+    </copy>
+	
+    <!-- Sign File -->
+    <exec executable="codesign" os="Mac OS X" failonerror="true">
+        <arg value="-f" />
+        <arg value="--deep" />
+        <arg value="-s" />
+        <arg value="Developer ID Application" />
+        <arg value="./app/SwingSet2.app" />
+    </exec>
+
+    <zip destfile="./SwingSet2.app.zip" basedir="${copyroot}/app"></zip>
+</target>
+
+
+
+
\ No newline at end of file diff --git a/build/macosx/appbundler/native/main.m b/build/macosx/appbundler/native/main.m index cfcc5a9e70..510c371d78 100644 --- a/build/macosx/appbundler/native/main.m +++ b/build/macosx/appbundler/native/main.m @@ -27,6 +27,7 @@ #import #include #include +#include #define JAVA_LAUNCH_ERROR "JavaLaunchError" @@ -34,15 +35,34 @@ #define WORKING_DIR "WorkingDirectory" #define JVM_MAIN_CLASS_NAME_KEY "JVMMainClassName" #define JVM_OPTIONS_KEY "JVMOptions" +#define JVM_DEFAULT_OPTIONS_KEY "JVMDefaultOptions" #define JVM_ARGUMENTS_KEY "JVMArguments" +#define JVM_CLASSPATH_KEY "JVMClassPath" +#define JVM_VERSION_KEY "JVMVersion" +#define JRE_PREFERRED_KEY "JREPreferred" +#define JDK_PREFERRED_KEY "JDKPreferred" +#define JVM_DEBUG_KEY "JVMDebug" +#define IGNORE_PSN_KEY "IgnorePSN" #define JVM_RUN_PRIVILEGED "JVMRunPrivileged" +#define JVM_RUN_JNLP "JVMJNLPLauncher" +#define JVM_RUN_JAR "JVMJARLauncher" + #define UNSPECIFIED_ERROR "An unknown error occurred." #define APP_ROOT_PREFIX "$APP_ROOT" +#define JVM_RUNTIME "$JVM_RUNTIME" + +#define JAVA_RUNTIME "/Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home" +#define LIBJLI_DY_LIB "lib/jli/libjli.dylib" +#define DEPLOY_LIB "lib/deploy.jar" -#define LIBJLI_DYLIB "/Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home/lib/jli/libjli.dylib" +//* + #define DLog(...) NSLog(@"%s %@", __PRETTY_FUNCTION__, [NSString stringWithFormat:__VA_ARGS__]) +/*/ + #define DLog(...) do { } while (0) +//*/ typedef int (JNICALL *JLI_Launch_t)(int argc, char ** argv, int jargc, const char** jargv, @@ -56,15 +76,32 @@ typedef int (JNICALL *JLI_Launch_t)(int argc, char ** argv, jboolean javaw, jint ergo); -int launch(char *); +static char** progargv = NULL; +static int progargc = 0; +static int launchCount = 0; -int main(int argc, char *argv[]) { +const char * tmpFile(); +int launch(char *, int, char **); + +NSString * findJavaDylib (NSString *, bool, bool, bool, bool); +NSString * findJREDylib (int, bool, bool); +NSString * findJDKDylib (int, bool, bool); +int extractMajorVersion (NSString *); +NSString * convertRelativeFilePath(NSString *); +NSString * addDirectoryToSystemArguments(NSUInteger, NSSearchPathDomainMask, NSString *, NSMutableArray *); +void addModifierFlagToSystemArguments(NSEventModifierFlags, NSString *, NSEventModifierFlags, NSMutableArray *); +int main(int argc, char *argv[]) { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; int result; @try { - launch(argv[0]); + if ((argc > 1) && (launchCount == 0)) { + progargc = argc - 1; + progargv = &argv[1]; + } + + launch(argv[0], progargc, progargv); result = 0; } @catch (NSException *exception) { NSAlert *alert = [[NSAlert alloc] init]; @@ -80,14 +117,11 @@ int main(int argc, char *argv[]) { return result; } -int launch(char *commandName) { +int launch(char *commandName, int progargc, char *progargv[]) { - //Attempt to disable Inertia scroll - //From https://developer.apple.com/library/mac/releasenotes/DriversKernelHardware/RN-MagicMouse/ - NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; - NSDictionary *appDefaults = [NSDictionary dictionaryWithObject:@"NO" - forKey:@"AppleMomentumScrollSupported"]; - [defaults registerDefaults:appDefaults]; + // Preparation for jnlp launcher arguments + const char *const_jargs = NULL; + const char *const_appclasspath = NULL; // Get the main bundle NSBundle *mainBundle = [NSBundle mainBundle]; @@ -95,39 +129,120 @@ int launch(char *commandName) { // Get the main bundle's info dictionary NSDictionary *infoDictionary = [mainBundle infoDictionary]; + // Test for debugging (but only on the second runthrough) + bool isDebugging = [[infoDictionary objectForKey:@JVM_DEBUG_KEY] boolValue]; + + if (isDebugging) { + DLog(@"\n\n\n\nLoading Application '%@'", [infoDictionary objectForKey:@"CFBundleName"]); + } + // Set the working directory based on config, defaulting to the user's home directory NSString *workingDir = [infoDictionary objectForKey:@WORKING_DIR]; if (workingDir != nil) { workingDir = [workingDir stringByReplacingOccurrencesOfString:@APP_ROOT_PREFIX withString:[mainBundle bundlePath]]; } else { - workingDir = NSHomeDirectory(); + workingDir = [[NSFileManager defaultManager] currentDirectoryPath]; + workingDir = NSHomeDirectory(); // REVIEW: Check which if these ones is realy the users home directory ... + } + if (isDebugging) { + DLog(@"Working Directory: '%@'", convertRelativeFilePath(workingDir)); } chdir([workingDir UTF8String]); // execute privileged NSString *privileged = [infoDictionary objectForKey:@JVM_RUN_PRIVILEGED]; - if (privileged != nil && getuid() != 0) { + if ( privileged != nil && getuid() != 0 ) { NSDictionary *error = [NSDictionary new]; + NSString *script = [NSString stringWithFormat:@"do shell script \"\\\"%@\\\" > /dev/null 2>&1 &\" with administrator privileges", [NSString stringWithCString:commandName encoding:NSASCIIStringEncoding]]; + + if (isDebugging) { + DLog(@"script: %@", script); + } + NSAppleScript *appleScript = [[NSAppleScript new] initWithSource:script]; if ([appleScript executeAndReturnError:&error]) { // This means we successfully elevated the application and can stop in here. - return 0; // Should this return 'error' instead? [fry] + return 0; } } // Locate the JLI_Launch() function NSString *runtime = [infoDictionary objectForKey:@JVM_RUNTIME_KEY]; + NSString *runtimePath = [[mainBundle builtInPlugInsPath] stringByAppendingPathComponent:runtime]; - const char *libjliPath = NULL; + NSString *jvmRequired = [infoDictionary objectForKey:@JVM_VERSION_KEY]; + bool exactVersionMatch = false; + bool jrePreferred = [[infoDictionary objectForKey:@JRE_PREFERRED_KEY] boolValue]; + bool jdkPreferred = [[infoDictionary objectForKey:@JDK_PREFERRED_KEY] boolValue]; + + if (jrePreferred && jdkPreferred) { + DLog(@"Specifying both JRE- and JDK-preferred means neither is preferred"); + jrePreferred = false; + jdkPreferred = false; + } + + // check for jnlp launcher name + // This basically circumvents the security problems introduced with 10.8.4 that JNLP Files must be signed to execute them without CTRL+CLick -> Open + // See: How to sign (dynamic) JNLP files for OSX 10.8.4 and Gatekeeper http://stackoverflow.com/questions/16958130/how-to-sign-dynamic-jnlp-files-for-osx-10-8-4-and-gatekeeper + // There is no solution to properly sign a dynamic jnlp file to date. Both Apple and Oracle have open rdars/tickets on this. + // The following mechanism encapsulates a JNLP file/template. It makes a temporary copy when executing. This ensures that the JNLP file can be updates from the server at runtime. + // YES, this may insert additional security threats, but it is still the only way to avoid permission problems. + // It is highly recommended that the resulting .app container is being signed with a certificate from Apple - otherwise you will not need this mechanism. + // Moved up here to check if we want to launch a JNLP. If so: make sure the version is below 9 + NSString *jnlplauncher = [infoDictionary objectForKey:@JVM_RUN_JNLP]; + if ( jnlplauncher != nil ) { + int required = 8; + if ( jvmRequired != nil ) { + required = extractMajorVersion (jvmRequired); + if (required > 8) { required = 8; } + } + + exactVersionMatch = true; + jvmRequired = [NSString stringWithFormat:@"1.%i", required]; + DLog(@"Will Require a JVM version '%i' due to JNLP restrictions", required); + } + + NSString *javaDylib; + + // If a runtime is set, we really want it. If it is not there, we will fail later on. if (runtime != nil) { - NSString *runtimePath = [[[NSBundle mainBundle] builtInPlugInsPath] stringByAppendingPathComponent:runtime]; - libjliPath = [[runtimePath stringByAppendingPathComponent:@"Contents/Home/jre/lib/jli/libjli.dylib"] fileSystemRepresentation]; - } else { - libjliPath = LIBJLI_DYLIB; + NSString *dylibRelPath = @"Contents/Home/jre"; + javaDylib = [[runtimePath stringByAppendingPathComponent:dylibRelPath] stringByAppendingPathComponent:@LIBJLI_DY_LIB]; + BOOL isDir; + NSFileManager *fm = [[NSFileManager alloc] init]; + BOOL javaDylibFileExists = [fm fileExistsAtPath:javaDylib isDirectory:&isDir]; + if (!javaDylibFileExists || isDir) { + dylibRelPath = @"Contents/Home"; + javaDylib = [[runtimePath stringByAppendingPathComponent:dylibRelPath] stringByAppendingPathComponent:@LIBJLI_DY_LIB]; + javaDylibFileExists = [fm fileExistsAtPath:javaDylib isDirectory:&isDir]; + if (!javaDylibFileExists || isDir) { + javaDylib = NULL; + } + } + if (isDebugging) { + DLog(@"Java Runtime (%@) Relative Path: '%@' (dylib: %@)", runtime, runtimePath, javaDylib); + } + } + else { + // Search for the runtimePath, then make it a libjli.dylib path. + runtimePath = findJavaDylib (jvmRequired, jrePreferred, jdkPreferred, isDebugging, exactVersionMatch); + javaDylib = [runtimePath stringByAppendingPathComponent:@LIBJLI_DY_LIB]; + + if (isDebugging) { + DLog(@"Java Runtime Dylib Path: '%@'", convertRelativeFilePath(javaDylib)); + } + } + + const char *libjliPath = NULL; + if (javaDylib != nil) + { + libjliPath = [javaDylib fileSystemRepresentation]; } + DLog(@"Launchpath: %s", libjliPath); + void *libJLI = dlopen(libjliPath, RTLD_LAZY); JLI_Launch_t jli_LaunchFxnPtr = NULL; @@ -136,123 +251,338 @@ int launch(char *commandName) { } if (jli_LaunchFxnPtr == NULL) { - [[NSException exceptionWithName:@JAVA_LAUNCH_ERROR - reason:NSLocalizedString(@"JRELoadError", @UNSPECIFIED_ERROR) - userInfo:nil] raise]; - } + NSString *msg; + + if (runtime == nil && jvmRequired != nil) { + int required = extractMajorVersion (jvmRequired); + + if (required < 7) { required = 7; } + + if (jdkPreferred) { + NSString *msga = NSLocalizedString(@"JDKxLoadFullError", @UNSPECIFIED_ERROR); + msg = [NSString stringWithFormat:msga, required]; + } + else { + NSString *msga = NSLocalizedString(@"JRExLoadFullError", @UNSPECIFIED_ERROR); + msg = [NSString stringWithFormat:msga, required]; + } + } + else { + msg = NSLocalizedString(@"JRELoadError", @UNSPECIFIED_ERROR); + } + + DLog(@"Error launching JVM Runtime (%@) Relative Path: '%@' (dylib: %@)\n error: %@", + runtime, runtimePath, javaDylib, msg); - // Get the main class name - NSString *mainClassName = [infoDictionary objectForKey:@JVM_MAIN_CLASS_NAME_KEY]; - if (mainClassName == nil) { [[NSException exceptionWithName:@JAVA_LAUNCH_ERROR - reason:NSLocalizedString(@"MainClassNameRequired", @UNSPECIFIED_ERROR) - userInfo:nil] raise]; + reason:msg userInfo:nil] raise]; } // Set the class path + NSFileManager *defaultFileManager = [NSFileManager defaultManager]; NSString *mainBundlePath = [mainBundle bundlePath]; - NSString *javaPath = - [mainBundlePath stringByAppendingString:@"/Contents/Java"]; - // Changed Contents/Java to the old Contents/Resources/Java [fry] - //[mainBundlePath stringByAppendingString:@"/Contents/Resources/Java"]; - // Removed the /Classes, because the P5 compiler (ECJ?) will throw an - // error if it doesn't exist. But it's harmless to leave the root dir, - // since it will always exist, and I guess if you wanted to put .class - // files in there, they'd work. If I knew more Cocoa, I'd just make this - // an empty string to start, to be appended a few lines later. [fry] - //NSMutableString *classPath = [NSMutableString stringWithFormat:@"-Djava.class.path=%@/Classes", javaPath]; - NSMutableString *classPath = [NSMutableString stringWithFormat:@"-Djava.class.path=%@", javaPath]; - NSFileManager *defaultFileManager = [NSFileManager defaultManager]; - NSArray *javaDirectoryContents = - [defaultFileManager contentsOfDirectoryAtPath:javaPath error:nil]; - if (javaDirectoryContents == nil) { + // make sure the bundle path does not contain a colon, as that messes up the java.class.path, + // because colons are used a path separators and cannot be escaped. + + // funny enough, Finder does not let you create folder with colons in their names, + // but when you create a folder with a slash, e.g. "audio/video", it is accepted + // and turned into... you guessed it, a colon: + // "audio:video" + if ([mainBundlePath rangeOfString:@":"].location != NSNotFound) { [[NSException exceptionWithName:@JAVA_LAUNCH_ERROR - reason:NSLocalizedString(@"JavaDirectoryNotFound", @UNSPECIFIED_ERROR) - userInfo:nil] raise]; + reason:NSLocalizedString(@"BundlePathContainsColon", @UNSPECIFIED_ERROR) + userInfo:nil] raise]; } - - for (NSString *file in javaDirectoryContents) { - if ([file hasSuffix:@".jar"]) { - [classPath appendFormat:@":%@/%@", javaPath, file]; - } + if (isDebugging) { + NSLog(@"Main Bundle Path: '%@'", mainBundlePath); } - /* - // search the 'lib' subfolder as well [fry] - NSString *libPath = - [mainBundlePath stringByAppendingString:@"/Contents/Resources/Java/lib"]; - NSArray *libDirectoryContents = - [defaultFileManager contentsOfDirectoryAtPath:libPath error:nil]; - if (libDirectoryContents != nil) { - for (NSString *file in libDirectoryContents) { - if ([file hasSuffix:@".jar"]) { - [classPath appendFormat:@":%@/%@", libPath, file]; - } - } - } - */ + // Set the class path + NSString *javaPath = [mainBundlePath stringByAppendingString:@"/Contents/Java"]; + NSMutableArray *systemArguments = [[NSMutableArray alloc] init]; + NSMutableString *classPath = [NSMutableString stringWithString:@"-Djava.class.path="]; // Set the library path - NSString *libraryPath = [NSString stringWithFormat:@"-Djava.library.path=:%@/Contents/Java:%@/Contents/MacOS", mainBundlePath, mainBundlePath]; + NSString *libraryPath = [NSString stringWithFormat:@"-Djava.library.path=%@/Contents/MacOS", mainBundlePath]; + [systemArguments addObject:libraryPath]; // Get the VM options - NSArray *options = [infoDictionary objectForKey:@JVM_OPTIONS_KEY]; + NSMutableArray *options = [[infoDictionary objectForKey:@JVM_OPTIONS_KEY] mutableCopy]; if (options == nil) { - options = [NSArray array]; + options = [NSMutableArray array]; + } + + // Get the VM default options + NSArray *defaultOptions = [NSArray array]; + NSDictionary *defaultOptionsDict = [infoDictionary objectForKey:@JVM_DEFAULT_OPTIONS_KEY]; + if (defaultOptionsDict != nil) { + NSMutableDictionary *defaults = [NSMutableDictionary dictionaryWithDictionary: defaultOptionsDict]; + // Replace default options with user specific options, if available + NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; + // Create special key that should be used by Java's java.util.Preferences impl + // Requires us to use "/" + bundleIdentifier.replace('.', '/') + "/JVMOptions/" as node on the Java side + // Beware: bundleIdentifiers shorter than 3 segments are placed in a different file! + // See java/util/prefs/MacOSXPreferences.java of OpenJDK for details + NSString *bundleDictionaryKey = [mainBundle bundleIdentifier]; + bundleDictionaryKey = [bundleDictionaryKey stringByReplacingOccurrencesOfString:@"." withString:@"/"]; + bundleDictionaryKey = [NSString stringWithFormat: @"/%@/", bundleDictionaryKey]; + + NSDictionary *bundleDictionary = [userDefaults dictionaryForKey: bundleDictionaryKey]; + if (bundleDictionary != nil) { + NSDictionary *jvmOptionsDictionary = [bundleDictionary objectForKey: @"JVMOptions/"]; + for (NSString *key in jvmOptionsDictionary) { + NSString *value = [jvmOptionsDictionary objectForKey:key]; + [defaults setObject: value forKey: key]; + } + } + defaultOptions = [defaults allValues]; } // Get the application arguments - NSArray *arguments = [infoDictionary objectForKey:@JVM_ARGUMENTS_KEY]; + NSMutableArray *arguments = [[infoDictionary objectForKey:@JVM_ARGUMENTS_KEY] mutableCopy]; if (arguments == nil) { - arguments = [NSArray array]; + arguments = [NSMutableArray array]; + } + + // Check for a defined JAR File below the Contents/Java folder + // If set, use this instead of a classpath setting + NSString *jarlauncher = [infoDictionary objectForKey:@JVM_RUN_JAR]; + + // Get the main class name + NSString *mainClassName = [infoDictionary objectForKey:@JVM_MAIN_CLASS_NAME_KEY]; + + if ( jnlplauncher != nil ) { + + const_appclasspath = [[runtimePath stringByAppendingPathComponent:@DEPLOY_LIB] fileSystemRepresentation]; + + // JNLP Launcher found, need to modify quite a bit now + [options addObject:@"-classpath"]; + [options addObject:[NSString stringWithFormat:@"%s", const_appclasspath]]; + + // unset the original classpath + classPath = nil; + + // Main Class is javaws + mainClassName=@"com.sun.javaws.Main"; + + // Optional stuff that javaws would do as well + [options addObject:@"-Dsun.awt.warmup=true"]; + [options addObject:@"-Xverify:remote"]; + [options addObject:@"-Djnlpx.remove=true"]; + [options addObject:@"-DtrustProxy=true"]; + + [options addObject:[NSString stringWithFormat:@"-Djava.security.policy=file:%@/lib/security/javaws.policy", runtimePath]]; + [options addObject:[NSString stringWithFormat:@"-Xbootclasspath/a:%@/lib/javaws.jar:%@/lib/deploy.jar:%@/lib/plugin.jar", runtimePath, runtimePath, runtimePath]]; + + // Argument that javaws does also + // [arguments addObject:@"-noWebStart"]; + + // Copy the jnlp to a temporary location + NSError *copyerror = nil; + NSString *tempFileName = [NSString stringWithCString:tmpFile() encoding:NSASCIIStringEncoding]; + // File now exists. + [defaultFileManager removeItemAtPath:tempFileName error:NULL]; + + // Check if this is absolute or relative (else) + NSString *jnlpPath = [mainBundlePath stringByAppendingPathComponent:jnlplauncher]; + if ( ![defaultFileManager fileExistsAtPath:jnlpPath] ) { + jnlpPath = [javaPath stringByAppendingPathComponent:jnlplauncher]; + } + + [defaultFileManager copyItemAtURL:[NSURL fileURLWithPath:jnlpPath] toURL:[NSURL fileURLWithPath:tempFileName] error:©error]; + if ( copyerror != nil ) { + NSLog(@"Error: %@", copyerror); + [[NSException exceptionWithName:@"Error while copying JNLP File" + reason:@"File copy error" + userInfo:copyerror.userInfo] raise]; + } + + // Add the jnlp as argument so that javaws.Main can read and delete it + [arguments addObject:tempFileName]; + + } else + // Either mainClassName or jarLauncher has to be set since this is not a jnlpLauncher + if ( mainClassName == nil && jarlauncher == nil ) { + [[NSException exceptionWithName:@JAVA_LAUNCH_ERROR + reason:NSLocalizedString(@"MainClassNameRequired", @UNSPECIFIED_ERROR) + userInfo:nil] raise]; + } + + if (isDebugging) { + DLog(@"Main Class Name: '%@'", mainClassName); + } + + // If a jar file is defined as launcher, disacard the javaPath + if ( jarlauncher != nil ) { + [classPath appendFormat:@":%@/%@", javaPath, jarlauncher]; + } else { + + NSArray *cp = [infoDictionary objectForKey:@JVM_CLASSPATH_KEY]; + if (cp == nil) { + + // Implicit classpath, so use the contents of the "Java" folder to build an explicit classpath + + [classPath appendFormat:@"%@/Classes", javaPath]; + NSFileManager *defaultFileManager = [NSFileManager defaultManager]; + NSArray *javaDirectoryContents = [defaultFileManager contentsOfDirectoryAtPath:javaPath error:nil]; + if (javaDirectoryContents == nil) { + [[NSException exceptionWithName:@JAVA_LAUNCH_ERROR + reason:NSLocalizedString(@"JavaDirectoryNotFound", @UNSPECIFIED_ERROR) + userInfo:nil] raise]; + } + + for (NSString *file in javaDirectoryContents) { + if ([file hasSuffix:@".jar"]) { + [classPath appendFormat:@":%@/%@", javaPath, file]; + } + } + + } else { + + // Explicit ClassPath + + int k = 0; + for (NSString *file in cp) { + if (k++ > 0) [classPath appendString:@":"]; // add separator if needed + file = [file stringByReplacingOccurrencesOfString:@APP_ROOT_PREFIX withString:[mainBundle bundlePath]]; + [classPath appendString:file]; + } + } + } + + if ( classPath != nil ) { + [systemArguments addObject:classPath]; } // Set OSX special folders - NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, - NSUserDomainMask, YES); - NSString *basePath = [paths objectAtIndex:0]; - NSString *libraryDirectory = [NSString stringWithFormat:@"-DLibraryDirectory=%@", basePath]; - - paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, - NSUserDomainMask, YES); - basePath = [paths objectAtIndex:0]; - NSString *documentsDirectory = [NSString stringWithFormat:@"-DDocumentsDirectory=%@", basePath]; - - paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, - NSUserDomainMask, YES); - basePath = [paths objectAtIndex:0]; - NSString *applicationSupportDirectory = [NSString stringWithFormat:@"-DApplicationSupportDirectory=%@", basePath]; - - paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, - NSUserDomainMask, YES); - basePath = [paths objectAtIndex:0]; - NSString *cachesDirectory = [NSString stringWithFormat:@"-DCachesDirectory=%@", basePath]; - - NSString *sandboxEnabled = @"true"; - if ([basePath rangeOfString:@"Containers"].location == NSNotFound) { - sandboxEnabled = @"false"; + NSString * libraryDirectory = addDirectoryToSystemArguments(NSLibraryDirectory, NSUserDomainMask, @"LibraryDirectory", systemArguments); + addDirectoryToSystemArguments(NSDocumentDirectory, NSUserDomainMask, @"DocumentsDirectory", systemArguments); + addDirectoryToSystemArguments(NSApplicationSupportDirectory, NSUserDomainMask, @"ApplicationSupportDirectory", systemArguments); + addDirectoryToSystemArguments(NSCachesDirectory, NSUserDomainMask, @"CachesDirectory", systemArguments); + addDirectoryToSystemArguments(NSApplicationDirectory, NSUserDomainMask, @"ApplicationDirectory", systemArguments); + addDirectoryToSystemArguments(NSAutosavedInformationDirectory, NSUserDomainMask, @"AutosavedInformationDirectory", systemArguments); + addDirectoryToSystemArguments(NSDesktopDirectory, NSUserDomainMask, @"DesktopDirectory", systemArguments); + addDirectoryToSystemArguments(NSDownloadsDirectory, NSUserDomainMask, @"DownloadsDirectory", systemArguments); + addDirectoryToSystemArguments(NSMoviesDirectory, NSUserDomainMask, @"MoviesDirectory", systemArguments); + addDirectoryToSystemArguments(NSMusicDirectory, NSUserDomainMask, @"MusicDirectory", systemArguments); + addDirectoryToSystemArguments(NSPicturesDirectory, NSUserDomainMask, @"PicturesDirectory", systemArguments); + addDirectoryToSystemArguments(NSSharedPublicDirectory, NSUserDomainMask, @"SharedPublicDirectory", systemArguments); + + addDirectoryToSystemArguments(NSLibraryDirectory, NSLocalDomainMask, @"SystemLibraryDirectory", systemArguments); + addDirectoryToSystemArguments(NSApplicationSupportDirectory, NSLocalDomainMask, @"SystemApplicationSupportDirectory", systemArguments); + addDirectoryToSystemArguments(NSCachesDirectory, NSLocalDomainMask, @"SystemCachesDirectory", systemArguments); + addDirectoryToSystemArguments(NSApplicationDirectory, NSLocalDomainMask, @"SystemApplicationDirectory", systemArguments); + addDirectoryToSystemArguments(NSUserDirectory, NSLocalDomainMask, @"SystemUserDirectory", systemArguments); + + // get the user's home directory, independent of the sandbox container + int bufsize; + if ((bufsize = sysconf(_SC_GETPW_R_SIZE_MAX)) != -1) { + char buffer[bufsize]; + struct passwd pwd, *result = NULL; + if (getpwuid_r(getuid(), &pwd, buffer, bufsize, &result) == 0 && result) { + [systemArguments addObject:[NSString stringWithFormat:@"-DUserHome=%s", pwd.pw_dir]]; + } + } + + //Sandbox + NSString *containersDirectory = [libraryDirectory stringByAppendingPathComponent:@"Containers"]; + NSString *sandboxEnabled = @"false"; + BOOL isDir; + NSFileManager *fm = [[NSFileManager alloc] init]; + BOOL containersDirExists = [fm fileExistsAtPath:containersDirectory isDirectory:&isDir]; + if (containersDirExists && isDir) { + sandboxEnabled = @"true"; } NSString *sandboxEnabledVar = [NSString stringWithFormat:@"-DSandboxEnabled=%@", sandboxEnabled]; + [systemArguments addObject:sandboxEnabledVar]; + + + // Mojave Dark Mode enabled? + NSString *osxMode = [[NSUserDefaults standardUserDefaults] stringForKey:@"AppleInterfaceStyle"]; + BOOL isDarkMode = (osxMode != nil && [osxMode isEqualToString:@"Dark"]); + + NSString *darkModeEnabledVar = [NSString stringWithFormat:@"-DDarkMode=%s", + (isDarkMode ? "true" : "false")]; + [systemArguments addObject:darkModeEnabledVar]; + + // Check for modifier keys on app launch + + // Since [NSEvent modifierFlags] is only available since OS X 10.6., only add properties if supported. + if ([NSEvent respondsToSelector:@selector(modifierFlags)]) { + NSEventModifierFlags launchModifierFlags = [NSEvent modifierFlags] & NSEventModifierFlagDeviceIndependentFlagsMask; + + [systemArguments addObject:[NSString stringWithFormat:@"-DLaunchModifierFlags=%lu", (unsigned long)launchModifierFlags]]; + + addModifierFlagToSystemArguments(NSEventModifierFlagCapsLock, @"LaunchModifierFlagCapsLock", launchModifierFlags, systemArguments); + addModifierFlagToSystemArguments(NSEventModifierFlagShift, @"LaunchModifierFlagShift", launchModifierFlags, systemArguments); + addModifierFlagToSystemArguments(NSEventModifierFlagControl, @"LaunchModifierFlagControl", launchModifierFlags, systemArguments); + addModifierFlagToSystemArguments(NSEventModifierFlagOption, @"LaunchModifierFlagOption", launchModifierFlags, systemArguments); + addModifierFlagToSystemArguments(NSEventModifierFlagCommand, @"LaunchModifierFlagCommand", launchModifierFlags, systemArguments); + addModifierFlagToSystemArguments(NSEventModifierFlagNumericPad, @"LaunchModifierFlagNumericPad", launchModifierFlags, systemArguments); + addModifierFlagToSystemArguments(NSEventModifierFlagHelp, @"LaunchModifierFlagHelp", launchModifierFlags, systemArguments); + addModifierFlagToSystemArguments(NSEventModifierFlagFunction, @"LaunchModifierFlagFunction", launchModifierFlags, systemArguments); + } + + + + // Remove -psn argument + int newProgargc = progargc; + char *newProgargv[newProgargc]; + for (int i = 0; i < progargc; i++) { + newProgargv[i] = progargv[i]; + } + + bool ignorePSN = [[infoDictionary objectForKey:@IGNORE_PSN_KEY] boolValue]; + if (ignorePSN) { + NSString *psnRegexp = @"^-psn_\\d_\\d+$"; + NSPredicate *psnTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", psnRegexp]; + + int shift = 0; + int i = 0; + while (i < newProgargc) { + NSString *s = [NSString stringWithFormat:@"%s", newProgargv[i]]; + if ([psnTest evaluateWithObject: s]){ + shift++; + newProgargc--; + } + newProgargv[i] = newProgargv[i+shift]; + i++; + } + } + + // replace $APP_ROOT in environment variables + NSDictionary* environment = [[NSProcessInfo processInfo] environment]; + for (NSString* key in environment) { + NSString* value = [environment objectForKey:key]; + NSString* newValue = [value stringByReplacingOccurrencesOfString:@APP_ROOT_PREFIX withString:[mainBundle bundlePath]]; + if (! [newValue isEqualToString:value]) { + setenv([key UTF8String], [newValue UTF8String], 1); + } + } // Initialize the arguments to JLI_Launch() // +5 due to the special directories and the sandbox enabled property - int argc = 1 + [options count] + 2 + [arguments count] + 1 + 5; + int argc = 1 + [systemArguments count] + [options count] + [defaultOptions count] + 1 + [arguments count] + newProgargc; char *argv[argc]; int i = 0; argv[i++] = commandName; - argv[i++] = strdup([classPath UTF8String]); - argv[i++] = strdup([libraryPath UTF8String]); - argv[i++] = strdup([libraryDirectory UTF8String]); - argv[i++] = strdup([documentsDirectory UTF8String]); - argv[i++] = strdup([applicationSupportDirectory UTF8String]); - argv[i++] = strdup([cachesDirectory UTF8String]); - argv[i++] = strdup([sandboxEnabledVar UTF8String]); + for (NSString *systemArgument in systemArguments) { + argv[i++] = strdup([systemArgument UTF8String]); + } for (NSString *option in options) { option = [option stringByReplacingOccurrencesOfString:@APP_ROOT_PREFIX withString:[mainBundle bundlePath]]; + option = [option stringByReplacingOccurrencesOfString:@JVM_RUNTIME withString:runtimePath]; argv[i++] = strdup([option UTF8String]); + if (isDebugging) { DLog(@"Option: %@",option); } + } + + for (NSString *defaultOption in defaultOptions) { + defaultOption = [defaultOption stringByReplacingOccurrencesOfString:@APP_ROOT_PREFIX withString:[mainBundle bundlePath]]; + argv[i++] = strdup([defaultOption UTF8String]); + if (isDebugging) { DLog(@"DefaultOption: %@",defaultOption); } } argv[i++] = strdup([mainClassName UTF8String]); @@ -262,16 +592,361 @@ int launch(char *commandName) { argv[i++] = strdup([argument UTF8String]); } + int ctr = 0; + for (ctr = 0; ctr < newProgargc; ctr++) { + argv[i++] = newProgargv[ctr]; + } + + // Print the full command line for debugging purposes... + if (isDebugging) { + DLog(@"Command line passed to application:"); + int j=0; + for(j=0; j= jvmRequired && !exactMatch) || (version == jvmRequired && exactMatch) ) { + if (isDebugging) { + DLog (@"JRE version qualifies"); + } + return @JAVA_RUNTIME; + } + } + } + @catch (NSException *exception) + { + DLog (@"JRE search exception: '%@'", [exception reason]); + } + + return nil; +} + +// Having failed to find a JRE in the usual location, see if a JDK is installed +// (probably in /Library/Java/JavaVirtualMachines). If so, return address of +// dylib in the JRE within the JDK. +/** + * Searches for a JDK dylib of the specified version or later. + */ +NSString * findJDKDylib ( + int jvmRequired, + bool isDebugging, + bool exactMatch) +{ + @try + { + NSTask *task = [[NSTask alloc] init]; + [task setLaunchPath:@"/usr/libexec/java_home"]; + + NSArray *args = [NSArray arrayWithObjects: @"-v", [NSString stringWithFormat:@"1.%i%@", jvmRequired, exactMatch?@"":@"+"], nil]; + [task setArguments:args]; + + NSPipe *stdout = [NSPipe pipe]; + [task setStandardOutput:stdout]; + + NSPipe *stderr = [NSPipe pipe]; + [task setStandardError:stderr]; + + [task setStandardInput:[NSPipe pipe]]; + + NSFileHandle *outHandle = [stdout fileHandleForReading]; + NSFileHandle *errHandle = [stderr fileHandleForReading]; + + [task launch]; + [task waitUntilExit]; + [task release]; + + NSData *data1 = [outHandle readDataToEndOfFile]; + NSData *data2 = [errHandle readDataToEndOfFile]; + + NSString *outRead = [[NSString alloc] initWithData:data1 + encoding:NSUTF8StringEncoding]; + NSString *errRead = [[NSString alloc] initWithData:data2 + encoding:NSUTF8StringEncoding]; + + // If matching JDK not found, outRead will include something like + // "Unable to find any JVMs matching version "1.X"." + if ( errRead != nil + && [errRead rangeOfString:@"Unable"].location != NSNotFound ) + { + if (isDebugging) { DLog (@"No matching JDK found."); } + return nil; + } + + int version = 0; + + NSRange vrange = [outRead rangeOfString:@"jdk1."]; + if (vrange.location == NSNotFound) { + // try the changed version layout from version 9 + vrange = [outRead rangeOfString:@"jdk-"]; + vrange.location += 4; + } else { + // otherwise remove the leading jdk + vrange.location += 3; + } + + if (vrange.location != NSNotFound) { + NSString *vstring = [outRead substringFromIndex:(vrange.location)]; + + vrange = [vstring rangeOfString:@"/"]; + vstring = [vstring substringToIndex:vrange.location]; + + version = extractMajorVersion(vstring); + + if (isDebugging) { + DLog (@"Found a Java %@ JDK", vstring); + DLog (@"Looks like major version %d", extractMajorVersion(vstring)); + } + } + + if ( (version >= jvmRequired && !exactMatch) || (version == jvmRequired && exactMatch) ) { + if (isDebugging) { + DLog (@"JDK version qualifies"); + } + + NSString *outread2 = [outRead stringByTrimmingCharactersInSet:[NSCharacterSet + whitespaceAndNewlineCharacterSet]]; + + // Return location where LIBJLI_DY_LIB is located. Note that the path was + // shortemed between JDK 8 and JDK 9. + if (version > 8) { + return outread2; + } + else { + return [outread2 stringByAppendingPathComponent:@"jre"]; + } + } + } + @catch (NSException *exception) + { + DLog (@"JDK search exception: '%@'", [exception reason]); + } + + return nil; +} + + +/** + * Extract the Java major version number from a string. We expect the input + * to look like either either "1.X", "1.X.Y_ZZ" or "X.Y.ZZ", and the + * returned result will be the integral value of X. Any failure to parse the + * string will return 0. + */ +int extractMajorVersion (NSString *vstring) { + if (vstring == nil) { return 0; } + + // Expecting either a java version of form 1.X, 1.X.Y_ZZ or jdk1.X.Y_ZZ. + // Strip everything from start and ending that aren't part of the version number + NSCharacterSet* nonDigits = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789."] invertedSet]; + vstring = [vstring stringByTrimmingCharactersInSet:nonDigits]; + + if([vstring hasPrefix:@"1."]) { // this is the version < 9 layout. Remove the leading "1." + vstring = [vstring substringFromIndex:2]; + } + + // the next integer token should be the major version, so read everything up to the first decimal point, if any + NSUInteger versionEndLoc = [vstring rangeOfString:@"."].location; + if (versionEndLoc != NSNotFound) { + vstring = [vstring substringToIndex:versionEndLoc]; + } + + return [vstring intValue]; +} + + +NSString * convertRelativeFilePath(NSString * path) { + return [path stringByStandardizingPath]; +} + +NSString * addDirectoryToSystemArguments(NSUInteger searchPath, NSSearchPathDomainMask domainMask, + NSString *systemProperty, NSMutableArray *systemArguments) { + NSArray *paths = NSSearchPathForDirectoriesInDomains(searchPath,domainMask, YES); + if ([paths count] > 0) { + NSString *basePath = [paths objectAtIndex:0]; + NSString *directory = [NSString stringWithFormat:@"-D%@=%@", systemProperty, basePath]; + [systemArguments addObject:directory]; + return basePath; + } + return nil; +} + +void addModifierFlagToSystemArguments(NSEventModifierFlags mask, NSString *systemProperty, NSEventModifierFlags modifierFlags, NSMutableArray *systemArguments) { + NSString *modifierFlagValue = (modifierFlags & mask) ? @"true" : @"false"; + NSString *modifierFlagVar = [NSString stringWithFormat:@"-D%@=%@", systemProperty, modifierFlagValue]; + [systemArguments addObject:modifierFlagVar]; +} diff --git a/build/macosx/appbundler/res/de.lproj/Localizable.strings b/build/macosx/appbundler/res/de.lproj/Localizable.strings new file mode 100644 index 0000000000..59f745d0cd --- /dev/null +++ b/build/macosx/appbundler/res/de.lproj/Localizable.strings @@ -0,0 +1,7 @@ +"JRELoadError" = "Die Java Laufzeitumgebung konnte nicht geladen werden."; +"JRExLoadError" = "Die Java %d Laufzeitumgebung konnte nicht geladen werden."; +"JRExLoadFullError" = "Diese Anwendung benötigt die Java %d Laufzeitumgebung oder höher auf Ihrem Computer installiert sein. Bitte installieren Sie die neueste Version von Java von www.java.com und erneut versuchen."; +"JDKxLoadFullError" = "Diese Anwendung benötigt die Java %d Laufzeitumgebung oder höher auf Ihrem Computer installiert sein. Bitte installieren Sie die neueste JDK von Oracle.com und erneut versuchen."; +"MainClassNameRequired" = "Hauptklassenname ist erforderlich."; +"JavaDirectoryNotFound" = "Das Java Verzeichnis ist nicht vorhanden."; +"BundlePathContainsColon" = "Kann nicht vom einem Ordner aus starten, der \"/\" in seinem Namen enthält."; diff --git a/build/macosx/appbundler/res/en.lproj/Localizable.strings b/build/macosx/appbundler/res/en.lproj/Localizable.strings index 0d306aaaf8..b052770d6e 100644 --- a/build/macosx/appbundler/res/en.lproj/Localizable.strings +++ b/build/macosx/appbundler/res/en.lproj/Localizable.strings @@ -1,3 +1,7 @@ "JRELoadError" = "Unable to load Java Runtime Environment."; +"JRExLoadError" = "Unable to load a Java %d Runtime Environment."; +"JRExLoadFullError" = "This application requires that Java %d or later be installed on your computer. Please download and install the latest version of Java from www.java.com and try again."; +"JDKxLoadFullError" = "This application requires that a Java %d JDK or later be installed on your computer. Please download and install the latest Java JDK from Oracle.com and try again."; "MainClassNameRequired" = "Main class name is required."; "JavaDirectoryNotFound" = "Unable to enumerate Java directory contents."; +"BundlePathContainsColon" = "Cannot launch from folder that contains a \"/\" in its name."; diff --git a/build/macosx/appbundler/res/fr.lproj/Localizable.strings b/build/macosx/appbundler/res/fr.lproj/Localizable.strings new file mode 100644 index 0000000000..693b44a373 --- /dev/null +++ b/build/macosx/appbundler/res/fr.lproj/Localizable.strings @@ -0,0 +1,7 @@ +"JRELoadError" = "Impossible d'utiliser un environnement Java."; +"JRExLoadError" = "Impossible d'utiliser un environnement Java %d."; +"JRExLoadFullError" = "Ce logiciel nécessite que Java %d ou plus récent être installés sur votre ordinateur. S'il vous plaît télécharger et installer la dernière version de Java à partir de www.java.com et essayez à nouveau."; +"JDKxLoadFullError" = "Ce logiciel nécessite que Java %d JDK ou plus récent être installés sur votre ordinateur. S'il vous plaît télécharger et installer le JDK plus récente de Oracle.com et essayez à nouveau."; +"MainClassNameRequired" = "Principal nom de classe est nécessaire."; +"JavaDirectoryNotFound" = "Impossible d'énumérer répertoire Java contenu."; +"BundlePathContainsColon" = "Pas de commencer à partir d'un dossier qui contient un \"/\" dans son nom."; \ No newline at end of file diff --git a/build/macosx/appbundler/src/com/oracle/appbundler/AppBundlerTask.java b/build/macosx/appbundler/src/com/oracle/appbundler/AppBundlerTask.java index df4c26bc73..dada420753 100644 --- a/build/macosx/appbundler/src/com/oracle/appbundler/AppBundlerTask.java +++ b/build/macosx/appbundler/src/com/oracle/appbundler/AppBundlerTask.java @@ -42,9 +42,14 @@ import java.nio.file.StandardCopyOption; import java.util.ArrayList; import java.util.Iterator; +import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; +import javax.xml.stream.XMLOutputFactory; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamWriter; + import org.apache.tools.ant.BuildException; import org.apache.tools.ant.DirectoryScanner; import org.apache.tools.ant.Task; @@ -56,704 +61,892 @@ * App bundler Ant task. */ public class AppBundlerTask extends Task { - // Output folder for generated bundle - private File outputDirectory = null; - - // General bundle properties - private String name = null; - private String displayName = null; - private String identifier = null; - private File iconFile = null; - private String executableName = EXECUTABLE_NAME; - - private String shortVersion = null; //"1.0"; - private String version = null; //"1.0"; - private String signature = "????"; - private String copyright = null; //""; - private String getInfo = null; - private String privileged = null; - private String workingDirectory = null; + // Output folder for generated bundle + private File outputDirectory = null; - private String applicationCategory = null; - private boolean highResolutionCapable = true; - // Oracle Java 8 requires 10.8.3 or later, so require it here. - private String minimumSystem = "10.8.3"; - // By default, don't embed Java FX. - private boolean javafx = false; + // General bundle properties + private String name = null; + private String displayName = null; + private String identifier = null; + private File icon = null; + private String executableName = EXECUTABLE_NAME; - // JVM info properties - private String mainClassName = null; - private FileSet runtime = null; - private ArrayList classPath = new ArrayList<>(); - private ArrayList libraryPath = new ArrayList<>(); - private ArrayList options = new ArrayList<>(); - private ArrayList arguments = new ArrayList<>(); - private ArrayList architectures = new ArrayList<>(); - private ArrayList bundleDocuments = new ArrayList<>(); + private String shortVersion = "1.0"; + private String version = "1.0"; + private String signature = "????"; + private String copyright = ""; + private String privileged = null; + private String workingDirectory = null; + private String minimumSystemVersion = null; - private Reference classPathRef; + private String jvmRequired = null; + private boolean jrePreferred = false; + private boolean jdkPreferred = false; - private static final String EXECUTABLE_NAME = "JavaAppLauncher"; - private static final String DEFAULT_ICON_NAME = "GenericApp.icns"; - private static final String OS_TYPE_CODE = "APPL"; + private String applicationCategory = null; - private static final int BUFFER_SIZE = 2048; + private boolean highResolutionCapable = true; + private boolean supportsAutomaticGraphicsSwitching = true; + private boolean hideDockIcon = false; + private boolean isDebug = false; + private boolean ignorePSN = false; + // JVM info properties + private String mainClassName = null; + private String jnlpLauncherName = null; + private String jarLauncherName = null; + private Runtime runtime = null; + private ArrayList classPath = new ArrayList<>(); + private ArrayList libraryPath = new ArrayList<>(); + private ArrayList