Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions plugins/dialog/android/src/main/java/DialogPlugin.kt
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,11 @@ class MessageOptions {
var cancelButtonLabel: String? = null
}

@InvokeArg
class SaveFileDialogOptions {
var title: String = ""
}

@TauriPlugin
class DialogPlugin(private val activity: Activity): Plugin(activity) {
var filePickerOptions: FilePickerOptions? = null
Expand Down Expand Up @@ -204,4 +209,46 @@ class DialogPlugin(private val activity: Activity): Plugin(activity) {
dialog.show()
}
}

@Command
fun saveFileDialog(invoke: Invoke) {
try {
val args = invoke.parseArgs(SaveFileDialogOptions::class.java)

val intent = Intent(Intent.ACTION_CREATE_DOCUMENT)
intent.addCategory(Intent.CATEGORY_OPENABLE)
intent.setType("text/plain")
intent.putExtra(Intent.EXTRA_TITLE, args.title)
startActivityForResult(invoke, intent, "saveFileDialogResult")
} catch (ex: Exception) {
val message = ex.message ?: "Failed to pick save file"
Logger.error(message)
invoke.reject(message)
}
}

@ActivityCallback
fun saveFileDialogResult(invoke: Invoke, result: ActivityResult) {
try {
when (result.resultCode) {
Activity.RESULT_OK -> {
val callResult = JSObject()
val intent: Intent? = result.data
if (intent != null) {
val uri = intent.getData()
if (uri != null) {
callResult.put("file", uri.toString())
}
}
invoke.resolve(callResult)
}
Activity.RESULT_CANCELED -> invoke.reject("File picker cancelled")
else -> invoke.reject("Failed to pick files")
}
} catch (ex: java.lang.Exception) {
val message = ex.message ?: "Failed to read file pick result"
Logger.error(message)
invoke.reject(message)
}
}
}
4 changes: 2 additions & 2 deletions plugins/dialog/src/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -193,9 +193,9 @@ pub(crate) async fn save<R: Runtime>(
dialog: State<'_, Dialog<R>>,
options: SaveDialogOptions,
) -> Result<Option<PathBuf>> {
#[cfg(mobile)]
#[cfg(any(target_os = "ios"))]
return Err(crate::Error::FileSaveDialogNotImplemented);
#[cfg(desktop)]
#[cfg(any(desktop, target_os = "android"))]
{
let mut dialog_builder = dialog.file();
#[cfg(any(windows, target_os = "macos"))]
Expand Down
7 changes: 4 additions & 3 deletions plugins/dialog/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,10 @@ use tauri::{
Manager, Runtime,
};

#[cfg(any(desktop, target_os = "ios"))]
use std::fs;

use std::{
fs,
path::{Path, PathBuf},
sync::mpsc::sync_channel,
};
Expand Down Expand Up @@ -471,7 +473,6 @@ impl<R: Runtime> FileDialogBuilder<R> {
/// })
/// })
/// ```
#[cfg(desktop)]
pub fn save_file<F: FnOnce(Option<PathBuf>) + Send + 'static>(self, f: F) {
save_file(self, f)
}
Expand Down Expand Up @@ -572,14 +573,14 @@ impl<R: Runtime> FileDialogBuilder<R> {
/// // the file path is `None` if the user closed the dialog
/// }
/// ```
#[cfg(desktop)]
pub fn blocking_save_file(self) -> Option<PathBuf> {
blocking_fn!(self, save_file)
}
}

// taken from deno source code: https://github.com/denoland/deno/blob/ffffa2f7c44bd26aec5ae1957e0534487d099f48/runtime/ops/fs.rs#L913
#[inline]
#[allow(unused)]
fn to_msec(maybe_time: std::result::Result<std::time::SystemTime, std::io::Error>) -> Option<u64> {
match maybe_time {
Ok(time) => {
Expand Down
23 changes: 23 additions & 0 deletions plugins/dialog/src/mobile.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use std::path::PathBuf;

use serde::{de::DeserializeOwned, Deserialize};
use tauri::{
Expand Down Expand Up @@ -49,6 +50,11 @@ struct FilePickerResponse {
files: Vec<FileResponse>,
}

#[derive(Debug, Deserialize)]
struct SaveFileResponse {
file: PathBuf,
}

pub fn pick_file<R: Runtime, F: FnOnce(Option<FileResponse>) + Send + 'static>(
dialog: FileDialogBuilder<R>,
f: F,
Expand Down Expand Up @@ -83,6 +89,23 @@ pub fn pick_files<R: Runtime, F: FnOnce(Option<Vec<FileResponse>>) + Send + 'sta
});
}

pub fn save_file<R: Runtime, F: FnOnce(Option<PathBuf>) + Send + 'static>(
dialog: FileDialogBuilder<R>,
f: F,
) {
std::thread::spawn(move || {
let res = dialog
.dialog
.0
.run_mobile_plugin::<SaveFileResponse>("saveFileDialog", dialog.payload(true));
if let Ok(response) = res {
f(Some(response.file))
} else {
f(None)
}
});
}

#[derive(Debug, Deserialize)]
struct ShowMessageDialogResponse {
#[allow(dead_code)]
Expand Down
2 changes: 2 additions & 0 deletions plugins/fs/android/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
/build
/.tauri
45 changes: 45 additions & 0 deletions plugins/fs/android/build.gradle.kts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
plugins {
id("com.android.library")
id("org.jetbrains.kotlin.android")
}

android {
namespace = "com.plugin.fs"
compileSdk = 34

defaultConfig {
minSdk = 21
targetSdk = 34

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(project(":tauri-android"))
}
21 changes: 21 additions & 0 deletions plugins/fs/android/proguard-rules.pro
Original file line number Diff line number Diff line change
@@ -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
31 changes: 31 additions & 0 deletions plugins/fs/android/settings.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
pluginManagement {
repositories {
mavenCentral()
gradlePluginPortal()
google()
}
resolutionStrategy {
eachPlugin {
switch (requested.id.id) {
case "com.android.library":
useVersion("8.0.2")
break
case "org.jetbrains.kotlin.android":
useVersion("1.8.20")
break
}
}
}
}

dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
mavenCentral()
google()

}
}

include ':tauri-android'
project(':tauri-android').projectDir = new File('./.tauri/tauri-api')
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package com.plugin.fs

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("com.plugin.fs", appContext.packageName)
}
}
3 changes: 3 additions & 0 deletions plugins/fs/android/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
</manifest>
39 changes: 39 additions & 0 deletions plugins/fs/android/src/main/java/FsPlugin.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package com.plugin.fs

import android.app.Activity
import android.net.Uri
import android.util.Log
import app.tauri.annotation.Command
import app.tauri.annotation.InvokeArg
import app.tauri.annotation.TauriPlugin
import app.tauri.plugin.JSObject
import app.tauri.plugin.Plugin
import app.tauri.plugin.Invoke

@InvokeArg
class WriteTextFileArgs {
val uri: String = ""
val content: String = ""
}

@TauriPlugin
class FsPlugin(private val activity: Activity): Plugin(activity) {
@Command
fun writeTextFile(invoke: Invoke) {
val args = invoke.parseArgs(WriteTextFileArgs::class.java)
val uri = Uri.parse(args.uri)
val content = args.content

if(uri != null){
activity.getContentResolver().openOutputStream(uri).use { ost ->
if(ost != null && content != null){
ost.write(content.toByteArray());
}
}
}

val ret = JSObject()
invoke.resolve(ret)
}
}

17 changes: 17 additions & 0 deletions plugins/fs/android/src/test/java/ExampleUnitTest.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package com.plugin.fs

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)
}
}
1 change: 1 addition & 0 deletions plugins/fs/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -190,5 +190,6 @@ permissions = [
tauri_plugin::Builder::new(COMMANDS)
.global_api_script_path("./api-iife.js")
.global_scope_schema(schemars::schema_for!(FsScopeEntry))
.android_path("android")
.build();
}
Loading