Android: Share to Voelin

Other apps could not hand anything to Voelin. The activity now takes
ACTION_SEND and ACTION_SEND_MULTIPLE of any type. Text and links go into
the composer of the current chat, which the phone then shows: one tap
sends them, and a mis-tap in the share sheet does not post into a busy
channel. Files are copied out of the sending app while its content URIs
are readable (on a thread of their own, under the name the app gives,
made safe as a path component) and uploaded to the current chat's
channel, or the channel we are in, and linked there as the composer's
attach button does. The copies live in the cache and are removed at the
next start.

Two development switches show both platform requests without a phone:
VOELIN_OPEN=notification (a tapped voice notification) and
VOELIN_OPEN=shared:<text>.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
selikhovandClaude Opus 5.5 committed 2026-10-03 17:48:38 +03:00
1 parent d4b6baaa42
commit ef976cf31e
9 files changed
+192 -7

No files matched your search

+11
View File
@@ -56,6 +56,17 @@
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<!--
"Share to Voelin": text and links go into the composer of
the current chat, files (pictures, videos, documents) are
uploaded to the current channel.
-->
<intent-filter android:label="@string/share_label">
<action android:name="android.intent.action.SEND" />
<action android:name="android.intent.action.SEND_MULTIPLE" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="*/*" />
</intent-filter>
</activity>
<!-- Keeps the microphone and the connection while in the background. -->
@@ -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<Uri> = 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. */
@@ -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?)
}
@@ -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 {
@@ -1,6 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Voelin</string>
<string name="share_label">Voelin</string>
<string name="channel_voice">Voice connection</string>
<string name="channel_screen">Screen sharing</string>
<string name="voice_connected">Connected to voice</string>
+20
View File
@@ -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(())
}
+1 -1
View File
@@ -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;
+10 -1
View File
@@ -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>` (text shared to the app on Android),
//! `pins`, `topics` (the drawers),
//! `topic:<id>` (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| {
+61 -3
View File
@@ -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<String>, files: Vec<PathBuf> },
}
static PENDING: Mutex<Vec<Request>> = 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<String>, files: Vec<PathBuf>) {
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 &current {
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"),
}
}
}