Initial commit
This commit is contained in:
9
android/.gitignore
vendored
Normal file
9
android/.gitignore
vendored
Normal file
@@ -0,0 +1,9 @@
|
||||
*.iml
|
||||
.gradle
|
||||
/local.properties
|
||||
/.idea/workspace.xml
|
||||
/.idea/libraries
|
||||
.DS_Store
|
||||
/build
|
||||
/captures
|
||||
.cxx
|
||||
51
android/build.gradle
Normal file
51
android/build.gradle
Normal file
@@ -0,0 +1,51 @@
|
||||
group 'org.moxxy.moxxy_native'
|
||||
version '1.0-SNAPSHOT'
|
||||
|
||||
buildscript {
|
||||
ext.kotlin_version = '1.8.21'
|
||||
repositories {
|
||||
google()
|
||||
mavenCentral()
|
||||
}
|
||||
|
||||
dependencies {
|
||||
classpath 'com.android.tools.build:gradle:7.1.2'
|
||||
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
|
||||
}
|
||||
}
|
||||
|
||||
allprojects {
|
||||
repositories {
|
||||
google()
|
||||
mavenCentral()
|
||||
}
|
||||
}
|
||||
|
||||
apply plugin: 'com.android.library'
|
||||
apply plugin: 'kotlin-android'
|
||||
|
||||
android {
|
||||
compileSdkVersion 33
|
||||
|
||||
compileOptions {
|
||||
sourceCompatibility JavaVersion.VERSION_1_8
|
||||
targetCompatibility JavaVersion.VERSION_1_8
|
||||
}
|
||||
|
||||
kotlinOptions {
|
||||
jvmTarget = '1.8'
|
||||
}
|
||||
|
||||
sourceSets {
|
||||
main.java.srcDirs += 'src/main/kotlin'
|
||||
}
|
||||
|
||||
defaultConfig {
|
||||
minSdkVersion 26
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
|
||||
implementation "androidx.activity:activity-ktx:1.7.2"
|
||||
}
|
||||
BIN
android/gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
BIN
android/gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
Binary file not shown.
5
android/gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
5
android/gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
@@ -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
|
||||
240
android/gradlew
vendored
Executable file
240
android/gradlew
vendored
Executable file
@@ -0,0 +1,240 @@
|
||||
#!/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 \
|
||||
"$@"
|
||||
|
||||
# Stop when "xargs" is not available.
|
||||
if ! command -v xargs >/dev/null 2>&1
|
||||
then
|
||||
die "xargs is not available"
|
||||
fi
|
||||
|
||||
# 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" "$@"
|
||||
91
android/gradlew.bat
vendored
Normal file
91
android/gradlew.bat
vendored
Normal file
@@ -0,0 +1,91 @@
|
||||
@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% equ 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% equ 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!
|
||||
set EXIT_CODE=%ERRORLEVEL%
|
||||
if %EXIT_CODE% equ 0 set EXIT_CODE=1
|
||||
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
|
||||
exit /b %EXIT_CODE%
|
||||
|
||||
:mainEnd
|
||||
if "%OS%"=="Windows_NT" endlocal
|
||||
|
||||
:omega
|
||||
1
android/settings.gradle
Normal file
1
android/settings.gradle
Normal file
@@ -0,0 +1 @@
|
||||
rootProject.name = 'moxxy_native'
|
||||
3
android/src/main/AndroidManifest.xml
Normal file
3
android/src/main/AndroidManifest.xml
Normal file
@@ -0,0 +1,3 @@
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
package="org.moxxy.moxxy_native">
|
||||
</manifest>
|
||||
@@ -0,0 +1,5 @@
|
||||
package org.moxxy.moxxy_native
|
||||
|
||||
object AsyncRequestTracker {
|
||||
val requestTracker: MutableMap<Int, (Result<Any>) -> Unit> = mutableMapOf()
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package org.moxxy.moxxy_native
|
||||
|
||||
const val TAG = "moxxy_native"
|
||||
|
||||
// Request codes
|
||||
const val PICK_FILE_REQUEST = 42
|
||||
const val PICK_FILES_REQUEST = 43
|
||||
const val PICK_FILE_WITH_DATA_REQUEST = 44
|
||||
@@ -0,0 +1,110 @@
|
||||
package org.moxxy.moxxy_native
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.util.Log
|
||||
import androidx.activity.result.PickVisualMediaRequest
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.annotation.NonNull
|
||||
|
||||
import io.flutter.embedding.engine.plugins.FlutterPlugin
|
||||
import io.flutter.embedding.engine.plugins.activity.ActivityAware
|
||||
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
|
||||
import org.moxxy.moxxy_native.generated.FilePickerType
|
||||
import org.moxxy.moxxy_native.generated.MoxxyPickerApi
|
||||
import org.moxxy.moxxy_native.picker.PickerResultListener
|
||||
|
||||
class MoxxyNativePlugin: FlutterPlugin, ActivityAware, MoxxyPickerApi {
|
||||
private var context: Context? = null
|
||||
private var activity: Activity? = null
|
||||
private lateinit var pickerListener: PickerResultListener
|
||||
|
||||
override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
|
||||
context = flutterPluginBinding.applicationContext
|
||||
MoxxyPickerApi.setUp(flutterPluginBinding.binaryMessenger, this)
|
||||
pickerListener = PickerResultListener(context!!)
|
||||
Log.d(TAG, "Attached to engine")
|
||||
}
|
||||
|
||||
override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
|
||||
Log.d(TAG, "Detached from engine")
|
||||
}
|
||||
|
||||
override fun onAttachedToActivity(binding: ActivityPluginBinding) {
|
||||
activity = binding.activity
|
||||
binding.addActivityResultListener(pickerListener)
|
||||
Log.d(TAG, "Attached to activity")
|
||||
}
|
||||
|
||||
override fun onDetachedFromActivityForConfigChanges() {
|
||||
activity = null
|
||||
Log.d(TAG, "Detached from activity")
|
||||
}
|
||||
|
||||
override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
|
||||
activity = binding.activity
|
||||
}
|
||||
|
||||
override fun onDetachedFromActivity() {
|
||||
activity = null
|
||||
Log.d(TAG, "Detached from activity")
|
||||
}
|
||||
|
||||
override fun pickFiles(
|
||||
type: FilePickerType,
|
||||
multiple: Boolean,
|
||||
callback: (Result<List<String>>) -> Unit
|
||||
) {
|
||||
val requestCode = if (multiple) PICK_FILES_REQUEST else PICK_FILE_REQUEST
|
||||
AsyncRequestTracker.requestTracker[requestCode] = callback as (Result<Any>) -> Unit
|
||||
if (type == FilePickerType.GENERIC) {
|
||||
val pickIntent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
|
||||
addCategory(Intent.CATEGORY_OPENABLE)
|
||||
this.type = "*/*"
|
||||
|
||||
// Allow/disallow picking multiple files
|
||||
putExtra(Intent.EXTRA_ALLOW_MULTIPLE, multiple)
|
||||
}
|
||||
activity?.startActivityForResult(pickIntent, requestCode)
|
||||
return
|
||||
}
|
||||
|
||||
val contract = when (multiple) {
|
||||
false -> ActivityResultContracts.PickVisualMedia()
|
||||
true -> ActivityResultContracts.PickMultipleVisualMedia()
|
||||
}
|
||||
val pickType = when (type) {
|
||||
// We keep FilePickerType.GENERIC here, even though we know that @type will never be
|
||||
// GENERIC to make Kotlin happy.
|
||||
FilePickerType.GENERIC, FilePickerType.IMAGE -> ActivityResultContracts.PickVisualMedia.ImageOnly
|
||||
FilePickerType.VIDEO -> ActivityResultContracts.PickVisualMedia.VideoOnly
|
||||
FilePickerType.IMAGEANDVIDEO -> ActivityResultContracts.PickVisualMedia.ImageAndVideo
|
||||
}
|
||||
val pickIntent = contract.createIntent(context!!, PickVisualMediaRequest(pickType))
|
||||
activity?.startActivityForResult(pickIntent, requestCode)
|
||||
}
|
||||
|
||||
override fun pickFileWithData(type: FilePickerType, callback: (Result<ByteArray?>) -> Unit) {
|
||||
AsyncRequestTracker.requestTracker[PICK_FILE_WITH_DATA_REQUEST] = callback as (Result<Any>) -> Unit
|
||||
if (type == FilePickerType.GENERIC) {
|
||||
val pickIntent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
|
||||
addCategory(Intent.CATEGORY_OPENABLE)
|
||||
this.type = "*/*"
|
||||
}
|
||||
activity?.startActivityForResult(pickIntent, PICK_FILE_WITH_DATA_REQUEST)
|
||||
return
|
||||
}
|
||||
|
||||
val pickType = when (type) {
|
||||
// We keep FilePickerType.GENERIC here, even though we know that @type will never be
|
||||
// GENERIC to make Kotlin happy.
|
||||
FilePickerType.GENERIC, FilePickerType.IMAGE -> ActivityResultContracts.PickVisualMedia.ImageOnly
|
||||
FilePickerType.VIDEO -> ActivityResultContracts.PickVisualMedia.VideoOnly
|
||||
FilePickerType.IMAGEANDVIDEO -> ActivityResultContracts.PickVisualMedia.ImageAndVideo
|
||||
}
|
||||
val contract = ActivityResultContracts.PickVisualMedia()
|
||||
val pickIntent = contract.createIntent(context!!, PickVisualMediaRequest(pickType))
|
||||
activity?.startActivityForResult(pickIntent, PICK_FILE_WITH_DATA_REQUEST)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
// Autogenerated from Pigeon (v11.0.1), do not edit directly.
|
||||
// See also: https://pub.dev/packages/pigeon
|
||||
|
||||
package org.moxxy.moxxy_native.generated
|
||||
|
||||
import android.util.Log
|
||||
import io.flutter.plugin.common.BasicMessageChannel
|
||||
import io.flutter.plugin.common.BinaryMessenger
|
||||
import io.flutter.plugin.common.MessageCodec
|
||||
import io.flutter.plugin.common.StandardMessageCodec
|
||||
import java.io.ByteArrayOutputStream
|
||||
import java.nio.ByteBuffer
|
||||
|
||||
private fun wrapResult(result: Any?): List<Any?> {
|
||||
return listOf(result)
|
||||
}
|
||||
|
||||
private fun wrapError(exception: Throwable): List<Any?> {
|
||||
if (exception is FlutterError) {
|
||||
return listOf(
|
||||
exception.code,
|
||||
exception.message,
|
||||
exception.details
|
||||
)
|
||||
} else {
|
||||
return listOf(
|
||||
exception.javaClass.simpleName,
|
||||
exception.toString(),
|
||||
"Cause: " + exception.cause + ", Stacktrace: " + Log.getStackTraceString(exception)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Error class for passing custom error details to Flutter via a thrown PlatformException.
|
||||
* @property code The error code.
|
||||
* @property message The error message.
|
||||
* @property details The error details. Must be a datatype supported by the api codec.
|
||||
*/
|
||||
class FlutterError (
|
||||
val code: String,
|
||||
override val message: String? = null,
|
||||
val details: Any? = null
|
||||
) : Throwable()
|
||||
|
||||
enum class FilePickerType(val raw: Int) {
|
||||
/** Pick only image(s) */
|
||||
IMAGE(0),
|
||||
/** Pick only video(s) */
|
||||
VIDEO(1),
|
||||
/** Pick image(s) and video(s) */
|
||||
IMAGEANDVIDEO(2),
|
||||
/** Pick any kind of file(s) */
|
||||
GENERIC(3);
|
||||
|
||||
companion object {
|
||||
fun ofRaw(raw: Int): FilePickerType? {
|
||||
return values().firstOrNull { it.raw == raw }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Generated interface from Pigeon that represents a handler of messages from Flutter. */
|
||||
interface MoxxyPickerApi {
|
||||
/**
|
||||
* Open either the photo picker or the generic file picker to get a list of paths that were
|
||||
* selected and are accessable. If the list is empty, then the user dismissed the picker without
|
||||
* selecting anything.
|
||||
*
|
||||
* [type] specifies what kind of file(s) should be picked.
|
||||
*
|
||||
* [multiple] controls whether multiple files can be picked (true) or just a single file
|
||||
* is enough (false).
|
||||
*/
|
||||
fun pickFiles(type: FilePickerType, multiple: Boolean, callback: (Result<List<String>>) -> Unit)
|
||||
/** Like [pickFiles] but sets multiple to false and returns the raw binary data from the file. */
|
||||
fun pickFileWithData(type: FilePickerType, callback: (Result<ByteArray?>) -> Unit)
|
||||
|
||||
companion object {
|
||||
/** The codec used by MoxxyPickerApi. */
|
||||
val codec: MessageCodec<Any?> by lazy {
|
||||
StandardMessageCodec()
|
||||
}
|
||||
/** Sets up an instance of `MoxxyPickerApi` to handle messages through the `binaryMessenger`. */
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
fun setUp(binaryMessenger: BinaryMessenger, api: MoxxyPickerApi?) {
|
||||
run {
|
||||
val channel = BasicMessageChannel<Any?>(binaryMessenger, "dev.flutter.pigeon.moxxy_native.MoxxyPickerApi.pickFiles", codec)
|
||||
if (api != null) {
|
||||
channel.setMessageHandler { message, reply ->
|
||||
val args = message as List<Any?>
|
||||
val typeArg = FilePickerType.ofRaw(args[0] as Int)!!
|
||||
val multipleArg = args[1] as Boolean
|
||||
api.pickFiles(typeArg, multipleArg) { result: Result<List<String>> ->
|
||||
val error = result.exceptionOrNull()
|
||||
if (error != null) {
|
||||
reply.reply(wrapError(error))
|
||||
} else {
|
||||
val data = result.getOrNull()
|
||||
reply.reply(wrapResult(data))
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
channel.setMessageHandler(null)
|
||||
}
|
||||
}
|
||||
run {
|
||||
val channel = BasicMessageChannel<Any?>(binaryMessenger, "dev.flutter.pigeon.moxxy_native.MoxxyPickerApi.pickFileWithData", codec)
|
||||
if (api != null) {
|
||||
channel.setMessageHandler { message, reply ->
|
||||
val args = message as List<Any?>
|
||||
val typeArg = FilePickerType.ofRaw(args[0] as Int)!!
|
||||
api.pickFileWithData(typeArg) { result: Result<ByteArray?> ->
|
||||
val error = result.exceptionOrNull()
|
||||
if (error != null) {
|
||||
reply.reply(wrapError(error))
|
||||
} else {
|
||||
val data = result.getOrNull()
|
||||
reply.reply(wrapResult(data))
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
channel.setMessageHandler(null)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
package org.moxxy.moxxy_native.picker
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.app.Activity
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.provider.OpenableColumns
|
||||
import android.util.Log
|
||||
import io.flutter.plugin.common.PluginRegistry.ActivityResultListener
|
||||
import org.moxxy.moxxy_native.AsyncRequestTracker
|
||||
import org.moxxy.moxxy_native.PICK_FILES_REQUEST
|
||||
import org.moxxy.moxxy_native.PICK_FILE_REQUEST
|
||||
import org.moxxy.moxxy_native.PICK_FILE_WITH_DATA_REQUEST
|
||||
import org.moxxy.moxxy_native.TAG
|
||||
import java.io.File
|
||||
import java.io.FileOutputStream
|
||||
import java.io.IOException
|
||||
import java.io.InputStream
|
||||
import java.io.OutputStream
|
||||
|
||||
class PickerResultListener(private val context: Context) : ActivityResultListener {
|
||||
/*
|
||||
* Attempt to deduce the filename for the URI @uri.
|
||||
* Based on https://stackoverflow.com/a/25005243
|
||||
*/
|
||||
@SuppressLint("Range")
|
||||
private fun queryFileName(context: Context, uri: Uri): String {
|
||||
var result: String? = null
|
||||
if (uri.scheme == "content") {
|
||||
val cursor = context.contentResolver.query(uri, null, null, null, null)
|
||||
cursor.use { cursor ->
|
||||
if (cursor != null && cursor.moveToFirst()) {
|
||||
result = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result ?: uri.path!!.split("/").last()
|
||||
}
|
||||
|
||||
/*
|
||||
* Copy from the input stream @input to the output stream @output.
|
||||
* On Android >= 13 uses Android's own copy method. Below, reads the stream in 4096 byte
|
||||
* segments and write them back.
|
||||
*
|
||||
* Based on https://github.com/flutter/packages/blob/b8b84b2304f00a3f93ce585cc7a30e1235bde7a0/packages/image_picker/image_picker_android/android/src/main/java/io/flutter/plugins/imagepicker/FileUtils.java#L130
|
||||
*/
|
||||
private fun copy(input: InputStream, output: OutputStream) {
|
||||
if (Build.VERSION.SDK_INT >= 33) {
|
||||
android.os.FileUtils.copy(input, output)
|
||||
} else {
|
||||
val buffer = ByteArray(4096)
|
||||
while (input.read(buffer).also {} != -1) {
|
||||
output.write(buffer)
|
||||
}
|
||||
output.flush()
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Copy the content of the file @uri is pointing to into the cache directory for access from
|
||||
* within Flutter.
|
||||
*
|
||||
* Based on https://github.com/flutter/packages/blob/b8b84b2304f00a3f93ce585cc7a30e1235bde7a0/packages/image_picker/image_picker_android/android/src/main/java/io/flutter/plugins/imagepicker/FileUtils.java#L54C64-L54C64
|
||||
*/
|
||||
private fun resolveContentUri(context: Context, uri: Uri): String? {
|
||||
try {
|
||||
val inputStream = context.contentResolver.openInputStream(uri)
|
||||
val cacheDir = File(context.cacheDir, "cache").apply {
|
||||
mkdir()
|
||||
deleteOnExit()
|
||||
}
|
||||
val cacheFile = File(cacheDir, queryFileName(context, uri))
|
||||
val outputStream = FileOutputStream(cacheFile)
|
||||
copy(inputStream!!, outputStream)
|
||||
|
||||
return cacheFile.path
|
||||
} catch (ex: IOException) {
|
||||
Log.d(TAG, "IO exception while resolving URI $uri: ${ex.message}")
|
||||
return null
|
||||
} catch (ex: SecurityException) {
|
||||
Log.d(TAG, "Security exception while resolving URI $uri: ${ex.message}")
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
private fun handlePickWithData(context: Context, resultCode: Int, data: Intent?, result: (Result<ByteArray?>) -> Unit) {
|
||||
// Handle not picking anything
|
||||
if (resultCode != Activity.RESULT_OK) {
|
||||
result(Result.success(null))
|
||||
return
|
||||
}
|
||||
|
||||
val returnBuffer = mutableListOf<Byte>()
|
||||
val readBuffer = ByteArray(4096)
|
||||
try {
|
||||
val inputStream = context.contentResolver.openInputStream(data!!.data!!)!!
|
||||
while (inputStream.read(readBuffer).also {} != -1) {
|
||||
returnBuffer.addAll(readBuffer.asList())
|
||||
}
|
||||
inputStream.close()
|
||||
|
||||
result(
|
||||
Result.success(returnBuffer.toByteArray()),
|
||||
)
|
||||
} catch (ex: IOException) {
|
||||
Log.w(TAG, "IO exception while reading URI ${data!!.data}: ${ex.message}")
|
||||
result(Result.success(null))
|
||||
} catch (ex: SecurityException) {
|
||||
Log.w(TAG, "Security exception while reading URI ${data!!.data}: ${ex.message}")
|
||||
result(Result.success(null))
|
||||
}
|
||||
}
|
||||
|
||||
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?): Boolean {
|
||||
Log.d(TAG, "Got result for $requestCode")
|
||||
if (requestCode != PICK_FILE_REQUEST && requestCode != PICK_FILES_REQUEST && requestCode != PICK_FILE_WITH_DATA_REQUEST) {
|
||||
Log.d(TAG, "Unknown result code")
|
||||
return false
|
||||
}
|
||||
|
||||
// Check if we have a request pending
|
||||
val result = AsyncRequestTracker.requestTracker.remove(requestCode)
|
||||
if (result == null) {
|
||||
Log.w(TAG, "Received result for $requestCode but we have no tracked request")
|
||||
return true
|
||||
}
|
||||
|
||||
if (requestCode == PICK_FILE_WITH_DATA_REQUEST) {
|
||||
handlePickWithData(context, resultCode, data, result as (Result<ByteArray?>) -> Unit)
|
||||
return true
|
||||
}
|
||||
|
||||
// No file(s) picked
|
||||
if (resultCode != Activity.RESULT_OK) {
|
||||
Log.d(TAG, "resultCode $resultCode != ${Activity.RESULT_OK}")
|
||||
result!!(Result.success(listOf<String>()))
|
||||
return true
|
||||
}
|
||||
|
||||
val pickedMultiple = requestCode == PICK_FILES_REQUEST
|
||||
val pickedFiles = mutableListOf<String>()
|
||||
if (pickedMultiple) {
|
||||
if (data!!.clipData != null) {
|
||||
Log.w(TAG, "Files shared: ${data!!.clipData!!.itemCount}")
|
||||
for (i in 0 until data!!.clipData!!.itemCount) {
|
||||
val path = resolveContentUri(context, data!!.clipData!!.getItemAt(i).uri)
|
||||
if (path != null) {
|
||||
pickedFiles.add(path)
|
||||
}
|
||||
}
|
||||
} else if (data!!.data != null) {
|
||||
// Handle the generic file picker with multiple=true returning only one file
|
||||
val path = resolveContentUri(context, data!!.data!!)
|
||||
if (path != null) {
|
||||
pickedFiles.add(path)
|
||||
}
|
||||
} else {
|
||||
Log.w(TAG, "Multi-file intent has no clipData and data")
|
||||
}
|
||||
} else {
|
||||
if (data!!.data != null) {
|
||||
val path = resolveContentUri(context, data!!.data!!)
|
||||
if (path != null) {
|
||||
pickedFiles.add(path)
|
||||
}
|
||||
} else {
|
||||
Log.w(TAG, "Single-file intent has no data")
|
||||
}
|
||||
}
|
||||
|
||||
result!!(Result.success(pickedFiles))
|
||||
return true
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user