diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index 6716b43..0bc2f83 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -56,6 +56,17 @@ + + + + + + + diff --git a/android/app/src/main/java/io/github/faumaray/voelin/MainActivity.kt b/android/app/src/main/java/io/github/faumaray/voelin/MainActivity.kt index 16bb883..deb65cb 100644 --- a/android/app/src/main/java/io/github/faumaray/voelin/MainActivity.kt +++ b/android/app/src/main/java/io/github/faumaray/voelin/MainActivity.kt @@ -3,13 +3,20 @@ package io.github.faumaray.voelin import android.app.NativeActivity import android.content.Intent import android.media.projection.MediaProjectionManager +import android.net.Uri +import android.os.Build import android.os.Bundle +import android.provider.OpenableColumns +import android.util.Log +import java.io.File import java.lang.ref.WeakReference +import kotlin.concurrent.thread /** * The window: a NativeActivity running `android_main` of libvoelin_android.so * (the Slint UI). Kotlin only handles what needs an Activity: permission - * prompts, the screen-capture consent dialog and a tapped notification. + * prompts, the screen-capture consent dialog, a tapped notification and + * what is shared to the app ("Share to Voelin"). */ class MainActivity : NativeActivity() { private var captureFps = 30 @@ -42,13 +49,80 @@ class MainActivity : NativeActivity() { moveTaskToBack(true) } - /** A tapped voice notification. */ + /** A tapped voice notification, or something shared to us. */ private fun handle(intent: Intent?) { when (intent?.action) { VoiceService.ACTION_OPEN_VOICE -> Native.onOpenVoice() + Intent.ACTION_SEND, Intent.ACTION_SEND_MULTIPLE -> share(intent) } } + /** + * Text goes into the current chat's composer; files are copied out of the + * sending app (its content URIs are readable only now) into our cache, + * then uploaded to the current channel by the Rust side. + */ + private fun share(intent: Intent) { + val subject = intent.getStringExtra(Intent.EXTRA_SUBJECT)?.trim().orEmpty() + val body = intent.getCharSequenceExtra(Intent.EXTRA_TEXT)?.toString()?.trim().orEmpty() + val text = when { + subject.isEmpty() -> body + body.isEmpty() || body.contains(subject) -> body.ifEmpty { subject } + else -> "$subject\n$body" + }.ifEmpty { null } + val uris = sharedUris(intent) + if (uris.isEmpty()) { + if (text != null) Native.onShare(text, null) + return + } + val resolver = contentResolver + val dir = File(cacheDir, "shared/${System.nanoTime()}") + thread(name = "voelin-share") { + val paths = uris.mapIndexedNotNull { i, uri -> + try { + val name = displayName(uri) ?: "shared-file-${i + 1}" + // Two shared files may have the same name. + val file = File(dir, name).takeUnless { it.exists() } ?: File(dir, "${i + 1}-$name") + dir.mkdirs() + resolver.openInputStream(uri)?.use { input -> + file.outputStream().use { input.copyTo(it) } + } ?: return@mapIndexedNotNull null + file.path + } catch (e: Exception) { + Log.w(TAG, "cannot read the shared $uri", e) + null + } + } + Native.onShare(text, paths.joinToString("\n").ifEmpty { null }) + } + } + + private fun sharedUris(intent: Intent): List = if (intent.action == Intent.ACTION_SEND_MULTIPLE) { + if (Build.VERSION.SDK_INT >= 33) { + intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM, Uri::class.java) + } else { + @Suppress("DEPRECATION") + intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM) + }.orEmpty() + } else { + listOfNotNull( + if (Build.VERSION.SDK_INT >= 33) { + intent.getParcelableExtra(Intent.EXTRA_STREAM, Uri::class.java) + } else { + @Suppress("DEPRECATION") + intent.getParcelableExtra(Intent.EXTRA_STREAM) + }, + ) + } + + /** The file name the sending app gives, made safe as one path component. */ + private fun displayName(uri: Uri): String? { + val name = contentResolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use { + if (it.moveToFirst()) it.getString(0) else null + } ?: uri.lastPathSegment + return name?.replace(Regex("[/\\\\\n\r\u0000]"), "_")?.trim()?.takeIf { it.isNotEmpty() && it != "." && it != ".." } + } + /** Show the system's "start recording or casting?" dialog. */ fun requestScreenCapture(fps: Int, maxSize: Int) { captureFps = fps @@ -72,6 +146,7 @@ class MainActivity : NativeActivity() { } companion object { + private const val TAG = "MainActivity" private const val REQUEST_SCREEN_CAPTURE = 1001 /** The activity in front, if any. */ diff --git a/android/app/src/main/java/io/github/faumaray/voelin/Native.kt b/android/app/src/main/java/io/github/faumaray/voelin/Native.kt index cc3ac44..c570966 100644 --- a/android/app/src/main/java/io/github/faumaray/voelin/Native.kt +++ b/android/app/src/main/java/io/github/faumaray/voelin/Native.kt @@ -57,4 +57,12 @@ object Native { /** The voice notification was tapped: show the voice channel. */ @JvmStatic external fun onOpenVoice() + + /** + * Shared to the app ("Share to Voelin"): text for the current chat's + * composer, and copies of the shared files (one path per line) for the + * current channel. + */ + @JvmStatic + external fun onShare(text: String?, paths: String?) } diff --git a/android/app/src/main/java/io/github/faumaray/voelin/VoelinApp.kt b/android/app/src/main/java/io/github/faumaray/voelin/VoelinApp.kt index 848ad83..700a3ac 100644 --- a/android/app/src/main/java/io/github/faumaray/voelin/VoelinApp.kt +++ b/android/app/src/main/java/io/github/faumaray/voelin/VoelinApp.kt @@ -1,6 +1,7 @@ package io.github.faumaray.voelin import android.app.Application +import java.io.File /** The process's application object; the Rust side reaches Android through it. */ class VoelinApp : Application() { @@ -8,6 +9,8 @@ class VoelinApp : Application() { super.onCreate() instance = this Notifications.createChannels(this) + // Copies of files shared to us (MainActivity.share) from before. + File(cacheDir, "shared").deleteRecursively() } companion object { diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml index fa92f27..f365cd0 100644 --- a/android/app/src/main/res/values/strings.xml +++ b/android/app/src/main/res/values/strings.xml @@ -1,6 +1,7 @@ Voelin + Voelin Voice connection Screen sharing Connected to voice diff --git a/crates/voelin-android/src/bridge.rs b/crates/voelin-android/src/bridge.rs index d33e2ed..f495476 100644 --- a/crates/voelin-android/src/bridge.rs +++ b/crates/voelin-android/src/bridge.rs @@ -428,3 +428,23 @@ fn on_open_voice<'local>(_env: &mut Env<'local>, _class: JClass<'local>) -> Resu voelin_ui::request(voelin_ui::Request::ShowVoice); Ok(()) } + +const _: jni::NativeMethod = native_method! { + java_type = "io.github.faumaray.voelin.Native", + static extern fn on_share(text: JString, paths: JString), +}; + +/// Shared to the app: text, and copies of the shared files (one path per +/// line). +fn on_share<'local>( + env: &mut Env<'local>, + _class: JClass<'local>, + text: JString<'local>, + paths: JString<'local>, +) -> Result<()> { + let text = if text.is_null() { None } else { Some(text.try_to_string(env)?) }; + let paths = if paths.is_null() { String::new() } else { paths.try_to_string(env)? }; + let files = paths.lines().filter(|l| !l.is_empty()).map(std::path::PathBuf::from).collect(); + voelin_ui::request(voelin_ui::Request::Share { text, files }); + Ok(()) +} diff --git a/crates/voelin-ui/src/chat.rs b/crates/voelin-ui/src/chat.rs index e444dc4..80bea68 100644 --- a/crates/voelin-ui/src/chat.rs +++ b/crates/voelin-ui/src/chat.rs @@ -750,7 +750,7 @@ impl App { } /// Upload a file into a channel and link it in the chat once it is up. - fn upload(&mut self, id: i64, channel: u64, from: PathBuf) { + pub(crate) fn upload(&mut self, id: i64, channel: u64, from: PathBuf) { let Some(name) = from.file_name().map(|n| n.to_string_lossy().to_string()) else { return }; let view = self.sessions.entry(id).or_default(); let transfer = view.next_transfer; diff --git a/crates/voelin-ui/src/dev.rs b/crates/voelin-ui/src/dev.rs index bff074a..d51be49 100644 --- a/crates/voelin-ui/src/dev.rs +++ b/crates/voelin-ui/src/dev.rs @@ -16,7 +16,9 @@ //! `emoji` (the picker), `client` (the volume dialog of the first other //! client once connected), `panel` / `no-panel` (the members panel), //! `voice` (the voice channel view; on the phone its own screen), -//! `members` (the phone's members page), `pins`, `topics` (the drawers), +//! `members` (the phone's members page), `notification` (a tapped voice +//! notification), `shared:` (text shared to the app on Android), +//! `pins`, `topics` (the drawers), //! `topic:` (a topic's messages), `member` (the member card of the //! first other client), `watch` (the first stream; with sample data the //! local test pattern in its place), `popout` (the same, popped out), @@ -160,6 +162,13 @@ pub(crate) fn start(ui: &MainWindow, switches: &Switches) -> Running { "pins" => nav.invoke_show_pins(true), // The phone's members page. "members" => nav.set_members_open(true), + // What Android hands over: a tapped voice notification, text + // shared to the app. + "notification" => crate::inbox::request(crate::inbox::Request::ShowVoice), + "shared" => crate::inbox::request(crate::inbox::Request::Share { + text: Some(arg.to_owned()), + files: Vec::new(), + }), "topics" => nav.invoke_show_topics(true), "topic" => { with_app(|app| { diff --git a/crates/voelin-ui/src/inbox.rs b/crates/voelin-ui/src/inbox.rs index b4deb32..0bb05c1 100644 --- a/crates/voelin-ui/src/inbox.rs +++ b/crates/voelin-ui/src/inbox.rs @@ -1,18 +1,26 @@ //! Requests from the platform around the window: on Android a tapped -//! notification. They can come from any thread and before the window runs; -//! [`request`] keeps them until the window takes them on its thread. +//! notification or something shared to the app ("Share to Voelin"). They +//! can come from any thread and before the window runs; [`request`] keeps +//! them until the window takes them on its thread. +use std::path::PathBuf; use std::sync::{Mutex, PoisonError}; use slint::ComponentHandle; +use voelin_model::ChatTarget; -use crate::app::{Nav, Page, with_app}; +use crate::app::{App, MobileTab, Nav, Page, with_app}; /// What the platform asks the window to do. #[derive(Clone, Debug, PartialEq, Eq)] pub enum Request { /// Show the voice channel we are in (the phone's voice screen). ShowVoice, + /// Shared to the app: the text goes into the current chat's composer + /// (to send with one tap, or edit, as a mis-tap in the share sheet + /// should not post into a chat), the files are uploaded to the current + /// channel and linked there, as the composer's attach button does. + Share { text: Option, files: Vec }, } static PENDING: Mutex> = Mutex::new(Vec::new()); @@ -38,6 +46,56 @@ pub(crate) fn take() { nav.invoke_show(Page::Server); nav.invoke_show_voice(true); } + Request::Share { text, files } => { + // The phone shows the chat it went to. + nav.set_mobile_tab(MobileTab::Chat); + nav.invoke_show(Page::Server); + with_app(|app| app.share(&nav, text, files)); + } + } + } +} + +impl App { + fn share(&mut self, nav: &Nav<'_>, text: Option, files: Vec) { + let current = self.current.and_then(|id| { + let view = self.sessions.get(&id)?; + let tab = &view.tabs[view.current_tab]; + // Files go to the channel of the chat, else to ours. + let channel = match tab.target { + ChatTarget::Channel(channel) => Some(channel), + _ => view.state.own_channel, + } + .map(|c| { + let name = view.presence.channels.get(&c).map(|c| c.name.as_str()); + (c, name.map_or_else(|| "the channel".to_owned(), |n| format!("#{n}"))) + }); + Some((id, tab.title.clone(), channel)) + }); + if let Some(text) = text.filter(|t| !t.trim().is_empty()) { + nav.set_draft(text.into()); + self.set_status(match ¤t { + Some((_, title, _)) => format!("Shared text is ready to send to {title}"), + None => "Shared text is in the composer".to_owned(), + }); + } + if files.is_empty() { + return; + } + match current { + Some((id, _, Some((channel, name)))) if !self.demo_ui => { + let count = files.len(); + for file in files { + self.upload(id, channel, file); + } + let what = if count == 1 { + "the shared file".to_owned() + } else { + format!("{count} files") + }; + self.set_status(format!("Uploading {what} to {name}")); + } + _ => self.set_status("Open a channel's chat (or join a channel) to share files there"), } } }