diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..f4527a6 --- /dev/null +++ b/.gitignore @@ -0,0 +1,39 @@ +# Javadocs +docs/ + +# Maven +deploy/ +target/ +log/ + +# IntelliJ +.idea/ +*.iml +out/ + +# Gradle +# Use local properties (e.g. to set a specific JDK) +gradle.properties +build/ +.gradle/ +gradle.properties + +# Eclipse +.settings/ +.project +.classpath + +# Mac +.DS_Store + +# Java +hs_err*.log + +# Other +*.tmp +*.bak +*.swp +*~.nib +*thumbs.db +bin/ +notebooks/ diff --git a/LICENSE b/LICENSE index 261eeb9..ee24645 100644 --- a/LICENSE +++ b/LICENSE @@ -186,7 +186,7 @@ same "printed page" as the copyright notice for easier identification within third-party archives. - Copyright [yyyy] [name of copyright owner] + Copyright 2022 QuPath Developers, The University of Edinburgh Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..6142aea --- /dev/null +++ b/build.gradle @@ -0,0 +1,105 @@ +plugins { + id 'java-library' + // To create a shadow/fat jar, including dependencies + id 'com.github.johnrengelman.shadow' version '7.0.0' + // To manage included native libraries + id 'org.bytedeco.gradle-javacpp-platform' +} + +repositories { + // Use this only for local development! +// mavenLocal() + + mavenCentral() + + maven { + url "https://maven.scijava.org/content/repositories/releases" + } + + maven { + url "https://maven.scijava.org/content/repositories/snapshots" + } + +} + +ext.moduleName = 'qupath.extension.py4j' + +description = 'Connect QuPath to Python using Py4J' + +version = "0.0.1-SNAPSHOT" + +dependencies { + def qupathVersion = "0.4.3" // For now + + shadow "io.github.qupath:qupath-gui-fx:${qupathVersion}" + shadow 'org.kordamp.ikonli:ikonli-javafx:12.3.1' + + shadow "org.slf4j:slf4j-api:2.0.0" + + shadow libs.guava + + implementation 'net.sf.py4j:py4j:0.10.9.7' + + testImplementation "io.github.qupath:qupath-gui-fx:${qupathVersion}" + testImplementation "org.junit.jupiter:junit-jupiter-api:5.7.2" + testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine' + +} + +processResources { + from ("${projectDir}/LICENSE.txt") { + into 'licenses/' + } +} + +tasks.register("copyDependencies", Copy) { + description "Copy dependencies into the build directory for use elsewhere" + group "QuPath" + + from configurations.default + into 'build/libs' +} + +/* + * Ensure Java 11 compatibility + */ +java { + toolchain { + languageVersion = JavaLanguageVersion.of(11) + } + if (project.properties['sources']) + withSourcesJar() + if (project.properties['javadocs']) + withJavadocJar() +} + +/* + * Create javadocs for all modules/packages in one place. + * Use -PstrictJavadoc=true to fail on error with doclint (which is rather strict). + */ +tasks.withType(Javadoc) { + options.encoding = 'UTF-8' + def strictJavadoc = findProperty('strictJavadoc') + if (!strictJavadoc) { + options.addStringOption('Xdoclint:none', '-quiet') + } +} + +/* + * Set encoding + */ +tasks.named('compileJava') { + options.encoding = 'UTF-8' +} + +/* + * Avoid 'Entry .gitkeep is a duplicate but no duplicate handling strategy has been set.' + * when using withSourcesJar() + */ +tasks.withType(org.gradle.jvm.tasks.Jar) { + duplicatesStrategy = DuplicatesStrategy.INCLUDE +} + +tasks.named('test') { + useJUnitPlatform() +} diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..41d9927 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..ae04661 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-7.5.1-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..1b6c787 --- /dev/null +++ b/gradlew @@ -0,0 +1,234 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${0##*/} + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..ac1b06f --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,89 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..24ffc22 --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'qupath-extension-py4j' diff --git a/src/main/java/qupath/ext/py4j/QuPathEntryPoint.java b/src/main/java/qupath/ext/py4j/QuPathEntryPoint.java new file mode 100644 index 0000000..d3da216 --- /dev/null +++ b/src/main/java/qupath/ext/py4j/QuPathEntryPoint.java @@ -0,0 +1,369 @@ +/*- + * Copyright 2022 QuPath developers, University of Edinburgh + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package qupath.ext.py4j; + +import com.google.common.collect.Lists; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.reflect.TypeToken; +import ij.ImagePlus; +import ij.io.FileSaver; +import javafx.application.Platform; +import qupath.imagej.tools.IJTools; +import qupath.lib.awt.common.BufferedImageTools; +import qupath.lib.common.GeneralTools; +import qupath.lib.gui.QuPathGUI; +import qupath.lib.gui.commands.SummaryMeasurementTableCommand; +import qupath.lib.gui.measure.ObservableMeasurementTableData; +import qupath.lib.gui.scripting.QPEx; +import qupath.lib.gui.tools.GuiTools; +import qupath.lib.gui.tools.GuiTools.SnapshotType; +import qupath.lib.gui.viewer.QuPathViewer; +import qupath.lib.images.ImageData; +import qupath.lib.images.servers.ImageServer; +import qupath.lib.io.FeatureCollection; +import qupath.lib.io.GsonTools; +import qupath.lib.objects.PathObject; +import qupath.lib.projects.ProjectImageEntry; +import qupath.lib.regions.ImagePlane; +import qupath.lib.regions.RegionRequest; +import qupath.lib.roi.interfaces.ROI; + +import javax.imageio.ImageIO; +import java.awt.image.BufferedImage; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Base64; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +/** + * Entry point for use with a Py4J Gateway. + * This provides useful methods to work with QuPath from Python. + * + * @author Pete Bankhead + */ +public class QuPathEntryPoint extends QPEx { + + public static String getExtensionVersion() { + return GeneralTools.getPackageVersion(QuPathEntryPoint.class); + } + + public static byte[] snapshot(QuPathGUI qupath) throws IOException { + // If we return the snapshot too quickly, we may not see the result of recent actions + try { + Platform.requestNextPulse(); + Thread.sleep(50L); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + return getImageBytes(GuiTools.makeSnapshot(qupath, SnapshotType.MAIN_SCENE), "png"); + } + + public static byte[] snapshot(QuPathViewer viewer) throws IOException { + try { + Platform.requestNextPulse(); + Thread.sleep(50L); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + return getImageBytes(GuiTools.makeViewerSnapshot(viewer), "png"); + } + + public static String snapshotBase64(QuPathGUI qupath) throws IOException { + return base64Encode(snapshot(qupath)); + } + + public static String snapshotBase64(QuPathViewer viewer) throws IOException { + return base64Encode(snapshot(viewer)); + } + + public static boolean openInQuPath(ProjectImageEntry entry) { + return GuiTools.callOnApplicationThread(() -> getQuPath().openImageEntry(entry)); + } + + public static String getDetectionMeasurementTable(ImageData imageData) { + if (imageData == null) + return ""; + return getMeasurementTable(imageData, imageData.getHierarchy().getDetectionObjects()); + } + + public static String getAnnotationMeasurementTable(ImageData imageData) { + if (imageData == null) + return ""; + return getMeasurementTable(imageData, imageData.getHierarchy().getAnnotationObjects()); + } + + public static String getMeasurementTable(ImageData imageData, Collection pathObjects) { + if (imageData == null || pathObjects == null || pathObjects.isEmpty()) + return ""; + var table = new ObservableMeasurementTableData(); + table.setImageData(imageData, pathObjects); + return SummaryMeasurementTableCommand.getTableModelString(table, "\t", Collections.emptyList()); + } + + /** + * Create a {@link PathObject} from a GeoJSON representation. + * @param geoJson + * @return + */ + public static PathObject toPathObject(String geoJson) { + return GsonTools.getInstance().fromJson(geoJson, PathObject.class); + } + + /** + * Create a {@link ROI} from a GeoJSON representation. + * @param geoJson + * @return + */ + public static ROI toROI(String geoJson) { + return GsonTools.getInstance().fromJson(geoJson, ROI.class); + } + + public static List toPathObjects(String geoJson) { + var gson = GsonTools.getInstance(); + return toPathObjects(gson.fromJson(geoJson, JsonElement.class)); + } + + public static List toPathObjects(JsonElement jsonElement) { + var gson = GsonTools.getInstance(); + if (jsonElement.isJsonArray()) { + return toStream(jsonElement.getAsJsonArray().asList(), 10) + .flatMap(e -> toPathObjects(e).stream()) + .collect(Collectors.toList()); + } + if (jsonElement.isJsonObject()) { + JsonObject jsonObject = jsonElement.getAsJsonObject(); + if (jsonObject.size() == 0) + return Collections.emptyList(); + if (jsonObject.has("features")) { + return toPathObjects(jsonObject.get("features")); + } else { + stripNulls(jsonObject); + return Collections.singletonList(gson.fromJson(jsonObject, PathObject.class)); + } + } else + return Collections.emptyList(); + } + + /** + * QuPath's v0.4.3 GeoJSON deserialization failed on some null entries, so make sure these are removed + * @param jsonObject + */ + private static void stripNulls(JsonObject jsonObject) { + for (String key : new ArrayList<>(jsonObject.keySet())) { + JsonElement member = jsonObject.get(key); + if (member == null || member.isJsonNull()) + jsonObject.remove(key); + else if (member.isJsonObject()) + stripNulls(member.getAsJsonObject()); + } + } + + + public static List toROIs(String geoJson) { + return GsonTools.getInstance().fromJson(geoJson, + new TypeToken>() {}.getType() + ); + } + + /** + * Convert a collection of PathObjects to a GeoJSON FeatureCollection. + * If there is a chance the resulting string will be too long, prefer instead + * {@link #toFeatureCollections(Collection, int)} to partition objects into separate feature collections. + * @param pathObjects + * @return + */ + public static String toFeatureCollection(Collection pathObjects) { + var collection = FeatureCollection.wrap(pathObjects); + return GsonTools.getInstance().toJson(collection); + } + + /** + * Create a GeoJSON FeatureCollection from a collection of PathObjects, partitioning into separate collections. + * This can be useful for performance reasons, and also to avoid the character limit for strings in Java and Python. + * @param pathObjects + * @param chunkSize + * @return + */ + public static List toFeatureCollections(Collection pathObjects, int chunkSize) { + return toStream(Lists.partition(new ArrayList<>(pathObjects), chunkSize), 4) + .map(QuPathEntryPoint::toFeatureCollection).collect(Collectors.toList()); + } + + public static List toGeoJsonFeatureList(Collection pathObjects) { + var gson = GsonTools.getInstance(); + return toStream(pathObjects, 100).map(p -> gson.toJson(p)).collect(Collectors.toList()); + } + + public static List getObjectIds(Collection pathObjects) { + return pathObjects.stream().map(p -> p.getID().toString()).collect(Collectors.toList()); + } + + public static List getMeasurementNames(Collection pathObjects) { + return pathObjects.stream() + .flatMap(p -> p.getMeasurementList().getMeasurementNames().stream()) + .distinct() + .collect(Collectors.toList()); + } + + public static List getMeasurements(Collection pathObjects, String name) { + return pathObjects.stream().map(p -> p.getMeasurements().getOrDefault(name, null)).collect(Collectors.toList()); + } + + private static Stream toStream(Collection collection, int minSizeForParallelism) { + if (collection.size() >= minSizeForParallelism) + return collection.parallelStream(); + else + return collection.stream(); + } + + public static String toGeoJsonFeature(PathObject pathObject) { + return GsonTools.getInstance().toJson(pathObject); + } + + public static String toGeoJson(ROI roi) { + return GsonTools.getInstance().toJson(roi); + } + + + public static byte[] getTiffStack(ImageServer server, double downsample) throws IOException { + return getTiffStack(server, downsample, 0, 0, server.getWidth(), server.getHeight()); + } + + public static byte[] getTiffStack(ImageServer server, double downsample, int x, int y, int width, int height) throws IOException { + return getTiffStack(server, downsample, x, y, width, height, 0, 0); + } + + public static byte[] getTiffStack(ImageServer server, double downsample, int x, int y, int width, int height, int z, int t) throws IOException { + return getTiffStack(server, RegionRequest.createInstance(server.getPath(), + downsample, x, y, width, height, z, t)); + } + + public static byte[] getTiffStack(ImageServer server, RegionRequest request) throws IOException { + var imp = IJTools.extractHyperstack(server, request); + return toTiffBytes(imp); + } + + public static String getTiffStackBase64(ImageServer server, double downsample) throws IOException { + return base64Encode(getTiffStack(server, downsample)); + } + + public static String getTiffStackBase64(ImageServer server, double downsample, int x, int y, int width, int height) throws IOException { + return base64Encode(getTiffStack(server, downsample, x, y, width, height)); + } + + public static String getTiffStackBase64(ImageServer server, double downsample, int x, int y, int width, int height, int z, int t) throws IOException { + return base64Encode(getTiffStack(server, downsample, x, y, width, height, z, t)); + } + + public static String getTiffStackBase64(ImageServer server, RegionRequest request) throws IOException { + return base64Encode(getTiffStack(server, request)); + } + + public static byte[] getImageBytes(ImageServer server, double downsample, String format) throws IOException { + return getImageBytes(server, downsample, 0, 0, server.getWidth(), server.getHeight(), format); + } + + public static byte[] getImageBytes(ImageServer server, double downsample, int x, int y, int width, int height, String format) throws IOException { + return getImageBytes(server, downsample, x, y, width, height, 0, 0, format); + } + + public static byte[] getImageBytes(ImageServer server, double downsample, int x, int y, int width, int height, int z, int t, String format) throws IOException { + var request = RegionRequest.createInstance(server.getPath(), + downsample, x, y, width, height, z, t); + byte[] result = getImageBytes(server, request, format); + return result; + } + + public static String getImageBase64(ImageServer server, double downsample, String format) throws IOException { + return base64Encode(getImageBytes(server, downsample, format)); + } + + public static String getImageBase64(ImageServer server, double downsample, int x, int y, int width, int height, String format) throws IOException { + return base64Encode(getImageBytes(server, downsample, x, y, width, height, format)); + } + + public static String getImageBase64(ImageServer server, double downsample, int x, int y, int width, int height, int z, int t, String format) throws IOException { + return base64Encode(getImageBytes(server, downsample, x, y, width, height, z, t, format)); + } + + public static String getImageBase64(ImageServer server, RegionRequest request, String format) throws IOException { + return base64Encode(getImageBytes(server, request, format)); + } + + public static byte[] getImageBytes(ImageServer server, RegionRequest request, String format) throws IOException { + if (isImageJFormat(format)) { + var imp = IJTools.convertToImagePlus(server, request).getImage(); + return toTiffBytes(imp); + } + var img = server.readRegion(request); + return getImageBytes(img, format); + } + + private static String base64Encode(byte[] bytes) { + return Base64.getEncoder().encodeToString(bytes); + } + + private static boolean isImageJFormat(String format) { + var fmt = format.toLowerCase(); + return Set.of("imagej tiff", "imagej tif").contains(fmt); + } + + private static String chooseAutoFormat(BufferedImage img) { + if (BufferedImageTools.is8bitColorType(img.getType())) + return "png"; + else + return "imagej tiff"; + } + + public static byte[] getImageBytes(BufferedImage img) throws IOException { + return getImageBytes(img, chooseAutoFormat(img)); + } + + public static byte[] getImageBytes(BufferedImage img, String format) throws IOException { + + if (format == null || "auto".equalsIgnoreCase(format) || format.isEmpty()) + format = chooseAutoFormat(img); + + var fmt = format.toLowerCase(); + if (isImageJFormat(fmt)) { + var imp = IJTools.convertToUncalibratedImagePlus("Image", img); + return toTiffBytes(imp); + } + + try (var stream = new ByteArrayOutputStream(Math.min(1024*1024*10, img.getWidth() * img.getHeight() + 1024))) { + ImageIO.write(img, format, stream); + var array = stream.toByteArray(); + return array; + } + + } + + + private static byte[] toTiffBytes(ImagePlus imp) { + return new FileSaver(imp).serialize(); + } + +} diff --git a/src/main/java/qupath/ext/py4j/QuPathPy4JExtension.java b/src/main/java/qupath/ext/py4j/QuPathPy4JExtension.java new file mode 100644 index 0000000..b74d324 --- /dev/null +++ b/src/main/java/qupath/ext/py4j/QuPathPy4JExtension.java @@ -0,0 +1,388 @@ +/*- + * Copyright 2022 QuPath developers, University of Edinburgh + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package qupath.ext.py4j; + +import java.util.Map; +import java.util.UUID; + +import org.controlsfx.control.action.Action; +import org.kordamp.ikonli.javafx.StackedFontIcon; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javafx.beans.binding.Bindings; +import javafx.beans.property.BooleanProperty; +import javafx.beans.property.ObjectProperty; +import javafx.beans.property.ReadOnlyBooleanProperty; +import javafx.beans.property.SimpleBooleanProperty; +import javafx.beans.property.SimpleObjectProperty; +import javafx.beans.value.ObservableBooleanValue; +import javafx.beans.value.ObservableValue; +import javafx.css.PseudoClass; +import javafx.geometry.Pos; +import javafx.scene.Node; +import javafx.scene.control.Button; +import javafx.scene.control.ButtonType; +import javafx.scene.control.ContentDisplay; +import javafx.scene.control.Label; +import javafx.scene.control.TextField; +import javafx.scene.control.Tooltip; +import javafx.scene.input.Clipboard; +import javafx.scene.input.DataFormat; +import javafx.scene.layout.GridPane; +import javafx.scene.text.TextAlignment; +import py4j.GatewayServer; +import py4j.GatewayServerListener; +import py4j.Py4JServerConnection; +import qupath.lib.common.Version; +import qupath.lib.gui.ActionTools; +import qupath.lib.gui.QuPathGUI; +import qupath.lib.gui.dialogs.Dialogs; +import qupath.lib.gui.extensions.QuPathExtension; +import qupath.lib.gui.prefs.PathPrefs; +import qupath.lib.gui.tools.PaneTools; + + +/** + * QuPath extension to enable Python and Java/QuPath to communicate, via Py4J (http://py4j.org). + * + * @author Pete Bankhead + */ +public class QuPathPy4JExtension implements QuPathExtension { + + private final static Logger logger = LoggerFactory.getLogger(QuPathPy4JExtension.class); + + private boolean isInstalled = false; + + private BooleanProperty enablePy4J = PathPrefs.createPersistentPreference("enablePy4J", true); + + private Py4JCommand command = new Py4JCommand(); + + @Override + public void installExtension(QuPathGUI qupath) { + if (isInstalled) { + logger.debug("{} is already installed", getName()); + return; + } + + isInstalled = true; + + qupath.getPreferencePane().addPropertyPreference( + enablePy4J, + Boolean.class, + "Enable Py4J", + "Py4J", + "Enable Py4J through the UI to accept connections - " + + "this enables QuPath to communicate with Python.\n" + + "See www.py4j.org for more info."); + + + var action = createGatewayAction(); + + var mi = ActionTools.createMenuItem(action); + mi.graphicProperty().unbind(); + mi.setGraphic(createGatewayIcon(command.gatewayRunningProperty())); + mi.visibleProperty().bind(enablePy4J); + + var btn = ActionTools.createButton(action, true); + btn.textProperty().unbind(); + btn.graphicProperty().unbind(); + btn.getStyleClass().add("toggle-button"); + command.gatewayRunningProperty().addListener((v, o, n) -> { + btn.pseudoClassStateChanged(PseudoClass.getPseudoClass("selected"), n); + if (n) + Dialogs.showInfoNotification("Py4J", "Py4J Gateway started"); + else + Dialogs.showInfoNotification("Py4J", "Py4J Gateway stopped"); + }); + btn.visibleProperty().bind(enablePy4J); + + btn.setGraphic(createGatewayIcon(command.gatewayRunningProperty())); + btn.setContentDisplay(ContentDisplay.GRAPHIC_ONLY); + + qupath.getToolBar().getItems().add(btn); + + var menu = qupath.getMenu("Extensions>Py4J", true); + menu.visibleProperty().bind(enablePy4J); + menu.getItems().add(mi); + } + + + private Action createGatewayAction() { + var action = new Action("Py4J", e -> { + if (command.isGatewayRunning()) + command.stopGateway(); + else + promptToStartGateway(); + }); + action.textProperty().bind(Bindings.createStringBinding(() -> { + if (action.isSelected()) + return "Stop Py4J Gateway"; + else + return "Start Py4J Gateway"; + }, action.selectedProperty())); + + action.setLongText("Start a Py4J Gateway to communicate between QuPath and Python"); + return action; + } + + + private Integer port = GatewayServer.DEFAULT_PORT; + private String token = ""; + + + private boolean promptToStartGateway() { + + if (command.isGatewayRunning()) { + logger.warn("Can't start new GatewayServer - please shut down the existing server first"); + return false; + } + + var title = "Py4J Gateway"; + + var pane = new GridPane(); + pane.setHgap(5); + pane.setVgap(5); + + var labelPort = new Label("Port"); + var tfPort = new TextField(); + tfPort.setPromptText("Default port (" + port + ")"); + + int row = 0; + + var labelInstructions = new Label("Create a Py4J Gateway so Python programs can \n" + + "access QuPath through a local network socket.\n" + + "Check out py4j.org for more details & security info.\n "); + labelInstructions.setTextAlignment(TextAlignment.CENTER); + labelInstructions.setAlignment(Pos.CENTER); + PaneTools.setToExpandGridPaneWidth(labelInstructions); + + PaneTools.addGridRow(pane, row++, 0, null, labelInstructions, labelInstructions); + + + PaneTools.addGridRow(pane, row++, 0, "Port number (integer), or leave blank to use the default Py4J port", + labelPort, tfPort); + + var labelAuthToken = new Label("Token"); + var tfAuthToken = new TextField(token); + tfAuthToken.setPromptText("Authentication token (optional)"); + tfAuthToken.setPrefColumnCount(24); + var btnRandomToken = new Button("Random"); + btnRandomToken.setOnAction(e -> tfAuthToken.setText(UUID.randomUUID().toString())); + btnRandomToken.setTooltip(new Tooltip("Generate a UUID to use as an authentication token")); + + var btnCopyToken = new Button("Copy"); + btnCopyToken.disableProperty().bind(tfAuthToken.textProperty().isEmpty()); + btnCopyToken.setOnAction(e -> { + Clipboard.getSystemClipboard().setContent(Map.of(DataFormat.PLAIN_TEXT, tfAuthToken.getText())); + Dialogs.showInfoNotification(title, "Token copied to clipboard!"); + }); + btnCopyToken.setTooltip(new Tooltip("Copy authentication token to clipboard (to use in Python)")); + + PaneTools.addGridRow(pane, row++, 0, "Authentication token - if provided, this needs to be entered on the Python side", + labelAuthToken, tfAuthToken); + var paneButtons = PaneTools.createColumnGrid(btnRandomToken, btnCopyToken); + paneButtons.setHgap(5); + PaneTools.setMaxWidth(Double.MAX_VALUE, btnRandomToken, btnCopyToken); + PaneTools.addGridRow(pane, row++, 0, null, null, paneButtons, paneButtons); + + var result = Dialogs.builder() + .title(title) + .content(pane) + .buttons(ButtonType.OK, ButtonType.CANCEL) + .showAndWait() + .orElse(ButtonType.CANCEL) == ButtonType.OK; + + if (!result) + return false; + + var builder = new GatewayServer.GatewayServerBuilder() + .entryPoint(new QuPathEntryPoint()); + + var portText = tfPort.getText(); + if (portText != null && !portText.isBlank()) { + try { + port = Integer.parseInt(portText); + } catch (NumberFormatException e) { + Dialogs.showErrorMessage(title, "Unable to parse port number - must be a valid integer"); + return false; + } + } else { + logger.debug("Using default port"); + port = GatewayServer.DEFAULT_PORT; + } + + if (port != null) + builder.javaPort(port); + + var authToken = tfAuthToken.getText(); + if (authToken != null && !authToken.isEmpty()) { + if (authToken.isBlank()) + logger.warn("Authentication token is blank (but not empty)"); + else + logger.debug("Setting token"); + builder.authToken(authToken); + } + token = authToken; + + var server = builder.build(); + command.gatewayServer.set(server); + + return true; + } + + + private Node createGatewayIcon(ObservableBooleanValue gatewayOn) { + var icon = new StackedFontIcon(); + icon.setIconCodeLiterals("ion4-logo-python"); + icon.setStyle("-fx-icon-color: -fx-text-fill;"); + icon.getStyleClass().add("qupath-icon"); + if (gatewayOn != null) { + icon.styleProperty().bind(Bindings.createObjectBinding(() -> { + if (gatewayOn.get()) { + return "-fx-icon-color: rgb(200, 20, 20);"; + } else { + return "-fx-icon-color: -fx-text-fill;"; + } + }, gatewayOn)); + } else + icon.setStyle("-fx-icon-color: -fx-text-fill;"); + return icon; + } + + + + @Override + public String getName() { + return "QuPath Py4J extension"; + } + + @Override + public String getDescription() { + return "Connect QuPath to Python via Py4J"; + } + + // TODO: Update when version is stabilized + @Override + public Version getQuPathVersion() { + return Version.parse("v0.4.0-SNAPSHOT"); + } + + + + + private static class Py4JCommand { + + private static final Logger logger = LoggerFactory.getLogger(Py4JCommand.class); + + private BooleanProperty gatewayRunning = new SimpleBooleanProperty(false); + + private ObjectProperty gatewayServer = new SimpleObjectProperty<>();; + + private Py4JListener listener; + + private Py4JCommand() { + gatewayServer.addListener(this::gatewayChanged); + } + + private void gatewayChanged(ObservableValue observable, GatewayServer oldValue, + GatewayServer newValue) { + if (oldValue != null) { + if (oldValue.getGateway().isStarted()) + oldValue.shutdown(); + oldValue.removeListener(listener); + } + if (newValue != null) { + if (listener == null) + listener = new Py4JListener(); + newValue.addListener(listener); + if (!newValue.getGateway().isStarted()) { + newValue.start(); + } + } + } + + + public void stopGateway() { + var server = gatewayServer.get(); + if (server != null) { + server.shutdown(); + server.removeListener(listener); + gatewayServer.set(null); + } + } + + + public boolean isGatewayRunning() { + return gatewayRunning.get(); + } + + public ReadOnlyBooleanProperty gatewayRunningProperty() { + return ReadOnlyBooleanProperty.readOnlyBooleanProperty(gatewayRunning); + } + + + private class Py4JListener implements GatewayServerListener { + + @Override + public void connectionError(Exception e) { + logger.error(e.getLocalizedMessage(), e); + } + + @Override + public void connectionStarted(Py4JServerConnection gatewayConnection) { + logger.info("Gateway connection started"); + } + + @Override + public void connectionStopped(Py4JServerConnection gatewayConnection) { + logger.info("Gateway connection stopped"); + } + + @Override + public void serverError(Exception e) { + logger.error(e.getLocalizedMessage(), e); + } + + @Override + public void serverPostShutdown() { + if (gatewayRunning.get()) { + logger.info("Py4J gateway shutdown"); + gatewayRunning.set(false); + } + } + + @Override + public void serverPreShutdown() {} + + @Override + public void serverStarted() { + logger.info("Py4J gateway started"); + gatewayRunning.set(true); + } + + @Override + public void serverStopped() { + logger.debug("Py4J gateway stopped"); + } + + } + + } + + +} diff --git a/src/main/resources/META-INF/services/qupath.lib.gui.extensions.QuPathExtension b/src/main/resources/META-INF/services/qupath.lib.gui.extensions.QuPathExtension new file mode 100644 index 0000000..3022331 --- /dev/null +++ b/src/main/resources/META-INF/services/qupath.lib.gui.extensions.QuPathExtension @@ -0,0 +1 @@ +qupath.ext.py4j.QuPathPy4JExtension \ No newline at end of file