Compare commits

...
Author SHA1 Message Date
yp 7df83a2391 remove var outputBaseName 2026-09-30 09:48:41 +03:00
yp 665d135292 merge dev 2026-09-30 09:47:42 +03:00
yp eb7aab2bae remove savedInstanceState 2026-09-04 18:33:10 +03:00
yp 1b65116334 remove logs 2026-09-04 18:24:56 +03:00
yp d2b53b9e56 fix: saving after canceling 2026-09-04 18:21:29 +03:00
10 changed files with 312 additions and 39 deletions

No files matched your search

@@ -74,6 +74,11 @@ private const val CREATE_FILE_ACTION_CODE = 2
private const val OPEN_FILE_ACTION_CODE = 3
private const val CHECK_NOTIFICATION_PERMISSION_ACTION_CODE = 4
// keep in sync with SystemController::SaveFileResult on the Qt side
private const val SAVE_FILE_RESULT_SAVED = 0
private const val SAVE_FILE_RESULT_CANCELLED = 1
private const val SAVE_FILE_RESULT_FAILED = 2
private const val PREFS_NOTIFICATION_PERMISSION_ASKED = "NOTIFICATION_PERMISSION_ASKED"
private const val OPEN_FILE_AFTER_RESUME_DELAY_MS = 400L
private const val KEY_PENDING_OPEN_FILE_URI = "pending_open_file_uri"
@@ -99,6 +104,10 @@ class AmneziaActivity : QtActivity() {
private val resumeHandler = Handler(Looper.getMainLooper())
private var pendingOpenFileUri: String? = null
private var openFileDeliveryScheduled = false
private var pendingSaveFileData: String? = null
private var awaitingSaveFileResult = false
private var pendingSaveFileResult: Int? = null
private var saveFileDeliveryScheduled = false
private val vpnServiceEventHandler: Handler by lazy(NONE) {
@@ -204,6 +213,7 @@ class AmneziaActivity : QtActivity() {
)
pendingOpenFileUri = savedInstanceState?.getString(KEY_PENDING_OPEN_FILE_URI)
openFileDeliveryScheduled = false
saveFileDeliveryScheduled = false
registerBroadcastReceivers()
intent?.let(::processIntent)
runBlocking { vpnProto = proto.await() }
@@ -282,6 +292,7 @@ class AmneziaActivity : QtActivity() {
// Cancel all pending operations when activity stops
resumeHandler.removeCallbacksAndMessages(null)
openFileDeliveryScheduled = false
saveFileDeliveryScheduled = false
Log.d(TAG, "Stop Amnezia activity")
doUnbindService()
mainScope.launch {
@@ -365,6 +376,7 @@ class AmneziaActivity : QtActivity() {
// Cancel all pending operations when activity pauses
resumeHandler.removeCallbacksAndMessages(null)
openFileDeliveryScheduled = false
saveFileDeliveryScheduled = false
Log.d(TAG, "Pause Amnezia activity")
}
@@ -391,6 +403,10 @@ class AmneziaActivity : QtActivity() {
}, OPEN_FILE_AFTER_RESUME_DELAY_MS)
}
if (pendingSaveFileResult != null && !saveFileDeliveryScheduled) {
scheduleSaveFileResultDelivery()
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
window.decorView.apply {
invalidate()
@@ -492,6 +508,14 @@ class AmneziaActivity : QtActivity() {
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
Log.d(TAG, "Process activity result, code: ${actionCodeToString(requestCode)}, " +
"resultCode: $resultCode, data: $data")
if (requestCode == CREATE_FILE_ACTION_CODE && awaitingSaveFileResult) {
actionResultHandlers.remove(requestCode)
handleSaveFileActivityResult(resultCode, data)
return
}
if (requestCode == CREATE_FILE_ACTION_CODE) {
Log.w(TAG, "Save file: activity result without awaitingSaveFileResult flag")
}
actionResultHandlers[requestCode]?.let { handler ->
when (resultCode) {
RESULT_OK -> handler.onSuccess(data)
@@ -733,35 +757,85 @@ class AmneziaActivity : QtActivity() {
@Suppress("unused")
fun saveFile(fileName: String, data: String) {
Log.d(TAG, "Save file $fileName")
pendingSaveFileData = data
awaitingSaveFileResult = true
mainScope.launch {
Intent(Intent.ACTION_CREATE_DOCUMENT).apply {
val intent = Intent(Intent.ACTION_CREATE_DOCUMENT).apply {
addCategory(Intent.CATEGORY_OPENABLE)
type = "text/*"
putExtra(Intent.EXTRA_TITLE, fileName)
}.also {
try {
startActivityForResult(it, CREATE_FILE_ACTION_CODE, ActivityResultHandler(
onSuccess = {
it?.data?.let { uri ->
Log.v(TAG, "Save file to $uri")
try {
contentResolver.openOutputStream(uri)?.use { os ->
os.bufferedWriter().use { it.write(data) }
}
} catch (e: IOException) {
Log.e(TAG, "Failed to save file $uri: $e")
// todo: send error to Qt
}
}
}
))
} catch (_: ActivityNotFoundException) {
Toast.makeText(this@AmneziaActivity, "Unsupported", Toast.LENGTH_LONG).show()
}
}
try {
@Suppress("DEPRECATION")
super.startActivityForResult(intent, CREATE_FILE_ACTION_CODE)
} catch (_: ActivityNotFoundException) {
Log.w(TAG, "Save file: CREATE_DOCUMENT not available on this device")
pendingSaveFileData = null
awaitingSaveFileResult = false
Toast.makeText(this@AmneziaActivity, "Unsupported", Toast.LENGTH_LONG).show()
reportFileSaved(SAVE_FILE_RESULT_FAILED)
}
}
}
private fun handleSaveFileActivityResult(resultCode: Int, data: Intent?) {
awaitingSaveFileResult = false
val fileData = pendingSaveFileData
pendingSaveFileData = null
if (resultCode == RESULT_OK) {
val uri = data?.data
if (uri == null || fileData == null) {
Log.w(TAG, "Save file: no uri or data in the picker result")
reportFileSaved(SAVE_FILE_RESULT_FAILED)
} else {
Log.v(TAG, "Save file to $uri")
try {
contentResolver.openOutputStream(uri)?.use { os ->
os.bufferedWriter().use { it.write(fileData) }
}
reportFileSaved(SAVE_FILE_RESULT_SAVED)
} catch (e: IOException) {
Log.e(TAG, "Failed to save file $uri: $e")
reportFileSaved(SAVE_FILE_RESULT_FAILED)
}
}
} else {
Log.v(TAG, "Save file cancelled by the user")
reportFileSaved(SAVE_FILE_RESULT_CANCELLED)
}
}
private fun reportFileSaved(result: Int) {
pendingSaveFileResult = result
if (isActivityResumed) {
scheduleSaveFileResultDelivery()
}
}
private fun scheduleSaveFileResultDelivery() {
if (pendingSaveFileResult == null || saveFileDeliveryScheduled) return
saveFileDeliveryScheduled = true
resumeHandler.postDelayed({
if (!isFinishing && !isDestroyed) {
val result = pendingSaveFileResult
pendingSaveFileResult = null
saveFileDeliveryScheduled = false
if (result != null) {
mainScope.launch {
qtInitialized.await()
QtAndroidController.onFileSaved(result)
}
} else {
Log.w(TAG, "Save file: pending result was cleared before Qt delivery")
}
} else {
Log.w(TAG, "Save file: activity finishing, deferring Qt delivery")
saveFileDeliveryScheduled = false
}
}, OPEN_FILE_AFTER_RESUME_DELAY_MS)
}
@Suppress("unused")
fun openFile(filter: String?) {
Log.v(TAG, "Open file with filter: $filter")
@@ -23,6 +23,8 @@ object QtAndroidController {
external fun onFileOpened(uri: String)
external fun onFileSaved(result: Int)
external fun onConfigImported(data: String)
external fun onAuthResult(result: Boolean)
@@ -23,6 +23,7 @@
#include "ui/controllers/importUiController.h"
#include "ui/controllers/api/subscriptionUiController.h"
#include "ui/controllers/updateUiController.h"
#include "ui/controllers/systemController.h"
#include "ui/models/serversModel.h"
#include "core/controllers/serversController.h"
#include "core/controllers/ipSplitTunnelingController.h"
@@ -100,6 +101,12 @@ void CoreSignalHandlers::initErrorMessagesHandler()
connect(m_coreController->m_settingsUiController, &SettingsUiController::errorOccurred, m_coreController->m_pageController,
qOverload<ErrorCode>(&PageController::showErrorMessage));
// any save/share dialog dismissed by the user, on every platform
connect(m_coreController->m_systemController, &SystemController::saveCancelledByUser, m_coreController->m_pageController,
[this]() {
emit m_coreController->m_pageController->showNotificationMessage(tr("Cancelled by user"));
});
}
void CoreSignalHandlers::initSettingsSplitTunnelingHandler()
@@ -97,6 +97,7 @@ bool AndroidController::initialize()
{"onVpnStateChanged", "(I)V", reinterpret_cast<void *>(onVpnStateChanged)},
{"onStatisticsUpdate", "(JJ)V", reinterpret_cast<void *>(onStatisticsUpdate)},
{"onFileOpened", "(Ljava/lang/String;)V", reinterpret_cast<void *>(onFileOpened)},
{"onFileSaved", "(I)V", reinterpret_cast<void *>(onFileSaved)},
{"onConfigImported", "(Ljava/lang/String;)V", reinterpret_cast<void *>(onConfigImported)},
{"onAuthResult", "(Z)V", reinterpret_cast<void *>(onAuthResult)},
{"decodeQrCode", "(Ljava/lang/String;)Z", reinterpret_cast<bool *>(decodeQrCode)},
@@ -154,11 +155,45 @@ void AndroidController::resetLastServer(int serverIndex)
callActivityMethod("resetLastServer", "(I)V", serverIndex);
}
void AndroidController::saveFile(const QString &fileName, const QString &data)
SystemController::SaveFileResult AndroidController::saveFile(const QString &fileName, const QString &data)
{
// keep in sync with SAVE_FILE_RESULT_* in AmneziaActivity.kt
int result = 2;
bool received = false;
QEventLoop wait;
const QMetaObject::Connection fileSavedConnection = connect(this, &AndroidController::fileSaved, this,
[&result, &received, &wait](int saveResult) {
result = saveResult;
received = true;
wait.quit();
});
callActivityMethod("saveFile", "(Ljava/lang/String;Ljava/lang/String;)V",
QJniObject::fromString(fileName).object<jstring>(),
QJniObject::fromString(data).object<jstring>());
while (!received) {
wait.exec();
if (received) {
break;
}
QEventLoop resumeWait;
const QMetaObject::Connection resumeConnection = connect(this, &AndroidController::activityResumed, &resumeWait,
&QEventLoop::quit,
static_cast<Qt::ConnectionType>(Qt::QueuedConnection | Qt::SingleShotConnection));
resumeWait.exec();
disconnect(resumeConnection);
}
disconnect(fileSavedConnection);
switch (result) {
case 0: return SystemController::SaveFileResult::Saved;
case 1: return SystemController::SaveFileResult::Cancelled;
default: return SystemController::SaveFileResult::Failed;
}
}
QString AndroidController::openFile(const QString &filter)
@@ -563,6 +598,15 @@ void AndroidController::onFileOpened(JNIEnv *env, jobject thiz, jstring uri)
emit AndroidController::instance()->fileOpened(AndroidUtils::convertJString(env, uri));
}
// static
void AndroidController::onFileSaved(JNIEnv *env, jobject thiz, jint result)
{
Q_UNUSED(env);
Q_UNUSED(thiz);
emit AndroidController::instance()->fileSaved(static_cast<int>(result));
}
// static
void AndroidController::onConfigImported(JNIEnv *env, jobject thiz, jstring data)
{
@@ -5,6 +5,7 @@
#include <QPixmap>
#include "core/protocols/vpnProtocol.h"
#include "ui/controllers/systemController.h"
using namespace amnezia;
@@ -32,7 +33,7 @@ public:
ErrorCode start(const QJsonObject &vpnConfig);
void stop();
void resetLastServer(int serverIndex);
void saveFile(const QString &fileName, const QString &data);
SystemController::SaveFileResult saveFile(const QString &fileName, const QString &data);
QString openFile(const QString &filter);
int getFd(const QString &fileName);
void closeFd();
@@ -75,6 +76,7 @@ signals:
void vpnStateChanged(ConnectionState state);
void statisticsUpdated(quint64 rxBytes, quint64 txBytes);
void fileOpened(QString uri);
void fileSaved(int result);
void configImported(QString config);
void importConfigFromOutside(QString config);
void initConnectionState(Vpn::ConnectionState state);
@@ -109,6 +111,7 @@ private:
static void onStatisticsUpdate(JNIEnv *env, jobject thiz, jlong rxBytes, jlong txBytes);
static void onConfigImported(JNIEnv *env, jobject thiz, jstring data);
static void onFileOpened(JNIEnv *env, jobject thiz, jstring uri);
static void onFileSaved(JNIEnv *env, jobject thiz, jint result);
static void onAuthResult(JNIEnv *env, jobject thiz, jboolean result);
static bool decodeQrCode(JNIEnv *env, jobject thiz, jstring data);
static void onImeInsetsChanged(JNIEnv *env, jobject thiz, jint heightDp);
+10 -1
View File
@@ -59,7 +59,16 @@ public:
void getBackendLogs(std::function<void(const QString &)> &&callback);
void checkStatus();
bool shareText(const QStringList &filesToSend);
// Outcome of the iOS share sheet.
// activityType is empty when the user dismissed the sheet without picking any destination.
struct ShareResult
{
bool completed = false;
QString activityType;
QString errorString;
};
bool shareText(const QStringList &filesToSend, ShareResult *result = nullptr);
QString openFile();
// Store-specific purchase failure reasons; values match StoreKit2Helper error codes
+22 -1
View File
@@ -941,7 +941,7 @@ void IosController::sendVpnExtensionMessage(NSDictionary* message, std::function
}
bool IosController::shareText(const QStringList& filesToSend) {
bool IosController::shareText(const QStringList& filesToSend, ShareResult *result) {
NSMutableArray *sharingItems = [NSMutableArray new];
for (int i = 0; i < filesToSend.size(); i++) {
@@ -951,18 +951,33 @@ bool IosController::shareText(const QStringList& filesToSend) {
#if !MACOS_NE
UIViewController *qtController = getViewController();
if (!qtController) {
qWarning() << "IosController::shareText: no root view controller, cannot present the share sheet";
if (result) {
result->errorString = QStringLiteral("no root view controller");
}
return false;
}
UIActivityViewController *activityController = [[UIActivityViewController alloc] initWithActivityItems:sharingItems applicationActivities:nil];
#endif
__block bool isAccepted = false;
__block QString pickedActivity;
__block QString errorString;
#if !MACOS_NE
[activityController setCompletionWithItemsHandler:^(NSString *activityType, BOOL completed, NSArray *returnedItems, NSError *activityError) {
isAccepted = completed;
pickedActivity = activityType ? QString::fromNSString(activityType) : QString();
if (activityError) {
errorString = QString::fromNSString(activityError.localizedDescription);
}
qDebug() << "IosController::shareText: completion handler, completed:" << (completed ? "YES" : "NO")
<< "activityType:" << (pickedActivity.isEmpty() ? QStringLiteral("<nil>") : pickedActivity)
<< "returnedItems:" << (returnedItems ? (int)returnedItems.count : -1)
<< "error:" << (errorString.isEmpty() ? QStringLiteral("<none>") : errorString);
emit finished();
}];
qDebug() << "IosController::shareText: presenting the share sheet for" << filesToSend.size() << "item(s)";
[qtController presentViewController:activityController animated:YES completion:nil];
UIPopoverPresentationController *popController = activityController.popoverPresentationController;
if (popController) {
@@ -975,6 +990,12 @@ bool IosController::shareText(const QStringList& filesToSend) {
QObject::connect(this, &IosController::finished, &wait, &QEventLoop::quit);
wait.exec();
if (result) {
result->completed = isAccepted;
result->activityType = pickedActivity;
result->errorString = errorString;
}
return isAccepted;
}
@@ -109,13 +109,21 @@ bool SubscriptionUiController::exportNativeConfig(const QString &serverId, const
}
QString nativeConfig;
qDebug() << "exportNativeConfig: requesting a new config from the gateway, country:" << serverCountryCode;
ErrorCode errorCode = m_subscriptionController->exportNativeConfig(serverId, serverCountryCode, nativeConfig);
if (errorCode != ErrorCode::NoError) {
qWarning() << "exportNativeConfig: the gateway request failed with" << errorCode;
emit errorOccurred(errorCode);
return false;
}
// at this point the gateway has already rotated the key: the previously issued config is dead
// and the new private key only lives inside nativeConfig
qDebug() << "exportNativeConfig: the gateway issued a new config, size:" << nativeConfig.size()
<< "- the previous one is now revoked";
const bool saved = SystemController::saveFile(fileName, nativeConfig);
qDebug() << "exportNativeConfig: saved:" << saved << "- refreshing the account info regardless,"
<< "the config is issued server side either way";
getAccountInfo(serverId, true);
return saved;
}
+102 -14
View File
@@ -20,49 +20,114 @@
#include <CoreFoundation/CoreFoundation.h>
#endif
namespace
{
const char *saveFileResultToString(SystemController::SaveFileResult result)
{
switch (result) {
case SystemController::SaveFileResult::Saved: return "Saved";
case SystemController::SaveFileResult::Cancelled: return "Cancelled";
case SystemController::SaveFileResult::Unknown: return "Unknown";
case SystemController::SaveFileResult::Failed: return "Failed";
}
return "?";
}
}
SystemController *SystemController::s_instance = nullptr;
SystemController::SystemController(QObject *parent)
: QObject(parent)
{
s_instance = this;
}
bool SystemController::saveFile(const QString &fileName, const QString &data)
SystemController::~SystemController()
{
if (s_instance == this) {
s_instance = nullptr;
}
}
void SystemController::notifySaveCancelled()
{
if (s_instance) {
emit s_instance->saveCancelledByUser();
} else {
qWarning() << "SystemController::saveFile: cancelled, but there is no SystemController instance to notify";
}
}
SystemController::SaveFileResult SystemController::saveFileEx(const QString &fileName, const QString &data)
{
#if defined Q_OS_ANDROID
AndroidController::instance()->saveFile(fileName, data);
return true;
const SaveFileResult result = AndroidController::instance()->saveFile(fileName, data);
return result;
#else
return saveFileEx(fileName, data.toUtf8());
#endif
return saveFile(fileName, data.toUtf8());
}
bool SystemController::saveFile(const QString &fileName, const QByteArray &data)
SystemController::SaveFileResult SystemController::saveFileEx(const QString &fileName, const QByteArray &data)
{
#if defined Q_OS_ANDROID
AndroidController::instance()->saveFile(fileName, QString::fromUtf8(data));
return true;
const SaveFileResult androidResult = AndroidController::instance()->saveFile(fileName, QString::fromUtf8(data));
return androidResult;
#endif
#ifdef Q_OS_IOS
QUrl fileUrl = QDir::tempPath() + "/" + fileName;
QFile file(fileUrl.toString());
const QString filePath = QDir::tempPath() + "/" + fileName;
QFile file(filePath);
qDebug() << "SystemController::saveFile: ios, staging" << data.size() << "bytes in" << filePath;
#else
QFile file(fileName);
qDebug() << "SystemController::saveFile: desktop, writing" << data.size() << "bytes to" << fileName;
#endif
if (!file.open(QIODevice::WriteOnly)) {
qWarning() << "SystemController::saveFile: cannot open" << fileName;
return false;
return SaveFileResult::Failed;
}
if (file.write(data) != data.size()) {
qWarning() << "SystemController::saveFile: write failed" << fileName;
file.close();
return false;
return SaveFileResult::Failed;
}
file.close();
#ifdef Q_OS_IOS
QStringList filesToSend;
filesToSend.append(fileUrl.toString());
return IosController::Instance()->shareText(filesToSend);
filesToSend.append(filePath);
IosController::ShareResult shareResult;
qDebug() << "SystemController::saveFile: ios, presenting the share sheet for" << fileName;
IosController::Instance()->shareText(filesToSend, &shareResult);
qDebug() << "SystemController::saveFile: ios share sheet closed, completed:" << shareResult.completed
<< "activityType:" << (shareResult.activityType.isEmpty() ? QStringLiteral("<none>") : shareResult.activityType)
<< "error:" << (shareResult.errorString.isEmpty() ? QStringLiteral("<none>") : shareResult.errorString);
// the temporary copy carries the config (and its private key), do not leave it behind
if (!QFile::remove(filePath)) {
qWarning() << "SystemController::saveFile: could not remove the temporary copy" << filePath;
}
if (shareResult.completed) {
return SaveFileResult::Saved;
}
// an empty activityType means no activity was ever started, i.e. the user closed the share sheet
if (shareResult.activityType.isEmpty()) {
if (!shareResult.errorString.isEmpty()) {
qWarning() << "SystemController::saveFile: cannot present the share sheet:" << shareResult.errorString;
return SaveFileResult::Failed;
}
qDebug() << "SystemController::saveFile: ios, the user dismissed the share sheet without picking a destination";
return SaveFileResult::Cancelled;
}
// a destination was picked but reported no success; some third-party share extensions
// report this even after a successful send, so do not claim either outcome
qWarning() << "SystemController::saveFile: share did not report success for" << shareResult.activityType
<< shareResult.errorString;
return SaveFileResult::Unknown;
#else
QFileInfo fi(fileName);
@@ -75,10 +140,28 @@ bool SystemController::saveFile(const QString &fileName, const QByteArray &data)
#ifndef MACOS_NE
QDesktopServices::openUrl(url);
#endif
return true;
return SaveFileResult::Saved;
#endif
}
bool SystemController::saveFile(const QString &fileName, const QString &data)
{
const SaveFileResult result = saveFileEx(fileName, data);
if (result == SaveFileResult::Cancelled) {
notifySaveCancelled();
}
return result == SaveFileResult::Saved;
}
bool SystemController::saveFile(const QString &fileName, const QByteArray &data)
{
const SaveFileResult result = saveFileEx(fileName, data);
if (result == SaveFileResult::Cancelled) {
notifySaveCancelled();
}
return result == SaveFileResult::Saved;
}
bool SystemController::readFile(const QString &fileName, QByteArray &data)
{
#ifdef Q_OS_ANDROID
@@ -156,10 +239,15 @@ QString SystemController::getFileName(const QString &acceptLabel, const QString
QObject::disconnect(this, &SystemController::fileDialogClosed, nullptr, nullptr);
if (!isFileDialogAccepted) {
qDebug() << "SystemController::getFileName: dialog cancelled by the user, isSaveMode:" << isSaveMode;
if (isSaveMode) {
notifySaveCancelled();
}
return "";
}
fileName = mainFileDialog->property("selectedFile").toString();
qDebug() << "SystemController::getFileName: picked" << fileName << "isSaveMode:" << isSaveMode;
return QUrl(fileName).toLocalFile();
}
+17
View File
@@ -9,6 +9,17 @@ class SystemController : public QObject
Q_OBJECT
public:
explicit SystemController(QObject *parent = nullptr);
~SystemController() override;
enum class SaveFileResult {
Saved,
Cancelled, // the user dismissed the save/share dialog without picking a destination
Unknown, // a destination was picked but it did not report success (some iOS share extensions do this)
Failed
};
static SaveFileResult saveFileEx(const QString &fileName, const QString &data);
static SaveFileResult saveFileEx(const QString &fileName, const QByteArray &data);
static bool saveFile(const QString &fileName, const QString &data);
static bool saveFile(const QString &fileName, const QByteArray &data);
@@ -26,8 +37,14 @@ public slots:
signals:
void fileDialogClosed(const bool isAccepted);
// emitted whenever the user dismisses a save/share dialog without choosing a destination
void saveCancelledByUser();
private:
static void notifySaveCancelled();
static SystemController *s_instance;
QObject *m_qmlRoot;
};