@ -0,0 +1,4 @@
|
||||
/target
|
||||
/Cargo.lock
|
||||
|
||||
!dist-js
|
@ -0,0 +1,18 @@
|
||||
[package]
|
||||
name = "tauri-plugin-camera"
|
||||
version = "0.0.0"
|
||||
description = "Ask the user take a photo with the camera or select an image from the gallery."
|
||||
authors.workspace = true
|
||||
license.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
exclude.workspace = true
|
||||
|
||||
[dependencies]
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
tauri.workspace = true
|
||||
thiserror.workspace = true
|
||||
|
||||
[build-dependencies]
|
||||
tauri-build.workspace = true
|
@ -0,0 +1,20 @@
|
||||
SPDXVersion: SPDX-2.1
|
||||
DataLicense: CC0-1.0
|
||||
PackageName: tauri
|
||||
DataFormat: SPDXRef-1
|
||||
PackageSupplier: Organization: The Tauri Programme in the Commons Conservancy
|
||||
PackageHomePage: https://tauri.app
|
||||
PackageLicenseDeclared: Apache-2.0
|
||||
PackageLicenseDeclared: MIT
|
||||
PackageCopyrightText: 2019-2022, The Tauri Programme in the Commons Conservancy
|
||||
PackageSummary: <text>Tauri is a rust project that enables developers to make secure
|
||||
and small desktop applications using a web frontend.
|
||||
</text>
|
||||
PackageComment: <text>The package includes the following libraries; see
|
||||
Relationship information.
|
||||
</text>
|
||||
Created: 2019-05-20T09:00:00Z
|
||||
PackageDownloadLocation: git://github.com/tauri-apps/tauri
|
||||
PackageDownloadLocation: git+https://github.com/tauri-apps/tauri.git
|
||||
PackageDownloadLocation: git+ssh://github.com/tauri-apps/tauri.git
|
||||
Creator: Person: Daniel Thompson-Yvetot
|
@ -0,0 +1,177 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2017 - Present Tauri Apps Contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
@ -0,0 +1,84 @@
|
||||
# Camera Plugin
|
||||
|
||||
Prompt the user to take a photo using the camera or pick an image from the gallery. Mobile only.
|
||||
|
||||
## Install
|
||||
|
||||
There are three general methods of installation that we can recommend.
|
||||
|
||||
1. Use crates.io and npm (easiest, and requires you to trust that our publishing pipeline worked)
|
||||
2. Pull sources directly from Github using git tags / revision hashes (most secure)
|
||||
3. Git submodule install this repo in your tauri project and then use file protocol to ingest the source (most secure, but inconvenient to use)
|
||||
|
||||
Install the Core plugin by adding the following to your `Cargo.toml` file:
|
||||
|
||||
```toml
|
||||
[dependencies]
|
||||
tauri-plugin-camera = { git = "https://github.com/tauri-apps/plugins-workspace", branch = "feat/camera" }
|
||||
```
|
||||
|
||||
You can install the JavaScript Guest bindings using your preferred JavaScript package manager:
|
||||
|
||||
> Note: Since most JavaScript package managers are unable to install packages from git monorepos we provide read-only mirrors of each plugin. This makes installation option 2 more ergonomic to use.
|
||||
|
||||
```sh
|
||||
npm install 'https://gitpkg.now.sh/tauri-apps/plugins-workspace/plugins/camera?feat/camera'
|
||||
# or
|
||||
yarn add 'https://gitpkg.now.sh/tauri-apps/plugins-workspace/plugins/camera?feat/camera'
|
||||
```
|
||||
|
||||
**NOT AVAILABLE YET, WILL BE READY WHEN WE MERGE THE BRANCH:**
|
||||
```sh
|
||||
pnpm add https://github.com/tauri-apps/tauri-plugin-camera
|
||||
# or
|
||||
npm add https://github.com/tauri-apps/tauri-plugin-camera
|
||||
# or
|
||||
yarn add https://github.com/tauri-apps/tauri-plugin-camera
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
Register the core plugin with Tauri:
|
||||
|
||||
`src-tauri/src/lib.rs`
|
||||
|
||||
```rust
|
||||
#[cfg_attr(mobile, tauri::mobile_entry_point)]
|
||||
pub fn run() {
|
||||
tauri::Builder::default()
|
||||
.plugin(tauri_plugin_camera::init())
|
||||
.run(tauri::generate_context!())
|
||||
.expect("error while running tauri application");
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
Afterwards all the plugin's APIs are available through the JavaScript guest bindings:
|
||||
|
||||
```javascript
|
||||
import { getPhoto } from "tauri-plugin-camera-api";
|
||||
const image = await getPhoto();
|
||||
```
|
||||
|
||||
### Android
|
||||
|
||||
Add the following permissions on the `src-tauri/gen/android/$(APPNAME)/app/src/main/AndroidManifest.xml` file:
|
||||
|
||||
```xml
|
||||
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
|
||||
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
|
||||
```
|
||||
|
||||
### iOS
|
||||
|
||||
Configure the following properties on `src-tauri/gen/apple/$(APPNAME)_iOS/Info.plist`:
|
||||
|
||||
```xml
|
||||
<key>NSCameraUsageDescription</key>
|
||||
<string>Description for the camera usage here</string>
|
||||
<key>NSPhotoLibraryAddUsageDescription</key>
|
||||
<string>Description for the library add usage here</string>
|
||||
<key>NSPhotoLibraryUsageDescription</key>
|
||||
<string>Description for the library usage here</string>
|
||||
```
|
||||
|
@ -0,0 +1,2 @@
|
||||
/build
|
||||
/tauri-api
|
@ -0,0 +1,46 @@
|
||||
plugins {
|
||||
id("com.android.library")
|
||||
id("org.jetbrains.kotlin.android")
|
||||
}
|
||||
|
||||
android {
|
||||
namespace = "app.tauri.camera"
|
||||
compileSdk = 32
|
||||
|
||||
defaultConfig {
|
||||
minSdk = 24
|
||||
targetSdk = 32
|
||||
|
||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||
consumerProguardFiles("consumer-rules.pro")
|
||||
}
|
||||
|
||||
buildTypes {
|
||||
release {
|
||||
isMinifyEnabled = false
|
||||
proguardFiles(
|
||||
getDefaultProguardFile("proguard-android-optimize.txt"),
|
||||
"proguard-rules.pro"
|
||||
)
|
||||
}
|
||||
}
|
||||
compileOptions {
|
||||
sourceCompatibility = JavaVersion.VERSION_1_8
|
||||
targetCompatibility = JavaVersion.VERSION_1_8
|
||||
}
|
||||
kotlinOptions {
|
||||
jvmTarget = "1.8"
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
|
||||
implementation("androidx.core:core-ktx:1.9.0")
|
||||
implementation("androidx.appcompat:appcompat:1.6.0")
|
||||
implementation("com.google.android.material:material:1.7.0")
|
||||
testImplementation("junit:junit:4.13.2")
|
||||
androidTestImplementation("androidx.test.ext:junit:1.1.5")
|
||||
androidTestImplementation("androidx.test.espresso:espresso-core:3.5.1")
|
||||
implementation("androidx.exifinterface:exifinterface:1.3.3")
|
||||
implementation(project(":tauri-android"))
|
||||
}
|
@ -0,0 +1,21 @@
|
||||
# Add project specific ProGuard rules here.
|
||||
# You can control the set of applied configuration files using the
|
||||
# proguardFiles setting in build.gradle.
|
||||
#
|
||||
# For more details, see
|
||||
# http://developer.android.com/guide/developing/tools/proguard.html
|
||||
|
||||
# If your project uses WebView with JS, uncomment the following
|
||||
# and specify the fully qualified class name to the JavaScript interface
|
||||
# class:
|
||||
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
|
||||
# public *;
|
||||
#}
|
||||
|
||||
# Uncomment this to preserve the line number information for
|
||||
# debugging stack traces.
|
||||
#-keepattributes SourceFile,LineNumberTable
|
||||
|
||||
# If you keep the line number information, uncomment this to
|
||||
# hide the original source file name.
|
||||
#-renamesourcefileattribute SourceFile
|
@ -0,0 +1,2 @@
|
||||
include ':tauri-android'
|
||||
project(':tauri-android').projectDir = new File('./tauri-api')
|
@ -0,0 +1,24 @@
|
||||
package app.tauri.camera
|
||||
|
||||
import androidx.test.platform.app.InstrumentationRegistry
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
|
||||
import org.junit.Assert.*
|
||||
|
||||
/**
|
||||
* Instrumented test, which will execute on an Android device.
|
||||
*
|
||||
* See [testing documentation](http://d.android.com/tools/testing).
|
||||
*/
|
||||
@RunWith(AndroidJUnit4::class)
|
||||
class ExampleInstrumentedTest {
|
||||
@Test
|
||||
fun useAppContext() {
|
||||
// Context of the app under test.
|
||||
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
|
||||
assertEquals("app.tauri.camera", appContext.packageName)
|
||||
}
|
||||
}
|
@ -0,0 +1,4 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
|
||||
</manifest>
|
@ -0,0 +1,102 @@
|
||||
package app.tauri.camera
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.app.Dialog
|
||||
import android.content.DialogInterface
|
||||
import android.graphics.Color
|
||||
import android.view.View
|
||||
import android.widget.LinearLayout
|
||||
import android.widget.TextView
|
||||
import androidx.coordinatorlayout.widget.CoordinatorLayout
|
||||
import com.google.android.material.bottomsheet.BottomSheetBehavior
|
||||
import com.google.android.material.bottomsheet.BottomSheetBehavior.BottomSheetCallback
|
||||
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
|
||||
|
||||
class CameraBottomSheetDialogFragment : BottomSheetDialogFragment() {
|
||||
fun interface BottomSheetOnSelectedListener {
|
||||
fun onSelected(index: Int)
|
||||
}
|
||||
|
||||
fun interface BottomSheetOnCanceledListener {
|
||||
fun onCanceled()
|
||||
}
|
||||
|
||||
private var selectedListener: BottomSheetOnSelectedListener? = null
|
||||
private var canceledListener: BottomSheetOnCanceledListener? = null
|
||||
private var options: List<String>? = null
|
||||
private var title: String? = null
|
||||
fun setTitle(title: String?) {
|
||||
this.title = title
|
||||
}
|
||||
|
||||
fun setOptions(
|
||||
options: List<String>?,
|
||||
selectedListener: BottomSheetOnSelectedListener,
|
||||
canceledListener: BottomSheetOnCanceledListener
|
||||
) {
|
||||
this.options = options
|
||||
this.selectedListener = selectedListener
|
||||
this.canceledListener = canceledListener
|
||||
}
|
||||
|
||||
override fun onCancel(dialog: DialogInterface) {
|
||||
super.onCancel(dialog)
|
||||
if (canceledListener != null) {
|
||||
canceledListener!!.onCanceled()
|
||||
}
|
||||
}
|
||||
|
||||
private val mBottomSheetBehaviorCallback: BottomSheetCallback = object : BottomSheetCallback() {
|
||||
override fun onStateChanged(bottomSheet: View, newState: Int) {
|
||||
if (newState == BottomSheetBehavior.STATE_HIDDEN) {
|
||||
dismiss()
|
||||
}
|
||||
}
|
||||
|
||||
override fun onSlide(bottomSheet: View, slideOffset: Float) {}
|
||||
}
|
||||
|
||||
@SuppressLint("RestrictedApi")
|
||||
override fun setupDialog(dialog: Dialog, style: Int) {
|
||||
super.setupDialog(dialog, style)
|
||||
if (options == null || options!!.size == 0) {
|
||||
return
|
||||
}
|
||||
val scale = resources.displayMetrics.density
|
||||
val layoutPaddingDp16 = 16.0f
|
||||
val layoutPaddingDp12 = 12.0f
|
||||
val layoutPaddingDp8 = 8.0f
|
||||
val layoutPaddingPx16 = (layoutPaddingDp16 * scale + 0.5f).toInt()
|
||||
val layoutPaddingPx12 = (layoutPaddingDp12 * scale + 0.5f).toInt()
|
||||
val layoutPaddingPx8 = (layoutPaddingDp8 * scale + 0.5f).toInt()
|
||||
val parentLayout = CoordinatorLayout(requireContext())
|
||||
val layout = LinearLayout(context)
|
||||
layout.orientation = LinearLayout.VERTICAL
|
||||
layout.setPadding(layoutPaddingPx16, layoutPaddingPx16, layoutPaddingPx16, layoutPaddingPx16)
|
||||
val ttv = TextView(context)
|
||||
ttv.setTextColor(Color.parseColor("#757575"))
|
||||
ttv.setPadding(layoutPaddingPx8, layoutPaddingPx8, layoutPaddingPx8, layoutPaddingPx8)
|
||||
ttv.text = title
|
||||
layout.addView(ttv)
|
||||
for (i in options!!.indices) {
|
||||
val tv = TextView(context)
|
||||
tv.setTextColor(Color.parseColor("#000000"))
|
||||
tv.setPadding(layoutPaddingPx12, layoutPaddingPx12, layoutPaddingPx12, layoutPaddingPx12)
|
||||
tv.text = options!![i]
|
||||
tv.setOnClickListener {
|
||||
if (selectedListener != null) {
|
||||
selectedListener!!.onSelected(i)
|
||||
}
|
||||
dismiss()
|
||||
}
|
||||
layout.addView(tv)
|
||||
}
|
||||
parentLayout.addView(layout.rootView)
|
||||
dialog.setContentView(parentLayout.rootView)
|
||||
val params = (parentLayout.parent as View).layoutParams as CoordinatorLayout.LayoutParams
|
||||
val behavior = params.behavior
|
||||
if (behavior != null && behavior is BottomSheetBehavior<*>) {
|
||||
behavior.addBottomSheetCallback(mBottomSheetBehaviorCallback)
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,827 @@
|
||||
package app.tauri.camera
|
||||
|
||||
import android.Manifest
|
||||
import android.app.Activity
|
||||
import android.content.*
|
||||
import android.content.pm.PackageManager
|
||||
import android.content.pm.ResolveInfo
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.BitmapFactory
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.os.Environment
|
||||
import android.os.Parcelable
|
||||
import android.provider.MediaStore
|
||||
import android.util.Base64
|
||||
import androidx.activity.result.ActivityResult
|
||||
import androidx.appcompat.app.AppCompatActivity
|
||||
import androidx.core.content.FileProvider
|
||||
import androidx.exifinterface.media.ExifInterface.*
|
||||
import app.tauri.*
|
||||
import app.tauri.annotation.*
|
||||
import app.tauri.plugin.*
|
||||
import org.json.JSONException
|
||||
import java.io.*
|
||||
import java.util.*
|
||||
import java.util.concurrent.Executor
|
||||
import java.util.concurrent.Executors
|
||||
|
||||
enum class CameraSource(val source: String) {
|
||||
PROMPT("PROMPT"), CAMERA("CAMERA"), PHOTOS("PHOTOS");
|
||||
}
|
||||
|
||||
enum class CameraResultType(val type: String) {
|
||||
BASE64("base64"), URI("uri"), DATAURL("dataUrl");
|
||||
}
|
||||
|
||||
class CameraSettings {
|
||||
var resultType: CameraResultType = CameraResultType.BASE64
|
||||
var quality = DEFAULT_QUALITY
|
||||
var isShouldResize = false
|
||||
var isShouldCorrectOrientation = DEFAULT_CORRECT_ORIENTATION
|
||||
var isSaveToGallery = DEFAULT_SAVE_IMAGE_TO_GALLERY
|
||||
var isAllowEditing = false
|
||||
var width = 0
|
||||
var height = 0
|
||||
var source: CameraSource = CameraSource.PROMPT
|
||||
|
||||
companion object {
|
||||
const val DEFAULT_QUALITY = 90
|
||||
const val DEFAULT_SAVE_IMAGE_TO_GALLERY = false
|
||||
const val DEFAULT_CORRECT_ORIENTATION = true
|
||||
}
|
||||
}
|
||||
|
||||
@TauriPlugin(
|
||||
permissions = [
|
||||
Permission(strings = [Manifest.permission.CAMERA], alias = "camera"),
|
||||
Permission(
|
||||
strings = [Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE],
|
||||
alias = "photos"
|
||||
)]
|
||||
)
|
||||
class CameraPlugin(private val activity: Activity): Plugin(activity) {
|
||||
// Permission alias constants
|
||||
val CAMERA = "camera"
|
||||
val PHOTOS = "photos"
|
||||
|
||||
// Message constants
|
||||
private val INVALID_RESULT_TYPE_ERROR = "Invalid resultType option"
|
||||
private val PERMISSION_DENIED_ERROR_CAMERA = "User denied access to camera"
|
||||
private val PERMISSION_DENIED_ERROR_PHOTOS = "User denied access to photos"
|
||||
private val NO_CAMERA_ERROR = "Device doesn't have a camera available"
|
||||
private val NO_CAMERA_ACTIVITY_ERROR = "Unable to resolve camera activity"
|
||||
private val NO_PHOTO_ACTIVITY_ERROR = "Unable to resolve photo activity"
|
||||
private val IMAGE_FILE_SAVE_ERROR = "Unable to create photo on disk"
|
||||
private val IMAGE_PROCESS_NO_FILE_ERROR = "Unable to process image, file not found on disk"
|
||||
private val UNABLE_TO_PROCESS_IMAGE = "Unable to process image"
|
||||
private val IMAGE_EDIT_ERROR = "Unable to edit image"
|
||||
private val IMAGE_GALLERY_SAVE_ERROR = "Unable to save the image in the gallery"
|
||||
|
||||
private var imageFileSavePath: String? = null
|
||||
private var imageEditedFileSavePath: String? = null
|
||||
private var imageFileUri: Uri? = null
|
||||
private var imagePickedContentUri: Uri? = null
|
||||
private var isEdited = false
|
||||
private var isFirstRequest = true
|
||||
private var isSaved = false
|
||||
|
||||
private var settings: CameraSettings = CameraSettings()
|
||||
|
||||
@PluginMethod
|
||||
fun getPhoto(invoke: Invoke) {
|
||||
isEdited = false
|
||||
settings = getSettings(invoke)
|
||||
doShow(invoke)
|
||||
}
|
||||
|
||||
@PluginMethod
|
||||
fun pickImages(invoke: Invoke) {
|
||||
settings = getSettings(invoke)
|
||||
openPhotos(invoke, multiple = true, skipPermission = false)
|
||||
}
|
||||
|
||||
@PluginMethod
|
||||
fun pickLimitedLibraryPhotos(invoke: Invoke) {
|
||||
invoke.reject("not supported on android")
|
||||
}
|
||||
|
||||
@PluginMethod
|
||||
fun getLimitedLibraryPhotos(invoke: Invoke) {
|
||||
invoke.reject("not supported on android")
|
||||
}
|
||||
|
||||
private fun doShow(invoke: Invoke) {
|
||||
when (settings.source) {
|
||||
CameraSource.CAMERA -> showCamera(invoke)
|
||||
CameraSource.PHOTOS -> showPhotos(invoke)
|
||||
else -> showPrompt(invoke)
|
||||
}
|
||||
}
|
||||
|
||||
private fun showPrompt(invoke: Invoke) {
|
||||
// We have all necessary permissions, open the camera
|
||||
val options: MutableList<String> = ArrayList()
|
||||
options.add(invoke.getString("promptLabelPhoto", "From Photos"))
|
||||
options.add(invoke.getString("promptLabelPicture", "Take Picture"))
|
||||
val fragment = CameraBottomSheetDialogFragment()
|
||||
fragment.setTitle(invoke.getString("promptLabelHeader", "Photo"))
|
||||
fragment.setOptions(
|
||||
options,
|
||||
{ index: Int ->
|
||||
if (index == 0) {
|
||||
settings.source = CameraSource.PHOTOS
|
||||
openPhotos(invoke)
|
||||
} else if (index == 1) {
|
||||
settings.source = CameraSource.CAMERA
|
||||
openCamera(invoke)
|
||||
}
|
||||
},
|
||||
{ invoke.reject("User cancelled photos app") })
|
||||
fragment.show((activity as AppCompatActivity).supportFragmentManager, "capacitorModalsActionSheet")
|
||||
}
|
||||
|
||||
private fun showCamera(invoke: Invoke) {
|
||||
if (!activity.packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY)) {
|
||||
invoke.reject(NO_CAMERA_ERROR)
|
||||
return
|
||||
}
|
||||
openCamera(invoke)
|
||||
}
|
||||
|
||||
private fun showPhotos(invoke: Invoke) {
|
||||
openPhotos(invoke)
|
||||
}
|
||||
|
||||
private fun checkCameraPermissions(invoke: Invoke): Boolean {
|
||||
// if the manifest does not contain the camera permissions key, we don't need to ask the user
|
||||
val needCameraPerms = isPermissionDeclared(CAMERA)
|
||||
val hasCameraPerms = !needCameraPerms || getPermissionState(CAMERA) === PermissionState.GRANTED
|
||||
val hasPhotoPerms = getPermissionState(PHOTOS) === PermissionState.GRANTED
|
||||
|
||||
// If we want to save to the gallery, we need two permissions
|
||||
if (settings.isSaveToGallery && !(hasCameraPerms && hasPhotoPerms) && isFirstRequest) {
|
||||
isFirstRequest = false
|
||||
val aliases = if (needCameraPerms) {
|
||||
arrayOf(CAMERA, PHOTOS)
|
||||
} else {
|
||||
arrayOf(PHOTOS)
|
||||
}
|
||||
requestPermissionForAliases(aliases, invoke, "cameraPermissionsCallback")
|
||||
return false
|
||||
} else if (!hasCameraPerms) {
|
||||
requestPermissionForAlias(CAMERA, invoke, "cameraPermissionsCallback")
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
private fun checkPhotosPermissions(invoke: Invoke): Boolean {
|
||||
if (getPermissionState(PHOTOS) !== PermissionState.GRANTED) {
|
||||
requestPermissionForAlias(PHOTOS, invoke, "cameraPermissionsCallback")
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* Completes the plugin invoke after a camera permission request
|
||||
*
|
||||
* @see .getPhoto
|
||||
* @param invoke the plugin invoke
|
||||
*/
|
||||
@PermissionCallback
|
||||
private fun cameraPermissionsCallback(invoke: Invoke) {
|
||||
// TODO: invoke.methodName()
|
||||
val methodName = "pickImages"
|
||||
if (methodName == "pickImages") {
|
||||
openPhotos(invoke, multiple = true, skipPermission = true)
|
||||
} else {
|
||||
if (settings.source === CameraSource.CAMERA && getPermissionState(CAMERA) !== PermissionState.GRANTED) {
|
||||
Logger.debug(
|
||||
getLogTag(),
|
||||
"User denied camera permission: " + getPermissionState(CAMERA).toString()
|
||||
)
|
||||
invoke.reject(PERMISSION_DENIED_ERROR_CAMERA)
|
||||
return
|
||||
} else if (settings.source === CameraSource.PHOTOS && getPermissionState(PHOTOS) !== PermissionState.GRANTED) {
|
||||
Logger.debug(
|
||||
getLogTag(),
|
||||
"User denied photos permission: " + getPermissionState(PHOTOS).toString()
|
||||
)
|
||||
invoke.reject(PERMISSION_DENIED_ERROR_PHOTOS)
|
||||
return
|
||||
}
|
||||
doShow(invoke)
|
||||
}
|
||||
}
|
||||
|
||||
private fun getSettings(invoke: Invoke): CameraSettings {
|
||||
val settings = CameraSettings()
|
||||
val resultType = getResultType(invoke.getString("resultType"))
|
||||
if (resultType != null) {
|
||||
settings.resultType = resultType
|
||||
}
|
||||
settings.isSaveToGallery =
|
||||
invoke.getBoolean(
|
||||
"saveToGallery",
|
||||
CameraSettings.DEFAULT_SAVE_IMAGE_TO_GALLERY
|
||||
)
|
||||
settings.isAllowEditing = invoke.getBoolean("allowEditing", false)
|
||||
settings.quality = invoke.getInt("quality", CameraSettings.DEFAULT_QUALITY)
|
||||
settings.width = invoke.getInt("width", 0)
|
||||
settings.height = invoke.getInt("height", 0)
|
||||
settings.isShouldResize = settings.width > 0 || settings.height > 0
|
||||
settings.isShouldCorrectOrientation =
|
||||
invoke.getBoolean(
|
||||
"correctOrientation",
|
||||
CameraSettings.DEFAULT_CORRECT_ORIENTATION
|
||||
)
|
||||
|
||||
try {
|
||||
settings.source =
|
||||
CameraSource.valueOf(
|
||||
invoke.getString(
|
||||
"source",
|
||||
CameraSource.PROMPT.source
|
||||
)
|
||||
)
|
||||
|
||||
} catch (ex: IllegalArgumentException) {
|
||||
settings.source = CameraSource.PROMPT
|
||||
}
|
||||
return settings
|
||||
}
|
||||
|
||||
private fun getResultType(resultType: String?): CameraResultType? {
|
||||
return if (resultType == null) {
|
||||
null
|
||||
} else try {
|
||||
CameraResultType.valueOf(resultType.uppercase(Locale.ROOT))
|
||||
} catch (ex: IllegalArgumentException) {
|
||||
Logger.debug(getLogTag(), "Invalid result type \"$resultType\", defaulting to base64")
|
||||
CameraResultType.BASE64
|
||||
}
|
||||
}
|
||||
|
||||
private fun openCamera(invoke: Invoke) {
|
||||
if (checkCameraPermissions(invoke)) {
|
||||
val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
|
||||
if (takePictureIntent.resolveActivity(activity.packageManager) != null) {
|
||||
// If we will be saving the photo, send the target file along
|
||||
try {
|
||||
val appId: String = activity.packageName
|
||||
val photoFile: File = CameraUtils.createImageFile(activity)
|
||||
imageFileSavePath = photoFile.absolutePath
|
||||
// TODO: Verify provider config exists
|
||||
imageFileUri = FileProvider.getUriForFile(
|
||||
activity,
|
||||
"$appId.fileprovider", photoFile
|
||||
)
|
||||
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageFileUri)
|
||||
} catch (ex: Exception) {
|
||||
invoke.reject(IMAGE_FILE_SAVE_ERROR, ex)
|
||||
return
|
||||
}
|
||||
startActivityForResult(invoke, takePictureIntent, "processCameraImage")
|
||||
} else {
|
||||
invoke.reject(NO_CAMERA_ACTIVITY_ERROR)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun openPhotos(invoke: Invoke) {
|
||||
openPhotos(invoke, multiple = false, skipPermission = false)
|
||||
}
|
||||
|
||||
private fun openPhotos(invoke: Invoke, multiple: Boolean, skipPermission: Boolean) {
|
||||
if (skipPermission || checkPhotosPermissions(invoke)) {
|
||||
val intent = Intent(Intent.ACTION_PICK)
|
||||
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, multiple)
|
||||
intent.setType("image/*")
|
||||
try {
|
||||
if (multiple) {
|
||||
intent.putExtra("multi-pick", multiple)
|
||||
intent.putExtra(Intent.EXTRA_MIME_TYPES, arrayOf("image/*"))
|
||||
startActivityForResult(invoke, intent, "processPickedImages")
|
||||
} else {
|
||||
startActivityForResult(invoke, intent, "processPickedImage")
|
||||
}
|
||||
} catch (ex: ActivityNotFoundException) {
|
||||
invoke.reject(NO_PHOTO_ACTIVITY_ERROR)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ActivityCallback
|
||||
fun processCameraImage(invoke: Invoke, result: ActivityResult?) {
|
||||
settings = getSettings(invoke)
|
||||
if (imageFileSavePath == null) {
|
||||
invoke.reject(IMAGE_PROCESS_NO_FILE_ERROR)
|
||||
return
|
||||
}
|
||||
// Load the image as a Bitmap
|
||||
val f = File(imageFileSavePath!!)
|
||||
val bmOptions: BitmapFactory.Options = BitmapFactory.Options()
|
||||
val contentUri: Uri = Uri.fromFile(f)
|
||||
val bitmap: Bitmap = BitmapFactory.decodeFile(imageFileSavePath, bmOptions)
|
||||
returnResult(invoke, bitmap, contentUri)
|
||||
}
|
||||
|
||||
@ActivityCallback
|
||||
fun processPickedImage(invoke: Invoke, result: ActivityResult) {
|
||||
settings = getSettings(invoke)
|
||||
val data: Intent? = result.data
|
||||
if (data == null) {
|
||||
invoke.reject("No image picked")
|
||||
return
|
||||
}
|
||||
val u: Uri = data.data!!
|
||||
imagePickedContentUri = u
|
||||
processPickedImage(u, invoke)
|
||||
}
|
||||
|
||||
@ActivityCallback
|
||||
fun processPickedImages(invoke: Invoke, result: ActivityResult) {
|
||||
val data: Intent? = result.data
|
||||
if (data != null) {
|
||||
val executor: Executor = Executors.newSingleThreadExecutor()
|
||||
executor.execute {
|
||||
val ret = JSObject()
|
||||
val photos = JSArray()
|
||||
if (data.clipData != null) {
|
||||
val count: Int = data.clipData!!.itemCount
|
||||
for (i in 0 until count) {
|
||||
val imageUri: Uri = data.clipData!!.getItemAt(i).uri
|
||||
val processResult = processPickedImages(imageUri)
|
||||
if (processResult.getString("error").isNotEmpty()
|
||||
) {
|
||||
invoke.reject(processResult.getString("error"))
|
||||
return@execute
|
||||
} else {
|
||||
photos.put(processResult)
|
||||
}
|
||||
}
|
||||
} else if (data.data != null) {
|
||||
val imageUri: Uri = data.data!!
|
||||
val processResult = processPickedImages(imageUri)
|
||||
if (processResult.getString("error").isNotEmpty()
|
||||
) {
|
||||
invoke.reject(processResult.getString("error"))
|
||||
return@execute
|
||||
} else {
|
||||
photos.put(processResult)
|
||||
}
|
||||
} else if (data.extras != null) {
|
||||
val bundle: Bundle = data.extras!!
|
||||
if (bundle.keySet().contains("selectedItems")) {
|
||||
val fileUris: ArrayList<Parcelable>? = bundle.getParcelableArrayList("selectedItems")
|
||||
if (fileUris != null) {
|
||||
for (fileUri in fileUris) {
|
||||
if (fileUri is Uri) {
|
||||
val imageUri: Uri = fileUri
|
||||
try {
|
||||
val processResult = processPickedImages(imageUri)
|
||||
if (processResult.getString("error").isNotEmpty()
|
||||
) {
|
||||
invoke.reject(processResult.getString("error"))
|
||||
return@execute
|
||||
} else {
|
||||
photos.put(processResult)
|
||||
}
|
||||
} catch (ex: SecurityException) {
|
||||
invoke.reject("SecurityException")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
ret.put("photos", photos)
|
||||
invoke.resolve(ret)
|
||||
}
|
||||
} else {
|
||||
invoke.reject("No images picked")
|
||||
}
|
||||
}
|
||||
|
||||
private fun processPickedImage(imageUri: Uri, invoke: Invoke) {
|
||||
var imageStream: InputStream? = null
|
||||
try {
|
||||
imageStream = activity.contentResolver.openInputStream(imageUri)
|
||||
val bitmap = BitmapFactory.decodeStream(imageStream)
|
||||
if (bitmap == null) {
|
||||
invoke.reject("Unable to process bitmap")
|
||||
return
|
||||
}
|
||||
returnResult(invoke, bitmap, imageUri)
|
||||
} catch (err: OutOfMemoryError) {
|
||||
invoke.reject("Out of memory")
|
||||
} catch (ex: FileNotFoundException) {
|
||||
invoke.reject("No such image found", ex)
|
||||
} finally {
|
||||
if (imageStream != null) {
|
||||
try {
|
||||
imageStream.close()
|
||||
} catch (e: IOException) {
|
||||
Logger.error(getLogTag(), UNABLE_TO_PROCESS_IMAGE, e)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun processPickedImages(imageUri: Uri): JSObject {
|
||||
var imageStream: InputStream? = null
|
||||
val ret = JSObject()
|
||||
try {
|
||||
imageStream = activity.contentResolver.openInputStream(imageUri)
|
||||
var bitmap = BitmapFactory.decodeStream(imageStream)
|
||||
if (bitmap == null) {
|
||||
ret.put("error", "Unable to process bitmap")
|
||||
return ret
|
||||
}
|
||||
val exif: ExifWrapper = ImageUtils.getExifData(activity, bitmap, imageUri)
|
||||
bitmap = try {
|
||||
prepareBitmap(bitmap, imageUri, exif)
|
||||
} catch (e: IOException) {
|
||||
ret.put("error", UNABLE_TO_PROCESS_IMAGE)
|
||||
return ret
|
||||
}
|
||||
// Compress the final image and prepare for output to client
|
||||
val bitmapOutputStream = ByteArrayOutputStream()
|
||||
bitmap.compress(Bitmap.CompressFormat.JPEG, settings.quality, bitmapOutputStream)
|
||||
val newUri: Uri? = getTempImage(imageUri, bitmapOutputStream)
|
||||
exif.copyExif(newUri?.path)
|
||||
if (newUri != null) {
|
||||
ret.put("format", "jpeg")
|
||||
ret.put("exif", exif.toJson())
|
||||
ret.put("data", newUri.toString())
|
||||
ret.put("assetUrl", assetUrl(newUri))
|
||||
} else {
|
||||
ret.put("error", UNABLE_TO_PROCESS_IMAGE)
|
||||
}
|
||||
return ret
|
||||
} catch (err: OutOfMemoryError) {
|
||||
ret.put("error", "Out of memory")
|
||||
} catch (ex: FileNotFoundException) {
|
||||
ret.put("error", "No such image found")
|
||||
Logger.error(getLogTag(), "No such image found", ex)
|
||||
} finally {
|
||||
if (imageStream != null) {
|
||||
try {
|
||||
imageStream.close()
|
||||
} catch (e: IOException) {
|
||||
Logger.error(getLogTag(), UNABLE_TO_PROCESS_IMAGE, e)
|
||||
}
|
||||
}
|
||||
}
|
||||
return ret
|
||||
}
|
||||
|
||||
@ActivityCallback
|
||||
private fun processEditedImage(invoke: Invoke, result: ActivityResult) {
|
||||
isEdited = true
|
||||
settings = getSettings(invoke)
|
||||
if (result.resultCode == Activity.RESULT_CANCELED) {
|
||||
// User cancelled the edit operation, if this file was picked from photos,
|
||||
// process the original picked image, otherwise process it as a camera photo
|
||||
if (imagePickedContentUri != null) {
|
||||
processPickedImage(imagePickedContentUri!!, invoke)
|
||||
} else {
|
||||
processCameraImage(invoke, result)
|
||||
}
|
||||
} else {
|
||||
processPickedImage(invoke, result)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Save the modified image on the same path,
|
||||
* or on a temporary location if it's a content url
|
||||
* @param uri
|
||||
* @param is
|
||||
* @return
|
||||
* @throws IOException
|
||||
*/
|
||||
@Throws(IOException::class)
|
||||
private fun saveImage(uri: Uri, input: InputStream): Uri? {
|
||||
var outFile = if (uri.scheme.equals("content")) {
|
||||
getTempFile(uri)
|
||||
} else {
|
||||
uri.path?.let { File(it) }
|
||||
}
|
||||
try {
|
||||
writePhoto(outFile!!, input)
|
||||
} catch (ex: FileNotFoundException) {
|
||||
// Some gallery apps return read only file url, create a temporary file for modifications
|
||||
outFile = getTempFile(uri)
|
||||
writePhoto(outFile, input)
|
||||
}
|
||||
return Uri.fromFile(outFile)
|
||||
}
|
||||
|
||||
@Throws(IOException::class)
|
||||
private fun writePhoto(outFile: File, input: InputStream) {
|
||||
val fos = FileOutputStream(outFile)
|
||||
val buffer = ByteArray(1024)
|
||||
var len: Int
|
||||
while (input.read(buffer).also { len = it } != -1) {
|
||||
fos.write(buffer, 0, len)
|
||||
}
|
||||
fos.close()
|
||||
}
|
||||
|
||||
private fun getTempFile(uri: Uri): File {
|
||||
var filename: String = Uri.parse(Uri.decode(uri.toString())).lastPathSegment!!
|
||||
if (!filename.contains(".jpg") && !filename.contains(".jpeg")) {
|
||||
filename += "." + Date().time + ".jpeg"
|
||||
}
|
||||
val cacheDir: File = activity.getCacheDir()
|
||||
return File(cacheDir, filename)
|
||||
}
|
||||
|
||||
/**
|
||||
* After processing the image, return the final result back to the invokeer.
|
||||
* @param invoke
|
||||
* @param bitmap
|
||||
* @param u
|
||||
*/
|
||||
private fun returnResult(invoke: Invoke, bitmap: Bitmap, u: Uri) {
|
||||
val exif: ExifWrapper = ImageUtils.getExifData(activity, bitmap, u)
|
||||
val preparedBitmap = try {
|
||||
prepareBitmap(bitmap, u, exif)
|
||||
} catch (e: IOException) {
|
||||
invoke.reject(UNABLE_TO_PROCESS_IMAGE)
|
||||
return
|
||||
}
|
||||
// Compress the final image and prepare for output to client
|
||||
val bitmapOutputStream = ByteArrayOutputStream()
|
||||
preparedBitmap.compress(Bitmap.CompressFormat.JPEG, settings.quality, bitmapOutputStream)
|
||||
if (settings.isAllowEditing && !isEdited) {
|
||||
editImage(invoke, u, bitmapOutputStream)
|
||||
return
|
||||
}
|
||||
val saveToGallery: Boolean =
|
||||
invoke.getBoolean("saveToGallery", CameraSettings.DEFAULT_SAVE_IMAGE_TO_GALLERY)
|
||||
if (saveToGallery && (imageEditedFileSavePath != null || imageFileSavePath != null)) {
|
||||
isSaved = true
|
||||
try {
|
||||
val fileToSavePath =
|
||||
if (imageEditedFileSavePath != null) imageEditedFileSavePath!! else imageFileSavePath!!
|
||||
val fileToSave = File(fileToSavePath)
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||
val resolver: ContentResolver = activity.contentResolver
|
||||
val values = ContentValues()
|
||||
values.put(MediaStore.MediaColumns.DISPLAY_NAME, fileToSave.name)
|
||||
values.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg")
|
||||
values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DCIM)
|
||||
val contentUri: Uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
|
||||
val uri: Uri = resolver.insert(contentUri, values)
|
||||
?: throw IOException("Failed to create new MediaStore record.")
|
||||
val stream: OutputStream = resolver.openOutputStream(uri)
|
||||
?: throw IOException("Failed to open output stream.")
|
||||
val inserted: Boolean =
|
||||
preparedBitmap.compress(Bitmap.CompressFormat.JPEG, settings.quality, stream)
|
||||
if (!inserted) {
|
||||
isSaved = false
|
||||
}
|
||||
} else {
|
||||
val inserted = MediaStore.Images.Media.insertImage(
|
||||
activity.contentResolver,
|
||||
fileToSavePath,
|
||||
fileToSave.name,
|
||||
""
|
||||
)
|
||||
if (inserted == null) {
|
||||
isSaved = false
|
||||
}
|
||||
}
|
||||
} catch (e: FileNotFoundException) {
|
||||
isSaved = false
|
||||
Logger.error(getLogTag(), IMAGE_GALLERY_SAVE_ERROR, e)
|
||||
} catch (e: IOException) {
|
||||
isSaved = false
|
||||
Logger.error(getLogTag(), IMAGE_GALLERY_SAVE_ERROR, e)
|
||||
}
|
||||
}
|
||||
if (settings.resultType === CameraResultType.BASE64) {
|
||||
returnBase64(invoke, exif, bitmapOutputStream)
|
||||
} else if (settings.resultType === CameraResultType.URI) {
|
||||
returnFileURI(invoke, exif, bitmap, u, bitmapOutputStream)
|
||||
} else if (settings.resultType === CameraResultType.DATAURL) {
|
||||
returnDataUrl(invoke, exif, bitmapOutputStream)
|
||||
} else {
|
||||
invoke.reject(INVALID_RESULT_TYPE_ERROR)
|
||||
}
|
||||
// Result returned, clear stored paths and images
|
||||
if (settings.resultType !== CameraResultType.URI) {
|
||||
deleteImageFile()
|
||||
}
|
||||
imageFileSavePath = null
|
||||
imageFileUri = null
|
||||
imagePickedContentUri = null
|
||||
imageEditedFileSavePath = null
|
||||
}
|
||||
|
||||
private fun deleteImageFile() {
|
||||
if (imageFileSavePath != null && !settings.isSaveToGallery) {
|
||||
val photoFile = File(imageFileSavePath!!)
|
||||
if (photoFile.exists()) {
|
||||
photoFile.delete()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun returnFileURI(
|
||||
invoke: Invoke,
|
||||
exif: ExifWrapper,
|
||||
bitmap: Bitmap,
|
||||
u: Uri,
|
||||
bitmapOutputStream: ByteArrayOutputStream
|
||||
) {
|
||||
val newUri: Uri? = getTempImage(u, bitmapOutputStream)
|
||||
exif.copyExif(newUri?.path)
|
||||
if (newUri != null) {
|
||||
val ret = JSObject()
|
||||
ret.put("format", "jpeg")
|
||||
ret.put("exif", exif.toJson())
|
||||
ret.put("data", newUri.toString())
|
||||
ret.put("assetUrl", assetUrl(newUri))
|
||||
ret.put("saved", isSaved)
|
||||
invoke.resolve(ret)
|
||||
} else {
|
||||
invoke.reject(UNABLE_TO_PROCESS_IMAGE)
|
||||
}
|
||||
}
|
||||
|
||||
private fun getTempImage(u: Uri, bitmapOutputStream: ByteArrayOutputStream): Uri? {
|
||||
var bis: ByteArrayInputStream? = null
|
||||
var newUri: Uri? = null
|
||||
try {
|
||||
bis = ByteArrayInputStream(bitmapOutputStream.toByteArray())
|
||||
newUri = saveImage(u, bis)
|
||||
} catch (_: IOException) {
|
||||
} finally {
|
||||
if (bis != null) {
|
||||
try {
|
||||
bis.close()
|
||||
} catch (e: IOException) {
|
||||
Logger.error(getLogTag(), UNABLE_TO_PROCESS_IMAGE, e)
|
||||
}
|
||||
}
|
||||
}
|
||||
return newUri
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply our standard processing of the bitmap, returning a new one and
|
||||
* recycling the old one in the process
|
||||
* @param bitmap
|
||||
* @param imageUri
|
||||
* @param exif
|
||||
* @return
|
||||
*/
|
||||
@Throws(IOException::class)
|
||||
private fun prepareBitmap(bitmap: Bitmap, imageUri: Uri, exif: ExifWrapper): Bitmap {
|
||||
var preparedBitmap: Bitmap = bitmap
|
||||
if (settings.isShouldCorrectOrientation) {
|
||||
val newBitmap: Bitmap = ImageUtils.correctOrientation(activity, preparedBitmap, imageUri, exif)
|
||||
preparedBitmap = replaceBitmap(preparedBitmap, newBitmap)
|
||||
}
|
||||
if (settings.isShouldResize) {
|
||||
val newBitmap: Bitmap = ImageUtils.resize(preparedBitmap, settings.width, settings.height)
|
||||
preparedBitmap = replaceBitmap(preparedBitmap, newBitmap)
|
||||
}
|
||||
return preparedBitmap
|
||||
}
|
||||
|
||||
private fun replaceBitmap(bitmap: Bitmap, newBitmap: Bitmap): Bitmap {
|
||||
if (bitmap !== newBitmap) {
|
||||
bitmap.recycle()
|
||||
}
|
||||
return newBitmap
|
||||
}
|
||||
|
||||
private fun returnDataUrl(
|
||||
invoke: Invoke,
|
||||
exif: ExifWrapper,
|
||||
bitmapOutputStream: ByteArrayOutputStream
|
||||
) {
|
||||
val byteArray: ByteArray = bitmapOutputStream.toByteArray()
|
||||
val encoded: String = Base64.encodeToString(byteArray, Base64.NO_WRAP)
|
||||
val data = JSObject()
|
||||
data.put("format", "jpeg")
|
||||
data.put("data", "data:image/jpeg;base64,$encoded")
|
||||
data.put("exif", exif.toJson())
|
||||
invoke.resolve(data)
|
||||
}
|
||||
|
||||
private fun returnBase64(
|
||||
invoke: Invoke,
|
||||
exif: ExifWrapper,
|
||||
bitmapOutputStream: ByteArrayOutputStream
|
||||
) {
|
||||
val byteArray: ByteArray = bitmapOutputStream.toByteArray()
|
||||
val encoded: String = Base64.encodeToString(byteArray, Base64.NO_WRAP)
|
||||
val data = JSObject()
|
||||
data.put("format", "jpeg")
|
||||
data.put("data", encoded)
|
||||
data.put("exif", exif.toJson())
|
||||
invoke.resolve(data)
|
||||
}
|
||||
|
||||
@PluginMethod
|
||||
override fun requestPermissions(invoke: Invoke) {
|
||||
// If the camera permission is defined in the manifest, then we have to prompt the user
|
||||
// or else we will get a security exception when trying to present the camera. If, however,
|
||||
// it is not defined in the manifest then we don't need to prompt and it will just work.
|
||||
if (isPermissionDeclared(CAMERA)) {
|
||||
// just request normally
|
||||
super.requestPermissions(invoke)
|
||||
} else {
|
||||
// the manifest does not define camera permissions, so we need to decide what to do
|
||||
// first, extract the permissions being requested
|
||||
val providedPerms = invoke.getArray("permissions", JSArray())
|
||||
var permsList: List<String>? = null
|
||||
try {
|
||||
permsList = providedPerms.toList()
|
||||
} catch (_: JSONException) {
|
||||
}
|
||||
if (permsList != null && permsList.size == 1 && permsList.contains(CAMERA)) {
|
||||
// the only thing being asked for was the camera so we can just return the current state
|
||||
checkPermissions(invoke)
|
||||
} else {
|
||||
// we need to ask about photos so request storage permissions
|
||||
requestPermissionForAlias(PHOTOS, invoke, "checkPermissions")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun getPermissionStates(): Map<String, PermissionState> {
|
||||
val permissionStates = super.getPermissionStates() as MutableMap
|
||||
|
||||
// If Camera is not in the manifest and therefore not required, say the permission is granted
|
||||
if (!isPermissionDeclared(CAMERA)) {
|
||||
permissionStates[CAMERA] = PermissionState.GRANTED
|
||||
}
|
||||
return permissionStates
|
||||
}
|
||||
|
||||
private fun editImage(invoke: Invoke, uri: Uri, bitmapOutputStream: ByteArrayOutputStream) {
|
||||
try {
|
||||
val tempImage = getTempImage(uri, bitmapOutputStream)
|
||||
val editIntent = createEditIntent(tempImage)
|
||||
if (editIntent != null) {
|
||||
startActivityForResult(invoke, editIntent, "processEditedImage")
|
||||
} else {
|
||||
invoke.reject(IMAGE_EDIT_ERROR)
|
||||
}
|
||||
} catch (ex: Exception) {
|
||||
invoke.reject(IMAGE_EDIT_ERROR, ex)
|
||||
}
|
||||
}
|
||||
|
||||
private fun createEditIntent(origPhotoUri: Uri?): Intent? {
|
||||
return try {
|
||||
val editFile = origPhotoUri?.path?.let { File(it) }
|
||||
val editUri: Uri = FileProvider.getUriForFile(
|
||||
activity,
|
||||
activity.packageName + ".fileprovider",
|
||||
editFile!!
|
||||
)
|
||||
val editIntent = Intent(Intent.ACTION_EDIT)
|
||||
editIntent.setDataAndType(editUri, "image/*")
|
||||
imageEditedFileSavePath = editFile.absolutePath
|
||||
val flags: Int =
|
||||
Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION
|
||||
editIntent.addFlags(flags)
|
||||
editIntent.putExtra(MediaStore.EXTRA_OUTPUT, editUri)
|
||||
val resInfoList: List<ResolveInfo> = activity
|
||||
.packageManager
|
||||
.queryIntentActivities(editIntent, PackageManager.MATCH_DEFAULT_ONLY)
|
||||
for (resolveInfo in resInfoList) {
|
||||
val packageName: String = resolveInfo.activityInfo.packageName
|
||||
activity.grantUriPermission(packageName, editUri, flags)
|
||||
}
|
||||
editIntent
|
||||
} catch (ex: Exception) {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
/*protected fun saveInstanceState(): Bundle? {
|
||||
val bundle: Bundle = super.saveInstanceState()
|
||||
if (bundle != null) {
|
||||
bundle.putString("cameraImageFileSavePath", imageFileSavePath)
|
||||
}
|
||||
return bundle
|
||||
}
|
||||
|
||||
protected fun restoreState(state: Bundle) {
|
||||
val storedImageFileSavePath: String = state.getString("cameraImageFileSavePath")
|
||||
if (storedImageFileSavePath != null) {
|
||||
imageFileSavePath = storedImageFileSavePath
|
||||
}
|
||||
}*/
|
||||
}
|
@ -0,0 +1,39 @@
|
||||
package app.tauri.camera
|
||||
|
||||
import android.app.Activity
|
||||
import android.net.Uri
|
||||
import android.os.Environment
|
||||
import androidx.core.content.FileProvider
|
||||
import app.tauri.Logger
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.*
|
||||
|
||||
object CameraUtils {
|
||||
@Throws(IOException::class)
|
||||
fun createImageFileUri(activity: Activity, appId: String): Uri {
|
||||
val photoFile = createImageFile(activity)
|
||||
return FileProvider.getUriForFile(
|
||||
activity,
|
||||
"$appId.fileprovider", photoFile
|
||||
)
|
||||
}
|
||||
|
||||
@Throws(IOException::class)
|
||||
fun createImageFile(activity: Activity): File {
|
||||
// Create an image file name
|
||||
val timeStamp: String = SimpleDateFormat("yyyyMMdd_HHmmss").format(Date())
|
||||
val imageFileName = "JPEG_" + timeStamp + "_"
|
||||
val storageDir =
|
||||
activity.getExternalFilesDir(Environment.DIRECTORY_PICTURES)
|
||||
return File.createTempFile(
|
||||
imageFileName, /* prefix */
|
||||
".jpg", /* suffix */
|
||||
storageDir /* directory */
|
||||
)
|
||||
}
|
||||
|
||||
internal val logTag: String
|
||||
internal get() = Logger.tags("CameraUtils")
|
||||
}
|
@ -0,0 +1,198 @@
|
||||
package app.tauri.camera
|
||||
|
||||
import androidx.exifinterface.media.ExifInterface.*
|
||||
import androidx.exifinterface.media.ExifInterface
|
||||
import app.tauri.plugin.JSObject
|
||||
|
||||
class ExifWrapper(private val exif: ExifInterface?) {
|
||||
private val attributes = arrayOf(
|
||||
TAG_APERTURE_VALUE,
|
||||
TAG_ARTIST,
|
||||
TAG_BITS_PER_SAMPLE,
|
||||
TAG_BODY_SERIAL_NUMBER,
|
||||
TAG_BRIGHTNESS_VALUE,
|
||||
TAG_CAMERA_OWNER_NAME,
|
||||
TAG_CFA_PATTERN,
|
||||
TAG_COLOR_SPACE,
|
||||
TAG_COMPONENTS_CONFIGURATION,
|
||||
TAG_COMPRESSED_BITS_PER_PIXEL,
|
||||
TAG_COMPRESSION,
|
||||
TAG_CONTRAST,
|
||||
TAG_COPYRIGHT,
|
||||
TAG_CUSTOM_RENDERED,
|
||||
TAG_DATETIME,
|
||||
TAG_DATETIME_DIGITIZED,
|
||||
TAG_DATETIME_ORIGINAL,
|
||||
TAG_DEFAULT_CROP_SIZE,
|
||||
TAG_DEVICE_SETTING_DESCRIPTION,
|
||||
TAG_DIGITAL_ZOOM_RATIO,
|
||||
TAG_DNG_VERSION,
|
||||
TAG_EXIF_VERSION,
|
||||
TAG_EXPOSURE_BIAS_VALUE,
|
||||
TAG_EXPOSURE_INDEX,
|
||||
TAG_EXPOSURE_MODE,
|
||||
TAG_EXPOSURE_PROGRAM,
|
||||
TAG_EXPOSURE_TIME,
|
||||
TAG_FILE_SOURCE,
|
||||
TAG_FLASH,
|
||||
TAG_FLASHPIX_VERSION,
|
||||
TAG_FLASH_ENERGY,
|
||||
TAG_FOCAL_LENGTH,
|
||||
TAG_FOCAL_LENGTH_IN_35MM_FILM,
|
||||
TAG_FOCAL_PLANE_RESOLUTION_UNIT,
|
||||
TAG_FOCAL_PLANE_X_RESOLUTION,
|
||||
TAG_FOCAL_PLANE_Y_RESOLUTION,
|
||||
TAG_F_NUMBER,
|
||||
TAG_GAIN_CONTROL,
|
||||
TAG_GAMMA,
|
||||
TAG_GPS_ALTITUDE,
|
||||
TAG_GPS_ALTITUDE_REF,
|
||||
TAG_GPS_AREA_INFORMATION,
|
||||
TAG_GPS_DATESTAMP,
|
||||
TAG_GPS_DEST_BEARING,
|
||||
TAG_GPS_DEST_BEARING_REF,
|
||||
TAG_GPS_DEST_DISTANCE,
|
||||
TAG_GPS_DEST_DISTANCE_REF,
|
||||
TAG_GPS_DEST_LATITUDE,
|
||||
TAG_GPS_DEST_LATITUDE_REF,
|
||||
TAG_GPS_DEST_LONGITUDE,
|
||||
TAG_GPS_DEST_LONGITUDE_REF,
|
||||
TAG_GPS_DIFFERENTIAL,
|
||||
TAG_GPS_DOP,
|
||||
TAG_GPS_H_POSITIONING_ERROR,
|
||||
TAG_GPS_IMG_DIRECTION,
|
||||
TAG_GPS_IMG_DIRECTION_REF,
|
||||
TAG_GPS_LATITUDE,
|
||||
TAG_GPS_LATITUDE_REF,
|
||||
TAG_GPS_LONGITUDE,
|
||||
TAG_GPS_LONGITUDE_REF,
|
||||
TAG_GPS_MAP_DATUM,
|
||||
TAG_GPS_MEASURE_MODE,
|
||||
TAG_GPS_PROCESSING_METHOD,
|
||||
TAG_GPS_SATELLITES,
|
||||
TAG_GPS_SPEED,
|
||||
TAG_GPS_SPEED_REF,
|
||||
TAG_GPS_STATUS,
|
||||
TAG_GPS_TIMESTAMP,
|
||||
TAG_GPS_TRACK,
|
||||
TAG_GPS_TRACK_REF,
|
||||
TAG_GPS_VERSION_ID,
|
||||
TAG_IMAGE_DESCRIPTION,
|
||||
TAG_IMAGE_LENGTH,
|
||||
TAG_IMAGE_UNIQUE_ID,
|
||||
TAG_IMAGE_WIDTH,
|
||||
TAG_INTEROPERABILITY_INDEX,
|
||||
TAG_ISO_SPEED,
|
||||
TAG_ISO_SPEED_LATITUDE_YYY,
|
||||
TAG_ISO_SPEED_LATITUDE_ZZZ,
|
||||
TAG_JPEG_INTERCHANGE_FORMAT,
|
||||
TAG_JPEG_INTERCHANGE_FORMAT_LENGTH,
|
||||
TAG_LENS_MAKE,
|
||||
TAG_LENS_MODEL,
|
||||
TAG_LENS_SERIAL_NUMBER,
|
||||
TAG_LENS_SPECIFICATION,
|
||||
TAG_LIGHT_SOURCE,
|
||||
TAG_MAKE,
|
||||
TAG_MAKER_NOTE,
|
||||
TAG_MAX_APERTURE_VALUE,
|
||||
TAG_METERING_MODE,
|
||||
TAG_MODEL,
|
||||
TAG_NEW_SUBFILE_TYPE,
|
||||
TAG_OECF,
|
||||
TAG_OFFSET_TIME,
|
||||
TAG_OFFSET_TIME_DIGITIZED,
|
||||
TAG_OFFSET_TIME_ORIGINAL,
|
||||
TAG_ORF_ASPECT_FRAME,
|
||||
TAG_ORF_PREVIEW_IMAGE_LENGTH,
|
||||
TAG_ORF_PREVIEW_IMAGE_START,
|
||||
TAG_ORF_THUMBNAIL_IMAGE,
|
||||
TAG_ORIENTATION,
|
||||
TAG_PHOTOGRAPHIC_SENSITIVITY,
|
||||
TAG_PHOTOMETRIC_INTERPRETATION,
|
||||
TAG_PIXEL_X_DIMENSION,
|
||||
TAG_PIXEL_Y_DIMENSION,
|
||||
TAG_PLANAR_CONFIGURATION,
|
||||
TAG_PRIMARY_CHROMATICITIES,
|
||||
TAG_RECOMMENDED_EXPOSURE_INDEX,
|
||||
TAG_REFERENCE_BLACK_WHITE,
|
||||
TAG_RELATED_SOUND_FILE,
|
||||
TAG_RESOLUTION_UNIT,
|
||||
TAG_ROWS_PER_STRIP,
|
||||
TAG_RW2_ISO,
|
||||
TAG_RW2_JPG_FROM_RAW,
|
||||
TAG_RW2_SENSOR_BOTTOM_BORDER,
|
||||
TAG_RW2_SENSOR_LEFT_BORDER,
|
||||
TAG_RW2_SENSOR_RIGHT_BORDER,
|
||||
TAG_RW2_SENSOR_TOP_BORDER,
|
||||
TAG_SAMPLES_PER_PIXEL,
|
||||
TAG_SATURATION,
|
||||
TAG_SCENE_CAPTURE_TYPE,
|
||||
TAG_SCENE_TYPE,
|
||||
TAG_SENSING_METHOD,
|
||||
TAG_SENSITIVITY_TYPE,
|
||||
TAG_SHARPNESS,
|
||||
TAG_SHUTTER_SPEED_VALUE,
|
||||
TAG_SOFTWARE,
|
||||
TAG_SPATIAL_FREQUENCY_RESPONSE,
|
||||
TAG_SPECTRAL_SENSITIVITY,
|
||||
TAG_STANDARD_OUTPUT_SENSITIVITY,
|
||||
TAG_STRIP_BYTE_COUNTS,
|
||||
TAG_STRIP_OFFSETS,
|
||||
TAG_SUBFILE_TYPE,
|
||||
TAG_SUBJECT_AREA,
|
||||
TAG_SUBJECT_DISTANCE,
|
||||
TAG_SUBJECT_DISTANCE_RANGE,
|
||||
TAG_SUBJECT_LOCATION,
|
||||
TAG_SUBSEC_TIME,
|
||||
TAG_SUBSEC_TIME_DIGITIZED,
|
||||
TAG_SUBSEC_TIME_ORIGINAL,
|
||||
TAG_THUMBNAIL_IMAGE_LENGTH,
|
||||
TAG_THUMBNAIL_IMAGE_WIDTH,
|
||||
TAG_TRANSFER_FUNCTION,
|
||||
TAG_USER_COMMENT,
|
||||
TAG_WHITE_BALANCE,
|
||||
TAG_WHITE_POINT,
|
||||
TAG_XMP,
|
||||
TAG_X_RESOLUTION,
|
||||
TAG_Y_CB_CR_COEFFICIENTS,
|
||||
TAG_Y_CB_CR_POSITIONING,
|
||||
TAG_Y_CB_CR_SUB_SAMPLING,
|
||||
TAG_Y_RESOLUTION
|
||||
)
|
||||
|
||||
fun toJson(): JSObject {
|
||||
val ret = JSObject()
|
||||
if (exif == null) {
|
||||
return ret
|
||||
}
|
||||
for (i in attributes.indices) {
|
||||
p(ret, attributes[i])
|
||||
}
|
||||
return ret
|
||||
}
|
||||
|
||||
fun p(o: JSObject, tag: String?) {
|
||||
val value = exif!!.getAttribute(tag!!)
|
||||
o.put(tag, value)
|
||||
}
|
||||
|
||||
fun copyExif(destFile: String?) {
|
||||
try {
|
||||
val destExif = ExifInterface(
|
||||
destFile!!
|
||||
)
|
||||
for (i in attributes.indices) {
|
||||
val value = exif!!.getAttribute(attributes[i])
|
||||
if (value != null) {
|
||||
destExif.setAttribute(attributes[i], value)
|
||||
}
|
||||
}
|
||||
destExif.saveAttributes()
|
||||
} catch (_: java.lang.Exception) {
|
||||
}
|
||||
}
|
||||
|
||||
fun resetOrientation() {
|
||||
exif!!.resetOrientation()
|
||||
}
|
||||
}
|
@ -0,0 +1,126 @@
|
||||
package app.tauri.camera
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.Matrix
|
||||
import android.net.Uri
|
||||
import androidx.exifinterface.media.ExifInterface
|
||||
import app.tauri.Logger
|
||||
import java.io.IOException
|
||||
import java.io.InputStream
|
||||
import java.lang.Integer.min
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
object ImageUtils {
|
||||
/**
|
||||
* Resize an image to the given max width and max height. Constraint can be put
|
||||
* on one dimension, or both. Resize will always preserve aspect ratio.
|
||||
* @param bitmap
|
||||
* @param desiredMaxWidth
|
||||
* @param desiredMaxHeight
|
||||
* @return a new, scaled Bitmap
|
||||
*/
|
||||
fun resize(bitmap: Bitmap, desiredMaxWidth: Int, desiredMaxHeight: Int): Bitmap {
|
||||
return resizePreservingAspectRatio(bitmap, desiredMaxWidth, desiredMaxHeight)
|
||||
}
|
||||
|
||||
/**
|
||||
* Resize an image to the given max width and max height. Constraint can be put
|
||||
* on one dimension, or both. Resize will always preserve aspect ratio.
|
||||
* @param bitmap
|
||||
* @param desiredMaxWidth
|
||||
* @param desiredMaxHeight
|
||||
* @return a new, scaled Bitmap
|
||||
*/
|
||||
private fun resizePreservingAspectRatio(
|
||||
bitmap: Bitmap,
|
||||
desiredMaxWidth: Int,
|
||||
desiredMaxHeight: Int
|
||||
): Bitmap {
|
||||
val width = bitmap.width
|
||||
val height = bitmap.height
|
||||
|
||||
// 0 is treated as 'no restriction'
|
||||
val maxHeight = if (desiredMaxHeight == 0) height else desiredMaxHeight
|
||||
val maxWidth = if (desiredMaxWidth == 0) width else desiredMaxWidth
|
||||
|
||||
// resize with preserved aspect ratio
|
||||
var newWidth = min(width, maxWidth).toFloat()
|
||||
var newHeight = height * newWidth / width
|
||||
if (newHeight > maxHeight) {
|
||||
newWidth = (width * maxHeight / height).toFloat()
|
||||
newHeight = maxHeight.toFloat()
|
||||
}
|
||||
return Bitmap.createScaledBitmap(bitmap, newWidth.roundToInt(), newHeight.roundToInt(), false)
|
||||
}
|
||||
|
||||
/**
|
||||
* Transform an image with the given matrix
|
||||
* @param bitmap
|
||||
* @param matrix
|
||||
* @return
|
||||
*/
|
||||
private fun transform(bitmap: Bitmap, matrix: Matrix): Bitmap {
|
||||
return Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, true)
|
||||
}
|
||||
|
||||
/**
|
||||
* Correct the orientation of an image by reading its exif information and rotating
|
||||
* the appropriate amount for portrait mode
|
||||
* @param bitmap
|
||||
* @param imageUri
|
||||
* @param exif
|
||||
* @return
|
||||
*/
|
||||
@Throws(IOException::class)
|
||||
fun correctOrientation(c: Context, bitmap: Bitmap, imageUri: Uri, exif: ExifWrapper): Bitmap {
|
||||
val orientation = getOrientation(c, imageUri)
|
||||
return if (orientation != 0) {
|
||||
val matrix = Matrix()
|
||||
matrix.postRotate(orientation.toFloat())
|
||||
exif.resetOrientation()
|
||||
transform(bitmap, matrix)
|
||||
} else {
|
||||
bitmap
|
||||
}
|
||||
}
|
||||
|
||||
@Throws(IOException::class)
|
||||
private fun getOrientation(c: Context, imageUri: Uri): Int {
|
||||
var result = 0
|
||||
c.getContentResolver().openInputStream(imageUri).use { iStream ->
|
||||
val exifInterface = ExifInterface(iStream!!)
|
||||
val orientation: Int = exifInterface.getAttributeInt(
|
||||
ExifInterface.TAG_ORIENTATION,
|
||||
ExifInterface.ORIENTATION_NORMAL
|
||||
)
|
||||
if (orientation == ExifInterface.ORIENTATION_ROTATE_90) {
|
||||
result = 90
|
||||
} else if (orientation == ExifInterface.ORIENTATION_ROTATE_180) {
|
||||
result = 180
|
||||
} else if (orientation == ExifInterface.ORIENTATION_ROTATE_270) {
|
||||
result = 270
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
fun getExifData(c: Context, bitmap: Bitmap?, imageUri: Uri): ExifWrapper {
|
||||
var stream: InputStream? = null
|
||||
try {
|
||||
stream = c.getContentResolver().openInputStream(imageUri)
|
||||
val exifInterface = ExifInterface(stream!!)
|
||||
return ExifWrapper(exifInterface)
|
||||
} catch (ex: IOException) {
|
||||
Logger.error("Error loading exif data from image", ex)
|
||||
} finally {
|
||||
if (stream != null) {
|
||||
try {
|
||||
stream.close()
|
||||
} catch (ignored: IOException) {
|
||||
}
|
||||
}
|
||||
}
|
||||
return ExifWrapper(null)
|
||||
}
|
||||
}
|
@ -0,0 +1,17 @@
|
||||
package app.tauri.camera
|
||||
|
||||
import org.junit.Test
|
||||
|
||||
import org.junit.Assert.*
|
||||
|
||||
/**
|
||||
* Example local unit test, which will execute on the development machine (host).
|
||||
*
|
||||
* See [testing documentation](http://d.android.com/tools/testing).
|
||||
*/
|
||||
class ExampleUnitTest {
|
||||
@Test
|
||||
fun addition_isCorrect() {
|
||||
assertEquals(4, 2 + 2)
|
||||
}
|
||||
}
|
@ -0,0 +1,16 @@
|
||||
// Copyright 2019-2022 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
use std::process::exit;
|
||||
|
||||
fn main() {
|
||||
if let Err(error) = tauri_build::mobile::PluginBuilder::new()
|
||||
.android_path("android")
|
||||
.ios_path("ios")
|
||||
.run()
|
||||
{
|
||||
println!("{error:#}");
|
||||
exit(1);
|
||||
}
|
||||
}
|
@ -0,0 +1,24 @@
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
|
||||
node_modules
|
||||
dist
|
||||
dist-ssr
|
||||
*.local
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
.idea
|
||||
.DS_Store
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
@ -0,0 +1 @@
|
||||
# Camera Example
|
@ -0,0 +1,14 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Tauri + Svelte</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="module" src="/src/main.js"></script>
|
||||
</body>
|
||||
</html>
|
@ -0,0 +1,34 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"moduleResolution": "Node",
|
||||
"target": "ESNext",
|
||||
"module": "ESNext",
|
||||
/**
|
||||
* svelte-preprocess cannot figure out whether you have
|
||||
* a value or a type, so tell TypeScript to enforce using
|
||||
* `import type` instead of `import` for Types.
|
||||
*/
|
||||
"importsNotUsedAsValues": "error",
|
||||
"isolatedModules": true,
|
||||
"resolveJsonModule": true,
|
||||
/**
|
||||
* To have warnings / errors of the Svelte compiler at the
|
||||
* correct position, enable source maps by default.
|
||||
*/
|
||||
"sourceMap": true,
|
||||
"esModuleInterop": true,
|
||||
"skipLibCheck": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"baseUrl": ".",
|
||||
/**
|
||||
* Typecheck JS in `.svelte` and `.js` files by default.
|
||||
* Disable this if you'd like to use dynamic types.
|
||||
*/
|
||||
"checkJs": true
|
||||
},
|
||||
/**
|
||||
* Use global.d.ts instead of compilerOptions.types
|
||||
* to avoid limiting type declarations.
|
||||
*/
|
||||
"include": ["src/**/*.d.ts", "src/**/*.js", "src/**/*.svelte"]
|
||||
}
|
@ -0,0 +1,23 @@
|
||||
{
|
||||
"name": "tauri-app",
|
||||
"private": true,
|
||||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vite build",
|
||||
"preview": "vite preview",
|
||||
"tauri": "tauri"
|
||||
},
|
||||
"dependencies": {
|
||||
"@tauri-apps/api": "^1.1.0",
|
||||
"tauri-plugin-camera-api": "link:../../"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@sveltejs/vite-plugin-svelte": "^1.0.1",
|
||||
"@tauri-apps/cli": "^2.0.0-alpha.0",
|
||||
"internal-ip": "^7.0.0",
|
||||
"svelte": "^3.49.0",
|
||||
"vite": "^3.0.2"
|
||||
}
|
||||
}
|
@ -0,0 +1,5 @@
|
||||
# Generated by Cargo
|
||||
# will have compiled files and executables
|
||||
/target/
|
||||
|
||||
.cargo
|
@ -0,0 +1,27 @@
|
||||
workspace = {}
|
||||
|
||||
[package]
|
||||
name = "app"
|
||||
version = "0.0.0"
|
||||
description = "A Tauri App"
|
||||
authors = ["you"]
|
||||
license = ""
|
||||
repository = ""
|
||||
edition = "2021"
|
||||
rust-version = "1.64"
|
||||
|
||||
[lib]
|
||||
crate-type = ["staticlib", "cdylib", "rlib"]
|
||||
|
||||
[build-dependencies]
|
||||
tauri-build = { git = "https://github.com/tauri-apps/tauri", branch = "next", features = [] }
|
||||
|
||||
[dependencies]
|
||||
serde_json = "1.0"
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
tauri = { git = "https://github.com/tauri-apps/tauri", branch = "next", features = ["api-all"] }
|
||||
tauri-plugin-camera = { path = "../../../" }
|
||||
|
||||
[features]
|
||||
# DO NOT remove this
|
||||
custom-protocol = [ "tauri/custom-protocol" ]
|
@ -0,0 +1,3 @@
|
||||
fn main() {
|
||||
tauri_build::build()
|
||||
}
|
@ -0,0 +1,12 @@
|
||||
# EditorConfig is awesome: https://EditorConfig.org
|
||||
|
||||
# top-most EditorConfig file
|
||||
root = true
|
||||
|
||||
[*]
|
||||
indent_style = space
|
||||
indent_size = 2
|
||||
end_of_line = lf
|
||||
charset = utf-8
|
||||
trim_trailing_whitespace = false
|
||||
insert_final_newline = false
|
@ -0,0 +1,18 @@
|
||||
*.iml
|
||||
.gradle
|
||||
/local.properties
|
||||
/.idea/caches
|
||||
/.idea/libraries
|
||||
/.idea/modules.xml
|
||||
/.idea/workspace.xml
|
||||
/.idea/navEditor.xml
|
||||
/.idea/assetWizardSettings.xml
|
||||
.DS_Store
|
||||
build
|
||||
/captures
|
||||
.externalNativeBuild
|
||||
.cxx
|
||||
local.properties
|
||||
|
||||
/tauri-plugins
|
||||
/tauri-api
|
@ -0,0 +1 @@
|
||||
/src/main/java/app/tauri/app/generated
|
@ -0,0 +1,117 @@
|
||||
plugins {
|
||||
id("com.android.application")
|
||||
id("org.jetbrains.kotlin.android")
|
||||
id("rustPlugin")
|
||||
}
|
||||
|
||||
android {
|
||||
compileSdk = 33
|
||||
defaultConfig {
|
||||
manifestPlaceholders["usesCleartextTraffic"] = "false"
|
||||
applicationId = "app.tauri.app"
|
||||
minSdk = 24
|
||||
targetSdk = 33
|
||||
versionCode = 1
|
||||
versionName = "1.0"
|
||||
}
|
||||
sourceSets.getByName("main") {
|
||||
// Vulkan validation layers
|
||||
val ndkHome = System.getenv("NDK_HOME")
|
||||
jniLibs.srcDir("${ndkHome}/sources/third_party/vulkan/src/build-android/jniLibs")
|
||||
}
|
||||
buildTypes {
|
||||
getByName("debug") {
|
||||
manifestPlaceholders["usesCleartextTraffic"] = "true"
|
||||
isDebuggable = true
|
||||
isJniDebuggable = true
|
||||
isMinifyEnabled = false
|
||||
packagingOptions {
|
||||
jniLibs.keepDebugSymbols.add("*/arm64-v8a/*.so")
|
||||
|
||||
jniLibs.keepDebugSymbols.add("*/armeabi-v7a/*.so")
|
||||
|
||||
jniLibs.keepDebugSymbols.add("*/x86/*.so")
|
||||
|
||||
jniLibs.keepDebugSymbols.add("*/x86_64/*.so")
|
||||
}
|
||||
}
|
||||
getByName("release") {
|
||||
isMinifyEnabled = true
|
||||
val proguards = fileTree(".") {
|
||||
include("*.pro")
|
||||
}
|
||||
proguardFiles(*proguards.toList().toTypedArray())
|
||||
}
|
||||
}
|
||||
flavorDimensions.add("abi")
|
||||
productFlavors {
|
||||
create("universal") {
|
||||
val abiList = findProperty("abiList") as? String
|
||||
|
||||
dimension = "abi"
|
||||
ndk {
|
||||
abiFilters += abiList?.split(",")?.map { it.trim() } ?: listOf( "arm64-v8a", "armeabi-v7a", "x86", "x86_64",
|
||||
)
|
||||
}
|
||||
}
|
||||
create("arm64") {
|
||||
dimension = "abi"
|
||||
ndk {
|
||||
abiFilters += listOf("arm64-v8a")
|
||||
}
|
||||
}
|
||||
|
||||
create("arm") {
|
||||
dimension = "abi"
|
||||
ndk {
|
||||
abiFilters += listOf("armeabi-v7a")
|
||||
}
|
||||
}
|
||||
|
||||
create("x86") {
|
||||
dimension = "abi"
|
||||
ndk {
|
||||
abiFilters += listOf("x86")
|
||||
}
|
||||
}
|
||||
|
||||
create("x86_64") {
|
||||
dimension = "abi"
|
||||
ndk {
|
||||
abiFilters += listOf("x86_64")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
assetPacks += mutableSetOf()
|
||||
namespace = "app.tauri.app"
|
||||
}
|
||||
|
||||
rust {
|
||||
rootDirRel = "../../../../"
|
||||
targets = listOf("aarch64", "armv7", "i686", "x86_64")
|
||||
arches = listOf("arm64", "arm", "x86", "x86_64")
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation("androidx.webkit:webkit:1.5.0")
|
||||
implementation("androidx.appcompat:appcompat:1.5.1")
|
||||
implementation("com.google.android.material:material:1.7.0")
|
||||
testImplementation("junit:junit:4.13.2")
|
||||
androidTestImplementation("androidx.test.ext:junit:1.1.4")
|
||||
androidTestImplementation("androidx.test.espresso:espresso-core:3.5.0")
|
||||
implementation(project(":tauri-android"))
|
||||
}
|
||||
|
||||
apply(from = "tauri.build.gradle.kts")
|
||||
|
||||
afterEvaluate {
|
||||
android.applicationVariants.all {
|
||||
tasks["mergeUniversalReleaseJniLibFolders"].dependsOn(tasks["rustBuildRelease"])
|
||||
tasks["mergeUniversalDebugJniLibFolders"].dependsOn(tasks["rustBuildDebug"])
|
||||
productFlavors.filter{ it.name != "universal" }.forEach { _ ->
|
||||
val archAndBuildType = name.capitalize()
|
||||
tasks["merge${archAndBuildType}JniLibFolders"].dependsOn(tasks["rustBuild${archAndBuildType}"])
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,21 @@
|
||||
# Add project specific ProGuard rules here.
|
||||
# You can control the set of applied configuration files using the
|
||||
# proguardFiles setting in build.gradle.
|
||||
#
|
||||
# For more details, see
|
||||
# http://developer.android.com/guide/developing/tools/proguard.html
|
||||
|
||||
# If your project uses WebView with JS, uncomment the following
|
||||
# and specify the fully qualified class name to the JavaScript interface
|
||||
# class:
|
||||
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
|
||||
# public *;
|
||||
#}
|
||||
|
||||
# Uncomment this to preserve the line number information for
|
||||
# debugging stack traces.
|
||||
#-keepattributes SourceFile,LineNumberTable
|
||||
|
||||
# If you keep the line number information, uncomment this to
|
||||
# hide the original source file name.
|
||||
#-renamesourcefileattribute SourceFile
|
@ -0,0 +1,24 @@
|
||||
# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
|
||||
|
||||
-keep class app.tauri.app.TauriActivity {
|
||||
getAppClass(...);
|
||||
getVersion();
|
||||
}
|
||||
|
||||
-keep class app.tauri.app.RustWebView {
|
||||
public <init>(...);
|
||||
loadUrlMainThread(...);
|
||||
}
|
||||
|
||||
-keep class app.tauri.app.Ipc {
|
||||
public <init>(...);
|
||||
@android.webkit.JavascriptInterface public <methods>;
|
||||
}
|
||||
|
||||
-keep class app.tauri.app.RustWebChromeClient,app.tauri.app.RustWebViewClient {
|
||||
public <init>(...);
|
||||
}
|
||||
|
||||
-keep class app.tauri.app.MainActivity {
|
||||
public getPluginManager();
|
||||
}
|
@ -0,0 +1,34 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
|
||||
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
|
||||
<application
|
||||
android:icon="@mipmap/ic_launcher"
|
||||
android:label="@string/app_name"
|
||||
android:theme="@style/Theme.app"
|
||||
android:usesCleartextTraffic="${usesCleartextTraffic}">
|
||||
<activity
|
||||
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|smallestScreenSize|screenLayout|uiMode"
|
||||
android:launchMode="singleTask"
|
||||
android:label="@string/main_activity_title"
|
||||
android:name=".MainActivity"
|
||||
android:exported="true">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<provider
|
||||
android:name="androidx.core.content.FileProvider"
|
||||
android:authorities="${applicationId}.fileprovider"
|
||||
android:exported="false"
|
||||
android:grantUriPermissions="true">
|
||||
<meta-data
|
||||
android:name="android.support.FILE_PROVIDER_PATHS"
|
||||
android:resource="@xml/file_paths" />
|
||||
</provider>
|
||||
</application>
|
||||
</manifest>
|
@ -0,0 +1,7 @@
|
||||
package app.tauri.app
|
||||
|
||||
import app.tauri.plugin.PluginManager
|
||||
|
||||
class MainActivity : TauriActivity() {
|
||||
var pluginManager: PluginManager = PluginManager(this)
|
||||
}
|
@ -0,0 +1 @@
|
||||
/home/lucas/projects/tauri/plugins-workspace/plugins/camera/examples/tauri-app/src-tauri/target/aarch64-linux-android/debug/libapp.so
|
@ -0,0 +1 @@
|
||||
/home/lucas/projects/tauri/plugins-workspace/plugins/camera/examples/tauri-app/src-tauri/target/i686-linux-android/debug/libapp.so
|
@ -0,0 +1,30 @@
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:aapt="http://schemas.android.com/aapt"
|
||||
android:width="108dp"
|
||||
android:height="108dp"
|
||||
android:viewportWidth="108"
|
||||
android:viewportHeight="108">
|
||||
<path android:pathData="M31,63.928c0,0 6.4,-11 12.1,-13.1c7.2,-2.6 26,-1.4 26,-1.4l38.1,38.1L107,108.928l-32,-1L31,63.928z">
|
||||
<aapt:attr name="android:fillColor">
|
||||
<gradient
|
||||
android:endX="85.84757"
|
||||
android:endY="92.4963"
|
||||
android:startX="42.9492"
|
||||
android:startY="49.59793"
|
||||
android:type="linear">
|
||||
<item
|
||||
android:color="#44000000"
|
||||
android:offset="0.0" />
|
||||
<item
|
||||
android:color="#00000000"
|
||||
android:offset="1.0" />
|
||||
</gradient>
|
||||
</aapt:attr>
|
||||
</path>
|
||||
<path
|
||||
android:fillColor="#FFFFFF"
|
||||
android:fillType="nonZero"
|
||||
android:pathData="M65.3,45.828l3.8,-6.6c0.2,-0.4 0.1,-0.9 -0.3,-1.1c-0.4,-0.2 -0.9,-0.1 -1.1,0.3l-3.9,6.7c-6.3,-2.8 -13.4,-2.8 -19.7,0l-3.9,-6.7c-0.2,-0.4 -0.7,-0.5 -1.1,-0.3C38.8,38.328 38.7,38.828 38.9,39.228l3.8,6.6C36.2,49.428 31.7,56.028 31,63.928h46C76.3,56.028 71.8,49.428 65.3,45.828zM43.4,57.328c-0.8,0 -1.5,-0.5 -1.8,-1.2c-0.3,-0.7 -0.1,-1.5 0.4,-2.1c0.5,-0.5 1.4,-0.7 2.1,-0.4c0.7,0.3 1.2,1 1.2,1.8C45.3,56.528 44.5,57.328 43.4,57.328L43.4,57.328zM64.6,57.328c-0.8,0 -1.5,-0.5 -1.8,-1.2s-0.1,-1.5 0.4,-2.1c0.5,-0.5 1.4,-0.7 2.1,-0.4c0.7,0.3 1.2,1 1.2,1.8C66.5,56.528 65.6,57.328 64.6,57.328L64.6,57.328z"
|
||||
android:strokeWidth="1"
|
||||
android:strokeColor="#00000000" />
|
||||
</vector>
|
@ -0,0 +1,170 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="108dp"
|
||||
android:height="108dp"
|
||||
android:viewportWidth="108"
|
||||
android:viewportHeight="108">
|
||||
<path
|
||||
android:fillColor="#3DDC84"
|
||||
android:pathData="M0,0h108v108h-108z" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M9,0L9,108"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M19,0L19,108"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M29,0L29,108"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M39,0L39,108"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M49,0L49,108"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M59,0L59,108"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M69,0L69,108"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M79,0L79,108"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M89,0L89,108"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M99,0L99,108"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M0,9L108,9"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M0,19L108,19"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M0,29L108,29"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M0,39L108,39"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M0,49L108,49"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M0,59L108,59"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M0,69L108,69"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M0,79L108,79"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M0,89L108,89"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M0,99L108,99"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M19,29L89,29"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M19,39L89,39"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M19,49L89,49"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M19,59L89,59"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M19,69L89,69"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M19,79L89,79"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M29,19L29,89"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M39,19L39,89"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M49,19L49,89"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M59,19L59,89"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M69,19L69,89"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M79,19L79,89"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
</vector>
|
@ -0,0 +1,18 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:app="http://schemas.android.com/apk/res-auto"
|
||||
xmlns:tools="http://schemas.android.com/tools"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"
|
||||
tools:context=".MainActivity">
|
||||
|
||||
<TextView
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="Hello World!"
|
||||
app:layout_constraintBottom_toBottomOf="parent"
|
||||
app:layout_constraintLeft_toLeftOf="parent"
|
||||
app:layout_constraintRight_toRightOf="parent"
|
||||
app:layout_constraintTop_toTopOf="parent" />
|
||||
|
||||
</androidx.constraintlayout.widget.ConstraintLayout>
|
After Width: | Height: | Size: 3.4 KiB |
After Width: | Height: | Size: 14 KiB |
After Width: | Height: | Size: 3.4 KiB |
After Width: | Height: | Size: 3.3 KiB |
After Width: | Height: | Size: 8.9 KiB |
After Width: | Height: | Size: 3.3 KiB |
After Width: | Height: | Size: 7.8 KiB |
After Width: | Height: | Size: 18 KiB |
After Width: | Height: | Size: 7.8 KiB |
After Width: | Height: | Size: 12 KiB |
After Width: | Height: | Size: 29 KiB |
After Width: | Height: | Size: 12 KiB |
After Width: | Height: | Size: 16 KiB |
After Width: | Height: | Size: 40 KiB |
After Width: | Height: | Size: 16 KiB |
@ -0,0 +1,16 @@
|
||||
<resources xmlns:tools="http://schemas.android.com/tools">
|
||||
<!-- Base application theme. -->
|
||||
<style name="Theme.app" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
|
||||
<!-- Primary brand color. -->
|
||||
<item name="colorPrimary">@color/purple_200</item>
|
||||
<item name="colorPrimaryVariant">@color/purple_700</item>
|
||||
<item name="colorOnPrimary">@color/black</item>
|
||||
<!-- Secondary brand color. -->
|
||||
<item name="colorSecondary">@color/teal_200</item>
|
||||
<item name="colorSecondaryVariant">@color/teal_200</item>
|
||||
<item name="colorOnSecondary">@color/black</item>
|
||||
<!-- Status bar color. -->
|
||||
<item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item>
|
||||
<!-- Customize your theme here. -->
|
||||
</style>
|
||||
</resources>
|
@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<color name="purple_200">#FFBB86FC</color>
|
||||
<color name="purple_500">#FF6200EE</color>
|
||||
<color name="purple_700">#FF3700B3</color>
|
||||
<color name="teal_200">#FF03DAC5</color>
|
||||
<color name="teal_700">#FF018786</color>
|
||||
<color name="black">#FF000000</color>
|
||||
<color name="white">#FFFFFFFF</color>
|
||||
</resources>
|
@ -0,0 +1,4 @@
|
||||
<resources>
|
||||
<string name="app_name">Tauri Camera</string>
|
||||
<string name="main_activity_title">Camera</string>
|
||||
</resources>
|
@ -0,0 +1,16 @@
|
||||
<resources xmlns:tools="http://schemas.android.com/tools">
|
||||
<!-- Base application theme. -->
|
||||
<style name="Theme.app" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
|
||||
<!-- Primary brand color. -->
|
||||
<item name="colorPrimary">@color/purple_500</item>
|
||||
<item name="colorPrimaryVariant">@color/purple_700</item>
|
||||
<item name="colorOnPrimary">@color/white</item>
|
||||
<!-- Secondary brand color. -->
|
||||
<item name="colorSecondary">@color/teal_200</item>
|
||||
<item name="colorSecondaryVariant">@color/teal_700</item>
|
||||
<item name="colorOnSecondary">@color/black</item>
|
||||
<!-- Status bar color. -->
|
||||
<item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item>
|
||||
<!-- Customize your theme here. -->
|
||||
</style>
|
||||
</resources>
|
@ -0,0 +1,5 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<paths xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<external-path name="my_images" path="." />
|
||||
<cache-path name="my_cache_images" path="." />
|
||||
</paths>
|
@ -0,0 +1,8 @@
|
||||
// THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
|
||||
|
||||
val implementation by configurations
|
||||
|
||||
dependencies {
|
||||
implementation(project(":tauri-plugin-camera"))
|
||||
|
||||
}
|
@ -0,0 +1,25 @@
|
||||
// Top-level build file where you can add configuration options common to all sub-projects/modules.
|
||||
buildscript {
|
||||
repositories {
|
||||
google()
|
||||
mavenCentral()
|
||||
}
|
||||
dependencies {
|
||||
classpath("com.android.tools.build:gradle:7.3.1")
|
||||
classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:1.6.10")
|
||||
// NOTE: Do not place your application dependencies here; they belong
|
||||
// in the individual module build.gradle files
|
||||
}
|
||||
}
|
||||
|
||||
allprojects {
|
||||
repositories {
|
||||
google()
|
||||
mavenCentral()
|
||||
}
|
||||
}
|
||||
|
||||
tasks.register("clean").configure {
|
||||
delete("build")
|
||||
}
|
||||
|
@ -0,0 +1,23 @@
|
||||
plugins {
|
||||
`kotlin-dsl`
|
||||
}
|
||||
|
||||
gradlePlugin {
|
||||
plugins {
|
||||
create("pluginsForCoolKids") {
|
||||
id = "rustPlugin"
|
||||
implementationClass = "app.tauri.RustPlugin"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
repositories {
|
||||
google()
|
||||
mavenCentral()
|
||||
}
|
||||
|
||||
dependencies {
|
||||
compileOnly(gradleApi())
|
||||
implementation("com.android.tools.build:gradle:7.3.1")
|
||||
}
|
||||
|
@ -0,0 +1,43 @@
|
||||
package app.tauri
|
||||
|
||||
import java.io.File
|
||||
import org.gradle.api.DefaultTask
|
||||
import org.gradle.api.GradleException
|
||||
import org.gradle.api.logging.LogLevel
|
||||
import org.gradle.api.tasks.Input
|
||||
import org.gradle.api.tasks.InputDirectory
|
||||
import org.gradle.api.tasks.PathSensitive
|
||||
import org.gradle.api.tasks.PathSensitivity
|
||||
import org.gradle.api.tasks.TaskAction
|
||||
|
||||
open class BuildTask : DefaultTask() {
|
||||
@InputDirectory
|
||||
@PathSensitive(PathSensitivity.RELATIVE)
|
||||
var rootDirRel: File? = null
|
||||
@Input
|
||||
var target: String? = null
|
||||
@Input
|
||||
var release: Boolean? = null
|
||||
|
||||
@TaskAction
|
||||
fun build() {
|
||||
val rootDirRel = rootDirRel ?: throw GradleException("rootDirRel cannot be null")
|
||||
val target = target ?: throw GradleException("target cannot be null")
|
||||
val release = release ?: throw GradleException("release cannot be null")
|
||||
project.exec {
|
||||
workingDir(File(project.projectDir, rootDirRel.path))
|
||||
executable("""pnpm""")
|
||||
args(listOf("run", "tauri", "android", "android-studio-script"))
|
||||
if (project.logger.isEnabled(LogLevel.DEBUG)) {
|
||||
args("-vv")
|
||||
} else if (project.logger.isEnabled(LogLevel.INFO)) {
|
||||
args("-v")
|
||||
}
|
||||
if (release) {
|
||||
args("--release")
|
||||
}
|
||||
args(listOf("--target", target))
|
||||
}.assertNormalExitValue()
|
||||
}
|
||||
}
|
||||
|
@ -0,0 +1,59 @@
|
||||
package app.tauri
|
||||
|
||||
import org.gradle.api.DefaultTask
|
||||
import org.gradle.api.GradleException
|
||||
import org.gradle.api.Plugin
|
||||
import org.gradle.api.Project
|
||||
import java.io.File
|
||||
import java.util.*
|
||||
|
||||
const val TASK_GROUP = "rust"
|
||||
|
||||
open class Config {
|
||||
var rootDirRel: String? = null
|
||||
var targets: List<String>? = null
|
||||
var arches: List<String>? = null
|
||||
}
|
||||
|
||||
open class RustPlugin : Plugin<Project> {
|
||||
private lateinit var config: Config
|
||||
|
||||
override fun apply(project: Project) {
|
||||
config = project.extensions.create("rust", Config::class.java)
|
||||
project.afterEvaluate {
|
||||
if (config.targets == null) {
|
||||
throw GradleException("targets cannot be null")
|
||||
}
|
||||
if (config.arches == null) {
|
||||
throw GradleException("arches cannot be null")
|
||||
}
|
||||
for (profile in listOf("debug", "release")) {
|
||||
val profileCapitalized = profile.capitalize(Locale.ROOT)
|
||||
val buildTask = project.tasks.maybeCreate(
|
||||
"rustBuild$profileCapitalized",
|
||||
DefaultTask::class.java
|
||||
).apply {
|
||||
group = TASK_GROUP
|
||||
description = "Build dynamic library in $profile mode for all targets"
|
||||
}
|
||||
for (targetPair in config.targets!!.withIndex()) {
|
||||
val targetName = targetPair.value
|
||||
val targetArch = config.arches!![targetPair.index]
|
||||
val targetArchCapitalized = targetArch.capitalize(Locale.ROOT)
|
||||
val targetBuildTask = project.tasks.maybeCreate(
|
||||
"rustBuild$targetArchCapitalized$profileCapitalized",
|
||||
BuildTask::class.java
|
||||
).apply {
|
||||
group = TASK_GROUP
|
||||
description = "Build dynamic library in $profile mode for $targetArch"
|
||||
rootDirRel = config.rootDirRel?.let { File(it) }
|
||||
target = targetName
|
||||
release = profile == "release"
|
||||
}
|
||||
buildTask.dependsOn(targetBuildTask)
|
||||
project.tasks.findByName("preBuild")?.mustRunAfter(targetBuildTask)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,23 @@
|
||||
# Project-wide Gradle settings.
|
||||
# IDE (e.g. Android Studio) users:
|
||||
# Gradle settings configured through the IDE *will override*
|
||||
# any settings specified in this file.
|
||||
# For more details on how to configure your build environment visit
|
||||
# http://www.gradle.org/docs/current/userguide/build_environment.html
|
||||
# Specifies the JVM arguments used for the daemon process.
|
||||
# The setting is particularly useful for tweaking memory settings.
|
||||
org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
|
||||
# When configured, Gradle will run in incubating parallel mode.
|
||||
# This option should only be used with decoupled projects. More details, visit
|
||||
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
|
||||
# org.gradle.parallel=true
|
||||
# AndroidX package structure to make it clearer which packages are bundled with the
|
||||
# Android operating system, and which are packaged with your app"s APK
|
||||
# https://developer.android.com/topic/libraries/support-library/androidx-rn
|
||||
android.useAndroidX=true
|
||||
# Kotlin code style for this project: "official" or "obsolete":
|
||||
kotlin.code.style=official
|
||||
# Enables namespacing of each library's R class so that its R class includes only the
|
||||
# resources declared in the library itself and none from the library's dependencies,
|
||||
# thereby reducing the size of the R class for that library
|
||||
android.nonTransitiveRClass=true
|
@ -0,0 +1,6 @@
|
||||
#Tue May 10 19:22:52 CST 2022
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-7.4-bin.zip
|
||||
distributionPath=wrapper/dists
|
||||
zipStorePath=wrapper/dists
|
||||
zipStoreBase=GRADLE_USER_HOME
|
@ -0,0 +1,185 @@
|
||||
#!/usr/bin/env sh
|
||||
|
||||
#
|
||||
# Copyright 2015 the original author or 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 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='"-Xmx64m" "-Xms64m"'
|
||||
|
||||
# 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 or MSYS, switch paths to Windows format before running java
|
||||
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; 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=`expr $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"
|
||||
|
||||
exec "$JAVACMD" "$@"
|
@ -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
|
@ -0,0 +1,6 @@
|
||||
include ':app'
|
||||
|
||||
include ':tauri-android'
|
||||
project(':tauri-android').projectDir = new File('./tauri-api')
|
||||
|
||||
apply from: 'tauri.settings.gradle'
|
@ -0,0 +1,3 @@
|
||||
// THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
|
||||
include ':tauri-plugin-camera'
|
||||
project(':tauri-plugin-camera').projectDir = new File('./tauri-plugins/tauri-plugin-camera')
|
After Width: | Height: | Size: 11 KiB |
After Width: | Height: | Size: 23 KiB |
After Width: | Height: | Size: 2.2 KiB |
After Width: | Height: | Size: 37 KiB |
After Width: | Height: | Size: 49 KiB |
@ -0,0 +1,11 @@
|
||||
// Copyright 2019-2022 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#[cfg_attr(mobile, tauri::mobile_entry_point)]
|
||||
pub fn run() {
|
||||
tauri::Builder::default()
|
||||
.plugin(tauri_plugin_camera::init())
|
||||
.run(tauri::generate_context!())
|
||||
.expect("error while running tauri application");
|
||||
}
|
@ -0,0 +1,66 @@
|
||||
{
|
||||
"build": {
|
||||
"beforeDevCommand": "pnpm dev",
|
||||
"beforeBuildCommand": "pnpm build",
|
||||
"devPath": "http://localhost:5173",
|
||||
"distDir": "../dist",
|
||||
"withGlobalTauri": false
|
||||
},
|
||||
"package": {
|
||||
"productName": "app",
|
||||
"version": "0.0.0"
|
||||
},
|
||||
"tauri": {
|
||||
"allowlist": {
|
||||
"all": true
|
||||
},
|
||||
"bundle": {
|
||||
"active": true,
|
||||
"category": "DeveloperTool",
|
||||
"copyright": "",
|
||||
"deb": {
|
||||
"depends": []
|
||||
},
|
||||
"externalBin": [],
|
||||
"icon": [
|
||||
"icons/32x32.png",
|
||||
"icons/128x128.png",
|
||||
"icons/128x128@2x.png",
|
||||
"icons/icon.icns",
|
||||
"icons/icon.ico"
|
||||
],
|
||||
"identifier": "app.tauri.camera-example",
|
||||
"longDescription": "",
|
||||
"macOS": {
|
||||
"entitlements": null,
|
||||
"exceptionDomain": "",
|
||||
"frameworks": [],
|
||||
"providerShortName": null,
|
||||
"signingIdentity": null
|
||||
},
|
||||
"resources": [],
|
||||
"shortDescription": "",
|
||||
"targets": "all",
|
||||
"windows": {
|
||||
"certificateThumbprint": null,
|
||||
"digestAlgorithm": "sha256",
|
||||
"timestampUrl": ""
|
||||
}
|
||||
},
|
||||
"security": {
|
||||
"csp": null
|
||||
},
|
||||
"updater": {
|
||||
"active": false
|
||||
},
|
||||
"windows": [
|
||||
{
|
||||
"fullscreen": false,
|
||||
"height": 600,
|
||||
"resizable": true,
|
||||
"title": "tauri-app",
|
||||
"width": 800
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
@ -0,0 +1,9 @@
|
||||
<script>
|
||||
import GetPhoto from "./lib/GetPhoto.svelte";
|
||||
</script>
|
||||
|
||||
<main class="container">
|
||||
<div class="row">
|
||||
<GetPhoto />
|
||||
</div>
|
||||
</main>
|
@ -0,0 +1,31 @@
|
||||
<script>
|
||||
import { getPhoto, ResultType, Source } from "tauri-plugin-camera-api";
|
||||
|
||||
let imageSrc = "";
|
||||
|
||||
async function get() {
|
||||
try {
|
||||
const image = await getPhoto({
|
||||
resultType: ResultType.Base64,
|
||||
source: Source.Camera,
|
||||
});
|
||||
imageSrc = `data:image/png;base64, ${image.data}`;
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<div>
|
||||
{#if imageSrc}
|
||||
<img src={imageSrc} alt="Selected" />
|
||||
{/if}
|
||||
<button on:click={get}> Get photo </button>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
img {
|
||||
max-width: 100vw;
|
||||
max-height: 80vh;
|
||||
}
|
||||
</style>
|
@ -0,0 +1,8 @@
|
||||
import "./style.css";
|
||||
import App from "./App.svelte";
|
||||
|
||||
const app = new App({
|
||||
target: document.getElementById("app"),
|
||||
});
|
||||
|
||||
export default app;
|
@ -0,0 +1,102 @@
|
||||
:root {
|
||||
font-family: Inter, Avenir, Helvetica, Arial, sans-serif;
|
||||
font-size: 16px;
|
||||
line-height: 24px;
|
||||
font-weight: 400;
|
||||
|
||||
color: #0f0f0f;
|
||||
background-color: #f6f6f6;
|
||||
|
||||
font-synthesis: none;
|
||||
text-rendering: optimizeLegibility;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
-webkit-text-size-adjust: 100%;
|
||||
}
|
||||
|
||||
.container {
|
||||
margin: 0;
|
||||
padding-top: 10vh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: center;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.logo {
|
||||
height: 6em;
|
||||
padding: 1.5em;
|
||||
will-change: filter;
|
||||
transition: 0.75s;
|
||||
}
|
||||
|
||||
.logo.tauri:hover {
|
||||
filter: drop-shadow(0 0 2em #24c8db);
|
||||
}
|
||||
|
||||
.row {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
a {
|
||||
font-weight: 500;
|
||||
color: #646cff;
|
||||
text-decoration: inherit;
|
||||
}
|
||||
|
||||
a:hover {
|
||||
color: #535bf2;
|
||||
}
|
||||
|
||||
h1 {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
input,
|
||||
button {
|
||||
border-radius: 8px;
|
||||
border: 1px solid transparent;
|
||||
padding: 0.6em 1.2em;
|
||||
font-size: 1em;
|
||||
font-weight: 500;
|
||||
font-family: inherit;
|
||||
color: #0f0f0f;
|
||||
background-color: #ffffff;
|
||||
transition: border-color 0.25s;
|
||||
box-shadow: 0 2px 2px rgba(0, 0, 0, 0.2);
|
||||
}
|
||||
|
||||
button {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
button:hover {
|
||||
border-color: #396cd8;
|
||||
}
|
||||
|
||||
input,
|
||||
button {
|
||||
outline: none;
|
||||
}
|
||||
|
||||
#greet-input {
|
||||
margin-right: 5px;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
color: #f6f6f6;
|
||||
background-color: #2f2f2f;
|
||||
}
|
||||
|
||||
a:hover {
|
||||
color: #24c8db;
|
||||
}
|
||||
|
||||
input,
|
||||
button {
|
||||
color: #ffffff;
|
||||
background-color: #0f0f0f98;
|
||||
}
|
||||
}
|
@ -0,0 +1,2 @@
|
||||
/// <reference types="svelte" />
|
||||
/// <reference types="vite/client" />
|
@ -0,0 +1,40 @@
|
||||
import { defineConfig } from "vite";
|
||||
import { svelte } from "@sveltejs/vite-plugin-svelte";
|
||||
import { internalIpV4 } from "internal-ip";
|
||||
|
||||
// https://vitejs.dev/config/
|
||||
export default defineConfig(async () => {
|
||||
const host = process.env.TAURI_PLATFORM === 'android' || process.env.TAURI_PLATFORM === 'ios' ? (await internalIpV4()) : 'localhost'
|
||||
return {
|
||||
plugins: [svelte()],
|
||||
|
||||
// Vite optons tailored for Tauri development and only applied in `tauri dev` or `tauri build`
|
||||
// prevent vite from obscuring rust errors
|
||||
clearScreen: false,
|
||||
// tauri expects a fixed port, fail if that port is not available
|
||||
server: {
|
||||
host: '0.0.0.0',
|
||||
port: 5173,
|
||||
strictPort: true,
|
||||
hmr: {
|
||||
protocol: 'ws',
|
||||
host,
|
||||
port: 5183
|
||||
},
|
||||
fs: {
|
||||
allow: ['.', '../../tooling/api/dist']
|
||||
}
|
||||
},
|
||||
// to make use of `TAURI_DEBUG` and other env variables
|
||||
// https://tauri.studio/v1/api/config#buildconfig.beforedevcommand
|
||||
envPrefix: ["VITE_", "TAURI_"],
|
||||
build: {
|
||||
// Tauri supports es2021
|
||||
target: ["es2021", "chrome100", "safari13"],
|
||||
// don't minify for debug builds
|
||||
minify: !process.env.TAURI_DEBUG ? "esbuild" : false,
|
||||
// produce sourcemaps for debug builds
|
||||
sourcemap: !!process.env.TAURI_DEBUG,
|
||||
},
|
||||
}
|
||||
});
|
@ -0,0 +1,50 @@
|
||||
// Copyright 2019-2022 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
import { invoke } from '@tauri-apps/api/tauri'
|
||||
|
||||
export enum Source {
|
||||
Prompt = 'PROMPT',
|
||||
Camera = 'CAMERA',
|
||||
Photos = 'PHOTOS'
|
||||
}
|
||||
|
||||
export enum ResultType {
|
||||
Uri = 'uri',
|
||||
Base64 = 'base64',
|
||||
DataUrl = 'dataUrl'
|
||||
}
|
||||
|
||||
export enum CameraDirection {
|
||||
Rear = 'REAR',
|
||||
Front = 'FRONT'
|
||||
}
|
||||
|
||||
export interface ImageOptions {
|
||||
quality?: number
|
||||
allowEditing?: boolean
|
||||
resultType?: ResultType
|
||||
saveToGallery?: boolean
|
||||
width?: number
|
||||
height?: number
|
||||
correctOrientation?: boolean
|
||||
source?: Source
|
||||
direction?: CameraDirection
|
||||
presentationStyle?: 'fullscreen' | 'popover'
|
||||
promptLabelHeader?: string
|
||||
promptLabelCancel?: string
|
||||
promptLabelPhoto?: string
|
||||
promptLabelPicture?: string
|
||||
}
|
||||
|
||||
export interface Image {
|
||||
data: string
|
||||
assetUrl?: string
|
||||
format: string
|
||||
saved: boolean
|
||||
exif: unknown
|
||||
}
|
||||
|
||||
export async function getPhoto(options?: ImageOptions): Promise<Image> {
|
||||
return await invoke('plugin:camera|getPhoto', { ...options })
|
||||
}
|
@ -0,0 +1,11 @@
|
||||
.DS_Store
|
||||
/.build
|
||||
/Packages
|
||||
/*.xcodeproj
|
||||
xcuserdata/
|
||||
DerivedData/
|
||||
.swiftpm/config/registries.json
|
||||
.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata
|
||||
.netrc
|
||||
Package.resolved
|
||||
/tauri-api
|
@ -0,0 +1,31 @@
|
||||
// swift-tools-version:5.7
|
||||
// The swift-tools-version declares the minimum version of Swift required to build this package.
|
||||
|
||||
import PackageDescription
|
||||
|
||||
let package = Package(
|
||||
name: "tauri-plugin-camera",
|
||||
platforms: [
|
||||
.iOS(.v11),
|
||||
],
|
||||
products: [
|
||||
// Products define the executables and libraries a package produces, and make them visible to other packages.
|
||||
.library(
|
||||
name: "tauri-plugin-camera",
|
||||
type: .static,
|
||||
targets: ["tauri-plugin-camera"]),
|
||||
],
|
||||
dependencies: [
|
||||
.package(name: "Tauri", path: "../../../../../core/tauri/mobile/ios-api")
|
||||
],
|
||||
targets: [
|
||||
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
|
||||
// Targets can depend on other targets in this package, and on products in packages this package depends on.
|
||||
.target(
|
||||
name: "tauri-plugin-camera",
|
||||
dependencies: [
|
||||
.byName(name: "Tauri")
|
||||
],
|
||||
path: "Sources")
|
||||
]
|
||||
)
|
@ -0,0 +1,3 @@
|
||||
# Tauri Plugin camera
|
||||
|
||||
A description of this package.
|
@ -0,0 +1,105 @@
|
||||
import UIKit
|
||||
import Photos
|
||||
|
||||
internal protocol CameraAuthorizationState {
|
||||
var authorizationState: String { get }
|
||||
}
|
||||
|
||||
extension AVAuthorizationStatus: CameraAuthorizationState {
|
||||
var authorizationState: String {
|
||||
switch self {
|
||||
case .denied, .restricted:
|
||||
return "denied"
|
||||
case .authorized:
|
||||
return "granted"
|
||||
case .notDetermined:
|
||||
fallthrough
|
||||
@unknown default:
|
||||
return "prompt"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension PHAuthorizationStatus: CameraAuthorizationState {
|
||||
var authorizationState: String {
|
||||
switch self {
|
||||
case .denied, .restricted:
|
||||
return "denied"
|
||||
case .authorized:
|
||||
return "granted"
|
||||
#if swift(>=5.3)
|
||||
// poor proxy for Xcode 12/iOS 14, should be removed once building with Xcode 12 is required
|
||||
case .limited:
|
||||
return "limited"
|
||||
#endif
|
||||
case .notDetermined:
|
||||
fallthrough
|
||||
@unknown default:
|
||||
return "prompt"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal extension PHAsset {
|
||||
/**
|
||||
Retrieves the image metadata for the asset.
|
||||
*/
|
||||
var imageData: [String: Any] {
|
||||
let options = PHImageRequestOptions()
|
||||
options.isSynchronous = true
|
||||
options.resizeMode = .none
|
||||
options.isNetworkAccessAllowed = false
|
||||
options.version = .current
|
||||
|
||||
var result: [String: Any] = [:]
|
||||
_ = PHCachingImageManager().requestImageDataAndOrientation(for: self, options: options) { (data, _, _, _) in
|
||||
if let data = data as NSData? {
|
||||
let options = [kCGImageSourceShouldCache as String: kCFBooleanFalse] as CFDictionary
|
||||
if let imgSrc = CGImageSourceCreateWithData(data, options),
|
||||
let metadata = CGImageSourceCopyPropertiesAtIndex(imgSrc, 0, options) as? [String: Any] {
|
||||
result = metadata
|
||||
}
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
internal extension UIImage {
|
||||
/**
|
||||
Generates a new image from the existing one, implicitly resetting any orientation.
|
||||
Dimensions greater than 0 will resize the image while preserving the aspect ratio.
|
||||
*/
|
||||
func reformat(to size: CGSize? = nil) -> UIImage {
|
||||
let imageHeight = self.size.height
|
||||
let imageWidth = self.size.width
|
||||
// determine the max dimensions, 0 is treated as 'no restriction'
|
||||
var maxWidth: CGFloat
|
||||
if let size = size, size.width > 0 {
|
||||
maxWidth = size.width
|
||||
} else {
|
||||
maxWidth = imageWidth
|
||||
}
|
||||
let maxHeight: CGFloat
|
||||
if let size = size, size.height > 0 {
|
||||
maxHeight = size.height
|
||||
} else {
|
||||
maxHeight = imageHeight
|
||||
}
|
||||
// adjust to preserve aspect ratio
|
||||
var targetWidth = min(imageWidth, maxWidth)
|
||||
var targetHeight = (imageHeight * targetWidth) / imageWidth
|
||||
if targetHeight > maxHeight {
|
||||
targetWidth = (imageWidth * maxHeight) / imageHeight
|
||||
targetHeight = maxHeight
|
||||
}
|
||||
// generate the new image and return
|
||||
let format: UIGraphicsImageRendererFormat = UIGraphicsImageRendererFormat.default()
|
||||
format.scale = 1.0
|
||||
format.opaque = false
|
||||
let renderer = UIGraphicsImageRenderer(size: CGSize(width: targetWidth, height: targetHeight), format: format)
|
||||
return renderer.image { (_) in
|
||||
self.draw(in: CGRect(origin: .zero, size: CGSize(width: targetWidth, height: targetHeight)))
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,576 @@
|
||||
import UIKit
|
||||
import WebKit
|
||||
import Tauri
|
||||
import Photos
|
||||
import PhotosUI
|
||||
|
||||
public class CameraPlugin: Plugin {
|
||||
private var invoke: Invoke?
|
||||
private var settings = CameraSettings()
|
||||
private let defaultSource = CameraSource.prompt
|
||||
private let defaultDirection = CameraDirection.rear
|
||||
private var multiple = false
|
||||
|
||||
private var imageCounter = 0
|
||||
|
||||
@objc override public func checkPermissions(_ invoke: Invoke) {
|
||||
var result: [String: Any] = [:]
|
||||
for permission in CameraPermissionType.allCases {
|
||||
let state: String
|
||||
switch permission {
|
||||
case .camera:
|
||||
state = AVCaptureDevice.authorizationStatus(for: .video).authorizationState
|
||||
case .photos:
|
||||
if #available(iOS 14, *) {
|
||||
state = PHPhotoLibrary.authorizationStatus(for: .readWrite).authorizationState
|
||||
} else {
|
||||
state = PHPhotoLibrary.authorizationStatus().authorizationState
|
||||
}
|
||||
}
|
||||
result[permission.rawValue] = state
|
||||
}
|
||||
invoke.resolve(result)
|
||||
}
|
||||
|
||||
@objc override public func requestPermissions(_ invoke: Invoke) {
|
||||
// get the list of desired types, if passed
|
||||
let typeList = invoke.getArray("permissions", String.self)?.compactMap({ (type) -> CameraPermissionType? in
|
||||
return CameraPermissionType(rawValue: type)
|
||||
}) ?? []
|
||||
// otherwise check everything
|
||||
let permissions: [CameraPermissionType] = (typeList.count > 0) ? typeList : CameraPermissionType.allCases
|
||||
// request the permissions
|
||||
let group = DispatchGroup()
|
||||
for permission in permissions {
|
||||
switch permission {
|
||||
case .camera:
|
||||
group.enter()
|
||||
AVCaptureDevice.requestAccess(for: .video) { _ in
|
||||
group.leave()
|
||||
}
|
||||
case .photos:
|
||||
group.enter()
|
||||
if #available(iOS 14, *) {
|
||||
PHPhotoLibrary.requestAuthorization(for: .readWrite) { (_) in
|
||||
group.leave()
|
||||
}
|
||||
} else {
|
||||
PHPhotoLibrary.requestAuthorization({ (_) in
|
||||
group.leave()
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
group.notify(queue: DispatchQueue.main) { [weak self] in
|
||||
self?.checkPermissions(invoke)
|
||||
}
|
||||
}
|
||||
|
||||
@objc func pickLimitedLibraryPhotos(_ invoke: Invoke) {
|
||||
if #available(iOS 14, *) {
|
||||
PHPhotoLibrary.requestAuthorization(for: .readWrite) { (granted) in
|
||||
if granted == .limited {
|
||||
if let viewController = self.manager.viewController {
|
||||
if #available(iOS 15, *) {
|
||||
PHPhotoLibrary.shared().presentLimitedLibraryPicker(from: viewController) { _ in
|
||||
self.getLimitedLibraryPhotos(invoke)
|
||||
}
|
||||
} else {
|
||||
PHPhotoLibrary.shared().presentLimitedLibraryPicker(from: viewController)
|
||||
invoke.resolve([
|
||||
"photos": []
|
||||
])
|
||||
}
|
||||
}
|
||||
} else {
|
||||
invoke.resolve([
|
||||
"photos": []
|
||||
])
|
||||
}
|
||||
}
|
||||
} else {
|
||||
invoke.unavailable("Not available on iOS 13")
|
||||
}
|
||||
}
|
||||
|
||||
@objc func getLimitedLibraryPhotos(_ invoke: Invoke) {
|
||||
if #available(iOS 14, *) {
|
||||
PHPhotoLibrary.requestAuthorization(for: .readWrite) { (granted) in
|
||||
if granted == .limited {
|
||||
|
||||
self.invoke = invoke
|
||||
|
||||
DispatchQueue.global(qos: .utility).async {
|
||||
let assets = PHAsset.fetchAssets(with: .image, options: nil)
|
||||
var processedImages: [ProcessedImage] = []
|
||||
|
||||
let imageManager = PHImageManager.default()
|
||||
let options = PHImageRequestOptions()
|
||||
options.deliveryMode = .highQualityFormat
|
||||
|
||||
let group = DispatchGroup()
|
||||
|
||||
for index in 0...(assets.count - 1) {
|
||||
let asset = assets.object(at: index)
|
||||
let fullSize = CGSize(width: asset.pixelWidth, height: asset.pixelHeight)
|
||||
|
||||
group.enter()
|
||||
imageManager.requestImage(for: asset, targetSize: fullSize, contentMode: .default, options: options) { image, _ in
|
||||
guard let image = image else {
|
||||
group.leave()
|
||||
return
|
||||
}
|
||||
processedImages.append(self.processedImage(from: image, with: asset.imageData))
|
||||
group.leave()
|
||||
}
|
||||
}
|
||||
|
||||
group.notify(queue: .global(qos: .utility)) { [weak self] in
|
||||
self?.returnImages(processedImages)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
invoke.resolve([
|
||||
"photos": []
|
||||
])
|
||||
}
|
||||
}
|
||||
} else {
|
||||
invoke.unavailable("Not available on iOS 13")
|
||||
}
|
||||
}
|
||||
|
||||
@objc func getPhoto(_ invoke: Invoke) {
|
||||
self.multiple = false
|
||||
self.invoke = invoke
|
||||
self.settings = cameraSettings(from: invoke)
|
||||
|
||||
// Make sure they have all the necessary info.plist settings
|
||||
if let missingUsageDescription = checkUsageDescriptions() {
|
||||
Logger.error("[PLUGIN]", "Camera", "-", missingUsageDescription)
|
||||
invoke.reject(missingUsageDescription)
|
||||
return
|
||||
}
|
||||
|
||||
DispatchQueue.main.async {
|
||||
switch self.settings.source {
|
||||
case .prompt:
|
||||
self.showPrompt()
|
||||
case .camera:
|
||||
self.showCamera()
|
||||
case .photos:
|
||||
self.showPhotos()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@objc func pickImages(_ invoke: Invoke) {
|
||||
self.multiple = true
|
||||
self.invoke = invoke
|
||||
self.settings = cameraSettings(from: invoke)
|
||||
DispatchQueue.main.async {
|
||||
self.showPhotos()
|
||||
}
|
||||
}
|
||||
|
||||
private func checkUsageDescriptions() -> String? {
|
||||
if let dict = Bundle.main.infoDictionary {
|
||||
for key in CameraPropertyListKeys.allCases where dict[key.rawValue] == nil {
|
||||
return key.missingMessage
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
private func cameraSettings(from invoke: Invoke) -> CameraSettings {
|
||||
var settings = CameraSettings()
|
||||
settings.jpegQuality = min(abs(CGFloat(invoke.getFloat("quality") ?? 100.0)) / 100.0, 1.0)
|
||||
settings.allowEditing = invoke.getBool("allowEditing") ?? false
|
||||
settings.source = CameraSource(rawValue: invoke.getString("source") ?? defaultSource.rawValue) ?? defaultSource
|
||||
settings.direction = CameraDirection(rawValue: invoke.getString("direction") ?? defaultDirection.rawValue) ?? defaultDirection
|
||||
if let typeString = invoke.getString("resultType"), let type = CameraResultType(rawValue: typeString) {
|
||||
settings.resultType = type
|
||||
}
|
||||
settings.saveToGallery = invoke.getBool("saveToGallery") ?? false
|
||||
|
||||
// Get the new image dimensions if provided
|
||||
settings.width = CGFloat(invoke.getInt("width") ?? 0)
|
||||
settings.height = CGFloat(invoke.getInt("height") ?? 0)
|
||||
if settings.width > 0 || settings.height > 0 {
|
||||
// We resize only if a dimension was provided
|
||||
settings.shouldResize = true
|
||||
}
|
||||
settings.shouldCorrectOrientation = invoke.getBool("correctOrientation") ?? true
|
||||
settings.userPromptText = CameraPromptText(title: invoke.getString("promptLabelHeader"),
|
||||
photoAction: invoke.getString("promptLabelPhoto"),
|
||||
cameraAction: invoke.getString("promptLabelPicture"),
|
||||
cancelAction: invoke.getString("promptLabelCancel"))
|
||||
if let styleString = invoke.getString("presentationStyle"), styleString == "popover" {
|
||||
settings.presentationStyle = .popover
|
||||
} else {
|
||||
settings.presentationStyle = .fullScreen
|
||||
}
|
||||
|
||||
return settings
|
||||
}
|
||||
}
|
||||
|
||||
// public delegate methods
|
||||
extension CameraPlugin: UIImagePickerControllerDelegate, UINavigationControllerDelegate, UIPopoverPresentationControllerDelegate {
|
||||
public func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
|
||||
picker.dismiss(animated: true)
|
||||
self.invoke?.reject("User cancelled photos app")
|
||||
}
|
||||
|
||||
public func popoverPresentationControllerDidDismissPopover(_ popoverPresentationController: UIPopoverPresentationController) {
|
||||
self.invoke?.reject("User cancelled photos app")
|
||||
}
|
||||
|
||||
public func presentationControllerDidDismiss(_ presentationController: UIPresentationController) {
|
||||
self.invoke?.reject("User cancelled photos app")
|
||||
}
|
||||
|
||||
public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {
|
||||
picker.dismiss(animated: true) {
|
||||
if let processedImage = self.processImage(from: info) {
|
||||
self.returnProcessedImage(processedImage)
|
||||
} else {
|
||||
self.invoke?.reject("Error processing image")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@available(iOS 14, *)
|
||||
extension CameraPlugin: PHPickerViewControllerDelegate {
|
||||
public func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
|
||||
picker.dismiss(animated: true, completion: nil)
|
||||
guard let result = results.first else {
|
||||
self.invoke?.reject("User cancelled photos app")
|
||||
return
|
||||
}
|
||||
if multiple {
|
||||
var images: [ProcessedImage] = []
|
||||
var processedCount = 0
|
||||
for img in results {
|
||||
guard img.itemProvider.canLoadObject(ofClass: UIImage.self) else {
|
||||
self.invoke?.reject("Error loading image")
|
||||
return
|
||||
}
|
||||
// extract the image
|
||||
img.itemProvider.loadObject(ofClass: UIImage.self) { [weak self] (reading, _) in
|
||||
if let image = reading as? UIImage {
|
||||
var asset: PHAsset?
|
||||
if let assetId = img.assetIdentifier {
|
||||
asset = PHAsset.fetchAssets(withLocalIdentifiers: [assetId], options: nil).firstObject
|
||||
}
|
||||
if let processedImage = self?.processedImage(from: image, with: asset?.imageData) {
|
||||
images.append(processedImage)
|
||||
}
|
||||
processedCount += 1
|
||||
if processedCount == results.count {
|
||||
self?.returnImages(images)
|
||||
}
|
||||
} else {
|
||||
self?.invoke?.reject("Error loading image")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} else {
|
||||
guard result.itemProvider.canLoadObject(ofClass: UIImage.self) else {
|
||||
self.invoke?.reject("Error loading image")
|
||||
return
|
||||
}
|
||||
// extract the image
|
||||
result.itemProvider.loadObject(ofClass: UIImage.self) { [weak self] (reading, _) in
|
||||
if let image = reading as? UIImage {
|
||||
var asset: PHAsset?
|
||||
if let assetId = result.assetIdentifier {
|
||||
asset = PHAsset.fetchAssets(withLocalIdentifiers: [assetId], options: nil).firstObject
|
||||
}
|
||||
if var processedImage = self?.processedImage(from: image, with: asset?.imageData) {
|
||||
processedImage.flags = .gallery
|
||||
self?.returnProcessedImage(processedImage)
|
||||
return
|
||||
}
|
||||
}
|
||||
self?.invoke?.reject("Error loading image")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private extension CameraPlugin {
|
||||
func returnImage(_ processedImage: ProcessedImage, isSaved: Bool) {
|
||||
guard let jpeg = processedImage.generateJPEG(with: settings.jpegQuality) else {
|
||||
self.invoke?.reject("Unable to convert image to jpeg")
|
||||
return
|
||||
}
|
||||
|
||||
if settings.resultType == CameraResultType.uri || multiple {
|
||||
guard let fileURL = try? saveTemporaryImage(jpeg),
|
||||
let webURL = manager.assetUrl(fromLocalURL: fileURL) else {
|
||||
invoke?.reject("Unable to get asset URL to file")
|
||||
return
|
||||
}
|
||||
if self.multiple {
|
||||
invoke?.resolve([
|
||||
"photos": [[
|
||||
"data": fileURL.absoluteString,
|
||||
"exif": processedImage.exifData,
|
||||
"assetUrl": webURL.absoluteString,
|
||||
"format": "jpeg"
|
||||
]]
|
||||
])
|
||||
return
|
||||
}
|
||||
invoke?.resolve([
|
||||
"data": fileURL.absoluteString,
|
||||
"exif": processedImage.exifData,
|
||||
"assetUrl": webURL.absoluteString,
|
||||
"format": "jpeg",
|
||||
"saved": isSaved
|
||||
])
|
||||
} else if settings.resultType == CameraResultType.base64 {
|
||||
self.invoke?.resolve([
|
||||
"data": jpeg.base64EncodedString(),
|
||||
"exif": processedImage.exifData,
|
||||
"format": "jpeg",
|
||||
"saved": isSaved
|
||||
])
|
||||
} else if settings.resultType == CameraResultType.dataURL {
|
||||
invoke?.resolve([
|
||||
"data": "data:image/jpeg;base64," + jpeg.base64EncodedString(),
|
||||
"exif": processedImage.exifData,
|
||||
"format": "jpeg",
|
||||
"saved": isSaved
|
||||
])
|
||||
}
|
||||
}
|
||||
|
||||
func returnImages(_ processedImages: [ProcessedImage]) {
|
||||
var photos: [JsonObject] = []
|
||||
for processedImage in processedImages {
|
||||
guard let jpeg = processedImage.generateJPEG(with: settings.jpegQuality) else {
|
||||
self.invoke?.reject("Unable to convert image to jpeg")
|
||||
return
|
||||
}
|
||||
|
||||
guard let fileURL = try? saveTemporaryImage(jpeg),
|
||||
let webURL = manager.assetUrl(fromLocalURL: fileURL) else {
|
||||
invoke?.reject("Unable to get asset URL to file")
|
||||
return
|
||||
}
|
||||
|
||||
photos.append([
|
||||
"path": fileURL.absoluteString,
|
||||
"exif": processedImage.exifData,
|
||||
"assetUrl": webURL.absoluteString,
|
||||
"format": "jpeg"
|
||||
])
|
||||
}
|
||||
invoke?.resolve([
|
||||
"photos": photos
|
||||
])
|
||||
}
|
||||
|
||||
func returnProcessedImage(_ processedImage: ProcessedImage) {
|
||||
// conditionally save the image
|
||||
if settings.saveToGallery && (processedImage.flags.contains(.edited) == true || processedImage.flags.contains(.gallery) == false) {
|
||||
_ = ImageSaver(image: processedImage.image) { error in
|
||||
var isSaved = false
|
||||
if error == nil {
|
||||
isSaved = true
|
||||
}
|
||||
self.returnImage(processedImage, isSaved: isSaved)
|
||||
}
|
||||
} else {
|
||||
self.returnImage(processedImage, isSaved: false)
|
||||
}
|
||||
}
|
||||
|
||||
func showPrompt() {
|
||||
// Build the action sheet
|
||||
let alert = UIAlertController(title: settings.userPromptText.title, message: nil, preferredStyle: UIAlertController.Style.actionSheet)
|
||||
alert.addAction(UIAlertAction(title: settings.userPromptText.photoAction, style: .default, handler: { [weak self] (_: UIAlertAction) in
|
||||
self?.showPhotos()
|
||||
}))
|
||||
|
||||
alert.addAction(UIAlertAction(title: settings.userPromptText.cameraAction, style: .default, handler: { [weak self] (_: UIAlertAction) in
|
||||
self?.showCamera()
|
||||
}))
|
||||
|
||||
alert.addAction(UIAlertAction(title: settings.userPromptText.cancelAction, style: .cancel, handler: { [weak self] (_: UIAlertAction) in
|
||||
self?.invoke?.reject("User cancelled photos app prompt")
|
||||
}))
|
||||
UIUtils.centerPopover(rootViewController: manager.viewController, popoverController: alert)
|
||||
self.manager.viewController?.present(alert, animated: true, completion: nil)
|
||||
}
|
||||
|
||||
func showCamera() {
|
||||
// check if we have a camera
|
||||
if manager.isSimEnvironment || !UIImagePickerController.isSourceTypeAvailable(UIImagePickerController.SourceType.camera) {
|
||||
Logger.error("[PLUGIN]", "Camera", "-", "Camera not available in simulator")
|
||||
invoke?.reject("Camera not available while running in Simulator")
|
||||
return
|
||||
}
|
||||
// check for permission
|
||||
let authStatus = AVCaptureDevice.authorizationStatus(for: .video)
|
||||
if authStatus == .restricted || authStatus == .denied {
|
||||
invoke?.reject("User denied access to camera")
|
||||
return
|
||||
}
|
||||
// we either already have permission or can prompt
|
||||
AVCaptureDevice.requestAccess(for: .video) { [weak self] granted in
|
||||
if granted {
|
||||
DispatchQueue.main.async {
|
||||
self?.presentCameraPicker()
|
||||
}
|
||||
} else {
|
||||
self?.invoke?.reject("User denied access to camera")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func showPhotos() {
|
||||
// check for permission
|
||||
let authStatus = PHPhotoLibrary.authorizationStatus()
|
||||
if authStatus == .restricted || authStatus == .denied {
|
||||
invoke?.reject("User denied access to photos")
|
||||
return
|
||||
}
|
||||
// we either already have permission or can prompt
|
||||
if authStatus == .authorized {
|
||||
presentSystemAppropriateImagePicker()
|
||||
} else {
|
||||
PHPhotoLibrary.requestAuthorization({ [weak self] (status) in
|
||||
if status == PHAuthorizationStatus.authorized {
|
||||
DispatchQueue.main.async { [weak self] in
|
||||
self?.presentSystemAppropriateImagePicker()
|
||||
}
|
||||
} else {
|
||||
self?.invoke?.reject("User denied access to photos")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func presentCameraPicker() {
|
||||
let picker = UIImagePickerController()
|
||||
picker.delegate = self
|
||||
picker.allowsEditing = self.settings.allowEditing
|
||||
// select the input
|
||||
picker.sourceType = .camera
|
||||
if settings.direction == .rear, UIImagePickerController.isCameraDeviceAvailable(.rear) {
|
||||
picker.cameraDevice = .rear
|
||||
} else if settings.direction == .front, UIImagePickerController.isCameraDeviceAvailable(.front) {
|
||||
picker.cameraDevice = .front
|
||||
}
|
||||
// present
|
||||
picker.modalPresentationStyle = settings.presentationStyle
|
||||
if settings.presentationStyle == .popover {
|
||||
picker.popoverPresentationController?.delegate = self
|
||||
UIUtils.centerPopover(rootViewController: manager.viewController, popoverController: picker)
|
||||
}
|
||||
manager.viewController?.present(picker, animated: true, completion: nil)
|
||||
}
|
||||
|
||||
func presentSystemAppropriateImagePicker() {
|
||||
if #available(iOS 14, *) {
|
||||
presentPhotoPicker()
|
||||
} else {
|
||||
presentImagePicker()
|
||||
}
|
||||
}
|
||||
|
||||
func presentImagePicker() {
|
||||
let picker = UIImagePickerController()
|
||||
picker.delegate = self
|
||||
picker.allowsEditing = self.settings.allowEditing
|
||||
// select the input
|
||||
picker.sourceType = .photoLibrary
|
||||
// present
|
||||
picker.modalPresentationStyle = settings.presentationStyle
|
||||
if settings.presentationStyle == .popover {
|
||||
picker.popoverPresentationController?.delegate = self
|
||||
UIUtils.centerPopover(rootViewController: manager.viewController, popoverController: picker)
|
||||
}
|
||||
manager.viewController?.present(picker, animated: true, completion: nil)
|
||||
}
|
||||
|
||||
@available(iOS 14, *)
|
||||
func presentPhotoPicker() {
|
||||
var configuration = PHPickerConfiguration(photoLibrary: PHPhotoLibrary.shared())
|
||||
configuration.selectionLimit = self.multiple ? (self.invoke?.getInt("limit") ?? 0) : 1
|
||||
configuration.filter = .images
|
||||
let picker = PHPickerViewController(configuration: configuration)
|
||||
picker.delegate = self
|
||||
// present
|
||||
picker.modalPresentationStyle = settings.presentationStyle
|
||||
if settings.presentationStyle == .popover {
|
||||
picker.popoverPresentationController?.delegate = self
|
||||
UIUtils.centerPopover(rootViewController: manager.viewController, popoverController: picker)
|
||||
}
|
||||
manager.viewController?.present(picker, animated: true, completion: nil)
|
||||
}
|
||||
|
||||
func saveTemporaryImage(_ data: Data) throws -> URL {
|
||||
var url: URL
|
||||
repeat {
|
||||
imageCounter += 1
|
||||
url = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("photo-\(imageCounter).jpg")
|
||||
} while FileManager.default.fileExists(atPath: url.path)
|
||||
|
||||
try data.write(to: url, options: .atomic)
|
||||
return url
|
||||
}
|
||||
|
||||
func processImage(from info: [UIImagePickerController.InfoKey: Any]) -> ProcessedImage? {
|
||||
var selectedImage: UIImage?
|
||||
var flags: PhotoFlags = []
|
||||
// get the image
|
||||
if let edited = info[UIImagePickerController.InfoKey.editedImage] as? UIImage {
|
||||
selectedImage = edited // use the edited version
|
||||
flags = flags.union([.edited])
|
||||
} else if let original = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
|
||||
selectedImage = original // use the original version
|
||||
}
|
||||
guard let image = selectedImage else {
|
||||
return nil
|
||||
}
|
||||
var metadata: [String: Any] = [:]
|
||||
// get the image's metadata from the picker or from the photo album
|
||||
if let photoMetadata = info[UIImagePickerController.InfoKey.mediaMetadata] as? [String: Any] {
|
||||
metadata = photoMetadata
|
||||
} else {
|
||||
flags = flags.union([.gallery])
|
||||
}
|
||||
if let asset = info[UIImagePickerController.InfoKey.phAsset] as? PHAsset {
|
||||
metadata = asset.imageData
|
||||
}
|
||||
// get the result
|
||||
var result = processedImage(from: image, with: metadata)
|
||||
result.flags = flags
|
||||
return result
|
||||
}
|
||||
|
||||
func processedImage(from image: UIImage, with metadata: [String: Any]?) -> ProcessedImage {
|
||||
var result = ProcessedImage(image: image, metadata: metadata ?? [:])
|
||||
// resizing the image only makes sense if we have real values to which to constrain it
|
||||
if settings.shouldResize, settings.width > 0 || settings.height > 0 {
|
||||
result.image = result.image.reformat(to: CGSize(width: settings.width, height: settings.height))
|
||||
result.overwriteMetadataOrientation(to: 1)
|
||||
} else if settings.shouldCorrectOrientation {
|
||||
// resizing implicitly reformats the image so this is only needed if we aren't resizing
|
||||
result.image = result.image.reformat()
|
||||
result.overwriteMetadataOrientation(to: 1)
|
||||
}
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
@_cdecl("init_plugin_camera")
|
||||
func initCameraPlugin(webview: WKWebView?) {
|
||||
Tauri.registerPlugin(webview: webview, name: "camera", plugin: CameraPlugin())
|
||||
}
|
@ -0,0 +1,142 @@
|
||||
import UIKit
|
||||
|
||||
// MARK: - Public
|
||||
|
||||
public enum CameraSource: String {
|
||||
case prompt = "PROMPT"
|
||||
case camera = "CAMERA"
|
||||
case photos = "PHOTOS"
|
||||
}
|
||||
|
||||
public enum CameraDirection: String {
|
||||
case rear = "REAR"
|
||||
case front = "FRONT"
|
||||
}
|
||||
|
||||
public enum CameraResultType: String {
|
||||
case base64
|
||||
case uri
|
||||
case dataURL = "dataUrl"
|
||||
}
|
||||
|
||||
struct CameraPromptText {
|
||||
let title: String
|
||||
let photoAction: String
|
||||
let cameraAction: String
|
||||
let cancelAction: String
|
||||
|
||||
init(title: String? = nil, photoAction: String? = nil, cameraAction: String? = nil, cancelAction: String? = nil) {
|
||||
self.title = title ?? "Photo"
|
||||
self.photoAction = photoAction ?? "From Photos"
|
||||
self.cameraAction = cameraAction ?? "Take Picture"
|
||||
self.cancelAction = cancelAction ?? "Cancel"
|
||||
}
|
||||
}
|
||||
|
||||
public struct CameraSettings {
|
||||
var source: CameraSource = CameraSource.prompt
|
||||
var direction: CameraDirection = CameraDirection.rear
|
||||
var resultType = CameraResultType.base64
|
||||
var userPromptText = CameraPromptText()
|
||||
var jpegQuality: CGFloat = 1.0
|
||||
var width: CGFloat = 0
|
||||
var height: CGFloat = 0
|
||||
var allowEditing = false
|
||||
var shouldResize = false
|
||||
var shouldCorrectOrientation = true
|
||||
var saveToGallery = false
|
||||
var presentationStyle = UIModalPresentationStyle.fullScreen
|
||||
}
|
||||
|
||||
public struct CameraResult {
|
||||
let image: UIImage?
|
||||
let metadata: [AnyHashable: Any]
|
||||
}
|
||||
|
||||
// MARK: - Internal
|
||||
|
||||
internal enum CameraPermissionType: String, CaseIterable {
|
||||
case camera
|
||||
case photos
|
||||
}
|
||||
|
||||
internal enum CameraPropertyListKeys: String, CaseIterable {
|
||||
case photoLibraryAddUsage = "NSPhotoLibraryAddUsageDescription"
|
||||
case photoLibraryUsage = "NSPhotoLibraryUsageDescription"
|
||||
case cameraUsage = "NSCameraUsageDescription"
|
||||
|
||||
var link: String {
|
||||
switch self {
|
||||
case .photoLibraryAddUsage:
|
||||
return "https://developer.apple.com/library/content/documentation/General/Reference/InfoPlistKeyReference/Articles/CocoaKeys.html#//apple_ref/doc/uid/TP40009251-SW73"
|
||||
case .photoLibraryUsage:
|
||||
return "https://developer.apple.com/library/content/documentation/General/Reference/InfoPlistKeyReference/Articles/CocoaKeys.html#//apple_ref/doc/uid/TP40009251-SW17"
|
||||
case .cameraUsage:
|
||||
return "https://developer.apple.com/library/content/documentation/General/Reference/InfoPlistKeyReference/Articles/CocoaKeys.html#//apple_ref/doc/uid/TP40009251-SW24"
|
||||
}
|
||||
}
|
||||
|
||||
var missingMessage: String {
|
||||
return "You are missing \(self.rawValue) in your Info.plist file." +
|
||||
" Camera will not function without it. Learn more: \(self.link)"
|
||||
}
|
||||
}
|
||||
|
||||
internal struct PhotoFlags: OptionSet {
|
||||
let rawValue: Int
|
||||
|
||||
static let edited = PhotoFlags(rawValue: 1 << 0)
|
||||
static let gallery = PhotoFlags(rawValue: 1 << 1)
|
||||
|
||||
static let all: PhotoFlags = [.edited, .gallery]
|
||||
}
|
||||
|
||||
internal struct ProcessedImage {
|
||||
var image: UIImage
|
||||
var metadata: [String: Any]
|
||||
var flags: PhotoFlags = []
|
||||
|
||||
var exifData: [String: Any] {
|
||||
var exifData = metadata["{Exif}"] as? [String: Any]
|
||||
exifData?["Orientation"] = metadata["Orientation"]
|
||||
exifData?["GPS"] = metadata["{GPS}"]
|
||||
return exifData ?? [:]
|
||||
}
|
||||
|
||||
mutating func overwriteMetadataOrientation(to orientation: Int) {
|
||||
replaceDictionaryOrientation(atNode: &metadata, to: orientation)
|
||||
}
|
||||
|
||||
func replaceDictionaryOrientation(atNode node: inout [String: Any], to orientation: Int) {
|
||||
for key in node.keys {
|
||||
if key == "Orientation", (node[key] as? Int) != nil {
|
||||
node[key] = orientation
|
||||
} else if var child = node[key] as? [String: Any] {
|
||||
replaceDictionaryOrientation(atNode: &child, to: orientation)
|
||||
node[key] = child
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func generateJPEG(with quality: CGFloat) -> Data? {
|
||||
// convert the UIImage to a jpeg
|
||||
guard let data = self.image.jpegData(compressionQuality: quality) else {
|
||||
return nil
|
||||
}
|
||||
// define our jpeg data as an image source and get its type
|
||||
guard let source = CGImageSourceCreateWithData(data as CFData, nil), let type = CGImageSourceGetType(source) else {
|
||||
return data
|
||||
}
|
||||
// allocate an output buffer and create the destination to receive the new data
|
||||
guard let output = NSMutableData(capacity: data.count), let destination = CGImageDestinationCreateWithData(output, type, 1, nil) else {
|
||||
return data
|
||||
}
|
||||
// pipe the source into the destination while overwriting the metadata, this encodes the metadata information into the image
|
||||
CGImageDestinationAddImageFromSource(destination, source, 0, self.metadata as CFDictionary)
|
||||
// finish
|
||||
guard CGImageDestinationFinalize(destination) else {
|
||||
return data
|
||||
}
|
||||
return output as Data
|
||||
}
|
||||
}
|
@ -0,0 +1,20 @@
|
||||
import UIKit
|
||||
|
||||
class ImageSaver: NSObject {
|
||||
|
||||
var onResult: ((Error?) -> Void) = {_ in }
|
||||
|
||||
init(image: UIImage, onResult:@escaping ((Error?) -> Void)) {
|
||||
self.onResult = onResult
|
||||
super.init()
|
||||
UIImageWriteToSavedPhotosAlbum(image, self, #selector(saveResult), nil)
|
||||
}
|
||||
|
||||
@objc func saveResult(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
|
||||
if let error = error {
|
||||
onResult(error)
|
||||
} else {
|
||||
onResult(nil)
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,8 @@
|
||||
import XCTest
|
||||
@testable import ExamplePlugin
|
||||
|
||||
final class ExamplePluginTests: XCTestCase {
|
||||
func testExample() throws {
|
||||
let plugin = ExamplePlugin()
|
||||
}
|
||||
}
|
@ -0,0 +1,33 @@
|
||||
{
|
||||
"name": "tauri-plugin-camera-api",
|
||||
"version": "0.0.0",
|
||||
"description": "Ask the user take a photo with the camera or select an image from the gallery.",
|
||||
"license": "MIT or APACHE-2.0",
|
||||
"authors": [
|
||||
"Tauri Programme within The Commons Conservancy"
|
||||
],
|
||||
"type": "module",
|
||||
"browser": "dist-js/index.min.js",
|
||||
"module": "dist-js/index.mjs",
|
||||
"types": "dist-js/index.d.ts",
|
||||
"exports": {
|
||||
"import": "./dist-js/index.mjs",
|
||||
"types": "./dist-js/index.d.ts",
|
||||
"browser": "./dist-js/index.min.js"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "rollup -c"
|
||||
},
|
||||
"files": [
|
||||
"dist-js",
|
||||
"!dist-js/**/*.map",
|
||||
"README.md",
|
||||
"LICENSE"
|
||||
],
|
||||
"devDependencies": {
|
||||
"tslib": "^2.4.1"
|
||||
},
|
||||
"dependencies": {
|
||||
"@tauri-apps/api": "^2.0.0-alpha.0"
|
||||
}
|
||||
}
|
@ -0,0 +1,11 @@
|
||||
import { readFileSync } from "fs";
|
||||
|
||||
import { createConfig } from "../../shared/rollup.config.mjs";
|
||||
|
||||
export default createConfig({
|
||||
input: "guest-js/index.ts",
|
||||
pkg: JSON.parse(
|
||||
readFileSync(new URL("./package.json", import.meta.url), "utf8")
|
||||
),
|
||||
external: [/^@tauri-apps\/api/],
|
||||
});
|