diff --git a/.github/workflows/java.yml b/.github/workflows/java.yml index d52a5da..fe9c6cd 100644 --- a/.github/workflows/java.yml +++ b/.github/workflows/java.yml @@ -30,6 +30,10 @@ jobs: - uses: arduino/setup-protoc@v3 with: repo-token: ${{ secrets.GITHUB_TOKEN }} + - uses: actions/setup-java@v4 + with: + distribution: 'temurin' + java-version: '11' - uses: gradle/actions/setup-gradle@v4 with: gradle-version: "8.10" # Quotes required to prevent YAML converting to number @@ -39,5 +43,10 @@ jobs: with: name: codemp-java-${{ matrix.platform.target }} path: dist/java/build/libs - - # TODO add a publish step to maven central + - run: gradle publish + working-directory: dist/java + env: + ORG_GRADLE_PROJECT_mavenCentralUsername: ${{ secrets.MAVEN_CENTRAL_USERNAME }} + ORG_GRADLE_PROJECT_mavenCentralPassword: ${{ secrets.MAVEN_CENTRAL_PASSWORD }} + ORG_GRADLE_PROJECT_signingInMemoryKey: ${{ secrets.MAVEN_CENTRAL_GPG_SECRET_KEY }} + ORG_GRADLE_PROJECT_signingInMemoryKeyPassword: ${{ secrets.MAVEN_CENTRAL_GPG_PASSWORD }} diff --git a/README.md b/README.md index 487eeca..b77c4e9 100644 --- a/README.md +++ b/README.md @@ -2,11 +2,11 @@ [![Actions Status](https://github.com/hexedtech/codemp/actions/workflows/test.yml/badge.svg)](https://github.com/hexedtech/codemp/actions) [![docs.rs Status](https://img.shields.io/docsrs/codemp)](https://docs.rs/codemp/) -[![Gitter Chat](https://img.shields.io/gitter/room/hexedtech/codemp)](https://gitter.im/hexedtech/codemp) [![Crates.io Version](https://img.shields.io/crates/v/codemp)](https://crates.io/crates/codemp) -[![NPM Version](https://img.shields.io/npm/v/codemp)](https://npmjs.org/package/codemp) -[![PyPI Version](https://img.shields.io/pypi/v/codemp)](https://pypi.org/project/codemp) -[![LuaRocks Version](https://img.shields.io/luarocks/v/alemi/codemp)](https://luarocks.org/modules/alemi/codemp) +[![Gitter Chat](https://img.shields.io/gitter/room/hexedtech/codemp)](https://gitter.im/hexedtech/codemp) +[![GitHub last commit](https://img.shields.io/github/last-commit/hexedtech/codemp)](https://github.com/hexedtech/codemp/commits/dev/) +[![GitHub commits since tagged version](https://img.shields.io/github/commits-since/hexedtech/codemp/v0.6.2)](https://github.com/hexedtech/codemp/releases/tag/v0.6.2) +[![Crates.io License](https://img.shields.io/crates/l/codemp)](https://github.com/hexedtech/codemp/blob/dev/LICENSE) > `codemp` is a **collaborative** text editing solution to work remotely. @@ -55,11 +55,17 @@ Adding a dependency on `codemp` is **easy**: Just `cargo add codemp` and check the docs for some examples. ### From supported languages -We provide first-class bindings for: - - [![JavaScript](https://github.com/hexedtech/codemp/actions/workflows/javascript.yml/badge.svg)](./dist/README.md#javascript) available from `npm` as [`codemp`](https://npmjs.org/package/codemp) - - [![Python](https://github.com/hexedtech/codemp/actions/workflows/python.yml/badge.svg)](./dist/README.md#python) available from `PyPI` as [`codemp`](https://pypi.org/project/codemp) - - [![Lua](https://github.com/hexedtech/codemp/actions/workflows/lua.yml/badge.svg)](./dist/README.md#lua) available from `LuaRocks` as [`codemp`](https://luarocks.org/modules/alemi/codemp) - - [![Java](https://github.com/hexedtech/codemp/actions/workflows/java.yml/badge.svg)](./dist/README.md#java) available on `MavenCentral` **SOON** +We provide first-class bindings for these other programming languages: + + +| | Build Status | Package | Build Instructions | +| ---------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------- | +| JavaScript | [![JavaScript Build](https://github.com/hexedtech/codemp/actions/workflows/javascript.yml/badge.svg)](https://github.com/hexedtech/codemp/actions/workflows/javascript.yml) | [![NPM Version](https://img.shields.io/npm/v/codemp)](https://npmjs.org/package/codemp) | [README](./dist/README.md#javascript) | +| Python | [![Python Build](https://github.com/hexedtech/codemp/actions/workflows/python.yml/badge.svg)](https://github.com/hexedtech/codemp/actions/workflows/python.yml) | [![PyPI Version](https://img.shields.io/pypi/v/codemp)](https://pypi.org/project/codemp) | [README](./dist/README.md#python) | +| Java | [![Java Build](https://github.com/hexedtech/codemp/actions/workflows/java.yml/badge.svg)](https://github.com/hexedtech/codemp/actions/workflows/java.yml) | [![LuaRocks Version](https://img.shields.io/luarocks/v/alemi/codemp)](https://luarocks.org/modules/alemi/codemp) | [README](./dist/README.md#java) | +| Lua | [![Lua Build](https://github.com/hexedtech/codemp/actions/workflows/lua.yml/badge.svg)](https://github.com/hexedtech/codemp/actions/workflows/lua.yml) | [![Maven Central Version](https://img.shields.io/maven-central/v/mp.code/codemp)](https://central.sonatype.com/artifact/mp.code/codemp) | [README](./dist/README.md#lua) | + + As a design philosophy, our binding APIs attempt to perfectly mimic their Rust counterparts, so the main documentation can still be referenced as source of truth. Refer to specific language documentation for specifics, differences and quirks. diff --git a/dist/java/build.gradle b/dist/java/build.gradle index 9496a40..c0a3b87 100644 --- a/dist/java/build.gradle +++ b/dist/java/build.gradle @@ -1,20 +1,18 @@ plugins { id 'java-library' - id 'maven-publish' - id 'com.github.johnrengelman.shadow' version '8.1.1' - id 'com.palantir.git-version' version '3.1.0' + id "com.vanniktech.maven.publish" version "0.29.0" + id 'com.google.osdetector' version '1.7.3' } group = 'mp.code' -version = versionDetails().lastTag.substring(1) +version = '0.0.3' java { - sourceCompatibility = targetCompatibility = JavaVersion.VERSION_1_8 + sourceCompatibility = targetCompatibility = JavaVersion.VERSION_11 } repositories { mavenCentral() - maven { url 'https://jitpack.io' } } sourceSets { @@ -22,18 +20,17 @@ sourceSets { } dependencies { - implementation 'com.github.adamheinrich:native-utils:master-SNAPSHOT' compileOnly 'org.projectlombok:lombok:1.18.34' annotationProcessor 'org.projectlombok:lombok:1.18.34' } -shadowJar { - archiveClassifier.set('') - dependencies { - include(dependency('com.github.adamheinrich:native-utils:master-SNAPSHOT')) - } +tasks.register('cargoBuild', Exec) { + workingDir '.' + commandLine 'cargo', 'build', '--release', '--features=java' } +jar.archiveClassifier = osdetector.classifier + def rustDir = projectDir.toPath() .parent .parent @@ -41,6 +38,7 @@ def rustDir = projectDir.toPath() .resolve('release') .toFile() processResources { + dependsOn cargoBuild outputs.upToDateWhen { false } // no caching from(rustDir) { include('*.dll') @@ -50,54 +48,34 @@ processResources { } } -tasks.register('cargoBuild', Exec) { - workingDir '.' - commandLine 'cargo', 'build', '--release', '--features=java' -} +import com.vanniktech.maven.publish.SonatypeHost +mavenPublishing { + publishToMavenCentral(SonatypeHost.CENTRAL_PORTAL) + signAllPublications() + coordinates(project.group, rootProject.name, project.version) -processResources.dependsOn cargoBuild -build.finalizedBy shadowJar - -publishing { - publications { - mavenJava(MavenPublication) { - artifactId = 'my-library' - from components.java - versionMapping { - usage('java-api') { - fromResolutionOf('runtimeClasspath') - } - usage('java-runtime') { - fromResolutionResult() - } + pom { + name = rootProject.name + description = "A collaborative editor plugin ecosystem" + inceptionYear = "2022" + url = "https://code.mp/" + licenses { + license { + name = "The GNU General Public License v3.0" + url = "https://www.gnu.org/licenses/gpl-3.0.txt" } - pom { - name = 'My Library' - description = 'A concise description of my library' - url = 'http://www.example.com/library' - properties = [ - myProp: "value", - "prop.with.dots": "anotherValue" - ] - licenses { - license { - name = 'The Apache License, Version 2.0' - url = 'http://www.apache.org/licenses/LICENSE-2.0.txt' - } - } - developers { - developer { - id = 'johnd' - name = 'John Doe' - email = 'john.doe@example.com' - } - } - scm { - connection = 'scm:git:git://example.com/my-library.git' - developerConnection = 'scm:git:ssh://example.com/my-library.git' - url = 'http://example.com/my-library/' - } + } + developers { + developer { + id = "zaaarf" + name = "zaaarf" + email = "zaaarf@codemp.dev" } } + scm { + url = "https://github.com/hexedtech/codemp/" + connection = "scm:git:git://github.com/hexedtech/codemp.git" + developerConnection = "scm:git:ssh://git@github.com/hexedtech/codemp.git" + } } } diff --git a/dist/java/src/mp/code/BufferController.java b/dist/java/src/mp/code/BufferController.java index df08a8b..0ae455f 100644 --- a/dist/java/src/mp/code/BufferController.java +++ b/dist/java/src/mp/code/BufferController.java @@ -17,6 +17,7 @@ public final class BufferController { BufferController(long ptr) { this.ptr = ptr; + Extensions.CLEANER.register(this, () -> free(ptr)); } private static native String get_name(long self); @@ -116,12 +117,8 @@ public final class BufferController { } private static native void free(long self); - @Override - protected void finalize() { - free(this.ptr); - } static { - Extensions.loadLibraryIfNotPresent(); + NativeUtils.loadLibraryIfNeeded(); } } diff --git a/dist/java/src/mp/code/Client.java b/dist/java/src/mp/code/Client.java index e9b715e..12bd9c3 100644 --- a/dist/java/src/mp/code/Client.java +++ b/dist/java/src/mp/code/Client.java @@ -22,6 +22,7 @@ public final class Client { Client(long ptr) { this.ptr = ptr; + Extensions.CLEANER.register(this, () -> free(ptr)); } /** @@ -146,12 +147,8 @@ public final class Client { } private static native void free(long self); - @Override - protected void finalize() { - free(this.ptr); - } static { - Extensions.loadLibraryIfNotPresent(); + NativeUtils.loadLibraryIfNeeded(); } } diff --git a/dist/java/src/mp/code/CursorController.java b/dist/java/src/mp/code/CursorController.java index 2b1f36d..ee3d238 100644 --- a/dist/java/src/mp/code/CursorController.java +++ b/dist/java/src/mp/code/CursorController.java @@ -16,6 +16,7 @@ public final class CursorController { CursorController(long ptr) { this.ptr = ptr; + Extensions.CLEANER.register(this, () -> free(ptr)); } private static native Cursor try_recv(long self) throws ControllerException; @@ -93,12 +94,8 @@ public final class CursorController { } private static native void free(long self); - @Override - protected void finalize() { - free(this.ptr); - } static { - Extensions.loadLibraryIfNotPresent(); + NativeUtils.loadLibraryIfNeeded(); } } diff --git a/dist/java/src/mp/code/Extensions.java b/dist/java/src/mp/code/Extensions.java index c6cddfa..93e141a 100644 --- a/dist/java/src/mp/code/Extensions.java +++ b/dist/java/src/mp/code/Extensions.java @@ -1,6 +1,6 @@ package mp.code; -import java.io.IOException; +import java.lang.ref.Cleaner; /** * A class holding utility functions, as well as functions which are specific @@ -8,6 +8,9 @@ import java.io.IOException; * broader CodeMP API. */ public final class Extensions { + /** A {@link Cleaner} handling freeing of memory for library objects. */ + static final Cleaner CLEANER = Cleaner.create(); + /** * Hashes the given {@link String} using CodeMP's hashing algorithm (xxh3). * @param input the string to hash @@ -37,21 +40,7 @@ public final class Extensions { */ public static native void setupTracing(String path, boolean debug); - private static boolean loaded = false; - static synchronized void loadLibraryIfNotPresent() { - if(loaded) return; - try { - String filename = System.getProperty("os.name").startsWith("Windows") - ? "/natives/codemp.dll" - : "/natives/libcodemp.so"; - cz.adamh.utils.NativeUtils.loadLibraryFromJar(filename); - loaded = true; - } catch(IOException e) { - throw new RuntimeException(e); - } - } - static { - Extensions.loadLibraryIfNotPresent(); + NativeUtils.loadLibraryIfNeeded(); } } diff --git a/dist/java/src/mp/code/NativeUtils.java b/dist/java/src/mp/code/NativeUtils.java new file mode 100644 index 0000000..9253d7d --- /dev/null +++ b/dist/java/src/mp/code/NativeUtils.java @@ -0,0 +1,160 @@ +/* + * Class NativeUtils is published under the The MIT License: + * + * Copyright (c) 2012 Adam Heinrich + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package mp.code; + +import java.io.*; +import java.nio.file.FileSystemNotFoundException; +import java.nio.file.FileSystems; +import java.nio.file.Files; +import java.nio.file.ProviderNotFoundException; +import java.nio.file.StandardCopyOption; +import java.util.Objects; + +/** + * A simple library class which helps with loading dynamic libraries stored in the + * JAR archive. These libraries usually contain implementation of some methods in + * native code (using JNI - Java Native Interface). + * @see http://adamheinrich.com/blog/2012/how-to-load-native-jni-library-from-jar + * @see https://github.com/adamheinrich/native-utils + */ +class NativeUtils { + + /** + * The minimum length a prefix for a file has to have according to {@link File#createTempFile(String, String)}}. + */ + private static final int MIN_PREFIX_LENGTH = 3; + + /** + * Prefix of the temporary folder where the native is stored. + */ + public static final String NATIVE_FOLDER_PATH_PREFIX = "nativeutils"; + + /** + * Temporary directory which will contain the DLLs. + */ + private static File temporaryDir; + + /** + * Private constructor - this class will never be instanced + */ + private NativeUtils() {} + + /** + * Loads library from current JAR archive. + * The file from JAR is copied into system temporary directory and then loaded. The temporary file is deleted after + * exiting. + * Method uses String as filename because the pathname is "abstract", not system-dependent. + * @param path The path of file inside JAR as absolute path (beginning with '/'), e.g. /package/File.ext + * @throws IOException If temporary file creation or read/write operation fails + * @throws IllegalArgumentException If source file (param path) does not exist + * @throws IllegalArgumentException If the path is not absolute or if the filename is shorter than three characters + * (restriction of {@link File#createTempFile(java.lang.String, java.lang.String)}). + * @throws FileNotFoundException If the file could not be found inside the JAR. + */ + @SuppressWarnings("ResultOfMethodCallIgnored") + private static void loadLibraryFromJar(String path) throws IOException { + if(null == path || !path.startsWith("/")) { + throw new IllegalArgumentException("The path has to be absolute (start with '/')."); + } + + // Obtain filename from path + String[] parts = path.split("/"); + String filename = (parts.length > 1) ? parts[parts.length - 1] : null; + + // Check if the filename is okay + if(filename == null || filename.length() < MIN_PREFIX_LENGTH) { + throw new IllegalArgumentException("The filename has to be at least 3 characters long."); + } + + // Prepare temporary file + if(temporaryDir == null) { + temporaryDir = createTempDirectory(); + temporaryDir.deleteOnExit(); + } + + File temp = new File(temporaryDir, filename); + + try(InputStream is = NativeUtils.class.getResourceAsStream(path)) { + Files.copy(Objects.requireNonNull(is), temp.toPath(), StandardCopyOption.REPLACE_EXISTING); + } catch (IOException e) { + temp.delete(); + throw e; + } catch (NullPointerException e) { + temp.delete(); + throw new FileNotFoundException("File " + path + " was not found inside JAR."); + } + + try { + System.load(temp.getAbsolutePath()); + } finally { + if(isPosixCompliant()) { + // Assume POSIX compliant file system, can be deleted after loading + temp.delete(); + } else { + // Assume non-POSIX, and don't delete until last file descriptor closed + temp.deleteOnExit(); + } + } + } + + private static boolean isPosixCompliant() { + try { + return FileSystems.getDefault() + .supportedFileAttributeViews() + .contains("posix"); + } catch (FileSystemNotFoundException | ProviderNotFoundException | SecurityException e) { + return false; + } + } + + private static File createTempDirectory() throws IOException { + String tempDir = System.getProperty("java.io.tmpdir"); + File generatedDir = new File(tempDir, NativeUtils.NATIVE_FOLDER_PATH_PREFIX + System.nanoTime()); + + if(!generatedDir.mkdir()) + throw new IOException("Failed to create temp directory " + generatedDir.getName()); + + return generatedDir; + } + + private static boolean loaded = false; + static synchronized void loadLibraryIfNeeded() { + if(loaded) return; + try { + String os = System.getProperty("os.name").toLowerCase(); + + String filename; + if(os.startsWith("windows")) { + filename = "/natives/codemp.dll"; + } else if(os.startsWith("mac")) { + filename = "/natives/libcodemp.dylib";; + } else filename = "/natives/libcodemp.so"; + loadLibraryFromJar(filename); + + loaded = true; + } catch(IOException e) { + throw new RuntimeException(e); + } + } +} diff --git a/dist/java/src/mp/code/Workspace.java b/dist/java/src/mp/code/Workspace.java index b6582bb..33f2de3 100644 --- a/dist/java/src/mp/code/Workspace.java +++ b/dist/java/src/mp/code/Workspace.java @@ -21,6 +21,7 @@ public final class Workspace { Workspace(long ptr) { this.ptr = ptr; + Extensions.CLEANER.register(this, () -> free(ptr)); } private static native String get_workspace_id(long self); @@ -170,13 +171,9 @@ public final class Workspace { } private static native void free(long self); - @Override - protected void finalize() { - free(this.ptr); - } static { - Extensions.loadLibraryIfNotPresent(); + NativeUtils.loadLibraryIfNeeded(); } /**