diff --git a/.gitignore b/.gitignore index 78fe79a..0a2adc8 100644 --- a/.gitignore +++ b/.gitignore @@ -1,22 +1,22 @@ -.idea/ +# IntelliJ +*.iml +.idea/workspace.xml +.idea/tasks.xml +.idea/gradle.xml +.idea/assetWizardSettings.xml +.idea/dictionaries +.idea/libraries +.idea/caches .gradle + build/ out/ local.properties .DS_Store -gradlew -gradlew.bat -gradle -*.iml # Ignore Gradle GUI config gradle-app.setting -# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) -!gradle-wrapper.jar - # Cache of project .gradletasknamecache -# # Work around https://youtrack.jetbrains.com/issue/IDEA-116898 -# gradle/wrapper/gradle-wrapper.properties diff --git a/.idea/codeStyles/Project.xml b/.idea/codeStyles/Project.xml new file mode 100644 index 0000000..681f41a --- /dev/null +++ b/.idea/codeStyles/Project.xml @@ -0,0 +1,116 @@ + + + + + + + +
+ + + + xmlns:android + + ^$ + + + +
+
+ + + + xmlns:.* + + ^$ + + + BY_NAME + +
+
+ + + + .*:id + + http://schemas.android.com/apk/res/android + + + +
+
+ + + + .*:name + + http://schemas.android.com/apk/res/android + + + +
+
+ + + + name + + ^$ + + + +
+
+ + + + style + + ^$ + + + +
+
+ + + + .* + + ^$ + + + BY_NAME + +
+
+ + + + .* + + http://schemas.android.com/apk/res/android + + + ANDROID_ATTRIBUTE_ORDER + +
+
+ + + + .* + + .* + + + BY_NAME + +
+
+
+
+
+
\ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..7bfef59 --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,9 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 0000000..32db24e --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/runConfigurations.xml b/.idea/runConfigurations.xml new file mode 100644 index 0000000..7f68460 --- /dev/null +++ b/.idea/runConfigurations.xml @@ -0,0 +1,12 @@ + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..35eb1dd --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/README-CN.md b/README-CN.md index 2123a18..3747279 100644 --- a/README-CN.md +++ b/README-CN.md @@ -32,6 +32,7 @@ McImage是无侵入式的全量压缩资源图片插件 ### Update Log > v0.0.2以后的用户更新到0.0.2以上需要升级你的mctools文件夹,已经上传到release。 +- 1.5.0 : 更新gradle plugin 到 3.5.0 ,更新获取android资源方式,修复了不支持缩写(assembleDebug 缩写 aD)的问题 - 1.4.0 : 区分优化类型,可选择ConvertWep或Compress, 默认选择Compress. 使用ConvertWep需要min sdk >= 18.但是压缩效果更好 - 1.3.0 : 支持多线程压缩,缩短执行时间 - 1.2.0 : 优先从系统获取压缩命令, 不存在使用本地文件命令 @@ -84,20 +85,19 @@ mctools ```groovy McImageConfig { isCheckSize true //是否检测图片大小,默认为true - optimizeType "ConertWebp" //优化类型,可选"ConvertWebp","Compress",转换为webp或原图压缩,默认Compress,使用ConvertWep需要min sdk >= 18.但是压缩效果更好 + optimizeType "Compress" //优化类型,可选"ConvertWebp","Compress",转换为webp或原图压缩,默认Compress,使用ConvertWep需要min sdk >= 18.但是压缩效果更好 maxSize 1*1024*1024 //大图片阈值,default 1MB enableWhenDebug false //debug下是否可用,default true isCheckPixels true // 是否检测大像素图片,default true - maxWidth 1000 //defualt 1000 如果开启图片宽高检查,默认的最大宽度 - maxHeight 1000 //defualt 1000 如果开启图片宽高检查,默认的最大高度 + maxWidth 1000 //default 1000 如果开启图片宽高检查,默认的最大宽度 + maxHeight 1000 //default 1000 如果开启图片宽高检查,默认的最大高度 whiteList = [ //默认为空,如果添加,对图片不进行任何处理 "icon_launcher.png" ] - mctoolsDir "$rootDir/tools" + mctoolsDir "$rootDir" isSupportAlphaWebp false //是否支持带有透明度的webp,default false,带有透明图的图片会进行压缩 multiThread true //是否开启多线程处理图片,default true - bigImageWhiteList = [ //默认为空,如果添加,大图检测将跳过这些图片 - ] + bigImageWhiteList = [] //默认为空,如果添加,大图检测将跳过这些图片 } ``` diff --git a/README.md b/README.md index bdb551b..413ff6c 100644 --- a/README.md +++ b/README.md @@ -34,15 +34,16 @@ The version 1.0.1 now support all build.gradle version! ### Update Log > The user use v0.0.2 update plugin need update your mctools dir together. -- 1.4.0 : Featrue, Support for selecting different optimization types,"ConvertWebp" or "Compress" can be chosen.Default "Compress". "CompressWebp" is a better compression ratio but it don't support api < 18 -- 1.3.0 : Featrue, Support multi-thread processing +- 1.5.0 : Update gradle plugin to 3.5.0 , change the get android resources way,fix not support abbreviation(such as assembleDebug use aD) bug. +- 1.4.0 : Feature, Support for selecting different optimization types,"ConvertWebp" or "Compress" can be chosen.Default "Compress". "CompressWebp" is a better compression ratio but it don't support api < 18 +- 1.3.0 : Feature, Support multi-thread processing - 1.2.0 : Feature, get compress command from system environment prior to local file - 1.0.1 : Bug fix, fix maxSize float error - 1.0.0 : Support AAPT2 , now don't need to close aapt2 with "android.enableAapt2=false", you can delete this line in gradle.properties. - 0.1.4 : Bug fix, add the white list feature, add the img width and height check feature. - 0.1.2 : Bug fix(Fix the problem that check image size not work) - 0.1.1 : Bug fix(Fix the problem not work for module and fix the problem of enableWhenDebug not work) -- 0.0.4 : Add auto choose system future.Remove webpQualitu config (Set inappropriate will result the img lossless) +- 0.0.4 : Add auto choose system future.Remove webpQuality config (Set inappropriate will result the img lossless) - 0.0.3 : Add webp ! It will auto convert your png (without alpha in min API < 18 and not work in min API < 14) and jpg to webp if it will become more small. - 0.0.2 : Improve the log. @@ -85,20 +86,19 @@ You can set the config in build.gradle.If you not set this,all config will use d ```groovy McImageConfig { isCheckSize true //Whether to detect image size,default true - optimizeType "ConertWebp" //Optimize Type,"ConvertWebp" or "Compress",default "Compress", "CompressWebp" is a better compression ratio but it don't support api < 18 + optimizeType "Compress" //Optimize Type,"ConvertWebp" or "Compress",default "Compress", "CompressWebp" is a better compression ratio but it don't support api < 18 maxSize 1*1024*1024 //big image size threshold,default 1MB - enableWhenDebug false //swithc in debug build,default true + enableWhenDebug false //switch in debug build,default true isCheckPixels true // Whether to detect image pixels of width and height,default true - maxWidth 1000 //defualt 1000 - maxHeight 1000 //defualt 1000 + maxWidth 1000 //default 1000 + maxHeight 1000 //default 1000 whiteList = [ //do not do any optimization for the images who in the list "icon_launcher.png" ] - mctoolsDir "$rootDir/tools" + mctoolsDir "$rootDir" isSupportAlphaWebp false //Whether support convert the Image with Alpha chanel to Webp,default false, the images with alpha chanels will be compressed.if config true, its need api level >=18 or do some compatible measures - multiThread true //Whether open muti-thread processing,default true - bigImageWhiteList = [ //do not detect big size or large pixels for the images who in the list - ] + multiThread true //Whether open multi-thread processing,default true + bigImageWhiteList = [] //do not detect big size or large pixels for the images who in the list } ``` diff --git a/bintray.gradle b/bintray.gradle index 2df0d55..5f2a9a9 100644 --- a/bintray.gradle +++ b/bintray.gradle @@ -4,7 +4,7 @@ apply plugin: 'com.jfrog.bintray' def siteUrl = 'https://github.com/Aweme/McImage' def gitUrl = 'https://github.com/Aweme/McImage.git' group = "com.smallsoho.mobcase" -version = "1.4.0" +version = "1.5.0" Properties properties = new Properties() properties.load(project.rootProject.file('local.properties').newDataInputStream()) diff --git a/build.gradle b/build.gradle index 66a2e7f..2bc6ada 100644 --- a/build.gradle +++ b/build.gradle @@ -9,8 +9,8 @@ buildscript { } dependencies { - classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.7.3' - classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.2.60" + classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.8.4' + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.50" } } @@ -22,7 +22,7 @@ allprojects { } dependencies { - compile gradleApi() - compile localGroovy() - compile 'com.android.tools.build:gradle:3.1.2' + implementation gradleApi() + implementation localGroovy() + implementation 'com.android.tools.build:gradle:3.5.0' } diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..f6b961f 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..2c5baad --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Fri Oct 18 12:32:35 CST 2019 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-5.4.1-all.zip diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..cccdd3d --- /dev/null +++ b/gradlew @@ -0,0 +1,172 @@ +#!/usr/bin/env sh + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$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="" + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# 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 + ;; + 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" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=$(save "$@") + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong +if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then + cd "$(dirname "$0")" +fi + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..e95643d --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,84 @@ +@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 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= + +@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 init + +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 init + +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 + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +: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 %CMD_LINE_ARGS% + +: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/publish.gradle b/publish.gradle index 7342cbb..de64585 100644 --- a/publish.gradle +++ b/publish.gradle @@ -1,8 +1,8 @@ apply plugin: 'maven' apply plugin: 'signing' -def DEBUG = true -def VERSION = '1.4.0' +def DEBUG = false +def VERSION = '1.5.0-SNAPSHOT' def GROUP = 'com.smallsoho.mobcase' def ARTIFACT = 'McImage' diff --git a/src/main/java/com/smallsoho/mcplugin/image/ImagePlugin.kt b/src/main/java/com/smallsoho/mcplugin/image/ImagePlugin.kt index 0581257..90af867 100644 --- a/src/main/java/com/smallsoho/mcplugin/image/ImagePlugin.kt +++ b/src/main/java/com/smallsoho/mcplugin/image/ImagePlugin.kt @@ -1,4 +1,4 @@ -package com.smallsoho.mcplugin.image; +package com.smallsoho.mcplugin.image import com.android.build.gradle.AppExtension import com.android.build.gradle.LibraryExtension @@ -11,7 +11,9 @@ import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.api.Task import java.io.File -import java.util.concurrent.* +import java.util.concurrent.Callable +import java.util.concurrent.Executors +import java.util.concurrent.Future class ImagePlugin : Plugin { @@ -20,11 +22,15 @@ class ImagePlugin : Plugin { private var oldSize: Long = 0 private var newSize: Long = 0 val bigImgList = ArrayList() + + var isDebugTask = false + var isContainAssembleTask = false + override fun apply(project: Project) { mcImageProject = project - //判断是library还是application + //check is library or application val hasAppPlugin = project.plugins.hasPlugin("com.android.application") val variants = if (hasAppPlugin) { (project.property("android") as AppExtension).applicationVariants @@ -36,75 +42,74 @@ class ImagePlugin : Plugin { project.extensions.create("McImageConfig", Config::class.java) mcImageConfig = project.property("McImageConfig") as Config - val taskNames = project.gradle.startParameter.taskNames - var isDebugTask = false - var isContainAssembleTask = false - for (index: Int in 0 until taskNames.size) { - val taskName = taskNames[index] - if (taskName.contains("assemble") || taskName.contains("resguard") || taskName.contains("bundle")) { - if (taskName.toLowerCase().endsWith("debug") && - taskName.toLowerCase().contains("debug")) { - isDebugTask = true + project.gradle.taskGraph.whenReady { + it.allTasks.forEach { task -> + val taskName = task.name + if (taskName.contains("assemble") || taskName.contains("resguard") || taskName.contains("bundle")) { + if (taskName.toLowerCase().endsWith("debug") && + taskName.toLowerCase().contains("debug")) { + isDebugTask = true + } + isContainAssembleTask = true + return@forEach } - isContainAssembleTask = true - break } } - //export build clean - if (!isContainAssembleTask) { - return - } - - project.afterEvaluate { _ -> - + project.afterEvaluate { variants.all { variant -> variant as BaseVariantImpl checkMcTools(project) - //debug enable - if (isDebugTask && !mcImageConfig.enableWhenDebug) { - println("Debug not run !") - return@all - } - - val mergeResourcesTask = project.tasks.findByName("merge${variant.name.capitalize()}Resources") + val mergeResourcesTask = variant.mergeResourcesProvider.get() val mcPicTask = project.task("McImage${variant.name.capitalize()}") - mcPicTask.doLast { _ -> - println("---- McImage Plugin Start ----") - println(mcImageConfig.toString()) + mcPicTask.doLast { + + //debug enable + if (isDebugTask && !mcImageConfig.enableWhenDebug) { + LogUtil.log("Debug not run ^_^") + return@doLast + } - val dir = variant.mergeResources.computeResourceSetList0() //强行调用一下 + //assemble passed + if (!isContainAssembleTask) { + LogUtil.log("Don't contain assemble task, mcimage passed") + return@doLast + } + + LogUtil.log("---- McImage Plugin Start ----") + LogUtil.log(mcImageConfig.toString()) + + val dir = variant.allRawAndroidResources.files val cacheList = ArrayList() val imageFileList = ArrayList() - if (dir != null) { - for (channelDir: File in dir) { - traverseResDir(channelDir, imageFileList, cacheList, object : IBigImage { - override fun onBigImage(file: File) { - bigImgList.add(file.absolutePath) - } - }) - } + for (channelDir: File in dir) { + traverseResDir(channelDir, imageFileList, cacheList, object : IBigImage { + override fun onBigImage(file: File) { + bigImgList.add(file.absolutePath) + } + }) } checkBigImage() val start = System.currentTimeMillis() - mtDispathOptimizeTask(imageFileList) - println(sizeInfo()) - println("---- McImage Plugin End ----, Total Time(ms) : ${System.currentTimeMillis() - start}") + mtDispatchOptimizeTask(imageFileList) + LogUtil.log(sizeInfo()) + LogUtil.log("---- McImage Plugin End ----, Total Time(ms) : ${System.currentTimeMillis() - start}") } + //chmod task val chmodTaskName = "chmod${variant.name.capitalize()}" val chmodTask = project.task(chmodTaskName) - chmodTask.doLast { _ -> + chmodTask.doLast { //chmod if linux if (Tools.isLinux()) { Tools.chmod() @@ -112,12 +117,13 @@ class ImagePlugin : Plugin { } //inject task - (project.tasks.findByName(chmodTask.name) as Task).dependsOn(mergeResourcesTask!!.taskDependencies.getDependencies(mergeResourcesTask)) + (project.tasks.findByName(chmodTask.name) as Task).dependsOn(mergeResourcesTask.taskDependencies.getDependencies(mergeResourcesTask)) (project.tasks.findByName(mcPicTask.name) as Task).dependsOn(project.tasks.findByName(chmodTask.name) as Task) mergeResourcesTask.dependsOn(project.tasks.findByName(mcPicTask.name)) } } + } private fun traverseResDir(file: File, imageFileList: ArrayList, cacheList: ArrayList, iBigImage: IBigImage) { @@ -127,7 +133,7 @@ class ImagePlugin : Plugin { cacheList.add(file.absolutePath) } if (file.isDirectory) { - file.listFiles().forEach { + file.listFiles()?.forEach { if (it.isDirectory) { traverseResDir(it, imageFileList, cacheList, iBigImage) } else { @@ -144,7 +150,7 @@ class ImagePlugin : Plugin { return } if (((mcImageConfig.isCheckSize && ImageUtil.isBigSizeImage(file, mcImageConfig.maxSize)) - || (mcImageConfig.isCheckPixels + || (mcImageConfig.isCheckPixels && ImageUtil.isBigPixelImage(file, mcImageConfig.maxWidth, mcImageConfig.maxHeight))) && !mcImageConfig.bigImageWhiteList.contains(file.name)) { iBigImage.onBigImage(file) @@ -152,8 +158,8 @@ class ImagePlugin : Plugin { imageFileList.add(file) } - private fun mtDispathOptimizeTask(imageFileList: ArrayList) { - if (imageFileList == null || imageFileList.size == 0 || !bigImgList.isEmpty()) { + private fun mtDispatchOptimizeTask(imageFileList: ArrayList) { + if (imageFileList.size == 0 || bigImgList.isNotEmpty()) { return } val coreNum = Runtime.getRuntime().availableProcessors() @@ -184,8 +190,8 @@ class ImagePlugin : Plugin { } private fun optimizeImage(file: File) { - var path: String = file.path - if(File(path).exists()) { + val path: String = file.path + if (File(path).exists()) { oldSize += File(path).length() } when (mcImageConfig.optimizeType) { @@ -198,13 +204,13 @@ class ImagePlugin : Plugin { } private fun countNewSize(path: String) { - if(File(path).exists()) { + if (File(path).exists()) { newSize += File(path).length() } else { //转成了webp val indexOfDot = path.lastIndexOf(".") val webpPath = path.substring(0, indexOfDot) + ".webp" - if(File(webpPath).exists()) { + if (File(webpPath).exists()) { newSize += File(webpPath).length() } else { LogUtil.log("McImage: optimizeImage have some Exception!!!") diff --git a/src/main/java/com/smallsoho/mcplugin/image/utils/CompressUtil.kt b/src/main/java/com/smallsoho/mcplugin/image/utils/CompressUtil.kt index a3a03ee..c5e60c9 100644 --- a/src/main/java/com/smallsoho/mcplugin/image/utils/CompressUtil.kt +++ b/src/main/java/com/smallsoho/mcplugin/image/utils/CompressUtil.kt @@ -10,18 +10,17 @@ class CompressUtil { if (!ImageUtil.isImage(imgFile)) { return } - val oldSize = imgFile.length() - var newSize = 0L + val newSize: Long if (ImageUtil.isJPG(imgFile)) { - var tempFilePath: String = "${imgFile.path.substring(0, imgFile.path.lastIndexOf("."))}_temp" + - "${imgFile.path.substring(imgFile.path.lastIndexOf("."))}" - Tools.cmd("guetzli", "${imgFile.path} ${tempFilePath}") - val tempFile: File = File(tempFilePath) + val tempFilePath: String = "${imgFile.path.substring(0, imgFile.path.lastIndexOf("."))}_temp" + + imgFile.path.substring(imgFile.path.lastIndexOf(".")) + Tools.cmd("guetzli", "${imgFile.path} $tempFilePath") + val tempFile = File(tempFilePath) newSize = tempFile.length() - println("newSize = ${newSize}") + LogUtil.log("newSize = $newSize") if (newSize < oldSize) { - var imgFileName: String = imgFile.path + val imgFileName: String = imgFile.path if (imgFile.exists()) { imgFile.delete() } diff --git a/src/main/java/com/smallsoho/mcplugin/image/utils/HookUtil.kt b/src/main/java/com/smallsoho/mcplugin/image/utils/HookUtil.kt deleted file mode 100644 index 586b3bf..0000000 --- a/src/main/java/com/smallsoho/mcplugin/image/utils/HookUtil.kt +++ /dev/null @@ -1,31 +0,0 @@ -package com.smallsoho.mcplugin.image.utils - -import com.android.build.gradle.tasks.MergeResources -import java.io.File - -fun MergeResources.computeResourceSetList0(): List? { - - val computeResourceSetListMethod = MergeResources::class.java.declaredMethods - .firstOrNull { it.name == "computeResourceSetList" && it.parameterCount == 0 } - ?: return null - - val oldIsAccessible = computeResourceSetListMethod.isAccessible - try { - computeResourceSetListMethod.isAccessible = true - - val resourceSets = computeResourceSetListMethod.invoke(this) as? Iterable<*> - - return resourceSets - ?.mapNotNull { resourceSet -> - val getSourceFiles = resourceSet?.javaClass?.methods?.find { it.name == "getSourceFiles" && it.parameterCount == 0 } - val files = getSourceFiles?.invoke(resourceSet) - @Suppress("UNCHECKED_CAST") - files as? Iterable - } - ?.flatten() - - } finally { - computeResourceSetListMethod.isAccessible = oldIsAccessible - } - -} \ No newline at end of file diff --git a/src/main/java/com/smallsoho/mcplugin/image/utils/ImageUtil.kt b/src/main/java/com/smallsoho/mcplugin/image/utils/ImageUtil.kt index 66eba80..33a700b 100644 --- a/src/main/java/com/smallsoho/mcplugin/image/utils/ImageUtil.kt +++ b/src/main/java/com/smallsoho/mcplugin/image/utils/ImageUtil.kt @@ -1,12 +1,9 @@ package com.smallsoho.mcplugin.image.utils import com.smallsoho.mcplugin.image.Const -import com.sun.org.apache.xpath.internal.operations.Bool - -import javax.imageio.ImageIO -import java.awt.image.BufferedImage import java.io.File import java.io.FileInputStream +import javax.imageio.ImageIO class ImageUtil { diff --git a/src/main/java/com/smallsoho/mcplugin/image/utils/LogUtil.kt b/src/main/java/com/smallsoho/mcplugin/image/utils/LogUtil.kt index 830c726..3acb77c 100644 --- a/src/main/java/com/smallsoho/mcplugin/image/utils/LogUtil.kt +++ b/src/main/java/com/smallsoho/mcplugin/image/utils/LogUtil.kt @@ -1,8 +1,11 @@ package com.smallsoho.mcplugin.image.utils +import java.lang.Exception + class LogUtil { companion object { + fun log(stage: String, filePath: String, oldInfo: String, newInfo: String) { println("[$stage][$filePath][oldInfo: $oldInfo][newInfo: $newInfo]") } @@ -14,6 +17,11 @@ class LogUtil { fun log(str: String) { println(str) } + + fun log(exception: Exception) { + println(exception) + } + } } diff --git a/src/main/java/com/smallsoho/mcplugin/image/utils/MergedUtil.kt b/src/main/java/com/smallsoho/mcplugin/image/utils/MergedUtil.kt deleted file mode 100644 index b77577d..0000000 --- a/src/main/java/com/smallsoho/mcplugin/image/utils/MergedUtil.kt +++ /dev/null @@ -1,32 +0,0 @@ -package com.smallsoho.mcplugin.image.utils - -import com.android.build.gradle.tasks.MergeResources -import java.io.File - -class MergedUtil { - companion object { - fun resourcesFileList(): List? { - val computeResourceSetListMethod = MergeResources::class.java.declaredMethods - .firstOrNull { it.name == "computeResourceSetList" && it.parameterCount == 0 } ?: return null - - val oldIsAccessible = computeResourceSetListMethod.isAccessible - try { - computeResourceSetListMethod.isAccessible = true - - val resourceSets = computeResourceSetListMethod.invoke(this) as? Iterable<*> - - return resourceSets - ?.mapNotNull { resourceSet -> - val getSourceFiles = resourceSet?.javaClass?.methods?.find { it.name == "getSourceFiles" && it.parameterCount == 0 } - val files = getSourceFiles?.invoke(resourceSet) - @Suppress("UNCHECKED_CAST") - files as? Iterable - } - ?.flatten() - - } finally { - computeResourceSetListMethod.isAccessible = oldIsAccessible - } - } - } -} \ No newline at end of file diff --git a/src/main/java/com/smallsoho/mcplugin/image/utils/Tools.kt b/src/main/java/com/smallsoho/mcplugin/image/utils/Tools.kt index 9dbf94c..91e5d00 100644 --- a/src/main/java/com/smallsoho/mcplugin/image/utils/Tools.kt +++ b/src/main/java/com/smallsoho/mcplugin/image/utils/Tools.kt @@ -71,7 +71,7 @@ class Tools { return try { bufferReader.readLine() } catch (e: Exception) { - println(e) + LogUtil.log(e) null } } diff --git a/src/main/java/com/smallsoho/mcplugin/image/webp/WebpUtils.kt b/src/main/java/com/smallsoho/mcplugin/image/webp/WebpUtils.kt index 7d189f1..4c72462 100644 --- a/src/main/java/com/smallsoho/mcplugin/image/webp/WebpUtils.kt +++ b/src/main/java/com/smallsoho/mcplugin/image/webp/WebpUtils.kt @@ -10,7 +10,6 @@ class WebpUtils { companion object { private const val VERSION_SUPPORT_WEBP = 14 //api>=14设设备支持webp - private const val VERSION_SUPPORT_TRANSPARENT_WEBP = 18 //api>=18支持透明通道 private const val TAG = "Webp" private fun isPNGConvertSupported(project: Project): Boolean {