diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b63da45 --- /dev/null +++ b/.gitignore @@ -0,0 +1,42 @@ +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ + +### IntelliJ IDEA ### +.idea/modules.xml +.idea/jarRepositories.xml +.idea/compiler.xml +.idea/libraries/ +*.iws +*.iml +*.ipr +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +### Eclipse ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ + +### Mac OS ### +.DS_Store \ No newline at end of file diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..13566b8 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,8 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Editor-based HTTP Client requests +/httpRequests/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml diff --git a/.idea/gradle.xml b/.idea/gradle.xml new file mode 100644 index 0000000..592fdc7 --- /dev/null +++ b/.idea/gradle.xml @@ -0,0 +1,19 @@ + + + + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..b4e6022 --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/.idea/uiDesigner.xml b/.idea/uiDesigner.xml new file mode 100644 index 0000000..2b63946 --- /dev/null +++ b/.idea/uiDesigner.xml @@ -0,0 +1,124 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..94a25f7 --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/.run/Publish Plugin.run.xml b/.run/Publish Plugin.run.xml new file mode 100644 index 0000000..9b72827 --- /dev/null +++ b/.run/Publish Plugin.run.xml @@ -0,0 +1,24 @@ + + + + + + + + true + true + false + + + \ No newline at end of file diff --git a/.run/Run IDE with Plugin.run.xml b/.run/Run IDE with Plugin.run.xml new file mode 100644 index 0000000..7747a29 --- /dev/null +++ b/.run/Run IDE with Plugin.run.xml @@ -0,0 +1,24 @@ + + + + + + + + true + true + false + + + \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..363c61c --- /dev/null +++ b/README.md @@ -0,0 +1,10 @@ +# jetbrains-qoi + +A qoi viewer for Jetbrains' ideas IDE. + +![Version](https://img.shields.io/jetbrains/plugin/v/19352-qoi-support) +![Rating](https://img.shields.io/jetbrains/plugin/r/stars/19352-qoi-support) +![Downloads](https://img.shields.io/jetbrains/plugin/d/19352-qoi-support) + +![preview.png](preview.png) + diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..9db1989 --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,45 @@ +plugins { + id("java") + id("org.jetbrains.intellij") version "1.5.2" +} + +group = "io.github.xiaozhuai" +version = "1.0.0" + +repositories { + mavenCentral() +} + +intellij { + version.set("2021.2") + type.set("IC") // Target IDE Platform + + plugins.set(listOf(/* Plugin Dependencies */)) +} + +tasks { + withType { + sourceCompatibility = "11" + targetCompatibility = "11" + } + + patchPluginXml { + sinceBuild.set("212") + untilBuild.set("222.*") + } + + signPlugin { + certificateChain.set(System.getenv("INTELLIJ_CERTIFICATE_CHAIN")) + privateKey.set(System.getenv("INTELLIJ_PRIVATE_KEY")) + password.set(System.getenv("INTELLIJ_PRIVATE_KEY_PASSWORD")) + } + + publishPlugin { + token.set(System.getenv("INTELLIJ_PUBLISH_TOKEN")) + } +} + +dependencies { + // !!! Do not forget to change QOIMetadata.QOI_LIBRARY_VERSION when upgrade qoi-java !!! + implementation("me.saharnooby:qoi-java:1.2.1") +} diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..7454180 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..aa991fc --- /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.4.2-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/preview.png b/preview.png new file mode 100644 index 0000000..7410c10 Binary files /dev/null and b/preview.png differ diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..75515b9 --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1 @@ +rootProject.name = "jetbrains-qoi" \ No newline at end of file diff --git a/src/main/java/io/github/xiaozhuai/jetbrains/qoi/QOIImageReaderSpi.java b/src/main/java/io/github/xiaozhuai/jetbrains/qoi/QOIImageReaderSpi.java new file mode 100644 index 0000000..e416376 --- /dev/null +++ b/src/main/java/io/github/xiaozhuai/jetbrains/qoi/QOIImageReaderSpi.java @@ -0,0 +1,196 @@ +package io.github.xiaozhuai.jetbrains.qoi; + +import me.saharnooby.qoi.*; + +import com.intellij.openapi.diagnostic.Logger; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import javax.imageio.ImageReadParam; +import javax.imageio.ImageReader; +import javax.imageio.ImageTypeSpecifier; +import javax.imageio.metadata.IIOMetadata; +import javax.imageio.spi.ImageReaderSpi; +import javax.imageio.stream.ImageInputStream; +import java.awt.image.BufferedImage; +import java.awt.image.DataBufferInt; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.IntBuffer; +import java.util.Iterator; +import java.util.Locale; + +public class QOIImageReaderSpi extends ImageReaderSpi { + private static final byte[] QOI_HEADER = {'q', 'o', 'i', 'f'}; + + private static final int MAX_FILE_SIZE = 0x06400000; // 100 MiBs + + QOIImageReaderSpi() { + vendorName = QOIMetadata.QOI_VENDOR; + version = QOIMetadata.QOI_LIBRARY_VERSION; + suffixes = QOIMetadata.QOI_SUFFIXES; + names = QOIMetadata.QOI_FORMAT_NAMES; + MIMETypes = QOIMetadata.QOI_MIME_TYPES; + pluginClassName = QOIReader.class.getName(); + inputTypes = new Class[]{ImageInputStream.class}; + } + + @Override + public boolean canDecodeInput(@NotNull Object source) throws IOException { + if (!(source instanceof ImageInputStream)) return false; + + ImageInputStream stream = (ImageInputStream) source; + long length = stream.length(); + // The length may be -1 for files of unknown size. + // Accept them for now and if needed, throw an IOException later. + if (length > MAX_FILE_SIZE) { + return false; + } + + stream.mark(); + try { + byte[] header = new byte[4]; + int bytesRead = stream.read(header, 0, 4); + return bytesRead == 4 + && arrayEquals(header, 0, QOI_HEADER.length, QOI_HEADER); + } finally { + try { + stream.reset(); + } catch (IOException e) { + Logger.getInstance(QOIImageReaderSpi.class).error(e); + } + } + } + + private static boolean arrayEquals(byte[] a1, int offset, int len, byte[] a2) { + for (int i = 0; i < len; i++) { + if (a1[offset + i] != a2[i]) { + return false; + } + } + return true; + } + + @Override + public @NotNull ImageReader createReaderInstance(Object extension) throws IOException { + return new QOIReader(this); + } + + @Override + public @NotNull String getDescription(Locale locale) { + return "QOI Image Decoder"; + } + + private static class QOIReader extends ImageReader { + private static final String UNABLE_TO_READ_QOI_IMAGE = "Unable to read qoi image"; + + private QOIImage image = null; + + private QOIReader(ImageReaderSpi originatingProvider) { + super(originatingProvider); + } + + @Override + public void dispose() { + image = null; + } + + @Override + public void setInput(Object input, boolean seekForwardOnly, boolean ignoreMetadata) { + super.setInput(input, seekForwardOnly, ignoreMetadata); + try { + byte[] bytes = readStreamFully((ImageInputStream) input); + image = QOIUtil.readImage(new ByteArrayInputStream(bytes), 4); + } catch (Exception e) { + image = null; + } + } + + @Override + public int getNumImages(boolean allowSearch) { + return image == null ? 0 : 1; + } + + private static byte[] readStreamFully(@NotNull ImageInputStream stream) throws IOException { + if (stream.length() != -1) { + byte[] bytes = new byte[(int) stream.length()]; // Integer overflow prevented by canDecode check in reader spi above. + stream.readFully(bytes); + return bytes; + } + + // Unknown file size + ByteArrayOutputStream buffer = new ByteArrayOutputStream(0x100000); // initialize with 1 MiB to minimize reallocation. + final int bufferSize = 0x4000; // 16k + byte[] bytes = new byte[bufferSize]; + int idx; + for (idx = 0; idx < MAX_FILE_SIZE / bufferSize; idx++) { // Just to make sure we don't exceed MAX_FILE_SIZE + int read = stream.read(bytes, 0, bufferSize); + buffer.write(bytes, 0, read); + if (read != bufferSize) { + break; + } + } + if (idx == MAX_FILE_SIZE / bufferSize) { + throw new IOException("qoi image too large"); + } + return buffer.toByteArray(); + } + + @Override + public int getWidth(int imageIndex) throws IOException { + if (image != null) { + return image.getWidth(); + } + throw new IOException(UNABLE_TO_READ_QOI_IMAGE); + } + + @Override + public int getHeight(int imageIndex) throws IOException { + if (image != null) { + return image.getHeight(); + } + throw new IOException(UNABLE_TO_READ_QOI_IMAGE); + } + + @Override + public @Nullable Iterator getImageTypes(int imageIndex) { + return null; + } + + @Override + public @Nullable IIOMetadata getStreamMetadata() { + return null; + } + + @Override + public @Nullable IIOMetadata getImageMetadata(int imageIndex) { + return null; + } + + @Override + public @NotNull BufferedImage read(int imageIndex, ImageReadParam param) throws IOException { + if (image == null) { + throw new IOException(UNABLE_TO_READ_QOI_IMAGE); + } + byte[] pixels = image.getPixelData(); + // rgba to argb + for (int i = 0; i < image.getWidth() * image.getHeight(); ++i) { + byte alpha = pixels[i * 4 + 3]; + pixels[i * 4 + 3] = pixels[i * 4 + 2]; + pixels[i * 4 + 2] = pixels[i * 4 + 1]; + pixels[i * 4 + 1] = pixels[i * 4]; + pixels[i * 4] = alpha; + } + @SuppressWarnings("UndesirableClassUsage") + BufferedImage bi = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB); + // Copy the bytes read above to the image's data buffer. + final int[] a = ((DataBufferInt) bi.getRaster().getDataBuffer()).getData(); + IntBuffer intBuf = ByteBuffer.wrap(pixels).asIntBuffer(); + assert a.length == intBuf.remaining(); + intBuf.get(a); + return bi; + } + } +} diff --git a/src/main/java/io/github/xiaozhuai/jetbrains/qoi/QOIImageWriterSpi.java b/src/main/java/io/github/xiaozhuai/jetbrains/qoi/QOIImageWriterSpi.java new file mode 100644 index 0000000..93a48f7 --- /dev/null +++ b/src/main/java/io/github/xiaozhuai/jetbrains/qoi/QOIImageWriterSpi.java @@ -0,0 +1,222 @@ +package io.github.xiaozhuai.jetbrains.qoi; + +import me.saharnooby.qoi.*; + +import org.jetbrains.annotations.NotNull; + +import javax.imageio.*; +import javax.imageio.metadata.IIOMetadata; +import javax.imageio.spi.ImageWriterSpi; +import javax.imageio.stream.ImageOutputStream; +import java.awt.*; +import java.awt.image.*; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.nio.ByteOrder; +import java.util.Iterator; +import java.util.Locale; + +public class QOIImageWriterSpi extends ImageWriterSpi { + QOIImageWriterSpi() { + vendorName = QOIMetadata.QOI_VENDOR; + version = QOIMetadata.QOI_LIBRARY_VERSION; + suffixes = QOIMetadata.QOI_SUFFIXES; + names = QOIMetadata.QOI_FORMAT_NAMES; + MIMETypes = QOIMetadata.QOI_MIME_TYPES; + pluginClassName = QOIWriter.class.getName(); + outputTypes = new Class[]{ImageOutputStream.class}; + } + + public static void writeImage(@NotNull BufferedImage image, + @NotNull OutputStream outputStream) throws IOException { + // Instead of + // ImageIO.write(image, QOIMetadata.QOI_FORMAT_LOWER_CASE, stream); + // which will pass null as the parameters to the ImageWriter, call through to the ImageWriter + // more directly so we can set up the proper parameters: + ImageTypeSpecifier type = ImageTypeSpecifier.createFromRenderedImage(image); + Iterator iterator = ImageIO.getImageWriters(type, QOIMetadata.QOI_FORMAT_LOWER_CASE); + if (iterator.hasNext()) { + ImageWriter writer = iterator.next(); + try (ImageOutputStream stream = ImageIO.createImageOutputStream(outputStream)) { + writer.setOutput(stream); + try { + ImageWriteParam param = new ImageWriteParam(writer.getLocale()); + writer.write(null, new IIOImage(image, null, null), param); + } finally { + writer.dispose(); + stream.flush(); + } + } + } + } + + @Override + public boolean canEncodeImage(ImageTypeSpecifier type) { + return canWriteImage(type); + } + + public static boolean canWriteImage(ImageTypeSpecifier type) { + SampleModel sm = type.getSampleModel(); + ColorModel cm = type.getColorModel(); + return (sm.getNumBands() >= 2 && sm.getNumBands() <= 4 || cm instanceof IndexColorModel) + && sm.getSampleSize(0) <= 8 + && sm.getWidth() <= 65535 + && sm.getHeight() <= 65535 + && (cm == null || cm.getComponentSize()[0] <= 8); + } + + @Override + public ImageWriter createWriterInstance(Object extension) throws IOException { + return new QOIWriter(this); + } + + @Override + public String getDescription(Locale locale) { + return "QOI Image Encoder"; + } + + private static class QOIWriter extends ImageWriter { + public QOIWriter(ImageWriterSpi originatingProvider) { + super(originatingProvider); + } + + @Override + public IIOMetadata getDefaultStreamMetadata(ImageWriteParam param) { + return new QOIMetadata(); + } + + @Override + public IIOMetadata getDefaultImageMetadata(ImageTypeSpecifier imageType, ImageWriteParam param) { + return new QOIMetadata(); + } + + @Override + public IIOMetadata convertStreamMetadata(IIOMetadata inData, ImageWriteParam param) { + return null; + } + + @Override + public IIOMetadata convertImageMetadata(IIOMetadata inData, ImageTypeSpecifier imageType, ImageWriteParam param) { + return null; + } + + private ImageOutputStream stream = null; + + @Override + public void setOutput(Object output) { + super.setOutput(output); + if (output != null) { + if (!(output instanceof ImageOutputStream)) { + throw new + IllegalArgumentException("output is not an ImageOutputStream"); + } + this.stream = (ImageOutputStream) output; + this.stream.setByteOrder(ByteOrder.LITTLE_ENDIAN); + } else { + this.stream = null; + } + } + + + @Override + public void write(IIOMetadata streamMetadata, IIOImage image, ImageWriteParam param) throws IOException { + if (stream == null) { + throw new IllegalStateException("output == null!"); + } + + Raster srcRas = getRaster(image); + + int minX = srcRas.getMinX(); + int minY = srcRas.getMinY(); + int width = srcRas.getWidth(); + int height = srcRas.getHeight(); + int maxX = minX + width; + int maxY = minY + height; + + byte[] data = new byte[width * height * 4]; + // TODO: This code is the inefficient fallback dealing with any color/sample model. + // However, we've restricted things in the canEncodeImage method so we might as well try + // to do it more efficiently + int index = 0; + SampleModel sampleModel = srcRas.getSampleModel(); + int bands = sampleModel.getNumBands(); + if (bands == 1) { + // Indexed image but not found in raster + return; + } + assert bands >= 2 && bands <= 4; // enforced in canEncodeImage + DataBuffer buffer = srcRas.getDataBuffer(); + if (bands >= 3) { + for (int y = minY; y < maxY; y++) { + for (int x = minX; x < maxX; x++) { + for (int band = 0; band < bands; band++) { + int sample = sampleModel.getSample(x, y, band, buffer); + data[index++] = (byte) sample; + } + if (bands == 3) { + data[index++] = (byte) 255; // implicit alpha in an RGB (not RGBA) image + } + } + } + } else { + assert bands == 2; + for (int y = minY; y < maxY; y++) { + for (int x = minX; x < maxX; x++) { + byte sample = (byte) sampleModel.getSample(x, y, 0, buffer); + data[index++] = sample; + data[index++] = sample; + data[index++] = sample; + byte alpha = (byte) sampleModel.getSample(x, y, 1, buffer); + data[index++] = alpha; + } + } + } + + ByteArrayOutputStream encoded = new ByteArrayOutputStream(); + QOIUtil.writeImage(QOIUtil.createFromPixelData(data, width, height, 4), encoded); + stream.write(encoded.toByteArray()); + } + + @NotNull + private static Raster getRaster(@NotNull IIOImage image) { + boolean rasterOnly = image.hasRaster(); + if (rasterOnly) { + return image.getRaster(); + } else { + RenderedImage renderedImage = image.getRenderedImage(); + if (renderedImage instanceof BufferedImage) { + // Convert indexed to RGB + BufferedImage bufferedImage = (BufferedImage) renderedImage; + if (renderedImage.getColorModel() instanceof IndexColorModel) { + //noinspection UndesirableClassUsage + BufferedImage rgb = new BufferedImage(bufferedImage.getWidth(), bufferedImage.getHeight(), BufferedImage.TYPE_INT_ARGB); + Graphics2D graphics = rgb.createGraphics(); + graphics.drawImage(bufferedImage, 0, 0, null); + graphics.dispose(); + return rgb.getRaster(); + } + return bufferedImage.getRaster(); + } else if (renderedImage.getNumXTiles() == 1 && + renderedImage.getNumYTiles() == 1) { + Raster raster = renderedImage.getTile(renderedImage.getMinTileX(), + renderedImage.getMinTileY()); + if (raster.getWidth() != renderedImage.getWidth() || + raster.getHeight() != renderedImage.getHeight()) { + raster = raster.createChild(raster.getMinX(), + raster.getMinY(), + renderedImage.getWidth(), + renderedImage.getHeight(), + raster.getMinX(), + raster.getMinY(), + null); + } + return raster; + } else { + return renderedImage.getData(); + } + } + } + } + +} diff --git a/src/main/java/io/github/xiaozhuai/jetbrains/qoi/QOIMetadata.java b/src/main/java/io/github/xiaozhuai/jetbrains/qoi/QOIMetadata.java new file mode 100644 index 0000000..e6ab9a5 --- /dev/null +++ b/src/main/java/io/github/xiaozhuai/jetbrains/qoi/QOIMetadata.java @@ -0,0 +1,37 @@ +package io.github.xiaozhuai.jetbrains.qoi; + +import org.w3c.dom.Node; + +import javax.imageio.metadata.IIOInvalidTreeException; +import javax.imageio.metadata.IIOMetadata; +import javax.imageio.metadata.IIOMetadataNode; + +public class QOIMetadata extends IIOMetadata { + public static final String QOI_FORMAT_LOWER_CASE = "qoi"; + public static final String QOI_FORMAT_UPPER_CASE = "QOI"; + public static final String[] QOI_FORMAT_NAMES = new String[]{QOI_FORMAT_UPPER_CASE, QOI_FORMAT_LOWER_CASE}; + public static final String EXT_QOI = QOI_FORMAT_LOWER_CASE; + public static final String[] QOI_SUFFIXES = new String[]{EXT_QOI}; + public static final String[] QOI_MIME_TYPES = new String[]{"image/qoi"}; + public static final String QOI_VENDOR = "QOI"; + + public static final String QOI_LIBRARY_VERSION = "1.2.1"; + + @Override + public boolean isReadOnly() { + return false; + } + + @Override + public Node getAsTree(String formatName) { + return new IIOMetadataNode(nativeMetadataFormatName); + } + + @Override + public void mergeTree(String formatName, Node root) throws IIOInvalidTreeException { + } + + @Override + public void reset() { + } +} diff --git a/src/main/java/io/github/xiaozhuai/jetbrains/qoi/QOIMetadataRegistrar.java b/src/main/java/io/github/xiaozhuai/jetbrains/qoi/QOIMetadataRegistrar.java new file mode 100644 index 0000000..4fb9e13 --- /dev/null +++ b/src/main/java/io/github/xiaozhuai/jetbrains/qoi/QOIMetadataRegistrar.java @@ -0,0 +1,19 @@ +package io.github.xiaozhuai.jetbrains.qoi; + +import com.intellij.openapi.diagnostic.Logger; + +import javax.imageio.spi.IIORegistry; +import javax.imageio.spi.ImageReaderSpi; +import javax.imageio.spi.ImageWriterSpi; + +public class QOIMetadataRegistrar { + private QOIMetadataRegistrar() { + ensureQoiRegistered(); + } + + public static void ensureQoiRegistered() { + IIORegistry defaultInstance = IIORegistry.getDefaultInstance(); + defaultInstance.registerServiceProvider(new QOIImageReaderSpi(), ImageReaderSpi.class); + defaultInstance.registerServiceProvider(new QOIImageWriterSpi(), ImageWriterSpi.class); + } +} diff --git a/src/main/resources/META-INF/plugin.xml b/src/main/resources/META-INF/plugin.xml new file mode 100644 index 0000000..e69e942 --- /dev/null +++ b/src/main/resources/META-INF/plugin.xml @@ -0,0 +1,13 @@ + + io.github.xiaozhuai.jetbrains-qoi + QOI Support + xiaozhuai + Allows viewing images in the QOI format in the IDE.

+ ]]>
+ com.intellij.modules.lang + + + + +
\ No newline at end of file diff --git a/src/main/resources/META-INF/pluginIcon.svg b/src/main/resources/META-INF/pluginIcon.svg new file mode 100644 index 0000000..960050f --- /dev/null +++ b/src/main/resources/META-INF/pluginIcon.svg @@ -0,0 +1,9 @@ + + + Layer 1 + + + + + + \ No newline at end of file