mirror of
https://github.com/wgtunnel/android.git
synced 2026-07-03 14:07:49 +02:00
Compare commits
41 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 5cc2ae0d01 | |||
| 7fdec509e9 | |||
| cab2945930 | |||
| 6a90cd02b9 | |||
| 7d810c7c3d | |||
| dad34b9e24 | |||
| fb33b8996f | |||
| ec3a5dcd65 | |||
| 7b443add3a | |||
| d70ef658e2 | |||
| c01b045022 | |||
| d3ea75869a | |||
| 0784c96011 | |||
| 553279ea76 | |||
| 89f6dec357 | |||
| ab7499a616 | |||
| 105c753c66 | |||
| d9f0de2dd4 | |||
| 82280091ad | |||
| b97b7cf989 | |||
| f83e40f6cc | |||
| 1fab9dfdf2 | |||
| a670931b06 | |||
| 2c0c88baf2 | |||
| 05e7cb7c04 | |||
| bc811f74ef | |||
| 09b669f54b | |||
| f08d73cbb7 | |||
| 7ca23d3ef5 | |||
| 7fdd95ea51 | |||
| e11f0f794a | |||
| fea31437cd | |||
| 1306fdc8b2 | |||
| d2e5d6d3bc | |||
| 960af02beb | |||
| 3f1ff22488 | |||
| d6b032845b | |||
| ffad6b331f | |||
| 1fb953e2fe | |||
| 893a03d3b1 | |||
| 30b577a03d |
+2
-1
@@ -1,2 +1,3 @@
|
||||
ko_fi: zaneschepke
|
||||
liberapay: zaneschepke
|
||||
liberapay: zaneschepke
|
||||
github: zaneschepke
|
||||
|
||||
@@ -15,6 +15,7 @@ A clear and concise description of what the bug is.
|
||||
- Device: [e.g. Pixel 4a]
|
||||
- Android Version: [e.g. Android 13]
|
||||
- App Version [e.g. 3.3.3]
|
||||
- Backend: [e.g. Kernel, Userspace]
|
||||
|
||||
**To Reproduce**
|
||||
Steps to reproduce the behavior:
|
||||
|
||||
@@ -33,25 +33,29 @@ on:
|
||||
workflow_call:
|
||||
|
||||
jobs:
|
||||
check_date:
|
||||
check_commits:
|
||||
name: Check for New Commits
|
||||
runs-on: ubuntu-latest
|
||||
name: Check latest commit
|
||||
outputs:
|
||||
should_run: ${{ steps.should_run.outputs.should_run }}
|
||||
has_new_commits: ${{ steps.check.outputs.new_commits }}
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: print latest_commit
|
||||
run: echo ${{ github.sha }}
|
||||
- id: should_run
|
||||
continue-on-error: true
|
||||
name: check latest commit is less than a day
|
||||
if: ${{ github.event_name == 'schedule' }}
|
||||
run: test -z $(git rev-list --after="23 hours" ${{ github.sha }}) && echo "::set-output name=should_run::false"
|
||||
- name: Checkout Repository
|
||||
uses: actions/checkout@v3
|
||||
with:
|
||||
fetch-depth: 0 # This fetches all history so we can check commits
|
||||
|
||||
- name: Check for new commits
|
||||
id: check
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
# This script checks for commits newer than 23 hours ago
|
||||
NEW_COMMITS=$(git rev-list --count --after="$(date -Iseconds -d '23 hours ago')" ${{ github.sha }})
|
||||
echo "new_commits=$NEW_COMMITS" >> $GITHUB_OUTPUT
|
||||
build:
|
||||
needs: check_date
|
||||
if: |
|
||||
github.event_name != 'schedule' ||
|
||||
(needs.check_date.outputs.should_run == 'true' && github.event_name == 'schedule')
|
||||
needs: check_commits
|
||||
if: ${{ needs.check_commits.outputs.has_new_commits > 0 && inputs.release_type != 'none' }}
|
||||
name: Build Signed APK
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
@@ -144,7 +148,7 @@ jobs:
|
||||
|
||||
# Save the APK after the Build job is complete to publish it as a Github release in the next job
|
||||
- name: Upload APK
|
||||
uses: actions/upload-artifact@v4.4.0
|
||||
uses: actions/upload-artifact@v4.4.3
|
||||
with:
|
||||
name: wgtunnel
|
||||
path: ${{ env.APK_PATH }}
|
||||
|
||||
@@ -44,6 +44,8 @@ android {
|
||||
getByName("debug").assets.srcDirs(files("$projectDir/schemas")) // Room
|
||||
}
|
||||
|
||||
buildConfigField("String[]", "LANGUAGES", "new String[]{ ${languageList().joinToString(separator = ", ") { "\"$it\"" }} }")
|
||||
|
||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||
vectorDrawables { useSupportLibrary = true }
|
||||
}
|
||||
@@ -72,12 +74,14 @@ android {
|
||||
"proguard-rules.pro",
|
||||
)
|
||||
signingConfig = signingConfigs.getByName(Constants.RELEASE)
|
||||
resValue("string", "provider", "\"${Constants.APP_NAME}.provider\"")
|
||||
}
|
||||
debug {
|
||||
applicationIdSuffix = ".debug"
|
||||
versionNameSuffix = "-debug"
|
||||
resValue("string", "app_name", "WG Tunnel - Debug")
|
||||
isDebuggable = true
|
||||
resValue("string", "provider", "\"${Constants.APP_NAME}.provider.debug\"")
|
||||
}
|
||||
|
||||
create(Constants.PRERELEASE) {
|
||||
@@ -85,6 +89,7 @@ android {
|
||||
applicationIdSuffix = ".prerelease"
|
||||
versionNameSuffix = "-pre"
|
||||
resValue("string", "app_name", "WG Tunnel - Pre")
|
||||
resValue("string", "provider", "\"${Constants.APP_NAME}.provider.pre\"")
|
||||
}
|
||||
|
||||
create(Constants.NIGHTLY) {
|
||||
@@ -92,6 +97,7 @@ android {
|
||||
applicationIdSuffix = ".nightly"
|
||||
versionNameSuffix = "-nightly"
|
||||
resValue("string", "app_name", "WG Tunnel - Nightly")
|
||||
resValue("string", "provider", "\"${Constants.APP_NAME}.provider.nightly\"")
|
||||
}
|
||||
|
||||
applicationVariants.all {
|
||||
@@ -129,8 +135,6 @@ android {
|
||||
packaging { resources { excludes += "/META-INF/{AL2.0,LGPL2.1}" } }
|
||||
}
|
||||
|
||||
val generalImplementation by configurations
|
||||
|
||||
dependencies {
|
||||
|
||||
implementation(project(":logcatter"))
|
||||
@@ -147,6 +151,7 @@ dependencies {
|
||||
implementation(libs.androidx.compose.ui.tooling.preview)
|
||||
implementation(libs.androidx.material3)
|
||||
implementation(libs.androidx.appcompat)
|
||||
implementation(libs.material)
|
||||
|
||||
// test
|
||||
testImplementation(libs.junit)
|
||||
|
||||
@@ -0,0 +1,232 @@
|
||||
{
|
||||
"formatVersion": 1,
|
||||
"database": {
|
||||
"version": 11,
|
||||
"identityHash": "4c9418386f72dfac5d28ab96c1e5ea0b",
|
||||
"entities": [
|
||||
{
|
||||
"tableName": "Settings",
|
||||
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `is_tunnel_enabled` INTEGER NOT NULL, `is_tunnel_on_mobile_data_enabled` INTEGER NOT NULL, `trusted_network_ssids` TEXT NOT NULL, `is_always_on_vpn_enabled` INTEGER NOT NULL, `is_tunnel_on_ethernet_enabled` INTEGER NOT NULL, `is_shortcuts_enabled` INTEGER NOT NULL DEFAULT false, `is_tunnel_on_wifi_enabled` INTEGER NOT NULL DEFAULT false, `is_kernel_enabled` INTEGER NOT NULL DEFAULT false, `is_restore_on_boot_enabled` INTEGER NOT NULL DEFAULT false, `is_multi_tunnel_enabled` INTEGER NOT NULL DEFAULT false, `is_ping_enabled` INTEGER NOT NULL DEFAULT false, `is_amnezia_enabled` INTEGER NOT NULL DEFAULT false, `is_wildcards_enabled` INTEGER NOT NULL DEFAULT false, `is_wifi_by_shell_enabled` INTEGER NOT NULL DEFAULT false)",
|
||||
"fields": [
|
||||
{
|
||||
"fieldPath": "id",
|
||||
"columnName": "id",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "isAutoTunnelEnabled",
|
||||
"columnName": "is_tunnel_enabled",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "isTunnelOnMobileDataEnabled",
|
||||
"columnName": "is_tunnel_on_mobile_data_enabled",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "trustedNetworkSSIDs",
|
||||
"columnName": "trusted_network_ssids",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "isAlwaysOnVpnEnabled",
|
||||
"columnName": "is_always_on_vpn_enabled",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "isTunnelOnEthernetEnabled",
|
||||
"columnName": "is_tunnel_on_ethernet_enabled",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "isShortcutsEnabled",
|
||||
"columnName": "is_shortcuts_enabled",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true,
|
||||
"defaultValue": "false"
|
||||
},
|
||||
{
|
||||
"fieldPath": "isTunnelOnWifiEnabled",
|
||||
"columnName": "is_tunnel_on_wifi_enabled",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true,
|
||||
"defaultValue": "false"
|
||||
},
|
||||
{
|
||||
"fieldPath": "isKernelEnabled",
|
||||
"columnName": "is_kernel_enabled",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true,
|
||||
"defaultValue": "false"
|
||||
},
|
||||
{
|
||||
"fieldPath": "isRestoreOnBootEnabled",
|
||||
"columnName": "is_restore_on_boot_enabled",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true,
|
||||
"defaultValue": "false"
|
||||
},
|
||||
{
|
||||
"fieldPath": "isMultiTunnelEnabled",
|
||||
"columnName": "is_multi_tunnel_enabled",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true,
|
||||
"defaultValue": "false"
|
||||
},
|
||||
{
|
||||
"fieldPath": "isPingEnabled",
|
||||
"columnName": "is_ping_enabled",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true,
|
||||
"defaultValue": "false"
|
||||
},
|
||||
{
|
||||
"fieldPath": "isAmneziaEnabled",
|
||||
"columnName": "is_amnezia_enabled",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true,
|
||||
"defaultValue": "false"
|
||||
},
|
||||
{
|
||||
"fieldPath": "isWildcardsEnabled",
|
||||
"columnName": "is_wildcards_enabled",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true,
|
||||
"defaultValue": "false"
|
||||
},
|
||||
{
|
||||
"fieldPath": "isWifiNameByShellEnabled",
|
||||
"columnName": "is_wifi_by_shell_enabled",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true,
|
||||
"defaultValue": "false"
|
||||
}
|
||||
],
|
||||
"primaryKey": {
|
||||
"autoGenerate": true,
|
||||
"columnNames": [
|
||||
"id"
|
||||
]
|
||||
},
|
||||
"indices": [],
|
||||
"foreignKeys": []
|
||||
},
|
||||
{
|
||||
"tableName": "TunnelConfig",
|
||||
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `wg_quick` TEXT NOT NULL, `tunnel_networks` TEXT NOT NULL DEFAULT '', `is_mobile_data_tunnel` INTEGER NOT NULL DEFAULT false, `is_primary_tunnel` INTEGER NOT NULL DEFAULT false, `am_quick` TEXT NOT NULL DEFAULT '', `is_Active` INTEGER NOT NULL DEFAULT false, `is_ping_enabled` INTEGER NOT NULL DEFAULT false, `ping_interval` INTEGER DEFAULT null, `ping_cooldown` INTEGER DEFAULT null, `ping_ip` TEXT DEFAULT null)",
|
||||
"fields": [
|
||||
{
|
||||
"fieldPath": "id",
|
||||
"columnName": "id",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "name",
|
||||
"columnName": "name",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "wgQuick",
|
||||
"columnName": "wg_quick",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "tunnelNetworks",
|
||||
"columnName": "tunnel_networks",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true,
|
||||
"defaultValue": "''"
|
||||
},
|
||||
{
|
||||
"fieldPath": "isMobileDataTunnel",
|
||||
"columnName": "is_mobile_data_tunnel",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true,
|
||||
"defaultValue": "false"
|
||||
},
|
||||
{
|
||||
"fieldPath": "isPrimaryTunnel",
|
||||
"columnName": "is_primary_tunnel",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true,
|
||||
"defaultValue": "false"
|
||||
},
|
||||
{
|
||||
"fieldPath": "amQuick",
|
||||
"columnName": "am_quick",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true,
|
||||
"defaultValue": "''"
|
||||
},
|
||||
{
|
||||
"fieldPath": "isActive",
|
||||
"columnName": "is_Active",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true,
|
||||
"defaultValue": "false"
|
||||
},
|
||||
{
|
||||
"fieldPath": "isPingEnabled",
|
||||
"columnName": "is_ping_enabled",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true,
|
||||
"defaultValue": "false"
|
||||
},
|
||||
{
|
||||
"fieldPath": "pingInterval",
|
||||
"columnName": "ping_interval",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": false,
|
||||
"defaultValue": "null"
|
||||
},
|
||||
{
|
||||
"fieldPath": "pingCooldown",
|
||||
"columnName": "ping_cooldown",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": false,
|
||||
"defaultValue": "null"
|
||||
},
|
||||
{
|
||||
"fieldPath": "pingIp",
|
||||
"columnName": "ping_ip",
|
||||
"affinity": "TEXT",
|
||||
"notNull": false,
|
||||
"defaultValue": "null"
|
||||
}
|
||||
],
|
||||
"primaryKey": {
|
||||
"autoGenerate": true,
|
||||
"columnNames": [
|
||||
"id"
|
||||
]
|
||||
},
|
||||
"indices": [
|
||||
{
|
||||
"name": "index_TunnelConfig_name",
|
||||
"unique": true,
|
||||
"columnNames": [
|
||||
"name"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_TunnelConfig_name` ON `${TABLE_NAME}` (`name`)"
|
||||
}
|
||||
],
|
||||
"foreignKeys": []
|
||||
}
|
||||
],
|
||||
"views": [],
|
||||
"setupQueries": [
|
||||
"CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
|
||||
"INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '4c9418386f72dfac5d28ab96c1e5ea0b')"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -3,17 +3,7 @@
|
||||
xmlns:tools="http://schemas.android.com/tools">
|
||||
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<uses-permission
|
||||
android:name="android.permission.READ_EXTERNAL_STORAGE"
|
||||
android:maxSdkVersion="32" />
|
||||
<uses-permission
|
||||
android:name="android.permission.WRITE_EXTERNAL_STORAGE"
|
||||
android:maxSdkVersion="32"
|
||||
tools:ignore="ScopedStorage" />
|
||||
<uses-permission
|
||||
android:name="android.permission.ACCESS_WIFI_STATE"
|
||||
android:maxSdkVersion="30"
|
||||
tools:ignore="LeanbackUsesWifi" />
|
||||
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
|
||||
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
|
||||
@@ -22,7 +12,8 @@
|
||||
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
|
||||
<!--foreground service exempt android 14-->
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SYSTEM_EXEMPTED" />
|
||||
<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />
|
||||
<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM"
|
||||
tools:ignore="ProtectedPermissions" />
|
||||
|
||||
<!--foreground service permissions-->
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||
@@ -49,6 +40,12 @@
|
||||
<uses-feature
|
||||
android:name="android.hardware.screen.portrait"
|
||||
android:required="false" />
|
||||
<uses-feature
|
||||
android:name="android.hardware.gamepad"
|
||||
android:required="false"/>
|
||||
|
||||
<uses-feature android:name="android.hardware.wifi"
|
||||
android:required="false"/>
|
||||
|
||||
<queries>
|
||||
<intent>
|
||||
@@ -66,12 +63,12 @@
|
||||
android:label="@string/app_name"
|
||||
android:roundIcon="@mipmap/ic_launcher_round"
|
||||
android:supportsRtl="true"
|
||||
android:theme="@style/Theme.AppSplashScreen"
|
||||
android:theme="@style/Theme.App.Start"
|
||||
tools:targetApi="tiramisu">
|
||||
<activity
|
||||
android:name=".ui.SplashActivity"
|
||||
android:name=".ui.MainActivity"
|
||||
android:exported="true"
|
||||
android:theme="@style/Theme.AppSplashScreen">
|
||||
android:theme="@style/Theme.WireguardAutoTunnel">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
|
||||
@@ -83,11 +80,6 @@
|
||||
android:name="android.app.shortcuts"
|
||||
android:resource="@xml/shortcuts" />
|
||||
</activity>
|
||||
<activity
|
||||
android:name=".ui.MainActivity"
|
||||
android:exported="true"
|
||||
android:theme="@style/Theme.WireguardAutoTunnel">
|
||||
</activity>
|
||||
<activity
|
||||
android:name="com.journeyapps.barcodescanner.CaptureActivity"
|
||||
android:screenOrientation="portrait"
|
||||
@@ -103,6 +95,16 @@
|
||||
android:launchMode="singleInstance"
|
||||
android:theme="@android:style/Theme.NoDisplay" />
|
||||
|
||||
<provider
|
||||
android:name="androidx.core.content.FileProvider"
|
||||
android:authorities="@string/provider"
|
||||
android:exported="false"
|
||||
android:grantUriPermissions="true">
|
||||
<meta-data
|
||||
android:name="android.support.FILE_PROVIDER_PATHS"
|
||||
android:resource="@xml/file_paths" />
|
||||
</provider>
|
||||
|
||||
<service
|
||||
android:name=".service.tile.TunnelControlTile"
|
||||
android:exported="true"
|
||||
@@ -164,6 +166,7 @@
|
||||
<service
|
||||
android:name=".service.foreground.TunnelBackgroundService"
|
||||
android:exported="false"
|
||||
android:persistent="true"
|
||||
android:foregroundServiceType="systemExempted"
|
||||
android:permission="android.permission.BIND_VPN_SERVICE">
|
||||
<intent-filter>
|
||||
@@ -184,10 +187,6 @@
|
||||
<action android:name="com.htc.intent.action.QUICKBOOT_POWERON" />
|
||||
</intent-filter>
|
||||
</receiver>
|
||||
<receiver
|
||||
android:name=".receiver.BackgroundActionReceiver"
|
||||
android:enabled="true"
|
||||
android:exported="false"/>
|
||||
<receiver
|
||||
android:name=".receiver.AppUpdateReceiver"
|
||||
android:exported="false">
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
package com.zaneschepke.wireguardautotunnel
|
||||
|
||||
import android.app.Application
|
||||
import android.content.Context
|
||||
import android.os.StrictMode
|
||||
import android.os.StrictMode.ThreadPolicy
|
||||
import com.zaneschepke.logcatter.LocalLogCollector
|
||||
import com.zaneschepke.logcatter.LogReader
|
||||
import com.zaneschepke.wireguardautotunnel.data.datastore.LocaleStorage
|
||||
import com.zaneschepke.wireguardautotunnel.module.ApplicationScope
|
||||
import com.zaneschepke.wireguardautotunnel.module.IoDispatcher
|
||||
import com.zaneschepke.wireguardautotunnel.util.LocaleUtil
|
||||
import com.zaneschepke.wireguardautotunnel.util.ReleaseTree
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.isRunningOnTv
|
||||
import dagger.hilt.android.HiltAndroidApp
|
||||
@@ -18,12 +21,16 @@ import javax.inject.Inject
|
||||
@HiltAndroidApp
|
||||
class WireGuardAutoTunnel : Application() {
|
||||
|
||||
val localeStorage: LocaleStorage by lazy {
|
||||
LocaleStorage(this)
|
||||
}
|
||||
|
||||
@Inject
|
||||
@ApplicationScope
|
||||
lateinit var applicationScope: CoroutineScope
|
||||
|
||||
@Inject
|
||||
lateinit var localLogCollector: LocalLogCollector
|
||||
lateinit var logReader: LogReader
|
||||
|
||||
@Inject
|
||||
@IoDispatcher
|
||||
@@ -47,11 +54,15 @@ class WireGuardAutoTunnel : Application() {
|
||||
}
|
||||
if (!isRunningOnTv()) {
|
||||
applicationScope.launch(ioDispatcher) {
|
||||
localLogCollector.start()
|
||||
logReader.start()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun attachBaseContext(base: Context) {
|
||||
super.attachBaseContext(LocaleUtil.getLocalizedContext(base, LocaleStorage(base).getPreferredLocale()))
|
||||
}
|
||||
|
||||
companion object {
|
||||
lateinit var instance: WireGuardAutoTunnel
|
||||
private set
|
||||
|
||||
@@ -11,7 +11,7 @@ import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
|
||||
|
||||
@Database(
|
||||
entities = [Settings::class, TunnelConfig::class],
|
||||
version = 10,
|
||||
version = 11,
|
||||
autoMigrations =
|
||||
[
|
||||
AutoMigration(from = 1, to = 2),
|
||||
@@ -36,6 +36,11 @@ import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
|
||||
AutoMigration(7, 8),
|
||||
AutoMigration(8, 9),
|
||||
AutoMigration(9, 10),
|
||||
AutoMigration(
|
||||
from = 10,
|
||||
to = 11,
|
||||
spec = RemoveTunnelPauseMigration::class,
|
||||
),
|
||||
],
|
||||
exportSchema = true,
|
||||
)
|
||||
@@ -55,3 +60,9 @@ abstract class AppDatabase : RoomDatabase() {
|
||||
columnName = "is_battery_saver_enabled",
|
||||
)
|
||||
class RemoveLegacySettingColumnsMigration : AutoMigrationSpec
|
||||
|
||||
@DeleteColumn(
|
||||
tableName = "Settings",
|
||||
columnName = "is_auto_tunnel_paused",
|
||||
)
|
||||
class RemoveTunnelPauseMigration : AutoMigrationSpec
|
||||
|
||||
+6
-4
@@ -21,10 +21,12 @@ class DataStoreManager(
|
||||
@IoDispatcher private val ioDispatcher: CoroutineDispatcher,
|
||||
) {
|
||||
companion object {
|
||||
val LOCATION_DISCLOSURE_SHOWN = booleanPreferencesKey("LOCATION_DISCLOSURE_SHOWN")
|
||||
val BATTERY_OPTIMIZE_DISABLE_SHOWN = booleanPreferencesKey("BATTERY_OPTIMIZE_DISABLE_SHOWN")
|
||||
val CURRENT_SSID = stringPreferencesKey("CURRENT_SSID")
|
||||
val IS_PIN_LOCK_ENABLED = booleanPreferencesKey("PIN_LOCK_ENABLED")
|
||||
val locationDisclosureShown = booleanPreferencesKey("LOCATION_DISCLOSURE_SHOWN")
|
||||
val batteryDisableShown = booleanPreferencesKey("BATTERY_OPTIMIZE_DISABLE_SHOWN")
|
||||
val currentSSID = stringPreferencesKey("CURRENT_SSID")
|
||||
val pinLockEnabled = booleanPreferencesKey("PIN_LOCK_ENABLED")
|
||||
val tunnelStatsExpanded = booleanPreferencesKey("TUNNEL_STATS_EXPANDED")
|
||||
val theme = stringPreferencesKey("THEME")
|
||||
}
|
||||
|
||||
// preferences
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.zaneschepke.wireguardautotunnel.data.datastore
|
||||
|
||||
import android.content.Context
|
||||
import android.content.SharedPreferences
|
||||
import com.zaneschepke.wireguardautotunnel.util.LocaleUtil
|
||||
|
||||
class LocaleStorage(context: Context) {
|
||||
private var preferences: SharedPreferences = context.getSharedPreferences("sp", Context.MODE_PRIVATE)
|
||||
|
||||
fun getPreferredLocale(): String {
|
||||
return preferences.getString("preferred_locale", LocaleUtil.OPTION_PHONE_LANGUAGE)!!
|
||||
}
|
||||
|
||||
fun setPreferredLocale(localeCode: String) {
|
||||
preferences.edit().putString("preferred_locale", localeCode).apply()
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,18 @@
|
||||
package com.zaneschepke.wireguardautotunnel.data.domain
|
||||
|
||||
import com.zaneschepke.wireguardautotunnel.ui.theme.Theme
|
||||
|
||||
data class GeneralState(
|
||||
val isLocationDisclosureShown: Boolean = LOCATION_DISCLOSURE_SHOWN_DEFAULT,
|
||||
val isBatteryOptimizationDisableShown: Boolean = BATTERY_OPTIMIZATION_DISABLE_SHOWN_DEFAULT,
|
||||
val isPinLockEnabled: Boolean = PIN_LOCK_ENABLED_DEFAULT,
|
||||
val isTunnelStatsExpanded: Boolean = IS_TUNNEL_STATS_EXPANDED,
|
||||
val theme: Theme = Theme.AUTOMATIC,
|
||||
) {
|
||||
companion object {
|
||||
const val LOCATION_DISCLOSURE_SHOWN_DEFAULT = false
|
||||
const val BATTERY_OPTIMIZATION_DISABLE_SHOWN_DEFAULT = false
|
||||
const val PIN_LOCK_ENABLED_DEFAULT = false
|
||||
const val IS_TUNNEL_STATS_EXPANDED = false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -40,11 +40,6 @@ data class Settings(
|
||||
defaultValue = "false",
|
||||
)
|
||||
val isMultiTunnelEnabled: Boolean = false,
|
||||
@ColumnInfo(
|
||||
name = "is_auto_tunnel_paused",
|
||||
defaultValue = "false",
|
||||
)
|
||||
val isAutoTunnelPaused: Boolean = false,
|
||||
@ColumnInfo(
|
||||
name = "is_ping_enabled",
|
||||
defaultValue = "false",
|
||||
@@ -55,4 +50,14 @@ data class Settings(
|
||||
defaultValue = "false",
|
||||
)
|
||||
val isAmneziaEnabled: Boolean = false,
|
||||
@ColumnInfo(
|
||||
name = "is_wildcards_enabled",
|
||||
defaultValue = "false",
|
||||
)
|
||||
val isWildcardsEnabled: Boolean = false,
|
||||
@ColumnInfo(
|
||||
name = "is_wifi_by_shell_enabled",
|
||||
defaultValue = "false",
|
||||
)
|
||||
val isWifiNameByShellEnabled: Boolean = false,
|
||||
)
|
||||
|
||||
+9
@@ -1,6 +1,7 @@
|
||||
package com.zaneschepke.wireguardautotunnel.data.repository
|
||||
|
||||
import com.zaneschepke.wireguardautotunnel.data.domain.GeneralState
|
||||
import com.zaneschepke.wireguardautotunnel.ui.theme.Theme
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
|
||||
interface AppStateRepository {
|
||||
@@ -20,5 +21,13 @@ interface AppStateRepository {
|
||||
|
||||
suspend fun setCurrentSsid(ssid: String)
|
||||
|
||||
suspend fun isTunnelStatsExpanded(): Boolean
|
||||
|
||||
suspend fun setTunnelStatsExpanded(expanded: Boolean)
|
||||
|
||||
suspend fun setTheme(theme: Theme)
|
||||
|
||||
suspend fun getTheme(): Theme
|
||||
|
||||
val generalStateFlow: Flow<GeneralState>
|
||||
}
|
||||
|
||||
+37
-11
@@ -2,6 +2,7 @@ package com.zaneschepke.wireguardautotunnel.data.repository
|
||||
|
||||
import com.zaneschepke.wireguardautotunnel.data.datastore.DataStoreManager
|
||||
import com.zaneschepke.wireguardautotunnel.data.domain.GeneralState
|
||||
import com.zaneschepke.wireguardautotunnel.ui.theme.Theme
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.map
|
||||
import timber.log.Timber
|
||||
@@ -11,38 +12,61 @@ class DataStoreAppStateRepository(
|
||||
) :
|
||||
AppStateRepository {
|
||||
override suspend fun isLocationDisclosureShown(): Boolean {
|
||||
return dataStoreManager.getFromStore(DataStoreManager.LOCATION_DISCLOSURE_SHOWN)
|
||||
return dataStoreManager.getFromStore(DataStoreManager.locationDisclosureShown)
|
||||
?: GeneralState.LOCATION_DISCLOSURE_SHOWN_DEFAULT
|
||||
}
|
||||
|
||||
override suspend fun setLocationDisclosureShown(shown: Boolean) {
|
||||
dataStoreManager.saveToDataStore(DataStoreManager.LOCATION_DISCLOSURE_SHOWN, shown)
|
||||
dataStoreManager.saveToDataStore(DataStoreManager.locationDisclosureShown, shown)
|
||||
}
|
||||
|
||||
override suspend fun isPinLockEnabled(): Boolean {
|
||||
return dataStoreManager.getFromStore(DataStoreManager.IS_PIN_LOCK_ENABLED)
|
||||
return dataStoreManager.getFromStore(DataStoreManager.pinLockEnabled)
|
||||
?: GeneralState.PIN_LOCK_ENABLED_DEFAULT
|
||||
}
|
||||
|
||||
override suspend fun setPinLockEnabled(enabled: Boolean) {
|
||||
dataStoreManager.saveToDataStore(DataStoreManager.IS_PIN_LOCK_ENABLED, enabled)
|
||||
dataStoreManager.saveToDataStore(DataStoreManager.pinLockEnabled, enabled)
|
||||
}
|
||||
|
||||
override suspend fun isBatteryOptimizationDisableShown(): Boolean {
|
||||
return dataStoreManager.getFromStore(DataStoreManager.BATTERY_OPTIMIZE_DISABLE_SHOWN)
|
||||
return dataStoreManager.getFromStore(DataStoreManager.batteryDisableShown)
|
||||
?: GeneralState.BATTERY_OPTIMIZATION_DISABLE_SHOWN_DEFAULT
|
||||
}
|
||||
|
||||
override suspend fun setBatteryOptimizationDisableShown(shown: Boolean) {
|
||||
dataStoreManager.saveToDataStore(DataStoreManager.BATTERY_OPTIMIZE_DISABLE_SHOWN, shown)
|
||||
dataStoreManager.saveToDataStore(DataStoreManager.batteryDisableShown, shown)
|
||||
}
|
||||
|
||||
override suspend fun getCurrentSsid(): String? {
|
||||
return dataStoreManager.getFromStore(DataStoreManager.CURRENT_SSID)
|
||||
return dataStoreManager.getFromStore(DataStoreManager.currentSSID)
|
||||
}
|
||||
|
||||
override suspend fun setCurrentSsid(ssid: String) {
|
||||
dataStoreManager.saveToDataStore(DataStoreManager.CURRENT_SSID, ssid)
|
||||
dataStoreManager.saveToDataStore(DataStoreManager.currentSSID, ssid)
|
||||
}
|
||||
|
||||
override suspend fun isTunnelStatsExpanded(): Boolean {
|
||||
return dataStoreManager.getFromStore(DataStoreManager.tunnelStatsExpanded)
|
||||
?: GeneralState.IS_TUNNEL_STATS_EXPANDED
|
||||
}
|
||||
|
||||
override suspend fun setTunnelStatsExpanded(expanded: Boolean) {
|
||||
dataStoreManager.saveToDataStore(DataStoreManager.tunnelStatsExpanded, expanded)
|
||||
}
|
||||
|
||||
override suspend fun setTheme(theme: Theme) {
|
||||
dataStoreManager.saveToDataStore(DataStoreManager.theme, theme.name)
|
||||
}
|
||||
|
||||
override suspend fun getTheme(): Theme {
|
||||
return dataStoreManager.getFromStore(DataStoreManager.theme)?.let {
|
||||
try {
|
||||
Theme.valueOf(it)
|
||||
} catch (_: IllegalArgumentException) {
|
||||
Theme.AUTOMATIC
|
||||
}
|
||||
} ?: Theme.AUTOMATIC
|
||||
}
|
||||
|
||||
override val generalStateFlow: Flow<GeneralState> =
|
||||
@@ -51,14 +75,16 @@ class DataStoreAppStateRepository(
|
||||
try {
|
||||
GeneralState(
|
||||
isLocationDisclosureShown =
|
||||
pref[DataStoreManager.LOCATION_DISCLOSURE_SHOWN]
|
||||
pref[DataStoreManager.locationDisclosureShown]
|
||||
?: GeneralState.LOCATION_DISCLOSURE_SHOWN_DEFAULT,
|
||||
isBatteryOptimizationDisableShown =
|
||||
pref[DataStoreManager.BATTERY_OPTIMIZE_DISABLE_SHOWN]
|
||||
pref[DataStoreManager.batteryDisableShown]
|
||||
?: GeneralState.BATTERY_OPTIMIZATION_DISABLE_SHOWN_DEFAULT,
|
||||
isPinLockEnabled =
|
||||
pref[DataStoreManager.IS_PIN_LOCK_ENABLED]
|
||||
pref[DataStoreManager.pinLockEnabled]
|
||||
?: GeneralState.PIN_LOCK_ENABLED_DEFAULT,
|
||||
isTunnelStatsExpanded = pref[DataStoreManager.tunnelStatsExpanded] ?: GeneralState.IS_TUNNEL_STATS_EXPANDED,
|
||||
theme = getTheme(),
|
||||
)
|
||||
} catch (e: IllegalArgumentException) {
|
||||
Timber.e(e)
|
||||
|
||||
-6
@@ -1,11 +1,9 @@
|
||||
package com.zaneschepke.wireguardautotunnel.data.repository
|
||||
|
||||
import com.zaneschepke.wireguardautotunnel.WireGuardAutoTunnel
|
||||
import com.zaneschepke.wireguardautotunnel.data.TunnelConfigDao
|
||||
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
|
||||
import com.zaneschepke.wireguardautotunnel.module.IoDispatcher
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.TunnelConfigs
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.requestTunnelTileServiceStateUpdate
|
||||
import kotlinx.coroutines.CoroutineDispatcher
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.withContext
|
||||
@@ -26,8 +24,6 @@ class RoomTunnelConfigRepository(
|
||||
override suspend fun save(tunnelConfig: TunnelConfig) {
|
||||
withContext(ioDispatcher) {
|
||||
tunnelConfigDao.save(tunnelConfig)
|
||||
}.also {
|
||||
WireGuardAutoTunnel.instance.requestTunnelTileServiceStateUpdate()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -60,8 +56,6 @@ class RoomTunnelConfigRepository(
|
||||
override suspend fun delete(tunnelConfig: TunnelConfig) {
|
||||
withContext(ioDispatcher) {
|
||||
tunnelConfigDao.delete(tunnelConfig)
|
||||
}.also {
|
||||
WireGuardAutoTunnel.instance.requestTunnelTileServiceStateUpdate()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
package com.zaneschepke.wireguardautotunnel.module
|
||||
|
||||
import android.content.Context
|
||||
import com.zaneschepke.logcatter.LocalLogCollector
|
||||
import com.zaneschepke.logcatter.LogcatUtil
|
||||
import com.zaneschepke.logcatter.LogReader
|
||||
import com.zaneschepke.logcatter.LogcatCollector
|
||||
import dagger.Module
|
||||
import dagger.Provides
|
||||
import dagger.hilt.InstallIn
|
||||
@@ -24,7 +24,7 @@ class AppModule {
|
||||
|
||||
@Singleton
|
||||
@Provides
|
||||
fun provideLogCollect(@ApplicationContext context: Context): LocalLogCollector {
|
||||
return LogcatUtil.init(context = context)
|
||||
fun provideLogCollect(@ApplicationContext context: Context): LogReader {
|
||||
return LogcatCollector.init(context = context)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,3 +9,11 @@ annotation class Kernel
|
||||
@Qualifier
|
||||
@Retention(AnnotationRetention.BINARY)
|
||||
annotation class Userspace
|
||||
|
||||
@Qualifier
|
||||
@Retention(AnnotationRetention.BINARY)
|
||||
annotation class TunnelShell
|
||||
|
||||
@Qualifier
|
||||
@Retention(AnnotationRetention.BINARY)
|
||||
annotation class AppShell
|
||||
|
||||
@@ -1,22 +0,0 @@
|
||||
package com.zaneschepke.wireguardautotunnel.module
|
||||
|
||||
import android.content.Context
|
||||
import androidx.navigation.NavHostController
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.navigation.NavigationService
|
||||
import dagger.Module
|
||||
import dagger.Provides
|
||||
import dagger.hilt.InstallIn
|
||||
import dagger.hilt.android.components.ActivityRetainedComponent
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import dagger.hilt.android.scopes.ActivityRetainedScoped
|
||||
|
||||
@Module
|
||||
@InstallIn(ActivityRetainedComponent::class)
|
||||
object NavigationModule {
|
||||
|
||||
@Provides
|
||||
@ActivityRetainedScoped
|
||||
fun provideNestedNavController(@ApplicationContext context: Context): NavHostController {
|
||||
return NavigationService(context).navController
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import com.wireguard.android.util.RootShell
|
||||
import com.wireguard.android.util.ToolsInstaller
|
||||
import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository
|
||||
import com.zaneschepke.wireguardautotunnel.data.repository.TunnelConfigRepository
|
||||
import com.zaneschepke.wireguardautotunnel.service.foreground.ServiceManager
|
||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelService
|
||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.WireGuardTunnel
|
||||
import dagger.Module
|
||||
@@ -24,9 +25,18 @@ import javax.inject.Singleton
|
||||
@Module
|
||||
@InstallIn(SingletonComponent::class)
|
||||
class TunnelModule {
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideRootShell(@ApplicationContext context: Context): RootShell {
|
||||
@TunnelShell
|
||||
fun provideTunnelRootShell(@ApplicationContext context: Context): RootShell {
|
||||
return RootShell(context)
|
||||
}
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
@AppShell
|
||||
fun provideAppRootShell(@ApplicationContext context: Context): RootShell {
|
||||
return RootShell(context)
|
||||
}
|
||||
|
||||
@@ -39,14 +49,14 @@ class TunnelModule {
|
||||
@Provides
|
||||
@Singleton
|
||||
@Userspace
|
||||
fun provideUserspaceBackend(@ApplicationContext context: Context, rootShell: RootShell): Backend {
|
||||
fun provideUserspaceBackend(@ApplicationContext context: Context, @TunnelShell rootShell: RootShell): Backend {
|
||||
return GoBackend(context, RootTunnelActionHandler(rootShell))
|
||||
}
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
@Kernel
|
||||
fun provideKernelBackend(@ApplicationContext context: Context, rootShell: RootShell): Backend {
|
||||
fun provideKernelBackend(@ApplicationContext context: Context, @TunnelShell rootShell: RootShell): Backend {
|
||||
return WgQuickBackend(context, rootShell, ToolsInstaller(context, rootShell), RootTunnelActionHandler(rootShell))
|
||||
}
|
||||
|
||||
@@ -65,6 +75,7 @@ class TunnelModule {
|
||||
tunnelConfigRepository: TunnelConfigRepository,
|
||||
@ApplicationScope applicationScope: CoroutineScope,
|
||||
@IoDispatcher ioDispatcher: CoroutineDispatcher,
|
||||
serviceManager: ServiceManager,
|
||||
): TunnelService {
|
||||
return WireGuardTunnel(
|
||||
amneziaBackend,
|
||||
@@ -73,6 +84,13 @@ class TunnelModule {
|
||||
appDataRepository,
|
||||
applicationScope,
|
||||
ioDispatcher,
|
||||
serviceManager,
|
||||
)
|
||||
}
|
||||
|
||||
@Singleton
|
||||
@Provides
|
||||
fun provideServiceManager(@ApplicationContext context: Context): ServiceManager {
|
||||
return ServiceManager.getInstance(context)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,12 +7,12 @@ import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository
|
||||
import com.zaneschepke.wireguardautotunnel.module.ApplicationScope
|
||||
import com.zaneschepke.wireguardautotunnel.service.foreground.ServiceManager
|
||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelService
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.startTunnelBackground
|
||||
import dagger.hilt.android.AndroidEntryPoint
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.launch
|
||||
import timber.log.Timber
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Provider
|
||||
|
||||
@AndroidEntryPoint
|
||||
class AppUpdateReceiver : BroadcastReceiver() {
|
||||
@@ -25,7 +25,10 @@ class AppUpdateReceiver : BroadcastReceiver() {
|
||||
lateinit var appDataRepository: AppDataRepository
|
||||
|
||||
@Inject
|
||||
lateinit var tunnelService: TunnelService
|
||||
lateinit var tunnelService: Provider<TunnelService>
|
||||
|
||||
@Inject
|
||||
lateinit var serviceManager: ServiceManager
|
||||
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
if (intent.action != Intent.ACTION_MY_PACKAGE_REPLACED) return
|
||||
@@ -33,11 +36,11 @@ class AppUpdateReceiver : BroadcastReceiver() {
|
||||
val settings = appDataRepository.settings.getSettings()
|
||||
if (settings.isAutoTunnelEnabled) {
|
||||
Timber.i("Restarting services after upgrade")
|
||||
ServiceManager.startWatcherServiceForeground(context)
|
||||
serviceManager.startAutoTunnel(true)
|
||||
}
|
||||
if (!settings.isAutoTunnelEnabled || settings.isAutoTunnelPaused) {
|
||||
if (!settings.isAutoTunnelEnabled) {
|
||||
val tunnels = appDataRepository.tunnels.getAll().filter { it.isActive }
|
||||
if (tunnels.isNotEmpty()) context.startTunnelBackground(tunnels.first().id)
|
||||
if (tunnels.isNotEmpty()) tunnelService.get().startTunnel(tunnels.first(), true)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
-61
@@ -1,61 +0,0 @@
|
||||
package com.zaneschepke.wireguardautotunnel.receiver
|
||||
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import com.zaneschepke.wireguardautotunnel.data.repository.TunnelConfigRepository
|
||||
import com.zaneschepke.wireguardautotunnel.module.ApplicationScope
|
||||
import com.zaneschepke.wireguardautotunnel.service.foreground.ServiceManager
|
||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelService
|
||||
import dagger.hilt.android.AndroidEntryPoint
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.launch
|
||||
import timber.log.Timber
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Provider
|
||||
|
||||
@AndroidEntryPoint
|
||||
class BackgroundActionReceiver : BroadcastReceiver() {
|
||||
|
||||
@Inject
|
||||
@ApplicationScope
|
||||
lateinit var applicationScope: CoroutineScope
|
||||
|
||||
@Inject
|
||||
lateinit var tunnelService: Provider<TunnelService>
|
||||
|
||||
@Inject
|
||||
lateinit var tunnelConfigRepository: TunnelConfigRepository
|
||||
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
val id = intent.getIntExtra(TUNNEL_ID_EXTRA_KEY, 0)
|
||||
if (id == 0) return
|
||||
when (intent.action) {
|
||||
ACTION_CONNECT -> {
|
||||
Timber.d("Connect actions")
|
||||
applicationScope.launch {
|
||||
val tunnel = tunnelConfigRepository.getById(id)
|
||||
tunnel?.let {
|
||||
ServiceManager.startTunnelBackgroundService(context)
|
||||
tunnelService.get().startTunnel(it)
|
||||
}
|
||||
}
|
||||
}
|
||||
ACTION_DISCONNECT -> {
|
||||
applicationScope.launch {
|
||||
val tunnel = tunnelConfigRepository.getById(id)
|
||||
tunnel?.let {
|
||||
ServiceManager.stopTunnelBackgroundService(context)
|
||||
tunnelService.get().stopTunnel(it)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val ACTION_CONNECT = "ACTION_CONNECT"
|
||||
const val ACTION_DISCONNECT = "ACTION_DISCONNECT"
|
||||
const val TUNNEL_ID_EXTRA_KEY = "tunnelId"
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,6 @@ import com.zaneschepke.wireguardautotunnel.module.ApplicationScope
|
||||
import com.zaneschepke.wireguardautotunnel.service.foreground.ServiceManager
|
||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelService
|
||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelState
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.startTunnelBackground
|
||||
import dagger.hilt.android.AndroidEntryPoint
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.launch
|
||||
@@ -28,6 +27,9 @@ class BootReceiver : BroadcastReceiver() {
|
||||
@ApplicationScope
|
||||
lateinit var applicationScope: CoroutineScope
|
||||
|
||||
@Inject
|
||||
lateinit var serviceManager: ServiceManager
|
||||
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
if (Intent.ACTION_BOOT_COMPLETED != intent.action) return
|
||||
applicationScope.launch {
|
||||
@@ -37,11 +39,11 @@ class BootReceiver : BroadcastReceiver() {
|
||||
val tunState = tunnelService.get().vpnState.value.status
|
||||
if (activeTunnels.isNotEmpty() && tunState != TunnelState.UP) {
|
||||
Timber.i("Starting previously active tunnel")
|
||||
context.startTunnelBackground(activeTunnels.first().id)
|
||||
tunnelService.get().startTunnel(activeTunnels.first(), true)
|
||||
}
|
||||
if (isAutoTunnelEnabled) {
|
||||
Timber.i("Starting watcher service from boot")
|
||||
ServiceManager.startWatcherServiceForeground(context)
|
||||
serviceManager.startAutoTunnel(true)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+151
-172
@@ -1,16 +1,18 @@
|
||||
package com.zaneschepke.wireguardautotunnel.service.foreground
|
||||
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.net.NetworkCapabilities
|
||||
import android.os.IBinder
|
||||
import android.os.PowerManager
|
||||
import androidx.core.app.ServiceCompat
|
||||
import androidx.lifecycle.LifecycleService
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import com.wireguard.android.util.RootShell
|
||||
import com.zaneschepke.wireguardautotunnel.R
|
||||
import com.zaneschepke.wireguardautotunnel.data.domain.Settings
|
||||
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
|
||||
import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository
|
||||
import com.zaneschepke.wireguardautotunnel.module.AppShell
|
||||
import com.zaneschepke.wireguardautotunnel.module.IoDispatcher
|
||||
import com.zaneschepke.wireguardautotunnel.module.MainImmediateDispatcher
|
||||
import com.zaneschepke.wireguardautotunnel.service.network.EthernetService
|
||||
@@ -23,15 +25,15 @@ import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelService
|
||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelState
|
||||
import com.zaneschepke.wireguardautotunnel.util.Constants
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.cancelWithMessage
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.isMatchingToWildcardList
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.getCurrentWifiName
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.isReachable
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.onNotRunning
|
||||
import dagger.hilt.android.AndroidEntryPoint
|
||||
import kotlinx.coroutines.CompletableDeferred
|
||||
import kotlinx.coroutines.CoroutineDispatcher
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.collectLatest
|
||||
import kotlinx.coroutines.flow.combine
|
||||
import kotlinx.coroutines.flow.distinctUntilChanged
|
||||
import kotlinx.coroutines.flow.update
|
||||
@@ -46,6 +48,10 @@ import javax.inject.Provider
|
||||
class AutoTunnelService : LifecycleService() {
|
||||
private val foregroundId = 122
|
||||
|
||||
@Inject
|
||||
@AppShell
|
||||
lateinit var rootShell: Provider<RootShell>
|
||||
|
||||
@Inject
|
||||
lateinit var wifiService: NetworkService<WifiService>
|
||||
|
||||
@@ -68,6 +74,9 @@ class AutoTunnelService : LifecycleService() {
|
||||
@IoDispatcher
|
||||
lateinit var ioDispatcher: CoroutineDispatcher
|
||||
|
||||
@Inject
|
||||
lateinit var serviceManager: ServiceManager
|
||||
|
||||
@Inject
|
||||
@MainImmediateDispatcher
|
||||
lateinit var mainImmediateDispatcher: CoroutineDispatcher
|
||||
@@ -82,14 +91,11 @@ class AutoTunnelService : LifecycleService() {
|
||||
private var pingJob: Job? = null
|
||||
private var networkEventJob: Job? = null
|
||||
|
||||
@get:Synchronized @set:Synchronized
|
||||
private var running: Boolean = false
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
lifecycleScope.launch(mainImmediateDispatcher) {
|
||||
kotlin.runCatching {
|
||||
launchNotification()
|
||||
launchWatcherNotification()
|
||||
}.onFailure {
|
||||
Timber.e(it)
|
||||
}
|
||||
@@ -104,32 +110,14 @@ class AutoTunnelService : LifecycleService() {
|
||||
|
||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||
Timber.d("onStartCommand executed with startId: $startId")
|
||||
if (intent != null) {
|
||||
val action = intent.action
|
||||
when (action) {
|
||||
Action.START.name,
|
||||
Action.START_FOREGROUND.name,
|
||||
-> startService()
|
||||
Action.STOP.name, Action.STOP_FOREGROUND.name -> stopService()
|
||||
}
|
||||
}
|
||||
serviceManager.autoTunnelService.complete(this)
|
||||
return super.onStartCommand(intent, flags, startId)
|
||||
}
|
||||
|
||||
private suspend fun launchNotification() {
|
||||
if (appDataRepository.settings.getSettings().isAutoTunnelPaused) {
|
||||
launchWatcherPausedNotification()
|
||||
} else {
|
||||
launchWatcherNotification()
|
||||
}
|
||||
}
|
||||
|
||||
private fun startService() {
|
||||
if (running) return
|
||||
running = true
|
||||
fun start() {
|
||||
kotlin.runCatching {
|
||||
lifecycleScope.launch(mainImmediateDispatcher) {
|
||||
launchNotification()
|
||||
launchWatcherNotification()
|
||||
initWakeLock()
|
||||
}
|
||||
startSettingsJob()
|
||||
@@ -139,7 +127,7 @@ class AutoTunnelService : LifecycleService() {
|
||||
}
|
||||
}
|
||||
|
||||
private fun stopService() {
|
||||
fun stop() {
|
||||
wakeLock?.let {
|
||||
if (it.isHeld) {
|
||||
it.release()
|
||||
@@ -151,10 +139,11 @@ class AutoTunnelService : LifecycleService() {
|
||||
override fun onDestroy() {
|
||||
cancelAndResetNetworkJobs()
|
||||
cancelAndResetPingJob()
|
||||
serviceManager.autoTunnelService = CompletableDeferred()
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
private fun launchWatcherNotification(description: String = getString(R.string.watcher_notification_text_active)) {
|
||||
private fun launchWatcherNotification(description: String = getString(R.string.monitoring_state_changes)) {
|
||||
val notification =
|
||||
notificationService.createNotification(
|
||||
channelId = getString(R.string.watcher_channel_id),
|
||||
@@ -170,13 +159,9 @@ class AutoTunnelService : LifecycleService() {
|
||||
)
|
||||
}
|
||||
|
||||
private fun launchWatcherPausedNotification() {
|
||||
launchWatcherNotification(getString(R.string.watcher_notification_text_paused))
|
||||
}
|
||||
|
||||
private fun initWakeLock() {
|
||||
wakeLock =
|
||||
(getSystemService(Context.POWER_SERVICE) as PowerManager).run {
|
||||
(getSystemService(POWER_SERVICE) as PowerManager).run {
|
||||
val tag = this.javaClass.name
|
||||
newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "$tag::lock").apply {
|
||||
try {
|
||||
@@ -224,28 +209,16 @@ class AutoTunnelService : LifecycleService() {
|
||||
when (status) {
|
||||
is NetworkStatus.Available -> {
|
||||
Timber.i("Gained Mobile data connection")
|
||||
autoTunnelStateFlow.update {
|
||||
it.copy(
|
||||
isMobileDataConnected = true,
|
||||
)
|
||||
}
|
||||
emitMobileDataConnected(true)
|
||||
}
|
||||
|
||||
is NetworkStatus.CapabilitiesChanged -> {
|
||||
autoTunnelStateFlow.update {
|
||||
it.copy(
|
||||
isMobileDataConnected = true,
|
||||
)
|
||||
}
|
||||
emitMobileDataConnected(true)
|
||||
Timber.i("Mobile data capabilities changed")
|
||||
}
|
||||
|
||||
is NetworkStatus.Unavailable -> {
|
||||
autoTunnelStateFlow.update {
|
||||
it.copy(
|
||||
isMobileDataConnected = false,
|
||||
)
|
||||
}
|
||||
emitMobileDataConnected(false)
|
||||
Timber.i("Lost mobile data connection")
|
||||
}
|
||||
}
|
||||
@@ -259,8 +232,7 @@ class AutoTunnelService : LifecycleService() {
|
||||
runCatching {
|
||||
do {
|
||||
val vpnState = tunnelService.get().vpnState.value
|
||||
val settings = appDataRepository.settings.getSettings()
|
||||
if (vpnState.status == TunnelState.UP && !settings.isAutoTunnelPaused) {
|
||||
if (vpnState.status == TunnelState.UP) {
|
||||
if (vpnState.tunnelConfig != null) {
|
||||
val config = TunnelConfig.configFromWgQuick(vpnState.tunnelConfig.wgQuick)
|
||||
val results = if (vpnState.tunnelConfig.pingIp != null) {
|
||||
@@ -290,17 +262,6 @@ class AutoTunnelService : LifecycleService() {
|
||||
}
|
||||
}
|
||||
|
||||
private fun onAutoTunnelPause(paused: Boolean) {
|
||||
if (autoTunnelStateFlow.value.settings.isAutoTunnelPaused
|
||||
!= paused
|
||||
) {
|
||||
when (paused) {
|
||||
true -> launchWatcherPausedNotification()
|
||||
false -> launchWatcherNotification()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun watchForSettingsChanges() {
|
||||
Timber.i("Starting settings watcher")
|
||||
withContext(ioDispatcher) {
|
||||
@@ -310,12 +271,13 @@ class AutoTunnelService : LifecycleService() {
|
||||
old.map { it.isActive } != new.map { it.isActive }
|
||||
},
|
||||
) { settings, tunnels ->
|
||||
Timber.d("Tunnels or settings changed!")
|
||||
autoTunnelStateFlow.value.copy(
|
||||
settings = settings,
|
||||
tunnels = tunnels,
|
||||
)
|
||||
}.collect {
|
||||
onAutoTunnelPause(it.settings.isAutoTunnelPaused)
|
||||
Timber.d("got new settings: ${it.settings}")
|
||||
manageJobsBySettings(it.settings)
|
||||
autoTunnelStateFlow.emit(it)
|
||||
}
|
||||
@@ -325,7 +287,12 @@ class AutoTunnelService : LifecycleService() {
|
||||
private suspend fun watchForVpnStateChanges() {
|
||||
Timber.i("Starting vpn state watcher")
|
||||
withContext(ioDispatcher) {
|
||||
tunnelService.get().vpnState.collect { state ->
|
||||
tunnelService.get().vpnState.distinctUntilChanged { old, new ->
|
||||
old.tunnelConfig?.id == new.tunnelConfig?.id
|
||||
}.collect { state ->
|
||||
autoTunnelStateFlow.update {
|
||||
it.copy(vpnState = state)
|
||||
}
|
||||
state.tunnelConfig?.let {
|
||||
val settings = appDataRepository.settings.getSettings()
|
||||
if (it.isPingEnabled && !settings.isPingEnabled) {
|
||||
@@ -389,7 +356,7 @@ class AutoTunnelService : LifecycleService() {
|
||||
mobileDataJob = null
|
||||
}
|
||||
|
||||
private fun updateEthernet(connected: Boolean) {
|
||||
private fun emitEthernetConnected(connected: Boolean) {
|
||||
autoTunnelStateFlow.update {
|
||||
it.copy(
|
||||
isEthernetConnected = connected,
|
||||
@@ -397,6 +364,30 @@ class AutoTunnelService : LifecycleService() {
|
||||
}
|
||||
}
|
||||
|
||||
private fun emitWifiConnected(connected: Boolean) {
|
||||
autoTunnelStateFlow.update {
|
||||
it.copy(
|
||||
isWifiConnected = connected,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun emitWifiSSID(ssid: String) {
|
||||
autoTunnelStateFlow.update {
|
||||
it.copy(
|
||||
currentNetworkSSID = ssid,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun emitMobileDataConnected(connected: Boolean) {
|
||||
autoTunnelStateFlow.update {
|
||||
it.copy(
|
||||
isMobileDataConnected = connected,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun watchForEthernetConnectivityChanges() {
|
||||
withContext(ioDispatcher) {
|
||||
Timber.i("Starting ethernet data watcher")
|
||||
@@ -404,16 +395,16 @@ class AutoTunnelService : LifecycleService() {
|
||||
when (status) {
|
||||
is NetworkStatus.Available -> {
|
||||
Timber.i("Gained Ethernet connection")
|
||||
updateEthernet(true)
|
||||
emitEthernetConnected(true)
|
||||
}
|
||||
|
||||
is NetworkStatus.CapabilitiesChanged -> {
|
||||
Timber.i("Ethernet capabilities changed")
|
||||
updateEthernet(true)
|
||||
emitEthernetConnected(true)
|
||||
}
|
||||
|
||||
is NetworkStatus.Unavailable -> {
|
||||
updateEthernet(false)
|
||||
emitEthernetConnected(false)
|
||||
Timber.i("Lost Ethernet connection")
|
||||
}
|
||||
}
|
||||
@@ -428,21 +419,13 @@ class AutoTunnelService : LifecycleService() {
|
||||
when (status) {
|
||||
is NetworkStatus.Available -> {
|
||||
Timber.i("Gained Wi-Fi connection")
|
||||
autoTunnelStateFlow.update {
|
||||
it.copy(
|
||||
isWifiConnected = true,
|
||||
)
|
||||
}
|
||||
emitWifiConnected(true)
|
||||
}
|
||||
|
||||
is NetworkStatus.CapabilitiesChanged -> {
|
||||
Timber.i("Wifi capabilities changed")
|
||||
autoTunnelStateFlow.update {
|
||||
it.copy(
|
||||
isWifiConnected = true,
|
||||
)
|
||||
}
|
||||
val ssid = wifiService.getNetworkName(status.networkCapabilities)
|
||||
emitWifiConnected(true)
|
||||
val ssid = getWifiSSID(status.networkCapabilities)
|
||||
ssid?.let { name ->
|
||||
if (name.contains(Constants.UNREADABLE_SSID)) {
|
||||
Timber.w("SSID unreadable: missing permissions")
|
||||
@@ -450,20 +433,12 @@ class AutoTunnelService : LifecycleService() {
|
||||
Timber.i("Detected valid SSID")
|
||||
}
|
||||
appDataRepository.appState.setCurrentSsid(name)
|
||||
autoTunnelStateFlow.update {
|
||||
it.copy(
|
||||
currentNetworkSSID = name,
|
||||
)
|
||||
}
|
||||
emitWifiSSID(name)
|
||||
} ?: Timber.w("Failed to read ssid")
|
||||
}
|
||||
|
||||
is NetworkStatus.Unavailable -> {
|
||||
autoTunnelStateFlow.update {
|
||||
it.copy(
|
||||
isWifiConnected = false,
|
||||
)
|
||||
}
|
||||
emitWifiConnected(false)
|
||||
Timber.i("Lost Wi-Fi connection")
|
||||
}
|
||||
}
|
||||
@@ -471,104 +446,108 @@ class AutoTunnelService : LifecycleService() {
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun getWifiSSID(networkCapabilities: NetworkCapabilities): String? {
|
||||
return withContext(ioDispatcher) {
|
||||
with(autoTunnelStateFlow.value.settings) {
|
||||
if (isWifiNameByShellEnabled) return@withContext rootShell.get().getCurrentWifiName()
|
||||
wifiService.getNetworkName(networkCapabilities)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun getMobileDataTunnel(): TunnelConfig? {
|
||||
return appDataRepository.tunnels.findByMobileDataTunnel().firstOrNull()
|
||||
}
|
||||
|
||||
private fun isTunnelDown(): Boolean {
|
||||
return tunnelService.get().vpnState.value.status == TunnelState.DOWN
|
||||
}
|
||||
|
||||
private suspend fun handleNetworkEventChanges() {
|
||||
withContext(ioDispatcher) {
|
||||
Timber.i("Starting network event watcher")
|
||||
autoTunnelStateFlow.collectLatest { watcherState ->
|
||||
autoTunnelStateFlow.collect { watcherState ->
|
||||
val autoTunnel = "Auto-tunnel watcher"
|
||||
if (!watcherState.settings.isAutoTunnelPaused) {
|
||||
// delay for rapid network state changes and then collect latest
|
||||
delay(Constants.WATCHER_COLLECTION_DELAY)
|
||||
val activeTunnel = tunnelService.get().vpnState.value.tunnelConfig
|
||||
val defaultTunnel = appDataRepository.getPrimaryOrFirstTunnel()
|
||||
when {
|
||||
watcherState.isEthernetConditionMet() -> {
|
||||
Timber.i("$autoTunnel - tunnel on on ethernet condition met")
|
||||
if (isTunnelDown()) {
|
||||
defaultTunnel?.let {
|
||||
// delay for rapid network state changes and then collect latest
|
||||
delay(Constants.WATCHER_COLLECTION_DELAY)
|
||||
val activeTunnel = watcherState.vpnState.tunnelConfig
|
||||
val defaultTunnel = appDataRepository.getPrimaryOrFirstTunnel()
|
||||
val isTunnelDown = tunnelService.get().getState() == TunnelState.DOWN
|
||||
when {
|
||||
watcherState.isEthernetConditionMet() -> {
|
||||
Timber.i("$autoTunnel - tunnel on on ethernet condition met")
|
||||
if (isTunnelDown) {
|
||||
defaultTunnel?.let {
|
||||
tunnelService.get().startTunnel(it)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
watcherState.isMobileDataConditionMet() -> {
|
||||
Timber.i("$autoTunnel - tunnel on mobile data condition met")
|
||||
val mobileDataTunnel = getMobileDataTunnel()
|
||||
val tunnel =
|
||||
mobileDataTunnel ?: defaultTunnel
|
||||
if (isTunnelDown || activeTunnel?.isMobileDataTunnel == false) {
|
||||
tunnel?.let {
|
||||
tunnelService.get().startTunnel(it)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
watcherState.isTunnelOffOnMobileDataConditionMet() -> {
|
||||
Timber.i("$autoTunnel - tunnel off on mobile data met, turning vpn off")
|
||||
if (!isTunnelDown) {
|
||||
activeTunnel?.let {
|
||||
tunnelService.get().stopTunnel(it)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
watcherState.isUntrustedWifiConditionMet() -> {
|
||||
Timber.i("Untrusted wifi condition met")
|
||||
if (activeTunnel == null || watcherState.isCurrentSSIDActiveTunnelNetwork() == false ||
|
||||
isTunnelDown
|
||||
) {
|
||||
Timber.i(
|
||||
"$autoTunnel - tunnel on ssid not associated with current tunnel condition met",
|
||||
)
|
||||
watcherState.getTunnelWithMatchingTunnelNetwork()?.let {
|
||||
Timber.i("Found tunnel associated with this SSID, bringing tunnel up: ${it.name}")
|
||||
if (isTunnelDown || activeTunnel?.id != it.id) {
|
||||
tunnelService.get().startTunnel(it)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
watcherState.isMobileDataConditionMet() -> {
|
||||
Timber.i("$autoTunnel - tunnel on mobile data condition met")
|
||||
val mobileDataTunnel = getMobileDataTunnel()
|
||||
val tunnel =
|
||||
mobileDataTunnel ?: defaultTunnel
|
||||
if (isTunnelDown() || activeTunnel?.isMobileDataTunnel == false) {
|
||||
tunnel?.let {
|
||||
tunnelService.get().startTunnel(it)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
watcherState.isTunnelOffOnMobileDataConditionMet() -> {
|
||||
Timber.i("$autoTunnel - tunnel off on mobile data met, turning vpn off")
|
||||
if (!isTunnelDown()) {
|
||||
activeTunnel?.let {
|
||||
tunnelService.get().stopTunnel(it)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
watcherState.isUntrustedWifiConditionMet() -> {
|
||||
Timber.i("Untrusted wifi condition met")
|
||||
if (activeTunnel?.tunnelNetworks?.isMatchingToWildcardList(watcherState.currentNetworkSSID) == false ||
|
||||
activeTunnel == null || isTunnelDown()
|
||||
) {
|
||||
Timber.i(
|
||||
"$autoTunnel - tunnel on ssid not associated with current tunnel condition met",
|
||||
)
|
||||
watcherState.tunnels.firstOrNull { it.tunnelNetworks.isMatchingToWildcardList(watcherState.currentNetworkSSID) }?.let {
|
||||
Timber.i("Found tunnel associated with this SSID, bringing tunnel up: ${it.name}")
|
||||
if (isTunnelDown() || activeTunnel?.id != it.id) {
|
||||
} ?: suspend {
|
||||
Timber.i("No tunnel associated with this SSID, using defaults")
|
||||
val default = appDataRepository.getPrimaryOrFirstTunnel()
|
||||
if (default?.name != tunnelService.get().name || isTunnelDown) {
|
||||
default?.let {
|
||||
tunnelService.get().startTunnel(it)
|
||||
}
|
||||
} ?: suspend {
|
||||
Timber.i("No tunnel associated with this SSID, using defaults")
|
||||
val default = appDataRepository.getPrimaryOrFirstTunnel()
|
||||
if (default?.name != tunnelService.get().name || isTunnelDown()) {
|
||||
default?.let {
|
||||
tunnelService.get().startTunnel(it)
|
||||
}
|
||||
}
|
||||
}.invoke()
|
||||
}
|
||||
}
|
||||
}.invoke()
|
||||
}
|
||||
}
|
||||
|
||||
watcherState.isTrustedWifiConditionMet() -> {
|
||||
Timber.i(
|
||||
"$autoTunnel - tunnel off on trusted wifi condition met, turning vpn off",
|
||||
)
|
||||
if (!isTunnelDown()) activeTunnel?.let { tunnelService.get().stopTunnel(it) }
|
||||
}
|
||||
watcherState.isTrustedWifiConditionMet() -> {
|
||||
Timber.i(
|
||||
"$autoTunnel - tunnel off on trusted wifi condition met, turning vpn off",
|
||||
)
|
||||
if (!isTunnelDown) activeTunnel?.let { tunnelService.get().stopTunnel(it) }
|
||||
}
|
||||
|
||||
watcherState.isTunnelOffOnWifiConditionMet() -> {
|
||||
Timber.i(
|
||||
"$autoTunnel - tunnel off on wifi condition met, turning vpn off",
|
||||
)
|
||||
if (!isTunnelDown()) activeTunnel?.let { tunnelService.get().stopTunnel(it) }
|
||||
}
|
||||
watcherState.isTunnelOffOnWifiConditionMet() -> {
|
||||
Timber.i(
|
||||
"$autoTunnel - tunnel off on wifi condition met, turning vpn off",
|
||||
)
|
||||
if (!isTunnelDown) activeTunnel?.let { tunnelService.get().stopTunnel(it) }
|
||||
}
|
||||
// TODO disable for this now
|
||||
// watcherState.isTunnelOffOnNoConnectivityMet() -> {
|
||||
// Timber.i(
|
||||
// "$autoTunnel - tunnel off on no connectivity met, turning vpn off",
|
||||
// )
|
||||
// if (!isTunnelDown) activeTunnel?.let { tunnelService.get().stopTunnel(it) }
|
||||
// }
|
||||
|
||||
watcherState.isTunnelOffOnNoConnectivityMet() -> {
|
||||
Timber.i(
|
||||
"$autoTunnel - tunnel off on no connectivity met, turning vpn off",
|
||||
)
|
||||
if (!isTunnelDown()) activeTunnel?.let { tunnelService.get().stopTunnel(it) }
|
||||
}
|
||||
|
||||
else -> {
|
||||
Timber.i("$autoTunnel - no condition met")
|
||||
}
|
||||
else -> {
|
||||
Timber.i("$autoTunnel - no condition met")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+33
-2
@@ -1,10 +1,13 @@
|
||||
package com.zaneschepke.wireguardautotunnel.service.foreground
|
||||
|
||||
import com.zaneschepke.wireguardautotunnel.data.domain.Settings
|
||||
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
|
||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.VpnState
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.TunnelConfigs
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.isMatchingToWildcardList
|
||||
|
||||
data class AutoTunnelState(
|
||||
val vpnState: VpnState = VpnState(),
|
||||
val isWifiConnected: Boolean = false,
|
||||
val isEthernetConnected: Boolean = false,
|
||||
val isMobileDataConnected: Boolean = false,
|
||||
@@ -41,7 +44,7 @@ data class AutoTunnelState(
|
||||
return (
|
||||
!isEthernetConnected &&
|
||||
isWifiConnected &&
|
||||
!settings.trustedNetworkSSIDs.isMatchingToWildcardList(currentNetworkSSID) &&
|
||||
!isCurrentSSIDTrusted() &&
|
||||
settings.isTunnelOnWifiEnabled
|
||||
)
|
||||
}
|
||||
@@ -51,7 +54,7 @@ data class AutoTunnelState(
|
||||
!isEthernetConnected &&
|
||||
(
|
||||
isWifiConnected &&
|
||||
settings.trustedNetworkSSIDs.isMatchingToWildcardList(currentNetworkSSID)
|
||||
isCurrentSSIDTrusted()
|
||||
)
|
||||
)
|
||||
}
|
||||
@@ -73,4 +76,32 @@ data class AutoTunnelState(
|
||||
!isMobileDataConnected
|
||||
)
|
||||
}
|
||||
|
||||
fun isCurrentSSIDTrusted(): Boolean {
|
||||
return if (settings.isWildcardsEnabled) {
|
||||
settings.trustedNetworkSSIDs.isMatchingToWildcardList(currentNetworkSSID)
|
||||
} else {
|
||||
settings.trustedNetworkSSIDs.contains(currentNetworkSSID)
|
||||
}
|
||||
}
|
||||
fun isCurrentSSIDActiveTunnelNetwork(): Boolean {
|
||||
val currentTunnelNetworks = vpnState.tunnelConfig?.tunnelNetworks
|
||||
return (
|
||||
if (settings.isWildcardsEnabled) {
|
||||
currentTunnelNetworks?.isMatchingToWildcardList(currentNetworkSSID)
|
||||
} else {
|
||||
currentTunnelNetworks?.contains(currentNetworkSSID)
|
||||
}
|
||||
) == true
|
||||
}
|
||||
|
||||
fun getTunnelWithMatchingTunnelNetwork(): TunnelConfig? {
|
||||
return tunnels.firstOrNull {
|
||||
if (settings.isWildcardsEnabled) {
|
||||
it.tunnelNetworks.isMatchingToWildcardList(currentNetworkSSID)
|
||||
} else {
|
||||
it.tunnelNetworks.contains(currentNetworkSSID)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+65
-51
@@ -3,69 +3,83 @@ package com.zaneschepke.wireguardautotunnel.service.foreground
|
||||
import android.app.Service
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.net.VpnService
|
||||
import com.zaneschepke.wireguardautotunnel.util.SingletonHolder
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.requestTunnelTileServiceStateUpdate
|
||||
import jakarta.inject.Inject
|
||||
import kotlinx.coroutines.CompletableDeferred
|
||||
import kotlinx.coroutines.ExperimentalCoroutinesApi
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.update
|
||||
import timber.log.Timber
|
||||
|
||||
object ServiceManager {
|
||||
private fun <T : Service> actionOnService(action: Action, context: Context, cls: Class<T>, extras: Map<String, Int>? = null) {
|
||||
if (VpnService.prepare(context) != null) return
|
||||
val intent =
|
||||
Intent(context, cls).also {
|
||||
it.action = action.name
|
||||
extras?.forEach { (k, v) -> it.putExtra(k, v) }
|
||||
}
|
||||
intent.component?.javaClass
|
||||
try {
|
||||
when (action) {
|
||||
Action.START_FOREGROUND, Action.STOP_FOREGROUND ->
|
||||
context.startForegroundService(
|
||||
intent,
|
||||
)
|
||||
@OptIn(ExperimentalCoroutinesApi::class)
|
||||
class ServiceManager
|
||||
@Inject constructor(private val context: Context) {
|
||||
|
||||
Action.START, Action.STOP -> context.startService(intent)
|
||||
private val _autoTunnelActive = MutableStateFlow(false)
|
||||
|
||||
val autoTunnelActive = _autoTunnelActive.asStateFlow()
|
||||
|
||||
var autoTunnelService = CompletableDeferred<AutoTunnelService>()
|
||||
var backgroundService = CompletableDeferred<TunnelBackgroundService>()
|
||||
|
||||
companion object : SingletonHolder<ServiceManager, Context>(::ServiceManager)
|
||||
|
||||
private fun <T : Service> startService(cls: Class<T>, background: Boolean) {
|
||||
runCatching {
|
||||
val intent = Intent(context, cls)
|
||||
if (background) {
|
||||
context.startForegroundService(intent)
|
||||
} else {
|
||||
context.startService(intent)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Timber.e(e.message)
|
||||
}.onFailure { Timber.e(it) }
|
||||
}
|
||||
|
||||
suspend fun startAutoTunnel(background: Boolean) {
|
||||
if (autoTunnelService.isCompleted) return _autoTunnelActive.update { true }
|
||||
kotlin.runCatching {
|
||||
startService(AutoTunnelService::class.java, background)
|
||||
autoTunnelService.await()
|
||||
autoTunnelService.getCompleted().start()
|
||||
_autoTunnelActive.update { true }
|
||||
}.onFailure {
|
||||
Timber.e(it)
|
||||
}
|
||||
}
|
||||
|
||||
fun startWatcherServiceForeground(context: Context) {
|
||||
actionOnService(
|
||||
Action.START_FOREGROUND,
|
||||
context,
|
||||
AutoTunnelService::class.java,
|
||||
)
|
||||
suspend fun startBackgroundService() {
|
||||
if (backgroundService.isCompleted) return
|
||||
kotlin.runCatching {
|
||||
startService(TunnelBackgroundService::class.java, true)
|
||||
backgroundService.await()
|
||||
backgroundService.getCompleted().start()
|
||||
}.onFailure {
|
||||
Timber.e(it)
|
||||
}
|
||||
}
|
||||
|
||||
fun startWatcherService(context: Context) {
|
||||
actionOnService(
|
||||
Action.START,
|
||||
context,
|
||||
AutoTunnelService::class.java,
|
||||
)
|
||||
fun stopBackgroundService() {
|
||||
if (!backgroundService.isCompleted) return
|
||||
runCatching {
|
||||
backgroundService.getCompleted().stop()
|
||||
}.onFailure {
|
||||
Timber.e(it)
|
||||
}
|
||||
}
|
||||
|
||||
fun stopWatcherService(context: Context) {
|
||||
actionOnService(
|
||||
Action.STOP,
|
||||
context,
|
||||
AutoTunnelService::class.java,
|
||||
)
|
||||
fun stopAutoTunnel() {
|
||||
if (!autoTunnelService.isCompleted) return
|
||||
runCatching {
|
||||
autoTunnelService.getCompleted().stop()
|
||||
_autoTunnelActive.update { false }
|
||||
}.onFailure {
|
||||
Timber.e(it)
|
||||
}
|
||||
}
|
||||
|
||||
fun startTunnelBackgroundService(context: Context) {
|
||||
actionOnService(
|
||||
Action.START_FOREGROUND,
|
||||
context,
|
||||
TunnelBackgroundService::class.java,
|
||||
)
|
||||
}
|
||||
|
||||
fun stopTunnelBackgroundService(context: Context) {
|
||||
actionOnService(
|
||||
Action.STOP,
|
||||
context,
|
||||
TunnelBackgroundService::class.java,
|
||||
)
|
||||
fun requestTunnelTileUpdate() {
|
||||
context.requestTunnelTileServiceStateUpdate()
|
||||
}
|
||||
}
|
||||
|
||||
+22
-14
@@ -3,10 +3,13 @@ package com.zaneschepke.wireguardautotunnel.service.foreground
|
||||
import android.app.Notification
|
||||
import android.content.Intent
|
||||
import android.os.IBinder
|
||||
import androidx.core.app.ServiceCompat
|
||||
import androidx.lifecycle.LifecycleService
|
||||
import com.zaneschepke.wireguardautotunnel.R
|
||||
import com.zaneschepke.wireguardautotunnel.service.notification.NotificationService
|
||||
import com.zaneschepke.wireguardautotunnel.util.Constants
|
||||
import dagger.hilt.android.AndroidEntryPoint
|
||||
import kotlinx.coroutines.CompletableDeferred
|
||||
import javax.inject.Inject
|
||||
|
||||
@AndroidEntryPoint
|
||||
@@ -15,11 +18,14 @@ class TunnelBackgroundService : LifecycleService() {
|
||||
@Inject
|
||||
lateinit var notificationService: NotificationService
|
||||
|
||||
@Inject
|
||||
lateinit var serviceManager: ServiceManager
|
||||
|
||||
private val foregroundId = 123
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
startForeground(foregroundId, createNotification())
|
||||
start()
|
||||
}
|
||||
|
||||
override fun onBind(intent: Intent): IBinder? {
|
||||
@@ -29,32 +35,34 @@ class TunnelBackgroundService : LifecycleService() {
|
||||
}
|
||||
|
||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||
if (intent != null) {
|
||||
val action = intent.action
|
||||
when (action) {
|
||||
Action.START.name,
|
||||
Action.START_FOREGROUND.name,
|
||||
-> startService()
|
||||
Action.STOP.name, Action.STOP_FOREGROUND.name -> stopService()
|
||||
}
|
||||
}
|
||||
serviceManager.backgroundService.complete(this)
|
||||
return super.onStartCommand(intent, flags, startId)
|
||||
}
|
||||
|
||||
private fun startService() {
|
||||
startForeground(foregroundId, createNotification())
|
||||
fun start() {
|
||||
ServiceCompat.startForeground(
|
||||
this,
|
||||
foregroundId,
|
||||
createNotification(),
|
||||
Constants.SYSTEM_EXEMPT_SERVICE_TYPE_ID,
|
||||
)
|
||||
}
|
||||
|
||||
private fun stopService() {
|
||||
fun stop() {
|
||||
stopForeground(STOP_FOREGROUND_REMOVE)
|
||||
stopSelf()
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
serviceManager.backgroundService = CompletableDeferred()
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
private fun createNotification(): Notification {
|
||||
return notificationService.createNotification(
|
||||
getString(R.string.vpn_channel_id),
|
||||
getString(R.string.vpn_channel_name),
|
||||
getString(R.string.tunnel_start_text),
|
||||
getString(R.string.tunnel_running),
|
||||
description = "",
|
||||
)
|
||||
}
|
||||
|
||||
+1
-27
@@ -5,8 +5,6 @@ import android.net.ConnectivityManager
|
||||
import android.net.Network
|
||||
import android.net.NetworkCapabilities
|
||||
import android.net.NetworkRequest
|
||||
import android.net.wifi.SupplicantState
|
||||
import android.net.wifi.WifiInfo
|
||||
import android.net.wifi.WifiManager
|
||||
import android.os.Build
|
||||
import kotlinx.coroutines.channels.awaitClose
|
||||
@@ -21,7 +19,7 @@ abstract class BaseNetworkService<T : BaseNetworkService<T>>(
|
||||
private val connectivityManager =
|
||||
context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
|
||||
|
||||
private val wifiManager =
|
||||
val wifiManager =
|
||||
context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
|
||||
|
||||
override val networkStatus =
|
||||
@@ -83,30 +81,6 @@ abstract class BaseNetworkService<T : BaseNetworkService<T>>(
|
||||
|
||||
awaitClose { connectivityManager.unregisterNetworkCallback(networkStatusCallback) }
|
||||
}
|
||||
|
||||
override fun getNetworkName(networkCapabilities: NetworkCapabilities): String? {
|
||||
var ssid: String? = getWifiNameFromCapabilities(networkCapabilities)
|
||||
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.R) {
|
||||
val info = wifiManager.connectionInfo
|
||||
if (info.supplicantState === SupplicantState.COMPLETED) {
|
||||
ssid = info.ssid
|
||||
}
|
||||
}
|
||||
return ssid?.trim('"')
|
||||
}
|
||||
|
||||
companion object {
|
||||
private fun getWifiNameFromCapabilities(networkCapabilities: NetworkCapabilities): String? {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||
val info: WifiInfo
|
||||
if (networkCapabilities.transportInfo is WifiInfo) {
|
||||
info = networkCapabilities.transportInfo as WifiInfo
|
||||
return info.ssid
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
inline fun <Result> Flow<NetworkStatus>.map(
|
||||
|
||||
+6
-1
@@ -10,4 +10,9 @@ class EthernetService
|
||||
constructor(
|
||||
@ApplicationContext context: Context,
|
||||
) :
|
||||
BaseNetworkService<EthernetService>(context, NetworkCapabilities.TRANSPORT_ETHERNET)
|
||||
BaseNetworkService<EthernetService>(context, NetworkCapabilities.TRANSPORT_ETHERNET) {
|
||||
|
||||
override fun isNetworkSecure(): Boolean {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
+5
-1
@@ -10,4 +10,8 @@ class MobileDataService
|
||||
constructor(
|
||||
@ApplicationContext context: Context,
|
||||
) :
|
||||
BaseNetworkService<MobileDataService>(context, NetworkCapabilities.TRANSPORT_CELLULAR)
|
||||
BaseNetworkService<MobileDataService>(context, NetworkCapabilities.TRANSPORT_CELLULAR) {
|
||||
override fun isNetworkSecure(): Boolean {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
package com.zaneschepke.wireguardautotunnel.service.network
|
||||
|
||||
import android.net.NetworkCapabilities
|
||||
import android.net.wifi.WifiInfo
|
||||
import android.os.Build
|
||||
|
||||
fun NetworkCapabilities.getWifiName(): String? {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||
val info: WifiInfo
|
||||
if (transportInfo is WifiInfo) {
|
||||
info = transportInfo as WifiInfo
|
||||
return info.ssid
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
+5
-1
@@ -4,7 +4,11 @@ import android.net.NetworkCapabilities
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
|
||||
interface NetworkService<T> {
|
||||
fun getNetworkName(networkCapabilities: NetworkCapabilities): String?
|
||||
fun getNetworkName(networkCapabilities: NetworkCapabilities): String? {
|
||||
return null
|
||||
}
|
||||
|
||||
fun isNetworkSecure(): Boolean
|
||||
|
||||
val networkStatus: Flow<NetworkStatus>
|
||||
}
|
||||
|
||||
+20
-1
@@ -2,6 +2,8 @@ package com.zaneschepke.wireguardautotunnel.service.network
|
||||
|
||||
import android.content.Context
|
||||
import android.net.NetworkCapabilities
|
||||
import android.net.wifi.SupplicantState
|
||||
import android.os.Build
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import javax.inject.Inject
|
||||
|
||||
@@ -10,4 +12,21 @@ class WifiService
|
||||
constructor(
|
||||
@ApplicationContext context: Context,
|
||||
) :
|
||||
BaseNetworkService<WifiService>(context, NetworkCapabilities.TRANSPORT_WIFI)
|
||||
BaseNetworkService<WifiService>(context, NetworkCapabilities.TRANSPORT_WIFI) {
|
||||
|
||||
override fun getNetworkName(networkCapabilities: NetworkCapabilities): String? {
|
||||
var ssid = networkCapabilities.getWifiName()
|
||||
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.S) {
|
||||
val info = wifiManager.connectionInfo
|
||||
if (info.supplicantState === SupplicantState.COMPLETED) {
|
||||
ssid = info.ssid
|
||||
}
|
||||
}
|
||||
return ssid?.trim('"')
|
||||
}
|
||||
|
||||
override fun isNetworkSecure(): Boolean {
|
||||
// TODO
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
+2
-2
@@ -9,7 +9,7 @@ import android.content.Intent
|
||||
import android.graphics.Color
|
||||
import androidx.core.app.NotificationCompat
|
||||
import com.zaneschepke.wireguardautotunnel.R
|
||||
import com.zaneschepke.wireguardautotunnel.ui.SplashActivity
|
||||
import com.zaneschepke.wireguardautotunnel.ui.MainActivity
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import javax.inject.Inject
|
||||
|
||||
@@ -63,7 +63,7 @@ constructor(
|
||||
}
|
||||
notificationManager.createNotificationChannel(channel)
|
||||
val pendingIntent: PendingIntent =
|
||||
Intent(context, SplashActivity::class.java).let { notificationIntent ->
|
||||
Intent(context, MainActivity::class.java).let { notificationIntent ->
|
||||
PendingIntent.getActivity(
|
||||
context,
|
||||
0,
|
||||
|
||||
+8
-16
@@ -6,9 +6,8 @@ import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository
|
||||
import com.zaneschepke.wireguardautotunnel.module.ApplicationScope
|
||||
import com.zaneschepke.wireguardautotunnel.service.foreground.Action
|
||||
import com.zaneschepke.wireguardautotunnel.service.foreground.AutoTunnelService
|
||||
import com.zaneschepke.wireguardautotunnel.service.foreground.ServiceManager
|
||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelService
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.startTunnelBackground
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.stopTunnelBackground
|
||||
import dagger.hilt.android.AndroidEntryPoint
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.launch
|
||||
@@ -24,6 +23,9 @@ class ShortcutsActivity : ComponentActivity() {
|
||||
@Inject
|
||||
lateinit var tunnelService: Provider<TunnelService>
|
||||
|
||||
@Inject
|
||||
lateinit var serviceManager: ServiceManager
|
||||
|
||||
@Inject
|
||||
@ApplicationScope
|
||||
lateinit var applicationScope: CoroutineScope
|
||||
@@ -44,26 +46,16 @@ class ShortcutsActivity : ComponentActivity() {
|
||||
Timber.d("Shortcut action on name: ${tunnelConfig?.name}")
|
||||
tunnelConfig?.let {
|
||||
when (intent.action) {
|
||||
Action.START.name -> this@ShortcutsActivity.startTunnelBackground(it.id)
|
||||
Action.STOP.name -> this@ShortcutsActivity.stopTunnelBackground(it.id)
|
||||
Action.START.name -> tunnelService.get().startTunnel(it, true)
|
||||
Action.STOP.name -> tunnelService.get().stopTunnel(it)
|
||||
else -> Unit
|
||||
}
|
||||
}
|
||||
}
|
||||
AutoTunnelService::class.java.simpleName, LEGACY_AUTO_TUNNEL_SERVICE_NAME -> {
|
||||
when (intent.action) {
|
||||
Action.START.name ->
|
||||
appDataRepository.settings.save(
|
||||
settings.copy(
|
||||
isAutoTunnelPaused = false,
|
||||
),
|
||||
)
|
||||
Action.STOP.name ->
|
||||
appDataRepository.settings.save(
|
||||
settings.copy(
|
||||
isAutoTunnelPaused = true,
|
||||
),
|
||||
)
|
||||
Action.START.name -> serviceManager.startAutoTunnel(true)
|
||||
Action.STOP.name -> serviceManager.stopAutoTunnel()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+28
-61
@@ -1,7 +1,6 @@
|
||||
package com.zaneschepke.wireguardautotunnel.service.tile
|
||||
|
||||
import android.content.Intent
|
||||
import android.os.Build
|
||||
import android.os.IBinder
|
||||
import android.service.quicksettings.Tile
|
||||
import android.service.quicksettings.TileService
|
||||
@@ -9,9 +8,9 @@ import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.LifecycleOwner
|
||||
import androidx.lifecycle.LifecycleRegistry
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import com.zaneschepke.wireguardautotunnel.R
|
||||
import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository
|
||||
import com.zaneschepke.wireguardautotunnel.module.ApplicationScope
|
||||
import com.zaneschepke.wireguardautotunnel.service.foreground.ServiceManager
|
||||
import dagger.hilt.android.AndroidEntryPoint
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.launch
|
||||
@@ -23,51 +22,18 @@ class AutoTunnelControlTile : TileService(), LifecycleOwner {
|
||||
@Inject
|
||||
lateinit var appDataRepository: AppDataRepository
|
||||
|
||||
@Inject
|
||||
lateinit var serviceManager: ServiceManager
|
||||
|
||||
@Inject
|
||||
@ApplicationScope
|
||||
lateinit var applicationScope: CoroutineScope
|
||||
|
||||
private val lifecycleRegistry: LifecycleRegistry = LifecycleRegistry(this)
|
||||
|
||||
/* This works around an annoying unsolved frameworks bug some people are hitting. */
|
||||
override fun onBind(intent: Intent): IBinder? {
|
||||
var ret: IBinder? = null
|
||||
try {
|
||||
ret = super.onBind(intent)
|
||||
} catch (e: Throwable) {
|
||||
Timber.e("Failed to bind to AutoTunnelTile")
|
||||
}
|
||||
return ret
|
||||
}
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE)
|
||||
|
||||
applicationScope.launch {
|
||||
appDataRepository.settings.getSettingsFlow().collect {
|
||||
kotlin.runCatching {
|
||||
when (it.isAutoTunnelEnabled) {
|
||||
true -> {
|
||||
if (it.isAutoTunnelPaused) {
|
||||
setInactive()
|
||||
setTileDescription(this@AutoTunnelControlTile.getString(R.string.paused))
|
||||
} else {
|
||||
setActive()
|
||||
setTileDescription(this@AutoTunnelControlTile.getString(R.string.active))
|
||||
}
|
||||
}
|
||||
|
||||
false -> {
|
||||
setTileDescription(this@AutoTunnelControlTile.getString(R.string.disabled))
|
||||
setUnavailable()
|
||||
}
|
||||
}
|
||||
}.onFailure {
|
||||
Timber.e(it)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onStopListening() {
|
||||
@@ -82,26 +48,28 @@ class AutoTunnelControlTile : TileService(), LifecycleOwner {
|
||||
override fun onStartListening() {
|
||||
super.onStartListening()
|
||||
lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START)
|
||||
lifecycleScope.launch {
|
||||
if (appDataRepository.tunnels.getAll().isEmpty()) return@launch setUnavailable()
|
||||
updateTileState()
|
||||
}
|
||||
}
|
||||
|
||||
private fun updateTileState() {
|
||||
serviceManager.autoTunnelActive.value.let {
|
||||
if (it) setActive() else setInactive()
|
||||
}
|
||||
}
|
||||
|
||||
override fun onClick() {
|
||||
super.onClick()
|
||||
unlockAndRun {
|
||||
lifecycleScope.launch {
|
||||
kotlin.runCatching {
|
||||
val settings = appDataRepository.settings.getSettings()
|
||||
if (settings.isAutoTunnelPaused) {
|
||||
return@launch appDataRepository.settings.save(
|
||||
settings.copy(
|
||||
isAutoTunnelPaused = false,
|
||||
),
|
||||
)
|
||||
}
|
||||
appDataRepository.settings.save(
|
||||
settings.copy(
|
||||
isAutoTunnelPaused = true,
|
||||
),
|
||||
)
|
||||
if (serviceManager.autoTunnelActive.value) {
|
||||
serviceManager.stopAutoTunnel()
|
||||
setInactive()
|
||||
} else {
|
||||
serviceManager.startAutoTunnel(true)
|
||||
setActive()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -128,16 +96,15 @@ class AutoTunnelControlTile : TileService(), LifecycleOwner {
|
||||
}
|
||||
}
|
||||
|
||||
private fun setTileDescription(description: String) {
|
||||
kotlin.runCatching {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||
qsTile.subtitle = description
|
||||
}
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
|
||||
qsTile.stateDescription = description
|
||||
}
|
||||
qsTile.updateTile()
|
||||
/* This works around an annoying unsolved frameworks bug some people are hitting. */
|
||||
override fun onBind(intent: Intent): IBinder? {
|
||||
var ret: IBinder? = null
|
||||
try {
|
||||
ret = super.onBind(intent)
|
||||
} catch (_: Throwable) {
|
||||
Timber.e("Failed to bind to TunnelControlTile")
|
||||
}
|
||||
return ret
|
||||
}
|
||||
|
||||
override val lifecycle: Lifecycle
|
||||
|
||||
+20
-7
@@ -1,6 +1,8 @@
|
||||
package com.zaneschepke.wireguardautotunnel.service.tile
|
||||
|
||||
import android.content.Intent
|
||||
import android.os.Build
|
||||
import android.os.IBinder
|
||||
import android.service.quicksettings.Tile
|
||||
import android.service.quicksettings.TileService
|
||||
import androidx.lifecycle.Lifecycle
|
||||
@@ -11,8 +13,6 @@ import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
|
||||
import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository
|
||||
import com.zaneschepke.wireguardautotunnel.module.ApplicationScope
|
||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelService
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.startTunnelBackground
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.stopTunnelBackground
|
||||
import dagger.hilt.android.AndroidEntryPoint
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.launch
|
||||
@@ -36,7 +36,6 @@ class TunnelControlTile : TileService(), LifecycleOwner {
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
Timber.d("onCreate for tile service")
|
||||
lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE)
|
||||
}
|
||||
|
||||
@@ -52,6 +51,7 @@ class TunnelControlTile : TileService(), LifecycleOwner {
|
||||
override fun onStartListening() {
|
||||
super.onStartListening()
|
||||
lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START)
|
||||
Timber.d("Updating tile!")
|
||||
lifecycleScope.launch {
|
||||
if (appDataRepository.tunnels.getAll().isEmpty()) return@launch setUnavailable()
|
||||
updateTileState()
|
||||
@@ -68,13 +68,15 @@ class TunnelControlTile : TileService(), LifecycleOwner {
|
||||
override fun onClick() {
|
||||
super.onClick()
|
||||
unlockAndRun {
|
||||
Timber.d("Click")
|
||||
lifecycleScope.launch {
|
||||
val context = this@TunnelControlTile
|
||||
val lastActive = appDataRepository.getStartTunnelConfig()
|
||||
lastActive?.let { tunnel ->
|
||||
if (tunnel.isActive) return@launch context.stopTunnelBackground(tunnel.id)
|
||||
context.startTunnelBackground(tunnel.id)
|
||||
if (tunnel.isActive) {
|
||||
tunnelService.get().stopTunnel(tunnel)
|
||||
} else {
|
||||
tunnelService.get().startTunnel(tunnel, true)
|
||||
}
|
||||
updateTileState()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -124,6 +126,17 @@ class TunnelControlTile : TileService(), LifecycleOwner {
|
||||
}
|
||||
}
|
||||
|
||||
/* This works around an annoying unsolved frameworks bug some people are hitting. */
|
||||
override fun onBind(intent: Intent): IBinder? {
|
||||
var ret: IBinder? = null
|
||||
try {
|
||||
ret = super.onBind(intent)
|
||||
} catch (_: Throwable) {
|
||||
Timber.e("Failed to bind to TunnelControlTile")
|
||||
}
|
||||
return ret
|
||||
}
|
||||
|
||||
override val lifecycle: Lifecycle
|
||||
get() = lifecycleRegistry
|
||||
}
|
||||
|
||||
+2
-1
@@ -5,7 +5,7 @@ import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
|
||||
interface TunnelService : Tunnel, org.amnezia.awg.backend.Tunnel {
|
||||
suspend fun startTunnel(tunnelConfig: TunnelConfig): Result<TunnelState>
|
||||
suspend fun startTunnel(tunnelConfig: TunnelConfig, background: Boolean = false): Result<TunnelState>
|
||||
|
||||
suspend fun stopTunnel(tunnelConfig: TunnelConfig): Result<TunnelState>
|
||||
|
||||
@@ -18,5 +18,6 @@ interface TunnelService : Tunnel, org.amnezia.awg.backend.Tunnel {
|
||||
suspend fun getState(): TunnelState
|
||||
|
||||
fun cancelStatsJob()
|
||||
|
||||
fun startStatsJob()
|
||||
}
|
||||
|
||||
+38
-4
@@ -8,6 +8,7 @@ import com.zaneschepke.wireguardautotunnel.data.repository.TunnelConfigRepositor
|
||||
import com.zaneschepke.wireguardautotunnel.module.ApplicationScope
|
||||
import com.zaneschepke.wireguardautotunnel.module.IoDispatcher
|
||||
import com.zaneschepke.wireguardautotunnel.module.Kernel
|
||||
import com.zaneschepke.wireguardautotunnel.service.foreground.ServiceManager
|
||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.statistics.AmneziaStatistics
|
||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.statistics.TunnelStatistics
|
||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.statistics.WireGuardStatistics
|
||||
@@ -24,6 +25,7 @@ import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import org.amnezia.awg.backend.Tunnel
|
||||
import timber.log.Timber
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Provider
|
||||
|
||||
@@ -36,6 +38,7 @@ constructor(
|
||||
private val appDataRepository: AppDataRepository,
|
||||
@ApplicationScope private val applicationScope: CoroutineScope,
|
||||
@IoDispatcher private val ioDispatcher: CoroutineDispatcher,
|
||||
private val serviceManager: ServiceManager,
|
||||
) : TunnelService {
|
||||
|
||||
private val _vpnState = MutableStateFlow(VpnState())
|
||||
@@ -50,6 +53,8 @@ constructor(
|
||||
|
||||
private var statsJob: Job? = null
|
||||
|
||||
private val runningHandle = AtomicBoolean(false)
|
||||
|
||||
private suspend fun backend(): Any {
|
||||
val settings = appDataRepository.settings.getSettings()
|
||||
if (settings.isKernelEnabled) return kernelBackend.get()
|
||||
@@ -87,9 +92,16 @@ constructor(
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun startTunnel(tunnelConfig: TunnelConfig): Result<TunnelState> {
|
||||
override suspend fun startTunnel(tunnelConfig: TunnelConfig, background: Boolean): Result<TunnelState> {
|
||||
return withContext(ioDispatcher) {
|
||||
if (runningHandle.get() == true && tunnelConfig == vpnState.value.tunnelConfig) {
|
||||
Timber.w("Tunnel already running")
|
||||
return@withContext Result.success(vpnState.value.status)
|
||||
}
|
||||
runningHandle.set(true)
|
||||
onBeforeStart(tunnelConfig)
|
||||
val settings = appDataRepository.settings.getSettings()
|
||||
if (background || settings.isKernelEnabled) startBackgroundService()
|
||||
setState(tunnelConfig, TunnelState.UP).onSuccess {
|
||||
emitTunnelState(it)
|
||||
}.onFailure {
|
||||
@@ -107,6 +119,9 @@ constructor(
|
||||
}.onFailure {
|
||||
Timber.e(it)
|
||||
onStopFailed()
|
||||
}.also {
|
||||
stopBackgroundService()
|
||||
runningHandle.set(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -141,20 +156,39 @@ constructor(
|
||||
}
|
||||
cancelStatsJob()
|
||||
resetBackendStatistics()
|
||||
runningHandle.set(false)
|
||||
}
|
||||
|
||||
private suspend fun shutDownActiveTunnel(config: TunnelConfig) {
|
||||
with(_vpnState.value) {
|
||||
if (status == TunnelState.UP && tunnelConfig != config) {
|
||||
tunnelConfig?.let { stopTunnel(it) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun startBackgroundService() {
|
||||
serviceManager.startBackgroundService()
|
||||
serviceManager.requestTunnelTileUpdate()
|
||||
}
|
||||
|
||||
private fun stopBackgroundService() {
|
||||
serviceManager.stopBackgroundService()
|
||||
serviceManager.requestTunnelTileUpdate()
|
||||
}
|
||||
|
||||
private suspend fun onBeforeStart(tunnelConfig: TunnelConfig) {
|
||||
if (_vpnState.value.status == TunnelState.UP) vpnState.value.tunnelConfig?.let { stopTunnel(it) }
|
||||
resetBackendStatistics()
|
||||
shutDownActiveTunnel(tunnelConfig)
|
||||
appDataRepository.tunnels.save(tunnelConfig.copy(isActive = true))
|
||||
emitVpnStateConfig(tunnelConfig)
|
||||
resetBackendStatistics()
|
||||
startStatsJob()
|
||||
}
|
||||
|
||||
private suspend fun onBeforeStop(tunnelConfig: TunnelConfig) {
|
||||
appDataRepository.tunnels.save(tunnelConfig.copy(isActive = false))
|
||||
cancelStatsJob()
|
||||
resetBackendStatistics()
|
||||
appDataRepository.tunnels.save(tunnelConfig.copy(isActive = false))
|
||||
}
|
||||
|
||||
private fun emitTunnelState(state: TunnelState) {
|
||||
|
||||
@@ -10,4 +10,5 @@ data class AppUiState(
|
||||
val tunnels: List<TunnelConfig> = emptyList(),
|
||||
val vpnState: VpnState = VpnState(),
|
||||
val generalState: GeneralState = GeneralState(),
|
||||
val autoTunnelActive: Boolean = false,
|
||||
)
|
||||
|
||||
@@ -2,61 +2,97 @@ package com.zaneschepke.wireguardautotunnel.ui
|
||||
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import androidx.navigation.NavHostController
|
||||
import com.zaneschepke.wireguardautotunnel.WireGuardAutoTunnel
|
||||
import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository
|
||||
import com.zaneschepke.wireguardautotunnel.module.IoDispatcher
|
||||
import com.zaneschepke.wireguardautotunnel.service.foreground.ServiceManager
|
||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelService
|
||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelState
|
||||
import com.zaneschepke.wireguardautotunnel.util.Constants
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.TunnelConfigs
|
||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||
import kotlinx.coroutines.CoroutineDispatcher
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.SharingStarted
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.collect
|
||||
import kotlinx.coroutines.flow.combine
|
||||
import kotlinx.coroutines.flow.onCompletion
|
||||
import kotlinx.coroutines.flow.stateIn
|
||||
import kotlinx.coroutines.flow.takeWhile
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.plus
|
||||
import xyz.teamgravity.pin_lock_compose.PinManager
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Provider
|
||||
|
||||
@HiltViewModel
|
||||
class AppViewModel
|
||||
@Inject
|
||||
constructor(
|
||||
private val appDataRepository: AppDataRepository,
|
||||
tunnelService: TunnelService,
|
||||
val navHostController: NavHostController,
|
||||
private val tunnelService: Provider<TunnelService>,
|
||||
@IoDispatcher private val ioDispatcher: CoroutineDispatcher,
|
||||
private val serviceManager: ServiceManager,
|
||||
) : ViewModel() {
|
||||
|
||||
private val _appUiState = MutableStateFlow(AppUiState())
|
||||
|
||||
val uiState =
|
||||
combine(
|
||||
appDataRepository.settings.getSettingsFlow(),
|
||||
appDataRepository.tunnels.getTunnelConfigsFlow(),
|
||||
tunnelService.vpnState,
|
||||
tunnelService.get().vpnState,
|
||||
appDataRepository.appState.generalStateFlow,
|
||||
) { settings, tunnels, tunnelState, generalState ->
|
||||
serviceManager.autoTunnelActive,
|
||||
) { settings, tunnels, tunnelState, generalState, autoTunnel ->
|
||||
AppUiState(
|
||||
settings,
|
||||
tunnels,
|
||||
tunnelState,
|
||||
generalState,
|
||||
autoTunnel,
|
||||
)
|
||||
}
|
||||
.stateIn(
|
||||
viewModelScope + ioDispatcher,
|
||||
SharingStarted.WhileSubscribed(Constants.SUBSCRIPTION_TIMEOUT),
|
||||
_appUiState.value,
|
||||
)
|
||||
|
||||
fun setTunnels(tunnels: TunnelConfigs) = viewModelScope.launch(ioDispatcher) {
|
||||
_appUiState.emit(
|
||||
_appUiState.value.copy(
|
||||
tunnels = tunnels,
|
||||
),
|
||||
}.stateIn(
|
||||
viewModelScope + ioDispatcher,
|
||||
SharingStarted.WhileSubscribed(Constants.SUBSCRIPTION_TIMEOUT),
|
||||
AppUiState(),
|
||||
)
|
||||
|
||||
private val _isAppReady = MutableStateFlow<Boolean>(false)
|
||||
val isAppReady = _isAppReady.asStateFlow()
|
||||
|
||||
init {
|
||||
viewModelScope.launch {
|
||||
initPin()
|
||||
initAutoTunnel()
|
||||
initTunnel()
|
||||
appReadyCheck()
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun appReadyCheck() {
|
||||
val tunnelCount = appDataRepository.tunnels.count()
|
||||
uiState.takeWhile { it.tunnels.size != tunnelCount }.onCompletion {
|
||||
_isAppReady.emit(true)
|
||||
}.collect()
|
||||
}
|
||||
|
||||
private suspend fun initTunnel() {
|
||||
if (tunnelService.get().getState() == TunnelState.UP) tunnelService.get().startStatsJob()
|
||||
val activeTunnels = appDataRepository.tunnels.getActive()
|
||||
if (activeTunnels.isNotEmpty() &&
|
||||
tunnelService.get().getState() == TunnelState.DOWN
|
||||
) {
|
||||
tunnelService.get().startTunnel(activeTunnels.first())
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun initPin() {
|
||||
val isPinEnabled = appDataRepository.appState.isPinLockEnabled()
|
||||
if (isPinEnabled) PinManager.initialize(WireGuardAutoTunnel.instance)
|
||||
}
|
||||
|
||||
private suspend fun initAutoTunnel() {
|
||||
val settings = appDataRepository.settings.getSettings()
|
||||
if (settings.isAutoTunnelEnabled) serviceManager.startAutoTunnel(false)
|
||||
}
|
||||
|
||||
fun onPinLockDisabled() = viewModelScope.launch(ioDispatcher) {
|
||||
@@ -67,4 +103,8 @@ constructor(
|
||||
fun onPinLockEnabled() = viewModelScope.launch {
|
||||
appDataRepository.appState.setPinLockEnabled(true)
|
||||
}
|
||||
|
||||
fun setLocationDisclosureShown() = viewModelScope.launch {
|
||||
appDataRepository.appState.setLocationDisclosureShown(true)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui
|
||||
|
||||
import android.content.Context
|
||||
import android.os.Bundle
|
||||
import androidx.activity.SystemBarStyle
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.activity.enableEdgeToEdge
|
||||
import androidx.activity.viewModels
|
||||
import androidx.appcompat.app.AppCompatActivity
|
||||
import androidx.compose.animation.core.tween
|
||||
import androidx.compose.animation.fadeIn
|
||||
import androidx.compose.animation.fadeOut
|
||||
import androidx.compose.foundation.focusable
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.WindowInsets
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material.icons.Icons
|
||||
@@ -19,185 +20,204 @@ import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.SnackbarData
|
||||
import androidx.compose.material3.SnackbarHost
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.surfaceColorAtElevation
|
||||
import androidx.compose.runtime.CompositionLocalProvider
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.focus.focusProperties
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.toArgb
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.hilt.navigation.compose.hiltViewModel
|
||||
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.navigation.compose.NavHost
|
||||
import androidx.navigation.compose.composable
|
||||
import androidx.navigation.compose.currentBackStackEntryAsState
|
||||
import androidx.navigation.compose.rememberNavController
|
||||
import androidx.navigation.toRoute
|
||||
import com.zaneschepke.wireguardautotunnel.R
|
||||
import com.zaneschepke.wireguardautotunnel.WireGuardAutoTunnel
|
||||
import com.zaneschepke.wireguardautotunnel.data.datastore.LocaleStorage
|
||||
import com.zaneschepke.wireguardautotunnel.data.repository.AppStateRepository
|
||||
import com.zaneschepke.wireguardautotunnel.service.foreground.ServiceManager
|
||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelService
|
||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelState
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.navigation.BottomNavBar
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.navigation.BottomNavItem
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.navigation.isCurrentRoute
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.prompt.CustomSnackBar
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.navigation.LocalFocusRequester
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.navigation.LocalNavController
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.snackbar.CustomSnackBar
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.snackbar.SnackbarControllerProvider
|
||||
import com.zaneschepke.wireguardautotunnel.ui.screens.config.ConfigScreen
|
||||
import com.zaneschepke.wireguardautotunnel.ui.screens.main.MainScreen
|
||||
import com.zaneschepke.wireguardautotunnel.ui.screens.options.OptionsScreen
|
||||
import com.zaneschepke.wireguardautotunnel.ui.screens.pinlock.PinLockScreen
|
||||
import com.zaneschepke.wireguardautotunnel.ui.screens.scanner.ScannerScreen
|
||||
import com.zaneschepke.wireguardautotunnel.ui.screens.settings.SettingsScreen
|
||||
import com.zaneschepke.wireguardautotunnel.ui.screens.settings.appearance.AppearanceScreen
|
||||
import com.zaneschepke.wireguardautotunnel.ui.screens.settings.appearance.display.DisplayScreen
|
||||
import com.zaneschepke.wireguardautotunnel.ui.screens.settings.appearance.language.LanguageScreen
|
||||
import com.zaneschepke.wireguardautotunnel.ui.screens.settings.autotunnel.AutoTunnelScreen
|
||||
import com.zaneschepke.wireguardautotunnel.ui.screens.settings.disclosure.LocationDisclosureScreen
|
||||
import com.zaneschepke.wireguardautotunnel.ui.screens.support.SupportScreen
|
||||
import com.zaneschepke.wireguardautotunnel.ui.screens.support.logs.LogsScreen
|
||||
import com.zaneschepke.wireguardautotunnel.ui.theme.WireguardAutoTunnelTheme
|
||||
import com.zaneschepke.wireguardautotunnel.util.Constants
|
||||
import com.zaneschepke.wireguardautotunnel.util.LocaleUtil
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.requestAutoTunnelTileServiceUpdate
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.requestTunnelTileServiceStateUpdate
|
||||
import dagger.hilt.android.AndroidEntryPoint
|
||||
import timber.log.Timber
|
||||
import javax.inject.Inject
|
||||
|
||||
@AndroidEntryPoint
|
||||
class MainActivity : AppCompatActivity() {
|
||||
|
||||
private val localeStorage: LocaleStorage by lazy {
|
||||
(application as WireGuardAutoTunnel).localeStorage
|
||||
}
|
||||
|
||||
private lateinit var oldPrefLocaleCode: String
|
||||
|
||||
@Inject
|
||||
lateinit var appStateRepository: AppStateRepository
|
||||
|
||||
@Inject
|
||||
lateinit var tunnelService: TunnelService
|
||||
|
||||
private val viewModel by viewModels<AppViewModel>()
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
|
||||
val isPinLockEnabled = intent.extras?.getBoolean(SplashActivity.IS_PIN_LOCK_ENABLED_KEY)
|
||||
|
||||
enableEdgeToEdge(
|
||||
navigationBarStyle = SystemBarStyle.auto(
|
||||
lightScrim = Color.Transparent.toArgb(),
|
||||
darkScrim = Color.Transparent.toArgb(),
|
||||
),
|
||||
)
|
||||
installSplashScreen().apply {
|
||||
setKeepOnScreenCondition {
|
||||
!viewModel.isAppReady.value
|
||||
}
|
||||
}
|
||||
|
||||
setContent {
|
||||
val appViewModel = hiltViewModel<AppViewModel>()
|
||||
val appUiState by appViewModel.uiState.collectAsStateWithLifecycle(lifecycle = this.lifecycle)
|
||||
val navController = appViewModel.navHostController
|
||||
val navBackStackEntry by navController.currentBackStackEntryAsState()
|
||||
val appUiState by viewModel.uiState.collectAsStateWithLifecycle(lifecycle = this.lifecycle)
|
||||
val navController = rememberNavController()
|
||||
val rootItemFocusRequester = remember { FocusRequester() }
|
||||
|
||||
LaunchedEffect(appUiState.vpnState.status) {
|
||||
val context = this@MainActivity
|
||||
when (appUiState.vpnState.status) {
|
||||
TunnelState.DOWN -> ServiceManager.stopTunnelBackgroundService(context)
|
||||
else -> Unit
|
||||
}
|
||||
context.requestTunnelTileServiceStateUpdate()
|
||||
LaunchedEffect(appUiState.tunnels) {
|
||||
Timber.d("Updating launched")
|
||||
requestTunnelTileServiceStateUpdate()
|
||||
}
|
||||
|
||||
SnackbarControllerProvider { host ->
|
||||
WireguardAutoTunnelTheme {
|
||||
val focusRequester = remember { FocusRequester() }
|
||||
Scaffold(
|
||||
snackbarHost = {
|
||||
SnackbarHost(host) { snackbarData: SnackbarData ->
|
||||
CustomSnackBar(
|
||||
snackbarData.visuals.message,
|
||||
isRtl = false,
|
||||
containerColor =
|
||||
MaterialTheme.colorScheme.surfaceColorAtElevation(
|
||||
2.dp,
|
||||
),
|
||||
)
|
||||
}
|
||||
},
|
||||
containerColor = MaterialTheme.colorScheme.background,
|
||||
modifier =
|
||||
Modifier
|
||||
.focusable()
|
||||
.focusProperties {
|
||||
if (navBackStackEntry?.isCurrentRoute(Route.Lock) == true) {
|
||||
Unit
|
||||
} else {
|
||||
up = focusRequester
|
||||
}
|
||||
},
|
||||
bottomBar = {
|
||||
BottomNavBar(
|
||||
navController,
|
||||
listOf(
|
||||
BottomNavItem(
|
||||
name = stringResource(R.string.tunnels),
|
||||
route = Route.Main,
|
||||
icon = Icons.Rounded.Home,
|
||||
),
|
||||
BottomNavItem(
|
||||
name = stringResource(R.string.settings),
|
||||
route = Route.Settings,
|
||||
icon = Icons.Rounded.Settings,
|
||||
),
|
||||
BottomNavItem(
|
||||
name = stringResource(R.string.support),
|
||||
route = Route.Support,
|
||||
icon = Icons.Rounded.QuestionMark,
|
||||
),
|
||||
),
|
||||
)
|
||||
},
|
||||
) { padding ->
|
||||
Surface(modifier = Modifier.fillMaxSize().padding(padding)) {
|
||||
NavHost(
|
||||
navController,
|
||||
enterTransition = { fadeIn(tween(Constants.TRANSITION_ANIMATION_TIME)) },
|
||||
exitTransition = { fadeOut(tween(Constants.TRANSITION_ANIMATION_TIME)) },
|
||||
startDestination = (if (isPinLockEnabled == true) Route.Lock else Route.Main),
|
||||
LaunchedEffect(appUiState.autoTunnelActive) {
|
||||
requestAutoTunnelTileServiceUpdate()
|
||||
}
|
||||
|
||||
with(appUiState.settings) {
|
||||
LaunchedEffect(isAutoTunnelEnabled) {
|
||||
this@MainActivity.requestAutoTunnelTileServiceUpdate()
|
||||
}
|
||||
}
|
||||
|
||||
CompositionLocalProvider(LocalFocusRequester provides rootItemFocusRequester) {
|
||||
CompositionLocalProvider(LocalNavController provides navController) {
|
||||
SnackbarControllerProvider { host ->
|
||||
WireguardAutoTunnelTheme(theme = appUiState.generalState.theme) {
|
||||
Scaffold(
|
||||
contentWindowInsets = WindowInsets(0.dp),
|
||||
snackbarHost = {
|
||||
SnackbarHost(host) { snackbarData: SnackbarData ->
|
||||
CustomSnackBar(
|
||||
snackbarData.visuals.message,
|
||||
isRtl = false,
|
||||
containerColor =
|
||||
MaterialTheme.colorScheme.surfaceColorAtElevation(
|
||||
2.dp,
|
||||
),
|
||||
)
|
||||
}
|
||||
},
|
||||
bottomBar = {
|
||||
BottomNavBar(
|
||||
navController,
|
||||
listOf(
|
||||
BottomNavItem(
|
||||
name = stringResource(R.string.tunnels),
|
||||
route = Route.Main,
|
||||
icon = Icons.Rounded.Home,
|
||||
),
|
||||
BottomNavItem(
|
||||
name = stringResource(R.string.settings),
|
||||
route = Route.Settings,
|
||||
icon = Icons.Rounded.Settings,
|
||||
),
|
||||
BottomNavItem(
|
||||
name = stringResource(R.string.support),
|
||||
route = Route.Support,
|
||||
icon = Icons.Rounded.QuestionMark,
|
||||
),
|
||||
),
|
||||
)
|
||||
},
|
||||
) {
|
||||
composable<Route.Main> {
|
||||
MainScreen(
|
||||
focusRequester = focusRequester,
|
||||
uiState = appUiState,
|
||||
navController = navController,
|
||||
)
|
||||
}
|
||||
composable<Route.Settings> {
|
||||
SettingsScreen(
|
||||
appViewModel = appViewModel,
|
||||
uiState = appUiState,
|
||||
navController = navController,
|
||||
focusRequester = focusRequester,
|
||||
)
|
||||
}
|
||||
composable<Route.Support> {
|
||||
SupportScreen(
|
||||
focusRequester = focusRequester,
|
||||
navController = navController,
|
||||
appUiState = appUiState,
|
||||
)
|
||||
}
|
||||
composable<Route.Logs> {
|
||||
LogsScreen()
|
||||
}
|
||||
composable<Route.Config> {
|
||||
val args = it.toRoute<Route.Config>()
|
||||
ConfigScreen(
|
||||
focusRequester = focusRequester,
|
||||
tunnelId = args.id,
|
||||
)
|
||||
}
|
||||
composable<Route.Option> {
|
||||
val args = it.toRoute<Route.Option>()
|
||||
OptionsScreen(
|
||||
navController = navController,
|
||||
tunnelId = args.id,
|
||||
focusRequester = focusRequester,
|
||||
appUiState = appUiState,
|
||||
)
|
||||
}
|
||||
composable<Route.Lock> {
|
||||
PinLockScreen(
|
||||
navController = navController,
|
||||
appViewModel = appViewModel,
|
||||
)
|
||||
Box(modifier = Modifier.fillMaxSize().padding(it)) {
|
||||
NavHost(
|
||||
navController,
|
||||
enterTransition = { fadeIn(tween(Constants.TRANSITION_ANIMATION_TIME)) },
|
||||
exitTransition = { fadeOut(tween(Constants.TRANSITION_ANIMATION_TIME)) },
|
||||
startDestination = (if (appUiState.generalState.isPinLockEnabled == true) Route.Lock else Route.Main),
|
||||
) {
|
||||
composable<Route.Main> {
|
||||
MainScreen(
|
||||
uiState = appUiState,
|
||||
)
|
||||
}
|
||||
composable<Route.Settings> {
|
||||
SettingsScreen(
|
||||
appViewModel = viewModel,
|
||||
uiState = appUiState,
|
||||
)
|
||||
}
|
||||
composable<Route.LocationDisclosure> {
|
||||
LocationDisclosureScreen(viewModel, appUiState)
|
||||
}
|
||||
composable<Route.AutoTunnel> {
|
||||
AutoTunnelScreen(
|
||||
appUiState,
|
||||
)
|
||||
}
|
||||
composable<Route.Appearance> {
|
||||
AppearanceScreen()
|
||||
}
|
||||
composable<Route.Language> {
|
||||
LanguageScreen(localeStorage)
|
||||
}
|
||||
composable<Route.Display> {
|
||||
DisplayScreen(appUiState)
|
||||
}
|
||||
composable<Route.Support> {
|
||||
SupportScreen()
|
||||
}
|
||||
composable<Route.Logs> {
|
||||
LogsScreen()
|
||||
}
|
||||
composable<Route.Config> {
|
||||
val args = it.toRoute<Route.Config>()
|
||||
ConfigScreen(
|
||||
tunnelId = args.id,
|
||||
)
|
||||
}
|
||||
composable<Route.Option> {
|
||||
val args = it.toRoute<Route.Option>()
|
||||
OptionsScreen(
|
||||
tunnelId = args.id,
|
||||
appUiState = appUiState,
|
||||
)
|
||||
}
|
||||
composable<Route.Lock> {
|
||||
PinLockScreen(
|
||||
appViewModel = viewModel,
|
||||
)
|
||||
}
|
||||
composable<Route.Scanner> {
|
||||
ScannerScreen()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -207,6 +227,21 @@ class MainActivity : AppCompatActivity() {
|
||||
}
|
||||
}
|
||||
|
||||
override fun attachBaseContext(newBase: Context) {
|
||||
oldPrefLocaleCode = LocaleStorage(newBase).getPreferredLocale()
|
||||
applyOverrideConfiguration(LocaleUtil.getLocalizedConfiguration(oldPrefLocaleCode))
|
||||
super.attachBaseContext(newBase)
|
||||
}
|
||||
|
||||
override fun onResume() {
|
||||
val currentLocaleCode = LocaleStorage(this).getPreferredLocale()
|
||||
if (oldPrefLocaleCode != currentLocaleCode) {
|
||||
recreate() // locale is changed, restart the activity to update
|
||||
oldPrefLocaleCode = currentLocaleCode
|
||||
}
|
||||
super.onResume()
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
super.onDestroy()
|
||||
tunnelService.cancelStatsJob()
|
||||
|
||||
@@ -9,6 +9,21 @@ sealed class Route {
|
||||
@Serializable
|
||||
data object Settings : Route()
|
||||
|
||||
@Serializable
|
||||
data object AutoTunnel : Route()
|
||||
|
||||
@Serializable
|
||||
data object LocationDisclosure : Route()
|
||||
|
||||
@Serializable
|
||||
data object Appearance : Route()
|
||||
|
||||
@Serializable
|
||||
data object Display : Route()
|
||||
|
||||
@Serializable
|
||||
data object Language : Route()
|
||||
|
||||
@Serializable
|
||||
data object Main : Route()
|
||||
|
||||
@@ -20,6 +35,9 @@ sealed class Route {
|
||||
@Serializable
|
||||
data object Lock : Route()
|
||||
|
||||
@Serializable
|
||||
data object Scanner : Route()
|
||||
|
||||
@Serializable
|
||||
data class Config(
|
||||
val id: Int,
|
||||
|
||||
@@ -1,87 +0,0 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.Intent
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.viewModels
|
||||
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import androidx.lifecycle.repeatOnLifecycle
|
||||
import com.zaneschepke.wireguardautotunnel.WireGuardAutoTunnel
|
||||
import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository
|
||||
import com.zaneschepke.wireguardautotunnel.data.repository.AppStateRepository
|
||||
import com.zaneschepke.wireguardautotunnel.service.foreground.ServiceManager
|
||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelService
|
||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelState
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.requestAutoTunnelTileServiceUpdate
|
||||
import dagger.hilt.android.AndroidEntryPoint
|
||||
import kotlinx.coroutines.async
|
||||
import kotlinx.coroutines.launch
|
||||
import xyz.teamgravity.pin_lock_compose.PinManager
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Provider
|
||||
|
||||
@SuppressLint("CustomSplashScreen")
|
||||
@AndroidEntryPoint
|
||||
class SplashActivity : ComponentActivity() {
|
||||
@Inject
|
||||
lateinit var appStateRepository: AppStateRepository
|
||||
|
||||
@Inject
|
||||
lateinit var appDataRepository: AppDataRepository
|
||||
|
||||
@Inject
|
||||
lateinit var tunnelService: Provider<TunnelService>
|
||||
|
||||
private val appViewModel: AppViewModel by viewModels()
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
|
||||
val splashScreen = installSplashScreen()
|
||||
splashScreen.setKeepOnScreenCondition { true }
|
||||
}
|
||||
super.onCreate(savedInstanceState)
|
||||
|
||||
lifecycleScope.launch {
|
||||
repeatOnLifecycle(Lifecycle.State.CREATED) {
|
||||
val pinLockEnabled = async {
|
||||
appStateRepository.isPinLockEnabled().also {
|
||||
if (it) PinManager.initialize(WireGuardAutoTunnel.instance)
|
||||
}
|
||||
}.await()
|
||||
async {
|
||||
val settings = appDataRepository.settings.getSettings()
|
||||
if (settings.isAutoTunnelEnabled) ServiceManager.startWatcherService(application.applicationContext)
|
||||
if (tunnelService.get().getState() == TunnelState.UP) tunnelService.get().startStatsJob()
|
||||
val activeTunnels = appDataRepository.tunnels.getActive()
|
||||
if (activeTunnels.isNotEmpty() &&
|
||||
tunnelService.get().getState() == TunnelState.DOWN
|
||||
) {
|
||||
tunnelService.get().startTunnel(activeTunnels.first())
|
||||
}
|
||||
}.await()
|
||||
|
||||
async {
|
||||
val tunnels = appDataRepository.tunnels.getAll()
|
||||
appViewModel.setTunnels(tunnels)
|
||||
}.await()
|
||||
|
||||
requestAutoTunnelTileServiceUpdate()
|
||||
|
||||
val intent =
|
||||
Intent(this@SplashActivity, MainActivity::class.java).apply {
|
||||
putExtra(IS_PIN_LOCK_ENABLED_KEY, pinLockEnabled)
|
||||
}
|
||||
startActivity(intent)
|
||||
finish()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val IS_PIN_LOCK_ENABLED_KEY = "is_pin_lock_enabled"
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -5,6 +5,7 @@ import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.material3.ButtonDefaults
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
@@ -17,7 +18,7 @@ fun ClickableIconButton(onClick: () -> Unit, onIconClick: () -> Unit, text: Stri
|
||||
onClick = onClick,
|
||||
enabled = enabled,
|
||||
) {
|
||||
Text(text, Modifier.weight(1f, false))
|
||||
Text(text, Modifier.weight(1f, false), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.primary)
|
||||
Spacer(modifier = Modifier.size(ButtonDefaults.IconSpacing))
|
||||
Icon(
|
||||
imageVector = icon,
|
||||
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.common
|
||||
|
||||
import androidx.compose.animation.animateContentSize
|
||||
import androidx.compose.foundation.ExperimentalFoundationApi
|
||||
import androidx.compose.foundation.combinedClickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
|
||||
@OptIn(ExperimentalFoundationApi::class)
|
||||
@Composable
|
||||
fun ExpandingRowListItem(
|
||||
leading: @Composable () -> Unit,
|
||||
text: String,
|
||||
onHold: () -> Unit = {},
|
||||
onClick: () -> Unit,
|
||||
trailing: @Composable () -> Unit,
|
||||
isExpanded: Boolean,
|
||||
expanded: @Composable () -> Unit = {},
|
||||
) {
|
||||
Box(
|
||||
modifier =
|
||||
Modifier
|
||||
.animateContentSize()
|
||||
.clip(RoundedCornerShape(30.dp))
|
||||
.combinedClickable(
|
||||
onClick = { onClick() },
|
||||
onLongClick = { onHold() },
|
||||
),
|
||||
) {
|
||||
Column {
|
||||
Row(
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 15.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(15.dp),
|
||||
modifier = Modifier.fillMaxWidth(13 / 20f),
|
||||
) {
|
||||
leading()
|
||||
Text(text, maxLines = 1, overflow = TextOverflow.Ellipsis, style = MaterialTheme.typography.labelLarge)
|
||||
}
|
||||
trailing()
|
||||
}
|
||||
if (isExpanded) expanded()
|
||||
}
|
||||
}
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.common
|
||||
|
||||
import androidx.compose.ui.geometry.Offset
|
||||
import androidx.compose.ui.input.nestedscroll.NestedScrollConnection
|
||||
import androidx.compose.ui.input.nestedscroll.NestedScrollSource
|
||||
|
||||
class NestedScrollListener(val onUp: () -> Unit, val onDown: () -> Unit) : NestedScrollConnection {
|
||||
override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {
|
||||
if (available.y < -1) onDown()
|
||||
if (available.y > 1) onUp()
|
||||
return Offset.Zero
|
||||
}
|
||||
}
|
||||
@@ -1,99 +0,0 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.common
|
||||
|
||||
import androidx.compose.animation.animateContentSize
|
||||
import androidx.compose.foundation.ExperimentalFoundationApi
|
||||
import androidx.compose.foundation.combinedClickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.statistics.TunnelStatistics
|
||||
import com.zaneschepke.wireguardautotunnel.util.NumberUtils
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.toThreeDecimalPlaceString
|
||||
|
||||
@OptIn(ExperimentalFoundationApi::class)
|
||||
@Composable
|
||||
fun RowListItem(
|
||||
icon: @Composable () -> Unit,
|
||||
text: String,
|
||||
onHold: () -> Unit,
|
||||
onClick: () -> Unit,
|
||||
rowButton: @Composable () -> Unit,
|
||||
expanded: Boolean,
|
||||
statistics: TunnelStatistics?,
|
||||
focusRequester: FocusRequester,
|
||||
) {
|
||||
Box(
|
||||
modifier =
|
||||
Modifier
|
||||
.focusRequester(focusRequester)
|
||||
.animateContentSize()
|
||||
.clip(RoundedCornerShape(30.dp))
|
||||
.combinedClickable(
|
||||
onClick = { onClick() },
|
||||
onLongClick = { onHold() },
|
||||
),
|
||||
) {
|
||||
Column {
|
||||
Row(
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 15.dp, vertical = 5.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.fillMaxWidth(13 / 20f),
|
||||
) {
|
||||
icon()
|
||||
Text(text, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
rowButton()
|
||||
}
|
||||
if (expanded) {
|
||||
statistics?.getPeers()?.forEach {
|
||||
Row(
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(end = 10.dp, bottom = 10.dp, start = 10.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.SpaceEvenly,
|
||||
) {
|
||||
// TODO change these to string resources
|
||||
val handshakeEpoch = statistics.peerStats(it)!!.latestHandshakeEpochMillis
|
||||
val peerTx = statistics.peerStats(it)!!.txBytes
|
||||
val peerRx = statistics.peerStats(it)!!.rxBytes
|
||||
val peerId = it.toBase64().subSequence(0, 3).toString() + "***"
|
||||
val handshakeSec =
|
||||
NumberUtils.getSecondsBetweenTimestampAndNow(handshakeEpoch)
|
||||
val handshake =
|
||||
if (handshakeSec == null) "never" else "$handshakeSec secs ago"
|
||||
val peerTxMB = NumberUtils.bytesToMB(peerTx).toThreeDecimalPlaceString()
|
||||
val peerRxMB = NumberUtils.bytesToMB(peerRx).toThreeDecimalPlaceString()
|
||||
val fontSize = 9.sp
|
||||
Text("peer: $peerId", fontSize = fontSize)
|
||||
Text("handshake: $handshake", fontSize = fontSize)
|
||||
Text("tx: $peerTxMB MB", fontSize = fontSize)
|
||||
Text("rx: $peerRxMB MB", fontSize = fontSize)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.common
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.zaneschepke.wireguardautotunnel.R
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.scaledHeight
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.scaledWidth
|
||||
|
||||
@Composable
|
||||
fun SelectedLabel() {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.End,
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
stringResource(id = R.string.selected),
|
||||
modifier =
|
||||
Modifier.padding(
|
||||
horizontal = 24.dp.scaledWidth(),
|
||||
vertical = 16.dp.scaledHeight(),
|
||||
),
|
||||
color =
|
||||
MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
)
|
||||
}
|
||||
}
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.common.button
|
||||
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.IntrinsicSize
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.CardDefaults
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.zaneschepke.wireguardautotunnel.ui.theme.iconSize
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.scaledHeight
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.scaledWidth
|
||||
import kotlin.let
|
||||
|
||||
@androidx.compose.runtime.Composable
|
||||
fun IconSurfaceButton(title: String, onClick: () -> Unit, selected: Boolean, leadingIcon: ImageVector? = null, description: String? = null) {
|
||||
val border: BorderStroke? =
|
||||
if (selected) {
|
||||
BorderStroke(
|
||||
1.dp,
|
||||
MaterialTheme.colorScheme.primary,
|
||||
)
|
||||
} else {
|
||||
null
|
||||
}
|
||||
Card(
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.height(IntrinsicSize.Min),
|
||||
shape = RoundedCornerShape(8.dp),
|
||||
border = border,
|
||||
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface),
|
||||
) {
|
||||
Box(
|
||||
modifier = Modifier.clickable { onClick() }
|
||||
.fillMaxWidth(),
|
||||
) {
|
||||
Column(
|
||||
modifier =
|
||||
Modifier
|
||||
.padding(horizontal = 8.dp.scaledWidth(), vertical = 10.dp.scaledHeight())
|
||||
.padding(end = 16.dp.scaledWidth()).padding(start = 8.dp.scaledWidth())
|
||||
.fillMaxSize(),
|
||||
verticalArrangement = Arrangement.Center,
|
||||
horizontalAlignment = Alignment.Start,
|
||||
) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.Companion.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(16.dp.scaledWidth()),
|
||||
) {
|
||||
Row(
|
||||
horizontalArrangement = Arrangement.spacedBy(
|
||||
16.dp.scaledWidth(),
|
||||
),
|
||||
verticalAlignment = Alignment.Companion.CenterVertically,
|
||||
modifier = Modifier.padding(vertical = if (description == null) 10.dp.scaledHeight() else 0.dp),
|
||||
) {
|
||||
leadingIcon?.let {
|
||||
Icon(
|
||||
leadingIcon,
|
||||
leadingIcon.name,
|
||||
Modifier.size(iconSize),
|
||||
if (selected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurface,
|
||||
)
|
||||
}
|
||||
Column {
|
||||
Text(
|
||||
title,
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
)
|
||||
description?.let {
|
||||
Text(
|
||||
description,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.common.button
|
||||
|
||||
import androidx.compose.material3.Switch
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.scale
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.scaledHeight
|
||||
|
||||
@Composable
|
||||
fun ScaledSwitch(checked: Boolean, onClick: (checked: Boolean) -> Unit, enabled: Boolean = true, modifier: Modifier = Modifier) {
|
||||
Switch(
|
||||
checked,
|
||||
{ onClick(it) },
|
||||
modifier.scale((52.dp.scaledHeight() / 52.dp)),
|
||||
enabled = enabled,
|
||||
)
|
||||
}
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.common.button
|
||||
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.CardDefaults
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.ripple
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.scaledHeight
|
||||
|
||||
@Composable
|
||||
fun SelectionItemButton(
|
||||
leading: (@Composable () -> Unit)? = null,
|
||||
buttonText: String,
|
||||
trailing: (@Composable () -> Unit)? = null,
|
||||
onClick: () -> Unit,
|
||||
ripple: Boolean = true,
|
||||
) {
|
||||
Card(
|
||||
modifier =
|
||||
Modifier.clip(RoundedCornerShape(8.dp))
|
||||
.clickable(
|
||||
indication = if (ripple) ripple() else null,
|
||||
interactionSource = remember { MutableInteractionSource() },
|
||||
onClick = { onClick() },
|
||||
)
|
||||
.height(56.dp.scaledHeight()),
|
||||
colors =
|
||||
CardDefaults.cardColors(
|
||||
containerColor = MaterialTheme.colorScheme.background,
|
||||
),
|
||||
) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.Start,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
) {
|
||||
leading?.let {
|
||||
it()
|
||||
}
|
||||
Text(
|
||||
buttonText,
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
)
|
||||
trailing?.let {
|
||||
it()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.common.button.surface
|
||||
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
|
||||
data class SelectionItem(
|
||||
val leadingIcon: ImageVector? = null,
|
||||
val trailing: (@Composable () -> Unit)? = null,
|
||||
val title: (@Composable () -> Unit),
|
||||
val description: (@Composable () -> Unit)? = null,
|
||||
val onClick: (() -> Unit)? = null,
|
||||
val height: Int = 64,
|
||||
)
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.common.button.surface
|
||||
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.CardDefaults
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.zaneschepke.wireguardautotunnel.ui.theme.iconSize
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.scaledHeight
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.scaledWidth
|
||||
|
||||
@Composable
|
||||
fun SurfaceSelectionGroupButton(items: List<SelectionItem>) {
|
||||
Card(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
shape = RoundedCornerShape(8.dp),
|
||||
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface),
|
||||
) {
|
||||
items.mapIndexed { index, item ->
|
||||
Box(
|
||||
contentAlignment = Alignment.Center,
|
||||
modifier = Modifier
|
||||
.then(item.onClick?.let { Modifier.clickable { it() } } ?: Modifier)
|
||||
.fillMaxWidth(),
|
||||
) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp.scaledHeight()),
|
||||
) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier
|
||||
.padding(start = 16.dp.scaledWidth())
|
||||
.weight(4f, false)
|
||||
.fillMaxWidth(),
|
||||
) {
|
||||
item.leadingIcon?.let { icon ->
|
||||
Icon(
|
||||
icon,
|
||||
icon.name,
|
||||
modifier = Modifier.size(iconSize),
|
||||
)
|
||||
}
|
||||
Column(
|
||||
horizontalAlignment = Alignment.Start,
|
||||
verticalArrangement = Arrangement.spacedBy(2.dp, Alignment.CenterVertically),
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(start = if (item.leadingIcon != null) 16.dp.scaledWidth() else 0.dp)
|
||||
.padding(vertical = if (item.description == null) 16.dp.scaledHeight() else 6.dp.scaledHeight()),
|
||||
) {
|
||||
item.title()
|
||||
item.description?.let {
|
||||
it()
|
||||
}
|
||||
}
|
||||
}
|
||||
item.trailing?.let {
|
||||
Box(
|
||||
contentAlignment = Alignment.CenterEnd,
|
||||
modifier = Modifier
|
||||
.padding(end = 24.dp.scaledWidth(), start = 16.dp.scaledWidth())
|
||||
.weight(1f),
|
||||
) {
|
||||
it()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (index + 1 != items.size) HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant)
|
||||
}
|
||||
}
|
||||
}
|
||||
+3
-5
@@ -3,35 +3,33 @@ package com.zaneschepke.wireguardautotunnel.ui.common.config
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Switch
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.Dp
|
||||
|
||||
@Composable
|
||||
fun ConfigurationToggle(
|
||||
label: String,
|
||||
enabled: Boolean = true,
|
||||
checked: Boolean,
|
||||
padding: Dp,
|
||||
onCheckChanged: (checked: Boolean) -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
Row(
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(padding),
|
||||
.fillMaxWidth(),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
) {
|
||||
Text(
|
||||
label,
|
||||
textAlign = TextAlign.Start,
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
modifier =
|
||||
Modifier
|
||||
.weight(
|
||||
|
||||
+1
-5
@@ -18,8 +18,6 @@ import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.ui.platform.LocalFocusManager
|
||||
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
|
||||
import androidx.compose.ui.res.stringResource
|
||||
@@ -32,7 +30,6 @@ fun SubmitConfigurationTextBox(
|
||||
value: String?,
|
||||
label: String,
|
||||
hint: String,
|
||||
focusRequester: FocusRequester,
|
||||
isErrorValue: (value: String?) -> Boolean,
|
||||
onSubmit: (value: String) -> Unit,
|
||||
keyboardOptions: KeyboardOptions = KeyboardOptions(
|
||||
@@ -50,8 +47,7 @@ fun SubmitConfigurationTextBox(
|
||||
OutlinedTextField(
|
||||
isError = isErrorValue(stateValue),
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.focusRequester(focusRequester),
|
||||
.fillMaxWidth(),
|
||||
value = stateValue,
|
||||
singleLine = true,
|
||||
interactionSource = interactionSource,
|
||||
|
||||
+8
-1
@@ -10,13 +10,20 @@ import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.runtime.Composable
|
||||
import com.zaneschepke.wireguardautotunnel.util.Constants
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.isRunningOnTv
|
||||
|
||||
@Composable
|
||||
fun rememberFileImportLauncherForResult(onNoFileExplorer: () -> Unit, onData: (data: Uri) -> Unit): ManagedActivityResultLauncher<String, Uri?> {
|
||||
return rememberLauncherForActivityResult(
|
||||
object : ActivityResultContracts.GetContent() {
|
||||
override fun createIntent(context: Context, input: String): Intent {
|
||||
val intent = super.createIntent(context, input)
|
||||
val intent = super.createIntent(context, input).apply {
|
||||
type = if (context.isRunningOnTv()) {
|
||||
Constants.ALLOWED_TV_FILE_TYPES
|
||||
} else {
|
||||
Constants.ALL_FILE_TYPES
|
||||
}
|
||||
}
|
||||
|
||||
/* AndroidTV now comes with stubs that do nothing but display a Toast less helpful than
|
||||
* what we can do, so detect this and throw an exception that we can catch later. */
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.common.label
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
|
||||
@Composable
|
||||
fun GroupLabel(title: String) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.Start,
|
||||
) {
|
||||
Text(
|
||||
title,
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.common.label
|
||||
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalClipboardManager
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.AnnotatedString
|
||||
import com.zaneschepke.wireguardautotunnel.BuildConfig
|
||||
import com.zaneschepke.wireguardautotunnel.R
|
||||
|
||||
@Composable
|
||||
fun VersionLabel() {
|
||||
val clipboardManager = LocalClipboardManager.current
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.Start,
|
||||
) {
|
||||
Text(
|
||||
"${stringResource(R.string.version)}: ${BuildConfig.VERSION_NAME}",
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
color = MaterialTheme.colorScheme.outline,
|
||||
modifier = Modifier.clickable {
|
||||
clipboardManager.setText(AnnotatedString(BuildConfig.VERSION_NAME))
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
+6
-11
@@ -10,10 +10,7 @@ import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.navigation.NavController
|
||||
import androidx.navigation.NavDestination.Companion.hasRoute
|
||||
import androidx.navigation.NavDestination.Companion.hierarchy
|
||||
import androidx.navigation.NavGraph.Companion.findStartDestination
|
||||
import androidx.navigation.compose.currentBackStackEntryAsState
|
||||
|
||||
@@ -22,18 +19,16 @@ fun BottomNavBar(navController: NavController, bottomNavItems: List<BottomNavIte
|
||||
var showBottomBar by rememberSaveable { mutableStateOf(true) }
|
||||
val navBackStackEntry by navController.currentBackStackEntryAsState()
|
||||
|
||||
showBottomBar = bottomNavItems.firstOrNull {
|
||||
navBackStackEntry?.destination?.hierarchy?.any { dest ->
|
||||
bottomNavItems.map { dest.hasRoute(route = it.route::class) }.contains(true)
|
||||
} == true
|
||||
} != null
|
||||
showBottomBar = bottomNavItems.any {
|
||||
navBackStackEntry?.isCurrentRoute(it.route::class) == true
|
||||
}
|
||||
|
||||
if (showBottomBar) {
|
||||
NavigationBar(
|
||||
containerColor = MaterialTheme.colorScheme.surface,
|
||||
) {
|
||||
bottomNavItems.forEach { item ->
|
||||
val selected = navBackStackEntry.isCurrentRoute(item.route)
|
||||
bottomNavItems.forEachIndexed { index, item ->
|
||||
val selected = navBackStackEntry.isCurrentRoute(item.route::class)
|
||||
NavigationBarItem(
|
||||
selected = selected,
|
||||
onClick = {
|
||||
@@ -53,7 +48,7 @@ fun BottomNavBar(navController: NavController, bottomNavItems: List<BottomNavIte
|
||||
label = {
|
||||
Text(
|
||||
text = item.name,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
)
|
||||
},
|
||||
icon = {
|
||||
|
||||
+5
-2
@@ -1,12 +1,15 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.common.navigation
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import androidx.navigation.NavBackStackEntry
|
||||
import androidx.navigation.NavDestination.Companion.hasRoute
|
||||
import androidx.navigation.NavDestination.Companion.hierarchy
|
||||
import com.zaneschepke.wireguardautotunnel.ui.Route
|
||||
import kotlin.reflect.KClass
|
||||
|
||||
fun NavBackStackEntry?.isCurrentRoute(route: Route): Boolean {
|
||||
@SuppressLint("RestrictedApi")
|
||||
fun <T : Route> NavBackStackEntry?.isCurrentRoute(cls: KClass<T>): Boolean {
|
||||
return this?.destination?.hierarchy?.any {
|
||||
it.hasRoute(route = route::class)
|
||||
it.hasRoute(route = cls)
|
||||
} == true
|
||||
}
|
||||
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.common.navigation
|
||||
|
||||
import androidx.compose.runtime.compositionLocalOf
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.navigation.NavHostController
|
||||
|
||||
val LocalNavController = compositionLocalOf<NavHostController> {
|
||||
error("NavController was not provided")
|
||||
}
|
||||
|
||||
val LocalFocusRequester = compositionLocalOf<FocusRequester> { error("FocusRequester is not provided") }
|
||||
-15
@@ -1,15 +0,0 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.common.navigation
|
||||
|
||||
import android.content.Context
|
||||
import androidx.navigation.NavHostController
|
||||
import androidx.navigation.compose.ComposeNavigator
|
||||
import androidx.navigation.compose.DialogNavigator
|
||||
|
||||
class NavigationService constructor(
|
||||
context: Context,
|
||||
) {
|
||||
val navController = NavHostController(context).apply {
|
||||
navigatorProvider.addNavigator(ComposeNavigator())
|
||||
navigatorProvider.addNavigator(DialogNavigator())
|
||||
}
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.common.navigation
|
||||
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.outlined.ArrowBack
|
||||
import androidx.compose.material3.CenterAlignedTopAppBar
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun TopNavBar(title: String, trailing: @Composable () -> Unit = {}, showBack: Boolean = true) {
|
||||
val navController = LocalNavController.current
|
||||
CenterAlignedTopAppBar(
|
||||
title = {
|
||||
Text(title)
|
||||
},
|
||||
navigationIcon = {
|
||||
if (showBack) {
|
||||
IconButton(onClick = { navController.popBackStack() }) {
|
||||
val icon = Icons.AutoMirrored.Outlined.ArrowBack
|
||||
Icon(
|
||||
imageVector = icon,
|
||||
contentDescription = icon.name,
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
actions = {
|
||||
trailing()
|
||||
},
|
||||
)
|
||||
}
|
||||
-27
@@ -1,27 +0,0 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.common.screen
|
||||
|
||||
import androidx.compose.foundation.focusable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.unit.dp
|
||||
|
||||
@Composable
|
||||
fun LoadingScreen() {
|
||||
Column(
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.Top,
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.focusable()
|
||||
.padding(),
|
||||
) {
|
||||
Column(modifier = Modifier.padding(120.dp)) { CircularProgressIndicator() }
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.common.prompt
|
||||
package com.zaneschepke.wireguardautotunnel.ui.common.snackbar
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.IntrinsicSize
|
||||
+2
-4
@@ -1,22 +1,20 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.common.text
|
||||
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.text.TextStyle
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
|
||||
@Composable
|
||||
fun SectionTitle(title: String, padding: Dp) {
|
||||
Text(
|
||||
title,
|
||||
textAlign = TextAlign.Start,
|
||||
style = TextStyle(fontSize = 18.sp, fontWeight = FontWeight.ExtraBold),
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
modifier = Modifier.padding(padding, bottom = 5.dp, top = 5.dp),
|
||||
)
|
||||
}
|
||||
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.common.textbox
|
||||
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.text.BasicTextField
|
||||
import androidx.compose.foundation.text.KeyboardActions
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedTextFieldDefaults
|
||||
import androidx.compose.material3.TextFieldDefaults
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.SolidColor
|
||||
import androidx.compose.ui.text.TextStyle
|
||||
import androidx.compose.ui.text.input.VisualTransformation
|
||||
import androidx.compose.ui.unit.dp
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun CustomTextField(
|
||||
value: String,
|
||||
modifier: Modifier = Modifier,
|
||||
textStyle: TextStyle = MaterialTheme.typography.bodyLarge.copy(color = MaterialTheme.colorScheme.onSurface),
|
||||
label: @Composable () -> Unit,
|
||||
containerColor: Color,
|
||||
onValueChange: (value: String) -> Unit = {},
|
||||
singleLine: Boolean = false,
|
||||
placeholder: @Composable (() -> Unit)? = null,
|
||||
keyboardOptions: KeyboardOptions,
|
||||
keyboardActions: KeyboardActions,
|
||||
supportingText: @Composable (() -> Unit)? = null,
|
||||
leading: @Composable (() -> Unit)? = null,
|
||||
trailing: @Composable (() -> Unit)? = null,
|
||||
isError: Boolean = false,
|
||||
readOnly: Boolean = false,
|
||||
enabled: Boolean = true,
|
||||
) {
|
||||
val interactionSource = remember { MutableInteractionSource() }
|
||||
val space = " "
|
||||
BasicTextField(
|
||||
value = value,
|
||||
textStyle = textStyle,
|
||||
onValueChange = {
|
||||
onValueChange(it)
|
||||
},
|
||||
keyboardActions = keyboardActions,
|
||||
keyboardOptions = keyboardOptions,
|
||||
readOnly = readOnly,
|
||||
cursorBrush = SolidColor(MaterialTheme.colorScheme.onSurface),
|
||||
modifier = modifier,
|
||||
interactionSource = interactionSource,
|
||||
enabled = enabled,
|
||||
singleLine = singleLine,
|
||||
) {
|
||||
OutlinedTextFieldDefaults.DecorationBox(
|
||||
value = space + value,
|
||||
innerTextField = {
|
||||
if (value.isEmpty()) {
|
||||
if (placeholder != null) {
|
||||
placeholder()
|
||||
}
|
||||
}
|
||||
it.invoke()
|
||||
},
|
||||
contentPadding = OutlinedTextFieldDefaults.contentPadding(top = 0.dp, bottom = 0.dp),
|
||||
leadingIcon = leading,
|
||||
trailingIcon = trailing,
|
||||
singleLine = singleLine,
|
||||
supportingText = supportingText,
|
||||
colors = TextFieldDefaults.colors().copy(
|
||||
disabledLabelColor = MaterialTheme.colorScheme.onSurface,
|
||||
disabledContainerColor = containerColor,
|
||||
focusedLabelColor = MaterialTheme.colorScheme.onSurface,
|
||||
focusedContainerColor = containerColor,
|
||||
unfocusedContainerColor = containerColor,
|
||||
focusedTextColor = MaterialTheme.colorScheme.onSurface,
|
||||
cursorColor = MaterialTheme.colorScheme.onSurface,
|
||||
),
|
||||
enabled = enabled,
|
||||
label = label,
|
||||
visualTransformation = VisualTransformation.None,
|
||||
interactionSource = interactionSource,
|
||||
placeholder = placeholder,
|
||||
container = {
|
||||
OutlinedTextFieldDefaults.ContainerBox(
|
||||
enabled,
|
||||
isError = isError,
|
||||
interactionSource,
|
||||
colors = TextFieldDefaults.colors().copy(
|
||||
errorContainerColor = containerColor,
|
||||
disabledLabelColor = MaterialTheme.colorScheme.onSurface,
|
||||
disabledContainerColor = containerColor,
|
||||
focusedIndicatorColor = MaterialTheme.colorScheme.onSurface,
|
||||
focusedLabelColor = MaterialTheme.colorScheme.onSurface,
|
||||
focusedContainerColor = containerColor,
|
||||
unfocusedContainerColor = containerColor,
|
||||
focusedTextColor = MaterialTheme.colorScheme.onSurface,
|
||||
cursorColor = MaterialTheme.colorScheme.onSurface,
|
||||
),
|
||||
shape = RoundedCornerShape(8.dp),
|
||||
focusedBorderThickness = 0.5.dp,
|
||||
unfocusedBorderThickness = 0.5.dp,
|
||||
)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
+35
-39
@@ -1,6 +1,5 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.screens.config
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.focusGroup
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
@@ -34,6 +33,7 @@ import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.derivedStateOf
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
@@ -56,8 +56,11 @@ import androidx.compose.ui.unit.dp
|
||||
import androidx.hilt.navigation.compose.hiltViewModel
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import com.zaneschepke.wireguardautotunnel.R
|
||||
import com.zaneschepke.wireguardautotunnel.ui.Route
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.config.ConfigurationTextBox
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.config.ConfigurationToggle
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.navigation.LocalNavController
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.navigation.TopNavBar
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.prompt.AuthorizationPrompt
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.snackbar.SnackbarController
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.text.SectionTitle
|
||||
@@ -65,11 +68,11 @@ import com.zaneschepke.wireguardautotunnel.ui.screens.config.components.Applicat
|
||||
import com.zaneschepke.wireguardautotunnel.ui.screens.main.ConfigType
|
||||
import com.zaneschepke.wireguardautotunnel.util.Constants
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.isRunningOnTv
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.scaledHeight
|
||||
import kotlinx.coroutines.delay
|
||||
|
||||
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
|
||||
@Composable
|
||||
fun ConfigScreen(tunnelId: Int, focusRequester: FocusRequester) {
|
||||
fun ConfigScreen(tunnelId: Int) {
|
||||
val viewModel = hiltViewModel<ConfigViewModel, ConfigViewModel.ConfigViewModelFactory> { factory ->
|
||||
factory.create(tunnelId)
|
||||
}
|
||||
@@ -78,22 +81,24 @@ fun ConfigScreen(tunnelId: Int, focusRequester: FocusRequester) {
|
||||
val snackbar = SnackbarController.current
|
||||
val clipboardManager: ClipboardManager = LocalClipboardManager.current
|
||||
val keyboardController = LocalSoftwareKeyboardController.current
|
||||
val navController = LocalNavController.current
|
||||
|
||||
var showApplicationsDialog by remember { mutableStateOf(false) }
|
||||
var showAuthPrompt by remember { mutableStateOf(false) }
|
||||
var isAuthenticated by remember { mutableStateOf(false) }
|
||||
var configType by remember { mutableStateOf(ConfigType.WIREGUARD) }
|
||||
|
||||
val uiState by viewModel.uiState.collectAsStateWithLifecycle()
|
||||
var configType by remember { mutableStateOf<ConfigType?>(null) }
|
||||
val derivedConfigType = remember {
|
||||
derivedStateOf<ConfigType> {
|
||||
configType ?: if (!uiState.hasAmneziaProperties()) ConfigType.WIREGUARD else ConfigType.AMNEZIA
|
||||
}
|
||||
}
|
||||
val saved by viewModel.saved.collectAsStateWithLifecycle(null)
|
||||
|
||||
LaunchedEffect(Unit) {
|
||||
if (!uiState.loading && context.isRunningOnTv()) {
|
||||
delay(Constants.FOCUS_REQUEST_DELAY)
|
||||
kotlin.runCatching {
|
||||
focusRequester.requestFocus()
|
||||
}.onFailure {
|
||||
delay(Constants.FOCUS_REQUEST_DELAY)
|
||||
focusRequester.requestFocus()
|
||||
}
|
||||
LaunchedEffect(saved) {
|
||||
if (saved == true) {
|
||||
navController.navigate(Route.Main)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -157,6 +162,9 @@ fun ConfigScreen(tunnelId: Int, focusRequester: FocusRequester) {
|
||||
}
|
||||
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopNavBar(stringResource(R.string.edit_tunnel))
|
||||
},
|
||||
floatingActionButtonPosition = FabPosition.End,
|
||||
floatingActionButton = {
|
||||
FloatingActionButton(
|
||||
@@ -174,7 +182,7 @@ fun ConfigScreen(tunnelId: Int, focusRequester: FocusRequester) {
|
||||
}
|
||||
},
|
||||
) {
|
||||
Column {
|
||||
Column(Modifier.padding(it)) {
|
||||
Column(
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.Top,
|
||||
@@ -199,7 +207,7 @@ fun ConfigScreen(tunnelId: Int, focusRequester: FocusRequester) {
|
||||
Modifier.fillMaxWidth(fillMaxWidth)
|
||||
}
|
||||
)
|
||||
.padding(bottom = 10.dp),
|
||||
.padding(bottom = 10.dp.scaledHeight()).padding(top = 24.dp.scaledHeight()),
|
||||
) {
|
||||
Column(
|
||||
horizontalAlignment = Alignment.Start,
|
||||
@@ -215,10 +223,8 @@ fun ConfigScreen(tunnelId: Int, focusRequester: FocusRequester) {
|
||||
)
|
||||
ConfigurationToggle(
|
||||
stringResource(id = R.string.show_amnezia_properties),
|
||||
checked = configType == ConfigType.AMNEZIA,
|
||||
padding = screenPadding,
|
||||
checked = derivedConfigType.value == ConfigType.AMNEZIA,
|
||||
onCheckChanged = { configType = if (it) ConfigType.AMNEZIA else ConfigType.WIREGUARD },
|
||||
modifier = Modifier.focusRequester(focusRequester),
|
||||
)
|
||||
ConfigurationTextBox(
|
||||
value = uiState.tunnelName,
|
||||
@@ -228,8 +234,7 @@ fun ConfigScreen(tunnelId: Int, focusRequester: FocusRequester) {
|
||||
hint = stringResource(R.string.tunnel_name).lowercase(),
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.focusRequester(focusRequester),
|
||||
.fillMaxWidth(),
|
||||
)
|
||||
OutlinedTextField(
|
||||
modifier =
|
||||
@@ -333,7 +338,7 @@ fun ConfigScreen(tunnelId: Int, focusRequester: FocusRequester) {
|
||||
modifier = Modifier.width(IntrinsicSize.Min),
|
||||
)
|
||||
}
|
||||
if (configType == ConfigType.AMNEZIA) {
|
||||
if (derivedConfigType.value == ConfigType.AMNEZIA) {
|
||||
ConfigurationTextBox(
|
||||
value = uiState.interfaceProxy.junkPacketCount,
|
||||
onValueChange = viewModel::onJunkPacketCountChanged,
|
||||
@@ -342,8 +347,7 @@ fun ConfigScreen(tunnelId: Int, focusRequester: FocusRequester) {
|
||||
hint = stringResource(R.string.junk_packet_count).lowercase(),
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.focusRequester(focusRequester),
|
||||
.fillMaxWidth(),
|
||||
)
|
||||
ConfigurationTextBox(
|
||||
value = uiState.interfaceProxy.junkPacketMinSize,
|
||||
@@ -356,8 +360,7 @@ fun ConfigScreen(tunnelId: Int, focusRequester: FocusRequester) {
|
||||
).lowercase(),
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.focusRequester(focusRequester),
|
||||
.fillMaxWidth(),
|
||||
)
|
||||
ConfigurationTextBox(
|
||||
value = uiState.interfaceProxy.junkPacketMaxSize,
|
||||
@@ -370,8 +373,7 @@ fun ConfigScreen(tunnelId: Int, focusRequester: FocusRequester) {
|
||||
).lowercase(),
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.focusRequester(focusRequester),
|
||||
.fillMaxWidth(),
|
||||
)
|
||||
ConfigurationTextBox(
|
||||
value = uiState.interfaceProxy.initPacketJunkSize,
|
||||
@@ -381,8 +383,7 @@ fun ConfigScreen(tunnelId: Int, focusRequester: FocusRequester) {
|
||||
hint = stringResource(R.string.init_packet_junk_size).lowercase(),
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.focusRequester(focusRequester),
|
||||
.fillMaxWidth(),
|
||||
)
|
||||
ConfigurationTextBox(
|
||||
value = uiState.interfaceProxy.responsePacketJunkSize,
|
||||
@@ -395,8 +396,7 @@ fun ConfigScreen(tunnelId: Int, focusRequester: FocusRequester) {
|
||||
).lowercase(),
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.focusRequester(focusRequester),
|
||||
.fillMaxWidth(),
|
||||
)
|
||||
ConfigurationTextBox(
|
||||
value = uiState.interfaceProxy.initPacketMagicHeader,
|
||||
@@ -409,8 +409,7 @@ fun ConfigScreen(tunnelId: Int, focusRequester: FocusRequester) {
|
||||
).lowercase(),
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.focusRequester(focusRequester),
|
||||
.fillMaxWidth(),
|
||||
)
|
||||
ConfigurationTextBox(
|
||||
value = uiState.interfaceProxy.responsePacketMagicHeader,
|
||||
@@ -423,8 +422,7 @@ fun ConfigScreen(tunnelId: Int, focusRequester: FocusRequester) {
|
||||
).lowercase(),
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.focusRequester(focusRequester),
|
||||
.fillMaxWidth(),
|
||||
)
|
||||
ConfigurationTextBox(
|
||||
value = uiState.interfaceProxy.underloadPacketMagicHeader,
|
||||
@@ -437,8 +435,7 @@ fun ConfigScreen(tunnelId: Int, focusRequester: FocusRequester) {
|
||||
).lowercase(),
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.focusRequester(focusRequester),
|
||||
.fillMaxWidth(),
|
||||
)
|
||||
ConfigurationTextBox(
|
||||
value = uiState.interfaceProxy.transportPacketMagicHeader,
|
||||
@@ -451,8 +448,7 @@ fun ConfigScreen(tunnelId: Int, focusRequester: FocusRequester) {
|
||||
).lowercase(),
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.focusRequester(focusRequester),
|
||||
.fillMaxWidth(),
|
||||
)
|
||||
}
|
||||
Row(
|
||||
|
||||
+3
@@ -18,6 +18,9 @@ data class ConfigUiState(
|
||||
var tunnelName: String = "",
|
||||
val isAmneziaEnabled: Boolean = false,
|
||||
) {
|
||||
fun hasAmneziaProperties(): Boolean {
|
||||
return this.interfaceProxy.junkPacketCount != ""
|
||||
}
|
||||
companion object {
|
||||
fun from(config: Config): ConfigUiState {
|
||||
val proxyPeers = config.peers.map { PeerProxy.from(it) }
|
||||
|
||||
+6
-4
@@ -6,7 +6,6 @@ import android.content.pm.PackageManager
|
||||
import android.os.Build
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import androidx.navigation.NavHostController
|
||||
import com.wireguard.config.Config
|
||||
import com.wireguard.config.Interface
|
||||
import com.wireguard.config.Peer
|
||||
@@ -17,7 +16,6 @@ import com.zaneschepke.wireguardautotunnel.WireGuardAutoTunnel
|
||||
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
|
||||
import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository
|
||||
import com.zaneschepke.wireguardautotunnel.module.IoDispatcher
|
||||
import com.zaneschepke.wireguardautotunnel.ui.Route
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.snackbar.SnackbarController
|
||||
import com.zaneschepke.wireguardautotunnel.ui.screens.config.model.PeerProxy
|
||||
import com.zaneschepke.wireguardautotunnel.util.Constants
|
||||
@@ -30,8 +28,10 @@ import dagger.assisted.AssistedFactory
|
||||
import dagger.assisted.AssistedInject
|
||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||
import kotlinx.coroutines.CoroutineDispatcher
|
||||
import kotlinx.coroutines.flow.MutableSharedFlow
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.SharingStarted
|
||||
import kotlinx.coroutines.flow.asSharedFlow
|
||||
import kotlinx.coroutines.flow.onStart
|
||||
import kotlinx.coroutines.flow.stateIn
|
||||
import kotlinx.coroutines.flow.update
|
||||
@@ -44,12 +44,14 @@ class ConfigViewModel
|
||||
@AssistedInject
|
||||
constructor(
|
||||
private val appDataRepository: AppDataRepository,
|
||||
private val navController: NavHostController,
|
||||
@Assisted val id: Int,
|
||||
@IoDispatcher private val ioDispatcher: CoroutineDispatcher,
|
||||
) : ViewModel() {
|
||||
private val packageManager = WireGuardAutoTunnel.instance.packageManager
|
||||
|
||||
private val _saved = MutableSharedFlow<Boolean>()
|
||||
val saved = _saved.asSharedFlow()
|
||||
|
||||
private val _uiState = MutableStateFlow(ConfigUiState())
|
||||
val uiState = _uiState.onStart {
|
||||
appDataRepository.tunnels.getById(id)?.let {
|
||||
@@ -335,7 +337,7 @@ constructor(
|
||||
SnackbarController.showMessage(
|
||||
StringValue.StringResource(R.string.config_changes_saved),
|
||||
)
|
||||
navController.navigate(Route.Main)
|
||||
_saved.emit(true)
|
||||
}.onFailure {
|
||||
Timber.e(it)
|
||||
val message = it.message?.substringAfter(":", missingDelimiterValue = "")
|
||||
|
||||
+1
-1
@@ -44,7 +44,7 @@ data class InterfaceProxy(
|
||||
publicKey = i.keyPair.publicKey.toBase64().trim(),
|
||||
privateKey = i.keyPair.privateKey.toBase64().trim(),
|
||||
addresses = i.addresses.joinToString(", ").trim(),
|
||||
dnsServers = i.dnsServers.joinToString(", ").replace("/", "").trim(),
|
||||
dnsServers = (i.dnsServers + i.dnsSearchDomains).joinToString(", ").replace("/", "").trim(),
|
||||
listenPort =
|
||||
if (i.listenPort.isPresent) {
|
||||
i.listenPort.get().toString().trim()
|
||||
|
||||
+117
-379
@@ -1,42 +1,33 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.screens.main
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.net.VpnService
|
||||
import android.provider.Settings
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.ActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.appcompat.app.AppCompatActivity.RESULT_OK
|
||||
import androidx.compose.foundation.ExperimentalFoundationApi
|
||||
import androidx.compose.foundation.focusable
|
||||
import androidx.compose.foundation.gestures.ScrollableDefaults
|
||||
import androidx.compose.foundation.gestures.detectTapGestures
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.lazy.rememberLazyListState
|
||||
import androidx.compose.foundation.overscroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Add
|
||||
import androidx.compose.material.icons.rounded.Bolt
|
||||
import androidx.compose.material.icons.rounded.Circle
|
||||
import androidx.compose.material.icons.rounded.CopyAll
|
||||
import androidx.compose.material.icons.rounded.Delete
|
||||
import androidx.compose.material.icons.rounded.Info
|
||||
import androidx.compose.material.icons.rounded.Settings
|
||||
import androidx.compose.material.icons.rounded.Smartphone
|
||||
import androidx.compose.material.icons.rounded.Star
|
||||
import androidx.compose.material.icons.outlined.Add
|
||||
import androidx.compose.material3.FabPosition
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Switch
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
@@ -44,105 +35,65 @@ import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.ui.geometry.Offset
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.hapticfeedback.HapticFeedbackType
|
||||
import androidx.compose.ui.input.nestedscroll.NestedScrollConnection
|
||||
import androidx.compose.ui.input.nestedscroll.NestedScrollSource
|
||||
import androidx.compose.ui.input.nestedscroll.nestedScroll
|
||||
import androidx.compose.ui.input.pointer.pointerInput
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalHapticFeedback
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.buildAnnotatedString
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.hilt.navigation.compose.hiltViewModel
|
||||
import androidx.navigation.NavController
|
||||
import com.journeyapps.barcodescanner.ScanContract
|
||||
import com.journeyapps.barcodescanner.ScanOptions
|
||||
import com.wireguard.android.backend.GoBackend
|
||||
import com.zaneschepke.wireguardautotunnel.R
|
||||
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
|
||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.HandshakeStatus
|
||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelState
|
||||
import com.zaneschepke.wireguardautotunnel.ui.AppUiState
|
||||
import com.zaneschepke.wireguardautotunnel.ui.Route
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.RowListItem
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.NestedScrollListener
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.dialog.InfoDialog
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.functions.rememberFileImportLauncherForResult
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.navigation.LocalNavController
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.navigation.TopNavBar
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.snackbar.SnackbarController
|
||||
import com.zaneschepke.wireguardautotunnel.ui.screens.main.components.AutoTunnelRowItem
|
||||
import com.zaneschepke.wireguardautotunnel.ui.screens.main.components.GettingStartedLabel
|
||||
import com.zaneschepke.wireguardautotunnel.ui.screens.main.components.ScrollDismissFab
|
||||
import com.zaneschepke.wireguardautotunnel.ui.screens.main.components.TunnelImportSheet
|
||||
import com.zaneschepke.wireguardautotunnel.ui.screens.main.components.TunnelRowItem
|
||||
import com.zaneschepke.wireguardautotunnel.ui.screens.main.components.VpnDeniedDialog
|
||||
import com.zaneschepke.wireguardautotunnel.ui.theme.corn
|
||||
import com.zaneschepke.wireguardautotunnel.ui.theme.mint
|
||||
import com.zaneschepke.wireguardautotunnel.util.Constants
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.handshakeStatus
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.isBatteryOptimizationsDisabled
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.isRunningOnTv
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.mapPeerStats
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.openWebUrl
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.startTunnelBackground
|
||||
import kotlinx.coroutines.delay
|
||||
import timber.log.Timber
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.scaledHeight
|
||||
|
||||
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
|
||||
@OptIn(ExperimentalFoundationApi::class)
|
||||
@Composable
|
||||
fun MainScreen(viewModel: MainViewModel = hiltViewModel(), uiState: AppUiState, focusRequester: FocusRequester, navController: NavController) {
|
||||
val haptic = LocalHapticFeedback.current
|
||||
fun MainScreen(viewModel: MainViewModel = hiltViewModel(), uiState: AppUiState) {
|
||||
val context = LocalContext.current
|
||||
val navController = LocalNavController.current
|
||||
val snackbar = SnackbarController.current
|
||||
|
||||
var showBottomSheet by remember { mutableStateOf(false) }
|
||||
var showVpnPermissionDialog by remember { mutableStateOf(false) }
|
||||
val isVisible = rememberSaveable { mutableStateOf(true) }
|
||||
var isFabVisible by rememberSaveable { mutableStateOf(true) }
|
||||
var showDeleteTunnelAlertDialog by remember { mutableStateOf(false) }
|
||||
var selectedTunnel by remember { mutableStateOf<TunnelConfig?>(null) }
|
||||
val isRunningOnTv = remember { context.isRunningOnTv() }
|
||||
|
||||
val nestedScrollConnection =
|
||||
remember {
|
||||
object : NestedScrollConnection {
|
||||
override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {
|
||||
// Hide FAB
|
||||
if (available.y < -1) {
|
||||
isVisible.value = false
|
||||
}
|
||||
// Show FAB
|
||||
if (available.y > 1) {
|
||||
isVisible.value = true
|
||||
}
|
||||
return Offset.Zero
|
||||
}
|
||||
}
|
||||
}
|
||||
val nestedScrollConnection = remember {
|
||||
NestedScrollListener({ isFabVisible = false }, { isFabVisible = true })
|
||||
}
|
||||
|
||||
val vpnActivityResultState =
|
||||
val vpnActivity =
|
||||
rememberLauncherForActivityResult(
|
||||
ActivityResultContracts.StartActivityForResult(),
|
||||
onResult = {
|
||||
val accepted = (it.resultCode == RESULT_OK)
|
||||
if (accepted) {
|
||||
Timber.d("VPN permission granted")
|
||||
} else {
|
||||
showVpnPermissionDialog = true
|
||||
}
|
||||
if (it.resultCode != RESULT_OK) showVpnPermissionDialog = true
|
||||
},
|
||||
)
|
||||
|
||||
LaunchedEffect(Unit) {
|
||||
if (context.isRunningOnTv()) {
|
||||
delay(Constants.FOCUS_REQUEST_DELAY)
|
||||
kotlin.runCatching {
|
||||
focusRequester.requestFocus()
|
||||
}.onFailure {
|
||||
delay(Constants.FOCUS_REQUEST_DELAY)
|
||||
focusRequester.requestFocus()
|
||||
}
|
||||
val batteryActivity =
|
||||
rememberLauncherForActivityResult(
|
||||
ActivityResultContracts.StartActivityForResult(),
|
||||
) { result: ActivityResult ->
|
||||
viewModel.setBatteryOptimizeDisableShown()
|
||||
}
|
||||
}
|
||||
|
||||
val tunnelFileImportResultLauncher = rememberFileImportLauncherForResult(onNoFileExplorer = {
|
||||
snackbar.showMessage(
|
||||
@@ -152,15 +103,12 @@ fun MainScreen(viewModel: MainViewModel = hiltViewModel(), uiState: AppUiState,
|
||||
viewModel.onTunnelFileSelected(data, context)
|
||||
})
|
||||
|
||||
val scanLauncher =
|
||||
rememberLauncherForActivityResult(
|
||||
contract = ScanContract(),
|
||||
onResult = {
|
||||
if (it.contents != null) {
|
||||
viewModel.onTunnelQrResult(it.contents)
|
||||
}
|
||||
},
|
||||
)
|
||||
val requestPermissionLauncher = rememberLauncherForActivityResult(
|
||||
ActivityResultContracts.RequestPermission(),
|
||||
) { isGranted ->
|
||||
if (!isGranted) return@rememberLauncherForActivityResult snackbar.showMessage("Camera permission required")
|
||||
navController.navigate(Route.Scanner)
|
||||
}
|
||||
|
||||
VpnDeniedDialog(showVpnPermissionDialog, onDismiss = { showVpnPermissionDialog = false })
|
||||
|
||||
@@ -168,7 +116,7 @@ fun MainScreen(viewModel: MainViewModel = hiltViewModel(), uiState: AppUiState,
|
||||
InfoDialog(
|
||||
onDismiss = { showDeleteTunnelAlertDialog = false },
|
||||
onAttest = {
|
||||
selectedTunnel?.let { viewModel.onDelete(it, context) }
|
||||
selectedTunnel?.let { viewModel::onDelete }
|
||||
showDeleteTunnelAlertDialog = false
|
||||
selectedTunnel = null
|
||||
},
|
||||
@@ -178,61 +126,87 @@ fun MainScreen(viewModel: MainViewModel = hiltViewModel(), uiState: AppUiState,
|
||||
)
|
||||
}
|
||||
|
||||
fun onTunnelToggle(checked: Boolean, tunnel: TunnelConfig) {
|
||||
if (checked) {
|
||||
if (uiState.settings.isKernelEnabled) {
|
||||
context.startTunnelBackground(tunnel.id)
|
||||
} else {
|
||||
viewModel.onTunnelStart(tunnel)
|
||||
fun requestBatteryOptimizationsDisabled() {
|
||||
val intent =
|
||||
Intent().apply {
|
||||
action = Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS
|
||||
data = Uri.parse("package:${context.packageName}")
|
||||
}
|
||||
} else {
|
||||
viewModel.onTunnelStop(
|
||||
tunnel,
|
||||
)
|
||||
}
|
||||
batteryActivity.launch(intent)
|
||||
}
|
||||
|
||||
fun launchQrScanner() {
|
||||
val scanOptions = ScanOptions()
|
||||
scanOptions.setDesiredBarcodeFormats(ScanOptions.QR_CODE)
|
||||
scanOptions.setOrientationLocked(true)
|
||||
scanOptions.setPrompt(
|
||||
context.getString(R.string.scanning_qr),
|
||||
)
|
||||
scanOptions.setBeepEnabled(false)
|
||||
scanLauncher.launch(scanOptions)
|
||||
fun onAutoTunnelToggle() {
|
||||
if (!uiState.generalState.isBatteryOptimizationDisableShown &&
|
||||
!context.isBatteryOptimizationsDisabled() && !isRunningOnTv
|
||||
) {
|
||||
return requestBatteryOptimizationsDisabled()
|
||||
}
|
||||
val intent = if (!uiState.settings.isKernelEnabled) {
|
||||
VpnService.prepare(context)
|
||||
} else {
|
||||
null
|
||||
}
|
||||
if (intent != null) return vpnActivity.launch(intent)
|
||||
viewModel.onToggleAutoTunnel()
|
||||
}
|
||||
|
||||
fun onTunnelToggle(checked: Boolean, tunnel: TunnelConfig) {
|
||||
val intent = if (uiState.settings.isKernelEnabled) null else VpnService.prepare(context)
|
||||
if (intent != null) return vpnActivity.launch(intent)
|
||||
if (!checked) viewModel.onTunnelStop(tunnel).also { return }
|
||||
viewModel.onTunnelStart(tunnel, uiState.settings.isKernelEnabled)
|
||||
}
|
||||
|
||||
Scaffold(
|
||||
modifier =
|
||||
Modifier.pointerInput(Unit) {
|
||||
if (uiState.tunnels.isNotEmpty()) {
|
||||
detectTapGestures(
|
||||
onTap = {
|
||||
selectedTunnel = null
|
||||
},
|
||||
)
|
||||
}
|
||||
if (uiState.tunnels.isEmpty()) return@pointerInput
|
||||
detectTapGestures(
|
||||
onTap = {
|
||||
selectedTunnel = null
|
||||
},
|
||||
)
|
||||
},
|
||||
floatingActionButtonPosition = FabPosition.End,
|
||||
floatingActionButton = {
|
||||
ScrollDismissFab(icon = {
|
||||
val icon = Icons.Filled.Add
|
||||
Icon(
|
||||
imageVector = icon,
|
||||
contentDescription = icon.name,
|
||||
tint = MaterialTheme.colorScheme.onPrimary,
|
||||
if (!isRunningOnTv) {
|
||||
ScrollDismissFab({
|
||||
val icon = Icons.Filled.Add
|
||||
Icon(
|
||||
imageVector = icon,
|
||||
contentDescription = icon.name,
|
||||
tint = MaterialTheme.colorScheme.onPrimary,
|
||||
)
|
||||
}, isVisible = isFabVisible, onClick = {
|
||||
showBottomSheet = true
|
||||
})
|
||||
}
|
||||
},
|
||||
topBar = {
|
||||
if (isRunningOnTv) {
|
||||
TopNavBar(
|
||||
showBack = false,
|
||||
title = stringResource(R.string.app_name),
|
||||
trailing = {
|
||||
IconButton(onClick = {
|
||||
showBottomSheet = true
|
||||
}) {
|
||||
val icon = Icons.Outlined.Add
|
||||
Icon(
|
||||
imageVector = icon,
|
||||
contentDescription = icon.name,
|
||||
)
|
||||
}
|
||||
},
|
||||
)
|
||||
}, focusRequester, isVisible = isVisible.value, onClick = {
|
||||
showBottomSheet = true
|
||||
})
|
||||
}
|
||||
},
|
||||
) {
|
||||
TunnelImportSheet(
|
||||
showBottomSheet,
|
||||
onDismiss = { showBottomSheet = false },
|
||||
onFileClick = { tunnelFileImportResultLauncher.launch(Constants.ALLOWED_FILE_TYPES) },
|
||||
onQrClick = { launchQrScanner() },
|
||||
onFileClick = { tunnelFileImportResultLauncher.launch(Constants.ALLOWED_TV_FILE_TYPES) },
|
||||
onQrClick = { requestPermissionLauncher.launch(android.Manifest.permission.CAMERA) },
|
||||
onManualImportClick = {
|
||||
navController.navigate(
|
||||
Route.Config(Constants.MANUAL_TUNNEL_CONFIG_ID),
|
||||
@@ -241,10 +215,10 @@ fun MainScreen(viewModel: MainViewModel = hiltViewModel(), uiState: AppUiState,
|
||||
)
|
||||
LazyColumn(
|
||||
horizontalAlignment = Alignment.Start,
|
||||
verticalArrangement = Arrangement.Top,
|
||||
verticalArrangement = Arrangement.spacedBy(5.dp.scaledHeight(), Alignment.Top),
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.fillMaxSize().padding(it)
|
||||
.overscroll(ScrollableDefaults.overscrollEffect())
|
||||
.nestedScroll(nestedScrollConnection),
|
||||
state = rememberLazyListState(0, uiState.tunnels.count()),
|
||||
@@ -256,70 +230,11 @@ fun MainScreen(viewModel: MainViewModel = hiltViewModel(), uiState: AppUiState,
|
||||
item {
|
||||
GettingStartedLabel(onClick = { context.openWebUrl(it) })
|
||||
}
|
||||
}
|
||||
item {
|
||||
if (uiState.settings.isAutoTunnelEnabled) {
|
||||
val itemFocusRequester = remember { FocusRequester() }
|
||||
val autoTunnelingLabel =
|
||||
buildAnnotatedString {
|
||||
append(stringResource(id = R.string.auto_tunneling))
|
||||
append(": ")
|
||||
if (uiState.settings.isAutoTunnelPaused) {
|
||||
append(
|
||||
stringResource(id = R.string.paused),
|
||||
)
|
||||
} else {
|
||||
append(
|
||||
stringResource(id = R.string.active),
|
||||
)
|
||||
}
|
||||
}
|
||||
RowListItem(
|
||||
icon = {
|
||||
val icon = Icons.Rounded.Bolt
|
||||
Icon(
|
||||
icon,
|
||||
icon.name,
|
||||
modifier =
|
||||
Modifier
|
||||
.padding(end = 8.5.dp)
|
||||
.size(25.dp),
|
||||
tint =
|
||||
if (uiState.settings.isAutoTunnelPaused) {
|
||||
Color.Gray
|
||||
} else {
|
||||
mint
|
||||
},
|
||||
)
|
||||
},
|
||||
text = autoTunnelingLabel.text,
|
||||
rowButton = {
|
||||
if (uiState.settings.isAutoTunnelPaused) {
|
||||
TextButton(
|
||||
modifier = Modifier.focusRequester(itemFocusRequester),
|
||||
onClick = { viewModel.resumeAutoTunneling() },
|
||||
) {
|
||||
Text(stringResource(id = R.string.resume))
|
||||
}
|
||||
} else {
|
||||
TextButton(
|
||||
modifier = Modifier.focusRequester(itemFocusRequester),
|
||||
onClick = { viewModel.pauseAutoTunneling() },
|
||||
) {
|
||||
Text(stringResource(id = R.string.pause))
|
||||
}
|
||||
}
|
||||
},
|
||||
onClick = {
|
||||
if (context.isRunningOnTv()) {
|
||||
itemFocusRequester.requestFocus()
|
||||
}
|
||||
},
|
||||
onHold = {},
|
||||
expanded = false,
|
||||
statistics = null,
|
||||
focusRequester = focusRequester,
|
||||
)
|
||||
} else {
|
||||
item {
|
||||
AutoTunnelRowItem(uiState, {
|
||||
onAutoTunnelToggle()
|
||||
})
|
||||
}
|
||||
}
|
||||
items(
|
||||
@@ -330,195 +245,18 @@ fun MainScreen(viewModel: MainViewModel = hiltViewModel(), uiState: AppUiState,
|
||||
it.id == tunnel.id &&
|
||||
it.isActive
|
||||
}
|
||||
val leadingIconColor =
|
||||
(
|
||||
if (
|
||||
isActive && uiState.vpnState.statistics != null
|
||||
) {
|
||||
uiState.vpnState.statistics.mapPeerStats()
|
||||
.map { it.value?.handshakeStatus() }
|
||||
.let { statuses ->
|
||||
when {
|
||||
statuses.all { it == HandshakeStatus.HEALTHY } -> mint
|
||||
statuses.any { it == HandshakeStatus.STALE } -> corn
|
||||
statuses.all { it == HandshakeStatus.NOT_STARTED } ->
|
||||
Color.Gray
|
||||
|
||||
else -> {
|
||||
Color.Gray
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
Color.Gray
|
||||
}
|
||||
)
|
||||
val itemFocusRequester = remember { FocusRequester() }
|
||||
val expanded = remember { mutableStateOf(false) }
|
||||
RowListItem(
|
||||
icon = {
|
||||
val circleIcon = Icons.Rounded.Circle
|
||||
val icon =
|
||||
if (tunnel.isPrimaryTunnel) {
|
||||
Icons.Rounded.Star
|
||||
} else if (tunnel.isMobileDataTunnel) {
|
||||
Icons.Rounded.Smartphone
|
||||
} else {
|
||||
circleIcon
|
||||
}
|
||||
Icon(
|
||||
icon,
|
||||
icon.name,
|
||||
tint = leadingIconColor,
|
||||
modifier =
|
||||
Modifier
|
||||
.padding(
|
||||
end = if (icon == circleIcon) 12.5.dp else 10.dp,
|
||||
start = if (icon == circleIcon) 2.5.dp else 0.dp,
|
||||
)
|
||||
.size(if (icon == circleIcon) 15.dp else 20.dp),
|
||||
)
|
||||
},
|
||||
text = tunnel.name,
|
||||
onHold = {
|
||||
haptic.performHapticFeedback(HapticFeedbackType.LongPress)
|
||||
selectedTunnel = tunnel
|
||||
},
|
||||
onClick = {
|
||||
if (!context.isRunningOnTv()) {
|
||||
if (
|
||||
isActive
|
||||
) {
|
||||
expanded.value = !expanded.value
|
||||
}
|
||||
} else {
|
||||
selectedTunnel = tunnel
|
||||
itemFocusRequester.requestFocus()
|
||||
}
|
||||
},
|
||||
statistics = uiState.vpnState.statistics,
|
||||
expanded = expanded.value,
|
||||
focusRequester = focusRequester,
|
||||
rowButton = {
|
||||
if (
|
||||
tunnel.id == selectedTunnel?.id &&
|
||||
!context.isRunningOnTv()
|
||||
) {
|
||||
Row {
|
||||
IconButton(
|
||||
onClick = {
|
||||
selectedTunnel?.let {
|
||||
navController.navigate(
|
||||
Route.Option(it.id),
|
||||
)
|
||||
}
|
||||
},
|
||||
) {
|
||||
val icon = Icons.Rounded.Settings
|
||||
Icon(
|
||||
icon,
|
||||
icon.name,
|
||||
)
|
||||
}
|
||||
IconButton(
|
||||
modifier = Modifier.focusable(),
|
||||
onClick = { viewModel.onCopyTunnel(selectedTunnel) },
|
||||
) {
|
||||
val icon = Icons.Rounded.CopyAll
|
||||
Icon(icon, icon.name)
|
||||
}
|
||||
IconButton(
|
||||
enabled = !isActive,
|
||||
modifier = Modifier.focusable(),
|
||||
onClick = { showDeleteTunnelAlertDialog = true },
|
||||
) {
|
||||
val icon = Icons.Rounded.Delete
|
||||
Icon(icon, icon.name)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (!isActive) expanded.value = false
|
||||
@Composable
|
||||
fun TunnelSwitch() = Switch(
|
||||
modifier = Modifier.focusRequester(itemFocusRequester),
|
||||
checked = isActive,
|
||||
onCheckedChange = { checked ->
|
||||
if (!checked) expanded.value = false
|
||||
val intent = if (uiState.settings.isKernelEnabled) null else GoBackend.VpnService.prepare(context)
|
||||
if (intent != null) return@Switch vpnActivityResultState.launch(intent)
|
||||
onTunnelToggle(checked, tunnel)
|
||||
},
|
||||
)
|
||||
if (context.isRunningOnTv()) {
|
||||
Row {
|
||||
IconButton(
|
||||
onClick = {
|
||||
selectedTunnel = tunnel
|
||||
selectedTunnel?.let {
|
||||
navController.navigate(
|
||||
Route.Option(it.id),
|
||||
)
|
||||
}
|
||||
},
|
||||
) {
|
||||
val icon = Icons.Rounded.Settings
|
||||
Icon(
|
||||
icon,
|
||||
icon.name,
|
||||
)
|
||||
}
|
||||
IconButton(
|
||||
modifier = Modifier.focusRequester(focusRequester),
|
||||
onClick = {
|
||||
if (
|
||||
uiState.vpnState.status == TunnelState.UP &&
|
||||
(uiState.vpnState.tunnelConfig?.name == tunnel.name)
|
||||
) {
|
||||
expanded.value = !expanded.value
|
||||
} else {
|
||||
snackbar.showMessage(
|
||||
context.getString(R.string.turn_on_tunnel),
|
||||
)
|
||||
}
|
||||
},
|
||||
) {
|
||||
val icon = Icons.Rounded.Info
|
||||
Icon(icon, icon.name)
|
||||
}
|
||||
IconButton(
|
||||
onClick = { viewModel.onCopyTunnel(tunnel) },
|
||||
) {
|
||||
val icon = Icons.Rounded.CopyAll
|
||||
Icon(icon, icon.name)
|
||||
}
|
||||
IconButton(
|
||||
onClick = {
|
||||
if (
|
||||
uiState.vpnState.status == TunnelState.UP &&
|
||||
tunnel.name == uiState.vpnState.tunnelConfig?.name
|
||||
) {
|
||||
snackbar.showMessage(
|
||||
context.getString(R.string.turn_off_tunnel),
|
||||
)
|
||||
} else {
|
||||
selectedTunnel = tunnel
|
||||
showDeleteTunnelAlertDialog = true
|
||||
}
|
||||
},
|
||||
) {
|
||||
val icon = Icons.Rounded.Delete
|
||||
Icon(
|
||||
icon,
|
||||
icon.name,
|
||||
)
|
||||
}
|
||||
TunnelSwitch()
|
||||
}
|
||||
} else {
|
||||
TunnelSwitch()
|
||||
}
|
||||
}
|
||||
},
|
||||
val expanded = uiState.generalState.isTunnelStatsExpanded
|
||||
TunnelRowItem(
|
||||
isActive,
|
||||
expanded,
|
||||
selectedTunnel?.id == tunnel.id,
|
||||
tunnel,
|
||||
vpnState = uiState.vpnState,
|
||||
{ selectedTunnel = tunnel },
|
||||
{ viewModel.onExpandedChanged(!expanded) },
|
||||
onDelete = { showDeleteTunnelAlertDialog = true },
|
||||
onCopy = { viewModel.onCopyTunnel(tunnel) },
|
||||
onSwitchClick = { onTunnelToggle(it, tunnel) },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
+49
-49
@@ -19,6 +19,8 @@ import com.zaneschepke.wireguardautotunnel.util.FileReadException
|
||||
import com.zaneschepke.wireguardautotunnel.util.InvalidFileExtensionException
|
||||
import com.zaneschepke.wireguardautotunnel.util.NumberUtils
|
||||
import com.zaneschepke.wireguardautotunnel.util.StringValue
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.extractNameAndNumber
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.hasNumberInParentheses
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.toWgQuickString
|
||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||
import kotlinx.coroutines.CoroutineDispatcher
|
||||
@@ -28,26 +30,24 @@ import timber.log.Timber
|
||||
import java.io.InputStream
|
||||
import java.util.zip.ZipInputStream
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Provider
|
||||
|
||||
@HiltViewModel
|
||||
class MainViewModel
|
||||
@Inject
|
||||
constructor(
|
||||
private val appDataRepository: AppDataRepository,
|
||||
val tunnelService: TunnelService,
|
||||
private val tunnelService: Provider<TunnelService>,
|
||||
@IoDispatcher private val ioDispatcher: CoroutineDispatcher,
|
||||
private val serviceManager: ServiceManager,
|
||||
) : ViewModel() {
|
||||
|
||||
private fun stopWatcherService(context: Context) {
|
||||
ServiceManager.stopWatcherService(context)
|
||||
}
|
||||
|
||||
fun onDelete(tunnel: TunnelConfig, context: Context) {
|
||||
fun onDelete(tunnel: TunnelConfig) {
|
||||
viewModelScope.launch {
|
||||
val settings = appDataRepository.settings.getSettings()
|
||||
val isPrimary = tunnel.isPrimaryTunnel
|
||||
if (appDataRepository.tunnels.count() == 1 || isPrimary) {
|
||||
stopWatcherService(context)
|
||||
serviceManager.stopAutoTunnel()
|
||||
resetTunnelSetting(settings)
|
||||
}
|
||||
appDataRepository.tunnels.delete(tunnel)
|
||||
@@ -63,14 +63,18 @@ constructor(
|
||||
)
|
||||
}
|
||||
|
||||
fun onTunnelStart(tunnelConfig: TunnelConfig) = viewModelScope.launch {
|
||||
fun onExpandedChanged(expanded: Boolean) = viewModelScope.launch {
|
||||
appDataRepository.appState.setTunnelStatsExpanded(expanded)
|
||||
}
|
||||
|
||||
fun onTunnelStart(tunnelConfig: TunnelConfig, background: Boolean) = viewModelScope.launch {
|
||||
Timber.i("Starting tunnel ${tunnelConfig.name}")
|
||||
tunnelService.startTunnel(tunnelConfig)
|
||||
tunnelService.get().startTunnel(tunnelConfig, background)
|
||||
}
|
||||
|
||||
fun onTunnelStop(tunnel: TunnelConfig) = viewModelScope.launch {
|
||||
Timber.i("Stopping active tunnel")
|
||||
tunnelService.stopTunnel(tunnel)
|
||||
tunnelService.get().stopTunnel(tunnel)
|
||||
}
|
||||
|
||||
private fun generateQrCodeDefaultName(config: String): String {
|
||||
@@ -96,28 +100,18 @@ constructor(
|
||||
return defaultName
|
||||
}
|
||||
|
||||
fun onTunnelQrResult(result: String) = viewModelScope.launch(ioDispatcher) {
|
||||
kotlin.runCatching {
|
||||
val amConfig = TunnelConfig.configFromAmQuick(result)
|
||||
val amQuick = amConfig.toAwgQuickString(true)
|
||||
val wgQuick = amConfig.toWgQuickString()
|
||||
|
||||
val tunnelName = makeTunnelNameUnique(generateQrCodeTunnelName(result))
|
||||
val tunnelConfig = TunnelConfig(name = tunnelName, wgQuick = wgQuick, amQuick = amQuick)
|
||||
saveTunnel(tunnelConfig)
|
||||
}.onFailure {
|
||||
Timber.e(it)
|
||||
SnackbarController.showMessage(StringValue.StringResource(R.string.error_invalid_code))
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun makeTunnelNameUnique(name: String): String {
|
||||
return withContext(ioDispatcher) {
|
||||
val tunnels = appDataRepository.tunnels.getAll()
|
||||
var tunnelName = name
|
||||
var num = 1
|
||||
while (tunnels.any { it.name == tunnelName }) {
|
||||
tunnelName = "$name($num)"
|
||||
tunnelName = if (!tunnelName.hasNumberInParentheses()) {
|
||||
"$name($num)"
|
||||
} else {
|
||||
val pair = tunnelName.extractNameAndNumber()
|
||||
"${pair?.first}($num)"
|
||||
}
|
||||
num++
|
||||
}
|
||||
tunnelName
|
||||
@@ -164,6 +158,21 @@ constructor(
|
||||
}
|
||||
}
|
||||
|
||||
fun onToggleAutoTunnel() = viewModelScope.launch {
|
||||
val settings = appDataRepository.settings.getSettings()
|
||||
val toggled = !settings.isAutoTunnelEnabled
|
||||
if (toggled) {
|
||||
serviceManager.startAutoTunnel(false)
|
||||
} else {
|
||||
serviceManager.stopAutoTunnel()
|
||||
}
|
||||
appDataRepository.settings.save(
|
||||
settings.copy(
|
||||
isAutoTunnelEnabled = toggled,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
private suspend fun saveTunnelsFromZipUri(uri: Uri, context: Context) {
|
||||
ZipInputStream(getInputStreamFromUri(uri, context)).use { zip ->
|
||||
generateSequence { zip.nextEntry }
|
||||
@@ -185,25 +194,15 @@ constructor(
|
||||
}
|
||||
}
|
||||
|
||||
fun setBatteryOptimizeDisableShown() = viewModelScope.launch {
|
||||
appDataRepository.appState.setBatteryOptimizationDisableShown(true)
|
||||
}
|
||||
|
||||
private suspend fun saveTunnelFromConfUri(name: String, uri: Uri, context: Context) {
|
||||
val stream = getInputStreamFromUri(uri, context) ?: throw FileReadException
|
||||
saveTunnelConfigFromStream(stream, name)
|
||||
}
|
||||
|
||||
fun pauseAutoTunneling() = viewModelScope.launch {
|
||||
val settings = appDataRepository.settings.getSettings()
|
||||
appDataRepository.settings.save(
|
||||
settings.copy(isAutoTunnelPaused = true),
|
||||
)
|
||||
}
|
||||
|
||||
fun resumeAutoTunneling() = viewModelScope.launch {
|
||||
val settings = appDataRepository.settings.getSettings()
|
||||
appDataRepository.settings.save(
|
||||
settings.copy(isAutoTunnelPaused = false),
|
||||
)
|
||||
}
|
||||
|
||||
private fun saveTunnel(tunnelConfig: TunnelConfig) = viewModelScope.launch {
|
||||
appDataRepository.tunnels.save(tunnelConfig)
|
||||
}
|
||||
@@ -251,14 +250,15 @@ constructor(
|
||||
|
||||
private fun saveSettings(settings: Settings) = viewModelScope.launch { appDataRepository.settings.save(settings) }
|
||||
|
||||
fun onCopyTunnel(tunnel: TunnelConfig?) = viewModelScope.launch {
|
||||
tunnel?.let {
|
||||
saveTunnel(
|
||||
TunnelConfig(
|
||||
name = it.name.plus(NumberUtils.randomThree()),
|
||||
wgQuick = it.wgQuick,
|
||||
),
|
||||
)
|
||||
}
|
||||
fun onCopyTunnel(tunnel: TunnelConfig) = viewModelScope.launch {
|
||||
saveTunnel(
|
||||
tunnel.copy(
|
||||
id = 0,
|
||||
isPrimaryTunnel = false,
|
||||
isMobileDataTunnel = false,
|
||||
isActive = false,
|
||||
name = makeTunnelNameUnique(tunnel.name),
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.screens.main.components
|
||||
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.rounded.Bolt
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.scale
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.zaneschepke.wireguardautotunnel.R
|
||||
import com.zaneschepke.wireguardautotunnel.ui.AppUiState
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.ExpandingRowListItem
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.button.ScaledSwitch
|
||||
import com.zaneschepke.wireguardautotunnel.ui.theme.SilverTree
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.isRunningOnTv
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.scaledHeight
|
||||
|
||||
@Composable
|
||||
fun AutoTunnelRowItem(appUiState: AppUiState, onToggle: () -> Unit) {
|
||||
val context = LocalContext.current
|
||||
val itemFocusRequester = remember { FocusRequester() }
|
||||
ExpandingRowListItem(
|
||||
leading = {
|
||||
val icon = Icons.Rounded.Bolt
|
||||
Icon(
|
||||
icon,
|
||||
icon.name,
|
||||
modifier =
|
||||
Modifier
|
||||
.size(16.dp.scaledHeight()).scale(1.5f),
|
||||
tint =
|
||||
if (!appUiState.autoTunnelActive) {
|
||||
Color.Gray
|
||||
} else {
|
||||
SilverTree
|
||||
},
|
||||
)
|
||||
},
|
||||
text = stringResource(R.string.auto_tunneling),
|
||||
trailing = {
|
||||
ScaledSwitch(
|
||||
appUiState.settings.isAutoTunnelEnabled,
|
||||
onClick = {
|
||||
onToggle()
|
||||
},
|
||||
)
|
||||
},
|
||||
onClick = {
|
||||
if (context.isRunningOnTv()) {
|
||||
itemFocusRequester.requestFocus()
|
||||
}
|
||||
},
|
||||
isExpanded = false,
|
||||
)
|
||||
}
|
||||
+1
-4
@@ -9,19 +9,16 @@ import androidx.compose.material3.FloatingActionButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.ui.unit.dp
|
||||
|
||||
@Composable
|
||||
fun ScrollDismissFab(icon: @Composable () -> Unit, focusRequester: FocusRequester, isVisible: Boolean, onClick: () -> Unit) {
|
||||
fun ScrollDismissFab(icon: @Composable () -> Unit, isVisible: Boolean, onClick: () -> Unit) {
|
||||
AnimatedVisibility(
|
||||
visible = isVisible,
|
||||
enter = slideInVertically(initialOffsetY = { it * 2 }),
|
||||
exit = slideOutVertically(targetOffsetY = { it * 2 }),
|
||||
modifier =
|
||||
Modifier
|
||||
.focusRequester(focusRequester)
|
||||
.focusGroup(),
|
||||
) {
|
||||
FloatingActionButton(
|
||||
|
||||
+198
@@ -0,0 +1,198 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.screens.main.components
|
||||
|
||||
import androidx.compose.foundation.focusable
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.rounded.Circle
|
||||
import androidx.compose.material.icons.rounded.CopyAll
|
||||
import androidx.compose.material.icons.rounded.Delete
|
||||
import androidx.compose.material.icons.rounded.Info
|
||||
import androidx.compose.material.icons.rounded.Settings
|
||||
import androidx.compose.material.icons.rounded.Smartphone
|
||||
import androidx.compose.material.icons.rounded.Star
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.hapticfeedback.HapticFeedbackType
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalHapticFeedback
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.zaneschepke.wireguardautotunnel.R
|
||||
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
|
||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.VpnState
|
||||
import com.zaneschepke.wireguardautotunnel.ui.Route
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.ExpandingRowListItem
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.button.ScaledSwitch
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.navigation.LocalNavController
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.snackbar.SnackbarController
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.asColor
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.isRunningOnTv
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.scaledHeight
|
||||
|
||||
@Composable
|
||||
fun TunnelRowItem(
|
||||
isActive: Boolean,
|
||||
expanded: Boolean,
|
||||
isSelected: Boolean,
|
||||
tunnel: TunnelConfig,
|
||||
vpnState: VpnState,
|
||||
onHold: () -> Unit,
|
||||
onClick: () -> Unit,
|
||||
onCopy: () -> Unit,
|
||||
onDelete: () -> Unit,
|
||||
onSwitchClick: (checked: Boolean) -> Unit,
|
||||
) {
|
||||
val leadingIconColor = if (!isActive) Color.Gray else vpnState.statistics.asColor()
|
||||
val context = LocalContext.current
|
||||
val snackbar = SnackbarController.current
|
||||
val navController = LocalNavController.current
|
||||
val haptic = LocalHapticFeedback.current
|
||||
val itemFocusRequester = remember { FocusRequester() }
|
||||
ExpandingRowListItem(
|
||||
leading = {
|
||||
val circleIcon = Icons.Rounded.Circle
|
||||
val icon =
|
||||
if (tunnel.isPrimaryTunnel) {
|
||||
Icons.Rounded.Star
|
||||
} else if (tunnel.isMobileDataTunnel) {
|
||||
Icons.Rounded.Smartphone
|
||||
} else {
|
||||
circleIcon
|
||||
}
|
||||
Icon(
|
||||
icon,
|
||||
icon.name,
|
||||
tint = leadingIconColor,
|
||||
modifier = Modifier.size(16.dp.scaledHeight()),
|
||||
)
|
||||
},
|
||||
text = tunnel.name,
|
||||
onHold = {
|
||||
haptic.performHapticFeedback(HapticFeedbackType.LongPress)
|
||||
onHold()
|
||||
},
|
||||
onClick = {
|
||||
if (!context.isRunningOnTv()) {
|
||||
if (isActive) {
|
||||
onClick()
|
||||
}
|
||||
} else {
|
||||
onHold()
|
||||
itemFocusRequester.requestFocus()
|
||||
}
|
||||
},
|
||||
isExpanded = expanded && isActive,
|
||||
expanded = { if (isActive && expanded) TunnelStatisticsRow(vpnState.statistics, tunnel) },
|
||||
trailing = {
|
||||
if (
|
||||
isSelected &&
|
||||
!context.isRunningOnTv()
|
||||
) {
|
||||
Row {
|
||||
IconButton(
|
||||
onClick = {
|
||||
navController.navigate(
|
||||
Route.Option(tunnel.id),
|
||||
)
|
||||
},
|
||||
) {
|
||||
val icon = Icons.Rounded.Settings
|
||||
Icon(
|
||||
icon,
|
||||
icon.name,
|
||||
)
|
||||
}
|
||||
IconButton(
|
||||
modifier = Modifier.focusable(),
|
||||
onClick = { onCopy() },
|
||||
) {
|
||||
val icon = Icons.Rounded.CopyAll
|
||||
Icon(icon, icon.name)
|
||||
}
|
||||
IconButton(
|
||||
enabled = !isActive,
|
||||
modifier = Modifier.focusable(),
|
||||
onClick = { onDelete() },
|
||||
) {
|
||||
val icon = Icons.Rounded.Delete
|
||||
Icon(icon, icon.name)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (context.isRunningOnTv()) {
|
||||
Row {
|
||||
IconButton(
|
||||
onClick = {
|
||||
onHold()
|
||||
navController.navigate(
|
||||
Route.Option(tunnel.id),
|
||||
)
|
||||
},
|
||||
) {
|
||||
val icon = Icons.Rounded.Settings
|
||||
Icon(
|
||||
icon,
|
||||
icon.name,
|
||||
)
|
||||
}
|
||||
IconButton(
|
||||
onClick = {
|
||||
if (isActive) {
|
||||
onClick()
|
||||
} else {
|
||||
snackbar.showMessage(
|
||||
context.getString(R.string.turn_on_tunnel),
|
||||
)
|
||||
}
|
||||
},
|
||||
) {
|
||||
val icon = Icons.Rounded.Info
|
||||
Icon(icon, icon.name)
|
||||
}
|
||||
IconButton(
|
||||
onClick = { onCopy() },
|
||||
) {
|
||||
val icon = Icons.Rounded.CopyAll
|
||||
Icon(icon, icon.name)
|
||||
}
|
||||
IconButton(
|
||||
onClick = {
|
||||
if (isActive) {
|
||||
snackbar.showMessage(
|
||||
context.getString(R.string.turn_off_tunnel),
|
||||
)
|
||||
} else {
|
||||
onHold()
|
||||
onDelete()
|
||||
}
|
||||
},
|
||||
) {
|
||||
val icon = Icons.Rounded.Delete
|
||||
Icon(
|
||||
icon,
|
||||
icon.name,
|
||||
)
|
||||
}
|
||||
ScaledSwitch(
|
||||
modifier = Modifier.focusRequester(itemFocusRequester),
|
||||
checked = isActive,
|
||||
onClick = onSwitchClick,
|
||||
)
|
||||
}
|
||||
} else {
|
||||
ScaledSwitch(
|
||||
modifier = Modifier.focusRequester(itemFocusRequester),
|
||||
checked = isActive,
|
||||
onClick = onSwitchClick,
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.screens.main.components
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.zaneschepke.wireguardautotunnel.R
|
||||
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
|
||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.statistics.TunnelStatistics
|
||||
import com.zaneschepke.wireguardautotunnel.util.NumberUtils
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.toThreeDecimalPlaceString
|
||||
|
||||
@Composable
|
||||
fun TunnelStatisticsRow(statistics: TunnelStatistics?, tunnelConfig: TunnelConfig) {
|
||||
val config = TunnelConfig.configFromAmQuick(tunnelConfig.wgQuick)
|
||||
|
||||
Row(
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(end = 10.dp, bottom = 10.dp, start = 45.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(30.dp, Alignment.Start),
|
||||
) {
|
||||
config.peers.forEach {
|
||||
val peerId = it.publicKey.toBase64().subSequence(0, 3).toString() + "***"
|
||||
val peerRx = statistics?.peerStats(it.publicKey)?.rxBytes ?: 0
|
||||
val peerTx = statistics?.peerStats(it.publicKey)?.txBytes ?: 0
|
||||
val peerTxMB = NumberUtils.bytesToMB(peerTx).toThreeDecimalPlaceString()
|
||||
val peerRxMB = NumberUtils.bytesToMB(peerRx).toThreeDecimalPlaceString()
|
||||
val handshake = statistics?.peerStats(it.publicKey)?.latestHandshakeEpochMillis?.let {
|
||||
if (it == 0L) {
|
||||
stringResource(R.string.never)
|
||||
} else {
|
||||
"${NumberUtils.getSecondsBetweenTimestampAndNow(it)} ${stringResource(R.string.sec)}"
|
||||
}
|
||||
} ?: stringResource(R.string.never)
|
||||
Column(
|
||||
verticalArrangement = Arrangement.spacedBy(10.dp),
|
||||
) {
|
||||
Text(
|
||||
stringResource(R.string.peer).lowercase() + ": $peerId",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.outline,
|
||||
)
|
||||
Text("tx: $peerTxMB MB", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.outline)
|
||||
}
|
||||
Column(
|
||||
verticalArrangement = Arrangement.spacedBy(10.dp),
|
||||
) {
|
||||
Text(stringResource(R.string.handshake) + ": $handshake", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.outline)
|
||||
Text("rx: $peerRxMB MB", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.outline)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+143
-284
@@ -1,32 +1,23 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.screens.options
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.ExperimentalLayoutApi
|
||||
import androidx.compose.foundation.layout.FlowRow
|
||||
import androidx.compose.foundation.layout.IntrinsicSize
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.text.KeyboardActions
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.filled.Edit
|
||||
import androidx.compose.material.icons.outlined.Add
|
||||
import androidx.compose.material.icons.outlined.Edit
|
||||
import androidx.compose.material.icons.outlined.NetworkPing
|
||||
import androidx.compose.material.icons.outlined.PhoneAndroid
|
||||
import androidx.compose.material.icons.outlined.Security
|
||||
import androidx.compose.material.icons.outlined.Star
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
@@ -36,303 +27,171 @@ import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalFocusManager
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontStyle
|
||||
import androidx.compose.ui.text.input.ImeAction
|
||||
import androidx.compose.ui.text.input.KeyboardCapitalization
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.hilt.navigation.compose.hiltViewModel
|
||||
import androidx.navigation.NavController
|
||||
import com.zaneschepke.wireguardautotunnel.R
|
||||
import com.zaneschepke.wireguardautotunnel.ui.AppUiState
|
||||
import com.zaneschepke.wireguardautotunnel.ui.Route
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.ClickableIconButton
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.config.ConfigurationToggle
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.config.SubmitConfigurationTextBox
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.text.SectionTitle
|
||||
import com.zaneschepke.wireguardautotunnel.ui.screens.main.components.ScrollDismissFab
|
||||
import com.zaneschepke.wireguardautotunnel.ui.screens.settings.components.WildcardSupportingLabel
|
||||
import com.zaneschepke.wireguardautotunnel.util.Constants
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.isRunningOnTv
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.isValidIpv4orIpv6Address
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.openWebUrl
|
||||
import kotlinx.coroutines.delay
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.button.ScaledSwitch
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.button.surface.SelectionItem
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.button.surface.SurfaceSelectionGroupButton
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.label.GroupLabel
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.navigation.LocalNavController
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.navigation.TopNavBar
|
||||
import com.zaneschepke.wireguardautotunnel.ui.screens.settings.autotunnel.components.TrustedNetworkTextBox
|
||||
import com.zaneschepke.wireguardautotunnel.ui.screens.settings.autotunnel.components.WildcardsLabel
|
||||
import com.zaneschepke.wireguardautotunnel.ui.theme.iconSize
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.scaledHeight
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.scaledWidth
|
||||
|
||||
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
|
||||
@OptIn(ExperimentalLayoutApi::class)
|
||||
@Composable
|
||||
fun OptionsScreen(
|
||||
optionsViewModel: OptionsViewModel = hiltViewModel(),
|
||||
navController: NavController,
|
||||
focusRequester: FocusRequester,
|
||||
appUiState: AppUiState,
|
||||
tunnelId: Int,
|
||||
) {
|
||||
val scrollState = rememberScrollState()
|
||||
val context = LocalContext.current
|
||||
fun OptionsScreen(optionsViewModel: OptionsViewModel = hiltViewModel(), appUiState: AppUiState, tunnelId: Int) {
|
||||
val navController = LocalNavController.current
|
||||
val config = appUiState.tunnels.first { it.id == tunnelId }
|
||||
|
||||
val interactionSource = remember { MutableInteractionSource() }
|
||||
val focusManager = LocalFocusManager.current
|
||||
val screenPadding = 5.dp
|
||||
val fillMaxWidth = .85f
|
||||
|
||||
var currentText by remember { mutableStateOf("") }
|
||||
|
||||
LaunchedEffect(Unit) {
|
||||
if (context.isRunningOnTv()) {
|
||||
delay(Constants.FOCUS_REQUEST_DELAY)
|
||||
kotlin.runCatching {
|
||||
focusRequester.requestFocus()
|
||||
}.onFailure {
|
||||
delay(Constants.FOCUS_REQUEST_DELAY)
|
||||
focusRequester.requestFocus()
|
||||
}
|
||||
}
|
||||
LaunchedEffect(config.tunnelNetworks) {
|
||||
currentText = ""
|
||||
}
|
||||
|
||||
fun saveTrustedSSID() {
|
||||
if (currentText.isNotEmpty()) {
|
||||
optionsViewModel.onSaveRunSSID(currentText, config)
|
||||
currentText = ""
|
||||
}
|
||||
}
|
||||
|
||||
Scaffold(
|
||||
floatingActionButton = {
|
||||
ScrollDismissFab(icon = {
|
||||
val icon = Icons.Filled.Edit
|
||||
Icon(
|
||||
imageVector = icon,
|
||||
contentDescription = icon.name,
|
||||
tint = MaterialTheme.colorScheme.onPrimary,
|
||||
)
|
||||
}, focusRequester, isVisible = true, onClick = {
|
||||
navController.navigate(
|
||||
Route.Config(config.id),
|
||||
)
|
||||
topBar = {
|
||||
TopNavBar(config.name, trailing = {
|
||||
IconButton(onClick = {
|
||||
navController.navigate(
|
||||
Route.Config(config.id),
|
||||
)
|
||||
}) {
|
||||
val icon = Icons.Outlined.Edit
|
||||
Icon(
|
||||
imageVector = icon,
|
||||
contentDescription = icon.name,
|
||||
)
|
||||
}
|
||||
})
|
||||
},
|
||||
) {
|
||||
Column(
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.Top,
|
||||
horizontalAlignment = Alignment.Start,
|
||||
verticalArrangement = Arrangement.spacedBy(24.dp.scaledHeight(), Alignment.Top),
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.verticalScroll(scrollState)
|
||||
.clickable(
|
||||
indication = null,
|
||||
interactionSource = interactionSource,
|
||||
) {
|
||||
focusManager.clearFocus()
|
||||
},
|
||||
.padding(it)
|
||||
.padding(top = 24.dp.scaledHeight())
|
||||
.padding(horizontal = 24.dp.scaledWidth()),
|
||||
) {
|
||||
Surface(
|
||||
tonalElevation = 2.dp,
|
||||
shadowElevation = 2.dp,
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
color = MaterialTheme.colorScheme.surface,
|
||||
modifier =
|
||||
(
|
||||
if (context.isRunningOnTv()) {
|
||||
Modifier
|
||||
.height(IntrinsicSize.Min)
|
||||
.fillMaxWidth(fillMaxWidth)
|
||||
.padding(top = 10.dp)
|
||||
} else {
|
||||
Modifier
|
||||
.fillMaxWidth(fillMaxWidth)
|
||||
.padding(top = 20.dp)
|
||||
}
|
||||
)
|
||||
.padding(bottom = 10.dp),
|
||||
) {
|
||||
Column(
|
||||
horizontalAlignment = Alignment.Start,
|
||||
verticalArrangement = Arrangement.Top,
|
||||
modifier = Modifier.padding(15.dp),
|
||||
) {
|
||||
SectionTitle(
|
||||
title = stringResource(id = R.string.general),
|
||||
padding = screenPadding,
|
||||
)
|
||||
ConfigurationToggle(
|
||||
stringResource(R.string.set_primary_tunnel),
|
||||
enabled = true,
|
||||
checked = config.isPrimaryTunnel,
|
||||
modifier =
|
||||
Modifier
|
||||
.focusRequester(focusRequester),
|
||||
padding = screenPadding,
|
||||
onCheckChanged = { optionsViewModel.onTogglePrimaryTunnel(config) },
|
||||
)
|
||||
}
|
||||
}
|
||||
Surface(
|
||||
tonalElevation = 2.dp,
|
||||
shadowElevation = 2.dp,
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
color = MaterialTheme.colorScheme.surface,
|
||||
modifier =
|
||||
(
|
||||
if (context.isRunningOnTv()) {
|
||||
Modifier
|
||||
.height(IntrinsicSize.Min)
|
||||
.fillMaxWidth(fillMaxWidth)
|
||||
.padding(top = 10.dp)
|
||||
} else {
|
||||
Modifier
|
||||
.fillMaxWidth(fillMaxWidth)
|
||||
.padding(top = 20.dp)
|
||||
}
|
||||
)
|
||||
.padding(bottom = 10.dp),
|
||||
) {
|
||||
Column(
|
||||
horizontalAlignment = Alignment.Start,
|
||||
verticalArrangement = Arrangement.Top,
|
||||
modifier = Modifier.padding(15.dp),
|
||||
) {
|
||||
SectionTitle(
|
||||
title = stringResource(id = R.string.auto_tunneling),
|
||||
padding = screenPadding,
|
||||
)
|
||||
ConfigurationToggle(
|
||||
stringResource(R.string.mobile_data_tunnel),
|
||||
enabled = true,
|
||||
checked = config.isMobileDataTunnel,
|
||||
padding = screenPadding,
|
||||
onCheckChanged = { optionsViewModel.onToggleIsMobileDataTunnel(config) },
|
||||
)
|
||||
Column {
|
||||
FlowRow(
|
||||
modifier =
|
||||
Modifier
|
||||
.padding(screenPadding)
|
||||
.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.spacedBy(5.dp),
|
||||
) {
|
||||
config.tunnelNetworks.forEach { ssid ->
|
||||
ClickableIconButton(
|
||||
onClick = {
|
||||
if (context.isRunningOnTv()) {
|
||||
focusRequester.requestFocus()
|
||||
optionsViewModel.onDeleteRunSSID(ssid, config)
|
||||
}
|
||||
},
|
||||
onIconClick = {
|
||||
if (context.isRunningOnTv()) focusRequester.requestFocus()
|
||||
optionsViewModel.onDeleteRunSSID(ssid, config)
|
||||
},
|
||||
text = ssid,
|
||||
icon = Icons.Filled.Close,
|
||||
enabled = true,
|
||||
)
|
||||
}
|
||||
if (config.tunnelNetworks.isEmpty()) {
|
||||
Text(
|
||||
stringResource(R.string.no_wifi_names_configured),
|
||||
fontStyle = FontStyle.Italic,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
)
|
||||
}
|
||||
}
|
||||
OutlinedTextField(
|
||||
enabled = true,
|
||||
value = currentText,
|
||||
onValueChange = { currentText = it },
|
||||
label = { Text(stringResource(id = R.string.use_tunnel_on_wifi_name)) },
|
||||
supportingText = { WildcardSupportingLabel { context.openWebUrl(it) } },
|
||||
modifier =
|
||||
Modifier
|
||||
.padding(
|
||||
start = screenPadding,
|
||||
top = 5.dp,
|
||||
bottom = 10.dp,
|
||||
),
|
||||
maxLines = 1,
|
||||
keyboardOptions =
|
||||
KeyboardOptions(
|
||||
capitalization = KeyboardCapitalization.None,
|
||||
imeAction = ImeAction.Done,
|
||||
),
|
||||
keyboardActions = KeyboardActions(onDone = { saveTrustedSSID() }),
|
||||
trailingIcon = {
|
||||
if (currentText != "") {
|
||||
IconButton(onClick = { saveTrustedSSID() }) {
|
||||
Icon(
|
||||
imageVector = Icons.Outlined.Add,
|
||||
contentDescription = stringResource(R.string.save_changes),
|
||||
tint = MaterialTheme.colorScheme.primary,
|
||||
GroupLabel(stringResource(R.string.auto_tunneling))
|
||||
SurfaceSelectionGroupButton(
|
||||
listOf(
|
||||
SelectionItem(
|
||||
Icons.Outlined.Star,
|
||||
title = {
|
||||
Text(
|
||||
stringResource(R.string.primary_tunnel),
|
||||
style = MaterialTheme.typography.bodyMedium.copy(MaterialTheme.colorScheme.onSurface),
|
||||
)
|
||||
},
|
||||
description = {
|
||||
Text(
|
||||
stringResource(R.string.set_primary_tunnel),
|
||||
style = MaterialTheme.typography.bodyMedium.copy(MaterialTheme.colorScheme.outline),
|
||||
)
|
||||
},
|
||||
trailing = {
|
||||
ScaledSwitch(
|
||||
config.isPrimaryTunnel,
|
||||
onClick = { optionsViewModel.onTogglePrimaryTunnel(config) },
|
||||
)
|
||||
},
|
||||
onClick = { optionsViewModel.onTogglePrimaryTunnel(config) },
|
||||
),
|
||||
SelectionItem(
|
||||
Icons.Outlined.PhoneAndroid,
|
||||
title = { Text(stringResource(R.string.mobile_tunnel), style = MaterialTheme.typography.bodyMedium.copy(MaterialTheme.colorScheme.onSurface)) },
|
||||
description = {
|
||||
Text(
|
||||
stringResource(R.string.mobile_data_tunnel),
|
||||
style = MaterialTheme.typography.bodyMedium.copy(MaterialTheme.colorScheme.outline),
|
||||
)
|
||||
},
|
||||
trailing = {
|
||||
ScaledSwitch(
|
||||
config.isMobileDataTunnel,
|
||||
onClick = { optionsViewModel.onToggleIsMobileDataTunnel(config) },
|
||||
)
|
||||
},
|
||||
onClick = { optionsViewModel.onToggleIsMobileDataTunnel(config) },
|
||||
),
|
||||
SelectionItem(
|
||||
Icons.Outlined.NetworkPing,
|
||||
title = {
|
||||
Text(
|
||||
stringResource(R.string.restart_on_ping),
|
||||
style = MaterialTheme.typography.bodyMedium.copy(MaterialTheme.colorScheme.onSurface),
|
||||
)
|
||||
},
|
||||
trailing = {
|
||||
ScaledSwitch(
|
||||
checked = config.isPingEnabled,
|
||||
onClick = { optionsViewModel.onToggleRestartOnPing(config) },
|
||||
)
|
||||
},
|
||||
onClick = { optionsViewModel.onToggleRestartOnPing(config) },
|
||||
),
|
||||
SelectionItem(
|
||||
title = {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp.scaledHeight()),
|
||||
) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier
|
||||
.weight(4f, false)
|
||||
.fillMaxWidth(),
|
||||
) {
|
||||
val icon = Icons.Outlined.Security
|
||||
Icon(
|
||||
icon,
|
||||
icon.name,
|
||||
modifier = Modifier.size(iconSize),
|
||||
)
|
||||
Column(
|
||||
horizontalAlignment = Alignment.Start,
|
||||
verticalArrangement = Arrangement.spacedBy(2.dp, Alignment.CenterVertically),
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(start = 16.dp.scaledWidth())
|
||||
.padding(vertical = 6.dp.scaledHeight()),
|
||||
) {
|
||||
Text(
|
||||
stringResource(R.string.use_tunnel_on_wifi_name),
|
||||
style = MaterialTheme.typography.bodyMedium.copy(MaterialTheme.colorScheme.onSurface),
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
ConfigurationToggle(
|
||||
stringResource(R.string.restart_on_ping),
|
||||
enabled = !appUiState.settings.isPingEnabled,
|
||||
checked = config.isPingEnabled || appUiState.settings.isPingEnabled,
|
||||
padding = screenPadding,
|
||||
onCheckChanged = { optionsViewModel.onToggleRestartOnPing(config) },
|
||||
)
|
||||
if (config.isPingEnabled || appUiState.settings.isPingEnabled) {
|
||||
SubmitConfigurationTextBox(
|
||||
config.pingIp,
|
||||
stringResource(R.string.set_custom_ping_ip),
|
||||
stringResource(R.string.default_ping_ip),
|
||||
focusRequester,
|
||||
isErrorValue = { !it.isNullOrBlank() && !it.isValidIpv4orIpv6Address() },
|
||||
onSubmit = {
|
||||
optionsViewModel.saveTunnelChanges(
|
||||
config.copy(pingIp = it.ifBlank { null }),
|
||||
)
|
||||
},
|
||||
)
|
||||
fun isSecondsError(seconds: String?): Boolean {
|
||||
return seconds?.let { value -> if (value.isBlank()) false else value.toLong() >= Long.MAX_VALUE / 1000 } ?: false
|
||||
}
|
||||
SubmitConfigurationTextBox(
|
||||
config.pingInterval?.let { (it / 1000).toString() },
|
||||
stringResource(R.string.set_custom_ping_internal),
|
||||
"(${stringResource(R.string.optional_default)} ${Constants.PING_INTERVAL / 1000})",
|
||||
focusRequester,
|
||||
keyboardOptions = KeyboardOptions(
|
||||
keyboardType = KeyboardType.Number,
|
||||
imeAction = ImeAction.Done,
|
||||
),
|
||||
isErrorValue = ::isSecondsError,
|
||||
onSubmit = {
|
||||
optionsViewModel.saveTunnelChanges(
|
||||
config.copy(pingInterval = if (it.isBlank()) null else it.toLong() * 1000),
|
||||
)
|
||||
},
|
||||
description = {
|
||||
TrustedNetworkTextBox(
|
||||
config.tunnelNetworks,
|
||||
onDelete = { optionsViewModel.onDeleteRunSSID(it, config) },
|
||||
currentText = currentText,
|
||||
onSave = { optionsViewModel.onSaveRunSSID(it, config) },
|
||||
onValueChange = { currentText = it },
|
||||
supporting = {
|
||||
if (appUiState.settings.isWildcardsEnabled) {
|
||||
WildcardsLabel()
|
||||
}
|
||||
},
|
||||
)
|
||||
SubmitConfigurationTextBox(
|
||||
config.pingCooldown?.let { (it / 1000).toString() },
|
||||
stringResource(R.string.set_custom_ping_cooldown),
|
||||
"(${stringResource(R.string.optional_default)} ${Constants.PING_COOLDOWN / 1000})",
|
||||
focusRequester,
|
||||
keyboardOptions = KeyboardOptions(
|
||||
keyboardType = KeyboardType.Number,
|
||||
),
|
||||
isErrorValue = ::isSecondsError,
|
||||
onSubmit = {
|
||||
optionsViewModel.saveTunnelChanges(
|
||||
config.copy(pingCooldown = if (it.isBlank()) null else it.toLong() * 1000),
|
||||
)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
),
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+1
@@ -32,6 +32,7 @@ constructor(
|
||||
}
|
||||
|
||||
fun onSaveRunSSID(ssid: String, tunnelConfig: TunnelConfig) = viewModelScope.launch {
|
||||
if (ssid.isBlank()) return@launch
|
||||
val trimmed = ssid.trim()
|
||||
val tunnelsWithName = appDataRepository.tunnels.findByTunnelNetworksName(trimmed)
|
||||
|
||||
|
||||
+6
-4
@@ -5,23 +5,24 @@ import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.navigation.NavController
|
||||
import com.zaneschepke.wireguardautotunnel.R
|
||||
import com.zaneschepke.wireguardautotunnel.ui.AppViewModel
|
||||
import com.zaneschepke.wireguardautotunnel.ui.Route
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.navigation.LocalNavController
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.snackbar.SnackbarController
|
||||
import com.zaneschepke.wireguardautotunnel.util.StringValue
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.isRunningOnTv
|
||||
import xyz.teamgravity.pin_lock_compose.PinLock
|
||||
|
||||
@Composable
|
||||
fun PinLockScreen(navController: NavController, appViewModel: AppViewModel) {
|
||||
fun PinLockScreen(appViewModel: AppViewModel) {
|
||||
val context = LocalContext.current
|
||||
val navController = LocalNavController.current
|
||||
val snackbar = SnackbarController.current
|
||||
PinLock(
|
||||
title = { pinExists ->
|
||||
Text(
|
||||
color = MaterialTheme.colorScheme.onSecondary,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
text =
|
||||
if (pinExists) {
|
||||
stringResource(id = R.string.enter_pin)
|
||||
@@ -32,7 +33,8 @@ fun PinLockScreen(navController: NavController, appViewModel: AppViewModel) {
|
||||
},
|
||||
)
|
||||
},
|
||||
color = MaterialTheme.colorScheme.secondary,
|
||||
backgroundColor = MaterialTheme.colorScheme.surface,
|
||||
textColor = MaterialTheme.colorScheme.onSurface,
|
||||
onPinCorrect = {
|
||||
// pin is correct, navigate or hide pin lock
|
||||
if (context.isRunningOnTv()) {
|
||||
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.screens.scanner
|
||||
|
||||
import android.app.Activity
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.viewinterop.AndroidView
|
||||
import androidx.hilt.navigation.compose.hiltViewModel
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import com.google.accompanist.permissions.ExperimentalPermissionsApi
|
||||
import com.journeyapps.barcodescanner.CompoundBarcodeView
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.navigation.LocalNavController
|
||||
|
||||
@OptIn(ExperimentalPermissionsApi::class)
|
||||
@Composable
|
||||
fun ScannerScreen(viewModel: ScannerViewModel = hiltViewModel()) {
|
||||
val context = LocalContext.current
|
||||
val navController = LocalNavController.current
|
||||
|
||||
val success = viewModel.success.collectAsStateWithLifecycle(null)
|
||||
|
||||
LaunchedEffect(success.value) {
|
||||
if (success.value != null) navController.popBackStack()
|
||||
}
|
||||
|
||||
val barcodeView = remember {
|
||||
CompoundBarcodeView(context).apply {
|
||||
this.initializeFromIntent((context as Activity).intent)
|
||||
this.setStatusText("")
|
||||
this.decodeSingle { result ->
|
||||
result.text?.let { barCodeOrQr ->
|
||||
viewModel.onTunnelQrResult(barCodeOrQr)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
AndroidView(factory = { barcodeView })
|
||||
DisposableEffect(Unit) {
|
||||
barcodeView.resume()
|
||||
onDispose {
|
||||
barcodeView.pause()
|
||||
}
|
||||
}
|
||||
}
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.screens.scanner
|
||||
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import com.zaneschepke.wireguardautotunnel.R
|
||||
import com.zaneschepke.wireguardautotunnel.data.domain.TunnelConfig
|
||||
import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository
|
||||
import com.zaneschepke.wireguardautotunnel.module.IoDispatcher
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.snackbar.SnackbarController
|
||||
import com.zaneschepke.wireguardautotunnel.util.NumberUtils
|
||||
import com.zaneschepke.wireguardautotunnel.util.StringValue
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.toWgQuickString
|
||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||
import kotlinx.coroutines.CoroutineDispatcher
|
||||
import kotlinx.coroutines.flow.MutableSharedFlow
|
||||
import kotlinx.coroutines.flow.asSharedFlow
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import timber.log.Timber
|
||||
import javax.inject.Inject
|
||||
|
||||
@HiltViewModel
|
||||
class ScannerViewModel @Inject
|
||||
constructor(
|
||||
private val appDataRepository: AppDataRepository,
|
||||
@IoDispatcher private val ioDispatcher: CoroutineDispatcher,
|
||||
) : ViewModel() {
|
||||
|
||||
private val _success = MutableSharedFlow<Boolean>()
|
||||
val success = _success.asSharedFlow()
|
||||
|
||||
private suspend fun makeTunnelNameUnique(name: String): String {
|
||||
return withContext(ioDispatcher) {
|
||||
val tunnels = appDataRepository.tunnels.getAll()
|
||||
var tunnelName = name
|
||||
var num = 1
|
||||
while (tunnels.any { it.name == tunnelName }) {
|
||||
tunnelName = "$name($num)"
|
||||
num++
|
||||
}
|
||||
tunnelName
|
||||
}
|
||||
}
|
||||
|
||||
fun onTunnelQrResult(result: String) = viewModelScope.launch(ioDispatcher) {
|
||||
kotlin.runCatching {
|
||||
val amConfig = TunnelConfig.configFromAmQuick(result)
|
||||
val amQuick = amConfig.toAwgQuickString(true)
|
||||
val wgQuick = amConfig.toWgQuickString()
|
||||
val tunnelName = makeTunnelNameUnique(generateQrCodeDefaultName(result))
|
||||
val tunnelConfig = TunnelConfig(name = tunnelName, wgQuick = wgQuick, amQuick = amQuick)
|
||||
appDataRepository.tunnels.save(tunnelConfig)
|
||||
_success.emit(true)
|
||||
}.onFailure {
|
||||
_success.emit(false)
|
||||
Timber.e(it)
|
||||
SnackbarController.showMessage(StringValue.StringResource(R.string.error_invalid_code))
|
||||
}
|
||||
}
|
||||
|
||||
private fun generateQrCodeDefaultName(config: String): String {
|
||||
return try {
|
||||
TunnelConfig.configFromAmQuick(config).peers[0].endpoint.get().host
|
||||
} catch (e: Exception) {
|
||||
Timber.e(e)
|
||||
NumberUtils.generateRandomTunnelName()
|
||||
}
|
||||
}
|
||||
}
|
||||
+241
-519
@@ -1,88 +1,61 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.screens.settings
|
||||
|
||||
import android.Manifest
|
||||
import android.app.Activity
|
||||
import android.content.Context.POWER_SERVICE
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.net.VpnService
|
||||
import android.os.Build
|
||||
import android.os.PowerManager
|
||||
import android.provider.Settings
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.ActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.appcompat.app.AppCompatActivity.RESULT_OK
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.focusable
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.ExperimentalLayoutApi
|
||||
import androidx.compose.foundation.layout.FlowRow
|
||||
import androidx.compose.foundation.layout.IntrinsicSize
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.text.KeyboardActions
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.outlined.Add
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material.icons.automirrored.outlined.ViewQuilt
|
||||
import androidx.compose.material.icons.filled.AppShortcut
|
||||
import androidx.compose.material.icons.outlined.AdminPanelSettings
|
||||
import androidx.compose.material.icons.outlined.Bolt
|
||||
import androidx.compose.material.icons.outlined.Code
|
||||
import androidx.compose.material.icons.outlined.FolderZip
|
||||
import androidx.compose.material.icons.outlined.Notifications
|
||||
import androidx.compose.material.icons.outlined.Pin
|
||||
import androidx.compose.material.icons.outlined.Restore
|
||||
import androidx.compose.material.icons.outlined.VpnLock
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.SideEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalFocusManager
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontStyle
|
||||
import androidx.compose.ui.text.input.ImeAction
|
||||
import androidx.compose.ui.text.input.KeyboardCapitalization
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.hilt.navigation.compose.hiltViewModel
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.navigation.NavController
|
||||
import com.google.accompanist.permissions.ExperimentalPermissionsApi
|
||||
import com.google.accompanist.permissions.isGranted
|
||||
import com.google.accompanist.permissions.rememberPermissionState
|
||||
import com.zaneschepke.wireguardautotunnel.R
|
||||
import com.zaneschepke.wireguardautotunnel.WireGuardAutoTunnel
|
||||
import com.zaneschepke.wireguardautotunnel.service.tunnel.TunnelState
|
||||
import com.zaneschepke.wireguardautotunnel.ui.AppUiState
|
||||
import com.zaneschepke.wireguardautotunnel.ui.AppViewModel
|
||||
import com.zaneschepke.wireguardautotunnel.ui.Route
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.ClickableIconButton
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.config.ConfigurationToggle
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.button.ScaledSwitch
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.button.surface.SelectionItem
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.button.surface.SurfaceSelectionGroupButton
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.navigation.LocalFocusRequester
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.navigation.LocalNavController
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.prompt.AuthorizationPrompt
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.snackbar.SnackbarController
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.text.SectionTitle
|
||||
import com.zaneschepke.wireguardautotunnel.ui.screens.main.components.VpnDeniedDialog
|
||||
import com.zaneschepke.wireguardautotunnel.ui.screens.settings.components.BackgroundLocationDialog
|
||||
import com.zaneschepke.wireguardautotunnel.ui.screens.settings.components.BackgroundLocationDisclosure
|
||||
import com.zaneschepke.wireguardautotunnel.ui.screens.settings.components.LocationServicesDialog
|
||||
import com.zaneschepke.wireguardautotunnel.ui.screens.settings.components.WildcardSupportingLabel
|
||||
import com.zaneschepke.wireguardautotunnel.ui.screens.settings.components.ForwardButton
|
||||
import com.zaneschepke.wireguardautotunnel.ui.theme.topPadding
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.isRunningOnTv
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.launchAppSettings
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.openWebUrl
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.launchNotificationSettings
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.launchVpnSettings
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.scaledHeight
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.scaledWidth
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.showToast
|
||||
import xyz.teamgravity.pin_lock_compose.PinManager
|
||||
|
||||
@@ -91,165 +64,22 @@ import xyz.teamgravity.pin_lock_compose.PinManager
|
||||
ExperimentalLayoutApi::class,
|
||||
)
|
||||
@Composable
|
||||
fun SettingsScreen(
|
||||
viewModel: SettingsViewModel = hiltViewModel(),
|
||||
appViewModel: AppViewModel,
|
||||
uiState: AppUiState,
|
||||
navController: NavController,
|
||||
focusRequester: FocusRequester,
|
||||
) {
|
||||
fun SettingsScreen(viewModel: SettingsViewModel = hiltViewModel(), appViewModel: AppViewModel, uiState: AppUiState) {
|
||||
val context = LocalContext.current
|
||||
val navController = LocalNavController.current
|
||||
val focusManager = LocalFocusManager.current
|
||||
val snackbar = SnackbarController.current
|
||||
val scrollState = rememberScrollState()
|
||||
val rootFocusRequester = LocalFocusRequester.current
|
||||
val isRunningOnTv = remember { context.isRunningOnTv() }
|
||||
|
||||
val interactionSource = remember { MutableInteractionSource() }
|
||||
val isRunningOnTv = context.isRunningOnTv()
|
||||
|
||||
val kernelSupport by viewModel.kernelSupport.collectAsStateWithLifecycle()
|
||||
|
||||
val fineLocationState = rememberPermissionState(Manifest.permission.ACCESS_FINE_LOCATION)
|
||||
var currentText by remember { mutableStateOf("") }
|
||||
var isBackgroundLocationGranted by remember { mutableStateOf(true) }
|
||||
var showVpnPermissionDialog by remember { mutableStateOf(false) }
|
||||
var showLocationServicesAlertDialog by remember { mutableStateOf(false) }
|
||||
val didExportFiles by remember { mutableStateOf(false) }
|
||||
var showAuthPrompt by remember { mutableStateOf(false) }
|
||||
var showLocationDialog by remember { mutableStateOf(false) }
|
||||
|
||||
val screenPadding = 5.dp
|
||||
val fillMaxWidth = .85f
|
||||
|
||||
LaunchedEffect(Unit) {
|
||||
viewModel.checkKernelSupport()
|
||||
}
|
||||
|
||||
LaunchedEffect(uiState.settings.trustedNetworkSSIDs) {
|
||||
currentText = ""
|
||||
}
|
||||
|
||||
val startForResult =
|
||||
rememberLauncherForActivityResult(
|
||||
ActivityResultContracts.StartActivityForResult(),
|
||||
) { result: ActivityResult ->
|
||||
if (result.resultCode == Activity.RESULT_OK) {
|
||||
result.data
|
||||
// Handle the Intent
|
||||
}
|
||||
viewModel.setBatteryOptimizeDisableShown()
|
||||
}
|
||||
|
||||
val vpnActivityResultState =
|
||||
rememberLauncherForActivityResult(
|
||||
ActivityResultContracts.StartActivityForResult(),
|
||||
onResult = {
|
||||
val accepted = (it.resultCode == RESULT_OK)
|
||||
if (accepted) {
|
||||
viewModel.onToggleAutoTunnel(context)
|
||||
} else {
|
||||
showVpnPermissionDialog = true
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
fun isBatteryOptimizationsDisabled(): Boolean {
|
||||
val pm = context.getSystemService(POWER_SERVICE) as PowerManager
|
||||
return pm.isIgnoringBatteryOptimizations(context.packageName)
|
||||
}
|
||||
|
||||
fun requestBatteryOptimizationsDisabled() {
|
||||
val intent =
|
||||
Intent().apply {
|
||||
action = Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS
|
||||
data = Uri.parse("package:${context.packageName}")
|
||||
}
|
||||
startForResult.launch(intent)
|
||||
}
|
||||
|
||||
fun handleAutoTunnelToggle() {
|
||||
if (!uiState.generalState.isBatteryOptimizationDisableShown &&
|
||||
!isBatteryOptimizationsDisabled() && !context.isRunningOnTv()
|
||||
) {
|
||||
return requestBatteryOptimizationsDisabled()
|
||||
}
|
||||
val intent = if (!uiState.settings.isKernelEnabled) {
|
||||
VpnService.prepare(context)
|
||||
} else {
|
||||
null
|
||||
}
|
||||
if (intent != null) return vpnActivityResultState.launch(intent)
|
||||
viewModel.onToggleAutoTunnel(context)
|
||||
}
|
||||
|
||||
fun saveTrustedSSID() {
|
||||
if (currentText.isNotEmpty()) {
|
||||
viewModel.onSaveTrustedSSID(currentText)
|
||||
}
|
||||
}
|
||||
|
||||
fun checkFineLocationGranted() {
|
||||
isBackgroundLocationGranted =
|
||||
if (!fineLocationState.status.isGranted) {
|
||||
false
|
||||
} else {
|
||||
viewModel.setLocationDisclosureShown()
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||
if (
|
||||
isRunningOnTv &&
|
||||
Build.VERSION.SDK_INT == Build.VERSION_CODES.Q
|
||||
) {
|
||||
checkFineLocationGranted()
|
||||
} else {
|
||||
val backgroundLocationState =
|
||||
rememberPermissionState(Manifest.permission.ACCESS_BACKGROUND_LOCATION)
|
||||
isBackgroundLocationGranted =
|
||||
if (!backgroundLocationState.status.isGranted) {
|
||||
false
|
||||
} else {
|
||||
SideEffect { viewModel.setLocationDisclosureShown() }
|
||||
true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P) {
|
||||
checkFineLocationGranted()
|
||||
}
|
||||
if (!uiState.generalState.isLocationDisclosureShown) {
|
||||
BackgroundLocationDisclosure(
|
||||
onDismiss = { viewModel.setLocationDisclosureShown() },
|
||||
onAttest = {
|
||||
context.launchAppSettings()
|
||||
viewModel.setLocationDisclosureShown()
|
||||
},
|
||||
scrollState,
|
||||
focusRequester,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
BackgroundLocationDialog(
|
||||
showLocationDialog,
|
||||
onDismiss = { showLocationDialog = false },
|
||||
onAttest = { showLocationDialog = false },
|
||||
)
|
||||
|
||||
LocationServicesDialog(
|
||||
showLocationServicesAlertDialog,
|
||||
onDismiss = { showVpnPermissionDialog = false },
|
||||
onAttest = { handleAutoTunnelToggle() },
|
||||
)
|
||||
|
||||
VpnDeniedDialog(showVpnPermissionDialog, onDismiss = { showVpnPermissionDialog = false })
|
||||
|
||||
if (showAuthPrompt) {
|
||||
AuthorizationPrompt(
|
||||
onSuccess = {
|
||||
showAuthPrompt = false
|
||||
viewModel.exportAllConfigs()
|
||||
viewModel.exportAllConfigs(context)
|
||||
},
|
||||
onError = { _ ->
|
||||
showAuthPrompt = false
|
||||
@@ -267,345 +97,237 @@ fun SettingsScreen(
|
||||
}
|
||||
|
||||
Column(
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.Top,
|
||||
horizontalAlignment = Alignment.Start,
|
||||
verticalArrangement = Arrangement.spacedBy(24.dp, Alignment.Top),
|
||||
modifier =
|
||||
Modifier
|
||||
.verticalScroll(rememberScrollState())
|
||||
.fillMaxSize()
|
||||
.verticalScroll(scrollState)
|
||||
.clickable(
|
||||
indication = null,
|
||||
interactionSource = interactionSource,
|
||||
) {
|
||||
focusManager.clearFocus()
|
||||
},
|
||||
) {
|
||||
Surface(
|
||||
tonalElevation = 2.dp,
|
||||
shadowElevation = 2.dp,
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
color = MaterialTheme.colorScheme.surface,
|
||||
modifier =
|
||||
(
|
||||
if (isRunningOnTv) {
|
||||
Modifier
|
||||
.height(IntrinsicSize.Min)
|
||||
.fillMaxWidth(fillMaxWidth)
|
||||
.padding(top = 10.dp)
|
||||
.padding(top = topPadding)
|
||||
.padding(bottom = 40.dp.scaledHeight())
|
||||
.padding(horizontal = 24.dp.scaledWidth())
|
||||
.then(
|
||||
if (!isRunningOnTv) {
|
||||
Modifier.clickable(
|
||||
indication = null,
|
||||
interactionSource = interactionSource,
|
||||
) {
|
||||
focusManager.clearFocus()
|
||||
}
|
||||
} else {
|
||||
Modifier
|
||||
.fillMaxWidth(fillMaxWidth)
|
||||
.padding(top = 20.dp)
|
||||
}
|
||||
)
|
||||
.padding(bottom = 10.dp),
|
||||
) {
|
||||
Column(
|
||||
horizontalAlignment = Alignment.Start,
|
||||
verticalArrangement = Arrangement.Top,
|
||||
modifier = Modifier.padding(15.dp),
|
||||
) {
|
||||
SectionTitle(
|
||||
title = stringResource(id = R.string.auto_tunneling),
|
||||
padding = screenPadding,
|
||||
)
|
||||
ConfigurationToggle(
|
||||
stringResource(id = R.string.tunnel_on_wifi),
|
||||
enabled = !uiState.settings.isAlwaysOnVpnEnabled,
|
||||
checked = uiState.settings.isTunnelOnWifiEnabled,
|
||||
padding = screenPadding,
|
||||
onCheckChanged = { checked ->
|
||||
if (!checked) viewModel.onToggleTunnelOnWifi()
|
||||
if (checked) {
|
||||
when (false) {
|
||||
isBackgroundLocationGranted -> showLocationDialog = true
|
||||
fineLocationState.status.isGranted -> showLocationDialog = true
|
||||
viewModel.isLocationEnabled(context) ->
|
||||
showLocationServicesAlertDialog = true
|
||||
else -> {
|
||||
viewModel.onToggleTunnelOnWifi()
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
),
|
||||
) {
|
||||
SurfaceSelectionGroupButton(
|
||||
listOf(
|
||||
SelectionItem(
|
||||
Icons.Outlined.Bolt,
|
||||
title = { Text(stringResource(R.string.auto_tunneling), style = MaterialTheme.typography.bodyMedium.copy(MaterialTheme.colorScheme.onSurface)) },
|
||||
description = {
|
||||
Text(
|
||||
stringResource(R.string.on_demand_rules),
|
||||
style = MaterialTheme.typography.bodySmall.copy(MaterialTheme.colorScheme.outline),
|
||||
)
|
||||
},
|
||||
modifier =
|
||||
if (uiState.settings.isAutoTunnelEnabled) {
|
||||
Modifier
|
||||
} else {
|
||||
Modifier
|
||||
.focusRequester(focusRequester)
|
||||
onClick = {
|
||||
if (!uiState.generalState.isLocationDisclosureShown) return@SelectionItem navController.navigate(Route.LocationDisclosure)
|
||||
navController.navigate(Route.AutoTunnel)
|
||||
},
|
||||
)
|
||||
if (uiState.settings.isTunnelOnWifiEnabled) {
|
||||
Column {
|
||||
FlowRow(
|
||||
modifier =
|
||||
Modifier
|
||||
.padding(screenPadding)
|
||||
.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.spacedBy(5.dp),
|
||||
) {
|
||||
uiState.settings.trustedNetworkSSIDs.forEach { ssid ->
|
||||
ClickableIconButton(
|
||||
onClick = {
|
||||
if (isRunningOnTv) {
|
||||
focusRequester.requestFocus()
|
||||
viewModel.onDeleteTrustedSSID(ssid)
|
||||
}
|
||||
},
|
||||
onIconClick = {
|
||||
if (isRunningOnTv) focusRequester.requestFocus()
|
||||
viewModel.onDeleteTrustedSSID(ssid)
|
||||
},
|
||||
text = ssid,
|
||||
icon = Icons.Filled.Close,
|
||||
)
|
||||
}
|
||||
if (uiState.settings.trustedNetworkSSIDs.isEmpty()) {
|
||||
Text(
|
||||
stringResource(R.string.none),
|
||||
fontStyle = FontStyle.Italic,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
)
|
||||
}
|
||||
}
|
||||
OutlinedTextField(
|
||||
value = currentText,
|
||||
onValueChange = { currentText = it },
|
||||
label = { Text(stringResource(R.string.add_trusted_ssid)) },
|
||||
modifier =
|
||||
Modifier
|
||||
.padding(
|
||||
start = screenPadding,
|
||||
top = 5.dp,
|
||||
bottom = 10.dp,
|
||||
),
|
||||
supportingText = { WildcardSupportingLabel { context.openWebUrl(it) } },
|
||||
maxLines = 1,
|
||||
keyboardOptions =
|
||||
KeyboardOptions(
|
||||
capitalization = KeyboardCapitalization.None,
|
||||
imeAction = ImeAction.Done,
|
||||
trailing = {
|
||||
ForwardButton(Modifier.focusable().focusRequester(rootFocusRequester)) { navController.navigate(Route.AutoTunnel) }
|
||||
},
|
||||
),
|
||||
),
|
||||
)
|
||||
SurfaceSelectionGroupButton(
|
||||
buildList {
|
||||
if (!isRunningOnTv) {
|
||||
addAll(
|
||||
listOf(
|
||||
SelectionItem(
|
||||
Icons.Filled.AppShortcut,
|
||||
{
|
||||
ScaledSwitch(
|
||||
uiState.settings.isShortcutsEnabled,
|
||||
onClick = { viewModel.onToggleShortcutsEnabled() },
|
||||
)
|
||||
},
|
||||
title = {
|
||||
Text(
|
||||
stringResource(R.string.enabled_app_shortcuts),
|
||||
style = MaterialTheme.typography.bodyMedium.copy(MaterialTheme.colorScheme.onSurface),
|
||||
)
|
||||
},
|
||||
onClick = { viewModel.onToggleShortcutsEnabled() },
|
||||
),
|
||||
keyboardActions = KeyboardActions(onDone = { saveTrustedSSID() }),
|
||||
trailingIcon = {
|
||||
if (currentText != "") {
|
||||
IconButton(onClick = { saveTrustedSSID() }) {
|
||||
Icon(
|
||||
imageVector = Icons.Outlined.Add,
|
||||
contentDescription =
|
||||
if (currentText == "") {
|
||||
stringResource(
|
||||
id =
|
||||
R.string
|
||||
.trusted_ssid_empty_description,
|
||||
)
|
||||
} else {
|
||||
stringResource(
|
||||
id =
|
||||
R.string
|
||||
.trusted_ssid_value_description,
|
||||
)
|
||||
},
|
||||
tint = MaterialTheme.colorScheme.primary,
|
||||
)
|
||||
}
|
||||
SelectionItem(
|
||||
Icons.Outlined.VpnLock,
|
||||
{
|
||||
ScaledSwitch(
|
||||
enabled = !(
|
||||
(
|
||||
uiState.settings.isTunnelOnWifiEnabled ||
|
||||
uiState.settings.isTunnelOnEthernetEnabled ||
|
||||
uiState.settings.isTunnelOnMobileDataEnabled
|
||||
) &&
|
||||
uiState.settings.isAutoTunnelEnabled
|
||||
),
|
||||
onClick = { viewModel.onToggleAlwaysOnVPN() },
|
||||
checked = uiState.settings.isAlwaysOnVpnEnabled,
|
||||
)
|
||||
},
|
||||
title = {
|
||||
Text(
|
||||
stringResource(R.string.always_on_vpn_support),
|
||||
style = MaterialTheme.typography.bodyMedium.copy(MaterialTheme.colorScheme.onSurface),
|
||||
)
|
||||
},
|
||||
onClick = { viewModel.onToggleAlwaysOnVPN() },
|
||||
),
|
||||
SelectionItem(
|
||||
Icons.Outlined.AdminPanelSettings,
|
||||
title = {
|
||||
Text(
|
||||
stringResource(R.string.kill_switch),
|
||||
style = MaterialTheme.typography.bodyMedium.copy(MaterialTheme.colorScheme.onSurface),
|
||||
)
|
||||
},
|
||||
onClick = {
|
||||
context.launchVpnSettings()
|
||||
},
|
||||
trailing = {
|
||||
ForwardButton { context.launchVpnSettings() }
|
||||
},
|
||||
),
|
||||
),
|
||||
)
|
||||
}
|
||||
add(
|
||||
SelectionItem(
|
||||
Icons.Outlined.Restore,
|
||||
{
|
||||
ScaledSwitch(
|
||||
uiState.settings.isRestoreOnBootEnabled,
|
||||
onClick = { viewModel.onToggleRestartAtBoot() },
|
||||
)
|
||||
},
|
||||
title = {
|
||||
Text(
|
||||
stringResource(R.string.restart_at_boot),
|
||||
style = MaterialTheme.typography.bodyMedium.copy(MaterialTheme.colorScheme.onSurface),
|
||||
)
|
||||
},
|
||||
onClick = { viewModel.onToggleRestartAtBoot() },
|
||||
),
|
||||
)
|
||||
},
|
||||
)
|
||||
|
||||
SurfaceSelectionGroupButton(
|
||||
listOf(
|
||||
SelectionItem(
|
||||
Icons.AutoMirrored.Outlined.ViewQuilt,
|
||||
title = { Text(stringResource(R.string.appearance), style = MaterialTheme.typography.bodyMedium.copy(MaterialTheme.colorScheme.onSurface)) },
|
||||
onClick = {
|
||||
navController.navigate(Route.Appearance)
|
||||
},
|
||||
trailing = {
|
||||
ForwardButton { navController.navigate(Route.Appearance) }
|
||||
},
|
||||
),
|
||||
SelectionItem(
|
||||
Icons.Outlined.Notifications,
|
||||
title = { Text(stringResource(R.string.notifications), style = MaterialTheme.typography.bodyMedium.copy(MaterialTheme.colorScheme.onSurface)) },
|
||||
onClick = {
|
||||
context.launchNotificationSettings()
|
||||
},
|
||||
trailing = {
|
||||
ForwardButton { context.launchNotificationSettings() }
|
||||
},
|
||||
),
|
||||
SelectionItem(
|
||||
Icons.Outlined.Pin,
|
||||
title = {
|
||||
Text(
|
||||
stringResource(R.string.enable_app_lock),
|
||||
style = MaterialTheme.typography.bodyMedium.copy(MaterialTheme.colorScheme.onSurface),
|
||||
)
|
||||
},
|
||||
trailing = {
|
||||
ScaledSwitch(
|
||||
uiState.generalState.isPinLockEnabled,
|
||||
onClick = {
|
||||
if (uiState.generalState.isPinLockEnabled) {
|
||||
appViewModel.onPinLockDisabled()
|
||||
} else {
|
||||
PinManager.initialize(context)
|
||||
navController.navigate(Route.Lock)
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
ConfigurationToggle(
|
||||
stringResource(R.string.tunnel_mobile_data),
|
||||
enabled = !uiState.settings.isAlwaysOnVpnEnabled,
|
||||
checked = uiState.settings.isTunnelOnMobileDataEnabled,
|
||||
padding = screenPadding,
|
||||
onCheckChanged = { viewModel.onToggleTunnelOnMobileData() },
|
||||
)
|
||||
ConfigurationToggle(
|
||||
stringResource(id = R.string.tunnel_on_ethernet),
|
||||
enabled = !uiState.settings.isAlwaysOnVpnEnabled,
|
||||
checked = uiState.settings.isTunnelOnEthernetEnabled,
|
||||
padding = screenPadding,
|
||||
onCheckChanged = { viewModel.onToggleTunnelOnEthernet() },
|
||||
)
|
||||
ConfigurationToggle(
|
||||
stringResource(R.string.restart_on_ping),
|
||||
checked = uiState.settings.isPingEnabled,
|
||||
padding = screenPadding,
|
||||
onCheckChanged = { viewModel.onToggleRestartOnPing() },
|
||||
)
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier =
|
||||
(
|
||||
if (!uiState.settings.isAutoTunnelEnabled) {
|
||||
Modifier
|
||||
} else {
|
||||
Modifier.focusRequester(
|
||||
focusRequester,
|
||||
)
|
||||
}
|
||||
)
|
||||
.fillMaxSize()
|
||||
.padding(top = 5.dp),
|
||||
horizontalArrangement = Arrangement.Center,
|
||||
) {
|
||||
TextButton(
|
||||
onClick = {
|
||||
if (uiState.tunnels.isEmpty()) return@TextButton context.showToast(R.string.tunnel_required)
|
||||
handleAutoTunnelToggle()
|
||||
},
|
||||
) {
|
||||
val autoTunnelButtonText =
|
||||
if (uiState.settings.isAutoTunnelEnabled) {
|
||||
stringResource(R.string.disable_auto_tunnel)
|
||||
} else {
|
||||
stringResource(id = R.string.enable_auto_tunnel)
|
||||
}
|
||||
Text(autoTunnelButtonText)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Surface(
|
||||
tonalElevation = 2.dp,
|
||||
shadowElevation = 2.dp,
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
color = MaterialTheme.colorScheme.surface,
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxWidth(fillMaxWidth)
|
||||
.padding(vertical = 10.dp),
|
||||
) {
|
||||
Column(
|
||||
horizontalAlignment = Alignment.Start,
|
||||
verticalArrangement = Arrangement.Top,
|
||||
modifier = Modifier.padding(15.dp),
|
||||
) {
|
||||
SectionTitle(
|
||||
title = stringResource(id = R.string.backend),
|
||||
padding = screenPadding,
|
||||
)
|
||||
ConfigurationToggle(
|
||||
stringResource(R.string.use_kernel),
|
||||
enabled =
|
||||
!(
|
||||
uiState.settings.isAutoTunnelEnabled ||
|
||||
uiState.settings.isAlwaysOnVpnEnabled ||
|
||||
(uiState.vpnState.status == TunnelState.UP) ||
|
||||
!kernelSupport
|
||||
),
|
||||
checked = uiState.settings.isKernelEnabled,
|
||||
padding = screenPadding,
|
||||
onCheckChanged = {
|
||||
viewModel.onToggleKernelMode()
|
||||
},
|
||||
)
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.padding(top = 5.dp),
|
||||
horizontalArrangement = Arrangement.Center,
|
||||
) {
|
||||
TextButton(
|
||||
onClick = {
|
||||
viewModel.onRequestRoot()
|
||||
},
|
||||
) {
|
||||
Text(stringResource(R.string.request_root))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Surface(
|
||||
tonalElevation = 2.dp,
|
||||
shadowElevation = 2.dp,
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
color = MaterialTheme.colorScheme.surface,
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxWidth(fillMaxWidth)
|
||||
.padding(vertical = 10.dp)
|
||||
.padding(bottom = 10.dp),
|
||||
) {
|
||||
Column(
|
||||
horizontalAlignment = Alignment.Start,
|
||||
verticalArrangement = Arrangement.Top,
|
||||
modifier = Modifier.padding(15.dp),
|
||||
) {
|
||||
SectionTitle(
|
||||
title = stringResource(id = R.string.other),
|
||||
padding = screenPadding,
|
||||
)
|
||||
if (!isRunningOnTv) {
|
||||
ConfigurationToggle(
|
||||
stringResource(R.string.always_on_vpn_support),
|
||||
enabled = !(
|
||||
uiState.settings.isTunnelOnWifiEnabled ||
|
||||
uiState.settings.isTunnelOnWifiEnabled ||
|
||||
uiState.settings.isTunnelOnMobileDataEnabled
|
||||
),
|
||||
checked = uiState.settings.isAlwaysOnVpnEnabled,
|
||||
padding = screenPadding,
|
||||
onCheckChanged = { viewModel.onToggleAlwaysOnVPN() },
|
||||
)
|
||||
ConfigurationToggle(
|
||||
stringResource(R.string.enabled_app_shortcuts),
|
||||
enabled = true,
|
||||
checked = uiState.settings.isShortcutsEnabled,
|
||||
padding = screenPadding,
|
||||
onCheckChanged = { viewModel.onToggleShortcutsEnabled() },
|
||||
)
|
||||
}
|
||||
ConfigurationToggle(
|
||||
stringResource(R.string.restart_at_boot),
|
||||
enabled = true,
|
||||
checked = uiState.settings.isRestoreOnBootEnabled,
|
||||
padding = screenPadding,
|
||||
onCheckChanged = {
|
||||
viewModel.onToggleRestartAtBoot()
|
||||
},
|
||||
)
|
||||
ConfigurationToggle(
|
||||
stringResource(R.string.enable_app_lock),
|
||||
enabled = true,
|
||||
checked = uiState.generalState.isPinLockEnabled,
|
||||
padding = screenPadding,
|
||||
onCheckChanged = {
|
||||
onClick = {
|
||||
if (uiState.generalState.isPinLockEnabled) {
|
||||
appViewModel.onPinLockDisabled()
|
||||
} else {
|
||||
// TODO may want to show a dialog before proceeding in the future
|
||||
PinManager.initialize(WireGuardAutoTunnel.instance)
|
||||
PinManager.initialize(context)
|
||||
navController.navigate(Route.Lock)
|
||||
}
|
||||
},
|
||||
)
|
||||
if (!isRunningOnTv) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.padding(top = 5.dp),
|
||||
horizontalArrangement = Arrangement.Center,
|
||||
) {
|
||||
TextButton(
|
||||
enabled = !didExportFiles,
|
||||
onClick = {
|
||||
if (uiState.tunnels.isEmpty()) return@TextButton context.showToast(R.string.tunnel_required)
|
||||
showAuthPrompt = true
|
||||
},
|
||||
) {
|
||||
Text(stringResource(R.string.export_configs))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
if (!isRunningOnTv) {
|
||||
SurfaceSelectionGroupButton(
|
||||
listOf(
|
||||
SelectionItem(
|
||||
Icons.Outlined.Code,
|
||||
title = { Text(stringResource(R.string.kernel), style = MaterialTheme.typography.bodyMedium.copy(MaterialTheme.colorScheme.onSurface)) },
|
||||
description = {
|
||||
Text(
|
||||
stringResource(R.string.use_kernel),
|
||||
style = MaterialTheme.typography.bodySmall.copy(MaterialTheme.colorScheme.outline),
|
||||
)
|
||||
},
|
||||
trailing = {
|
||||
ScaledSwitch(
|
||||
uiState.settings.isKernelEnabled,
|
||||
onClick = { viewModel.onToggleKernelMode() },
|
||||
enabled = !(
|
||||
uiState.settings.isAutoTunnelEnabled ||
|
||||
uiState.settings.isAlwaysOnVpnEnabled ||
|
||||
(uiState.vpnState.status == TunnelState.UP)
|
||||
),
|
||||
)
|
||||
},
|
||||
onClick = {
|
||||
viewModel.onToggleKernelMode()
|
||||
},
|
||||
),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
if (!isRunningOnTv) {
|
||||
SurfaceSelectionGroupButton(
|
||||
listOf(
|
||||
SelectionItem(
|
||||
Icons.Outlined.FolderZip,
|
||||
title = {
|
||||
Text(
|
||||
stringResource(R.string.export_configs),
|
||||
style = MaterialTheme.typography.bodyMedium.copy(MaterialTheme.colorScheme.onSurface),
|
||||
)
|
||||
},
|
||||
onClick = {
|
||||
if (uiState.tunnels.isEmpty()) return@SelectionItem context.showToast(R.string.tunnel_required)
|
||||
showAuthPrompt = true
|
||||
},
|
||||
),
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+15
-140
@@ -1,8 +1,7 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.screens.settings
|
||||
|
||||
import android.content.Context
|
||||
import android.location.LocationManager
|
||||
import androidx.core.location.LocationManagerCompat
|
||||
import androidx.core.content.FileProvider
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import com.wireguard.android.backend.WgQuickBackend
|
||||
@@ -10,21 +9,19 @@ import com.wireguard.android.util.RootShell
|
||||
import com.zaneschepke.wireguardautotunnel.R
|
||||
import com.zaneschepke.wireguardautotunnel.data.domain.Settings
|
||||
import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository
|
||||
import com.zaneschepke.wireguardautotunnel.module.AppShell
|
||||
import com.zaneschepke.wireguardautotunnel.module.IoDispatcher
|
||||
import com.zaneschepke.wireguardautotunnel.service.foreground.ServiceManager
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.snackbar.SnackbarController
|
||||
import com.zaneschepke.wireguardautotunnel.util.FileUtils
|
||||
import com.zaneschepke.wireguardautotunnel.util.StringValue
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.launchShareFile
|
||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||
import kotlinx.coroutines.CoroutineDispatcher
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.SharingStarted
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.stateIn
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.io.File
|
||||
import java.time.Instant
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Provider
|
||||
|
||||
@@ -33,86 +30,18 @@ class SettingsViewModel
|
||||
@Inject
|
||||
constructor(
|
||||
private val appDataRepository: AppDataRepository,
|
||||
private val rootShell: Provider<RootShell>,
|
||||
@AppShell private val rootShell: Provider<RootShell>,
|
||||
private val fileUtils: FileUtils,
|
||||
@IoDispatcher private val ioDispatcher: CoroutineDispatcher,
|
||||
) : ViewModel() {
|
||||
|
||||
private val _kernelSupport = MutableStateFlow(false)
|
||||
val kernelSupport = _kernelSupport.asStateFlow()
|
||||
private val settings = appDataRepository.settings.getSettingsFlow()
|
||||
.stateIn(viewModelScope, SharingStarted.Eagerly, Settings())
|
||||
|
||||
fun onSaveTrustedSSID(ssid: String) = viewModelScope.launch {
|
||||
val trimmed = ssid.trim()
|
||||
with(settings.value) {
|
||||
if (!trustedNetworkSSIDs.contains(trimmed)) {
|
||||
this.trustedNetworkSSIDs.add(ssid)
|
||||
appDataRepository.settings.save(this)
|
||||
} else {
|
||||
SnackbarController.showMessage(
|
||||
StringValue.StringResource(
|
||||
R.string.error_ssid_exists,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun setLocationDisclosureShown() = viewModelScope.launch {
|
||||
appDataRepository.appState.setLocationDisclosureShown(true)
|
||||
}
|
||||
|
||||
fun setBatteryOptimizeDisableShown() = viewModelScope.launch {
|
||||
appDataRepository.appState.setBatteryOptimizationDisableShown(true)
|
||||
}
|
||||
|
||||
fun onToggleTunnelOnMobileData() = viewModelScope.launch {
|
||||
with(settings.value) {
|
||||
appDataRepository.settings.save(
|
||||
copy(
|
||||
isTunnelOnMobileDataEnabled = !this.isTunnelOnMobileDataEnabled,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun onDeleteTrustedSSID(ssid: String) = viewModelScope.launch {
|
||||
with(settings.value) {
|
||||
appDataRepository.settings.save(
|
||||
copy(
|
||||
trustedNetworkSSIDs = (this.trustedNetworkSSIDs - ssid).toMutableList(),
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun exportTunnels(files: List<File>) = viewModelScope.launch {
|
||||
fileUtils.saveFilesToZip(files).onSuccess {
|
||||
SnackbarController.showMessage(StringValue.StringResource(R.string.exported_configs_message))
|
||||
}.onFailure {
|
||||
SnackbarController.showMessage(StringValue.StringResource(R.string.export_configs_failed))
|
||||
}
|
||||
}
|
||||
|
||||
fun onToggleAutoTunnel(context: Context) = viewModelScope.launch {
|
||||
with(settings.value) {
|
||||
var isAutoTunnelPaused = this.isAutoTunnelPaused
|
||||
if (isAutoTunnelEnabled) {
|
||||
ServiceManager.stopWatcherService(context)
|
||||
} else {
|
||||
ServiceManager.startWatcherService(context)
|
||||
isAutoTunnelPaused = false
|
||||
}
|
||||
appDataRepository.settings.save(
|
||||
copy(
|
||||
isAutoTunnelEnabled = !isAutoTunnelEnabled,
|
||||
isAutoTunnelPaused = isAutoTunnelPaused,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun onToggleAlwaysOnVPN() = viewModelScope.launch {
|
||||
with(settings.value) {
|
||||
appDataRepository.settings.save(
|
||||
@@ -123,24 +52,6 @@ constructor(
|
||||
}
|
||||
}
|
||||
|
||||
fun onToggleTunnelOnEthernet() = viewModelScope.launch {
|
||||
with(settings.value) {
|
||||
appDataRepository.settings.save(
|
||||
copy(
|
||||
isTunnelOnEthernetEnabled = !isTunnelOnEthernetEnabled,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun isLocationEnabled(context: Context): Boolean {
|
||||
val locationManager =
|
||||
context.getSystemService(
|
||||
Context.LOCATION_SERVICE,
|
||||
) as LocationManager
|
||||
return LocationManagerCompat.isLocationEnabled(locationManager)
|
||||
}
|
||||
|
||||
fun onToggleShortcutsEnabled() = viewModelScope.launch {
|
||||
with(settings.value) {
|
||||
appDataRepository.settings.save(
|
||||
@@ -161,33 +72,11 @@ constructor(
|
||||
}
|
||||
}
|
||||
|
||||
fun onToggleTunnelOnWifi() = viewModelScope.launch {
|
||||
with(settings.value) {
|
||||
appDataRepository.settings.save(
|
||||
copy(
|
||||
isTunnelOnWifiEnabled = !isTunnelOnWifiEnabled,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun onToggleAmnezia() = viewModelScope.launch {
|
||||
with(settings.value) {
|
||||
if (isKernelEnabled) {
|
||||
saveKernelMode(false)
|
||||
}
|
||||
appDataRepository.settings.save(
|
||||
copy(
|
||||
isAmneziaEnabled = !isAmneziaEnabled,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun onToggleKernelMode() = viewModelScope.launch {
|
||||
with(settings.value) {
|
||||
if (!isKernelEnabled) {
|
||||
requestRoot().onSuccess {
|
||||
if (!isKernelSupported()) return@onSuccess SnackbarController.showMessage(StringValue.StringResource(R.string.kernel_not_supported))
|
||||
appDataRepository.settings.save(
|
||||
copy(
|
||||
isKernelEnabled = true,
|
||||
@@ -201,23 +90,9 @@ constructor(
|
||||
}
|
||||
}
|
||||
|
||||
fun onToggleRestartOnPing() = viewModelScope.launch {
|
||||
with(settings.value) {
|
||||
appDataRepository.settings.save(
|
||||
copy(
|
||||
isPingEnabled = !isPingEnabled,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun checkKernelSupport() = viewModelScope.launch {
|
||||
val kernelSupport =
|
||||
withContext(ioDispatcher) {
|
||||
WgQuickBackend.hasKernelSupport()
|
||||
}
|
||||
_kernelSupport.update {
|
||||
kernelSupport
|
||||
private suspend fun isKernelSupported(): Boolean {
|
||||
return withContext(ioDispatcher) {
|
||||
WgQuickBackend.hasKernelSupport()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -242,16 +117,16 @@ constructor(
|
||||
}
|
||||
}
|
||||
|
||||
fun onRequestRoot() = viewModelScope.launch {
|
||||
requestRoot()
|
||||
}
|
||||
|
||||
fun exportAllConfigs() = viewModelScope.launch {
|
||||
fun exportAllConfigs(context: Context) = viewModelScope.launch {
|
||||
kotlin.runCatching {
|
||||
val shareFile = fileUtils.createNewShareFile("wg-export_${Instant.now().epochSecond}.zip")
|
||||
val tunnels = appDataRepository.tunnels.getAll()
|
||||
val wgFiles = fileUtils.createWgFiles(tunnels)
|
||||
val amFiles = fileUtils.createAmFiles(tunnels)
|
||||
exportTunnels(wgFiles + amFiles)
|
||||
val allFiles = wgFiles + amFiles
|
||||
fileUtils.zipAll(shareFile, allFiles)
|
||||
val uri = FileProvider.getUriForFile(context, context.getString(R.string.provider), shareFile)
|
||||
context.launchShareFile(uri)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.screens.settings.appearance
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.outlined.Contrast
|
||||
import androidx.compose.material.icons.outlined.Translate
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.zaneschepke.wireguardautotunnel.R
|
||||
import com.zaneschepke.wireguardautotunnel.ui.Route
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.button.surface.SelectionItem
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.button.surface.SurfaceSelectionGroupButton
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.navigation.LocalNavController
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.navigation.TopNavBar
|
||||
import com.zaneschepke.wireguardautotunnel.ui.screens.settings.components.ForwardButton
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.scaledHeight
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.scaledWidth
|
||||
|
||||
@Composable
|
||||
fun AppearanceScreen() {
|
||||
val navController = LocalNavController.current
|
||||
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopNavBar(stringResource(R.string.appearance))
|
||||
},
|
||||
) {
|
||||
Column(
|
||||
horizontalAlignment = Alignment.Start,
|
||||
verticalArrangement = Arrangement.spacedBy(24.dp.scaledHeight(), Alignment.Top),
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxSize().padding(it)
|
||||
.padding(top = 24.dp.scaledHeight())
|
||||
.padding(horizontal = 24.dp.scaledWidth()),
|
||||
) {
|
||||
SurfaceSelectionGroupButton(
|
||||
listOf(
|
||||
SelectionItem(
|
||||
Icons.Outlined.Translate,
|
||||
title = { Text(stringResource(R.string.language), style = MaterialTheme.typography.bodyMedium.copy(MaterialTheme.colorScheme.onSurface)) },
|
||||
onClick = { navController.navigate(Route.Language) },
|
||||
trailing = {
|
||||
ForwardButton { navController.navigate(Route.Language) }
|
||||
},
|
||||
),
|
||||
),
|
||||
)
|
||||
SurfaceSelectionGroupButton(
|
||||
listOf(
|
||||
SelectionItem(
|
||||
Icons.Outlined.Contrast,
|
||||
title = { Text(stringResource(R.string.display_theme), style = MaterialTheme.typography.bodyMedium.copy(MaterialTheme.colorScheme.onSurface)) },
|
||||
onClick = { navController.navigate(Route.Display) },
|
||||
trailing = {
|
||||
ForwardButton { navController.navigate(Route.Display) }
|
||||
},
|
||||
),
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.screens.settings.appearance.display
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.hilt.navigation.compose.hiltViewModel
|
||||
import com.zaneschepke.wireguardautotunnel.R
|
||||
import com.zaneschepke.wireguardautotunnel.ui.AppUiState
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.button.IconSurfaceButton
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.navigation.TopNavBar
|
||||
import com.zaneschepke.wireguardautotunnel.ui.theme.Theme
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.scaledHeight
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.scaledWidth
|
||||
|
||||
@Composable
|
||||
fun DisplayScreen(appUiState: AppUiState, viewModel: DisplayViewModel = hiltViewModel()) {
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopNavBar(stringResource(R.string.display_theme))
|
||||
},
|
||||
) {
|
||||
Column(
|
||||
horizontalAlignment = Alignment.Start,
|
||||
verticalArrangement = Arrangement.spacedBy(24.dp.scaledHeight(), Alignment.Top),
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.padding(it)
|
||||
.padding(top = 24.dp.scaledHeight())
|
||||
.padding(horizontal = 24.dp.scaledWidth()),
|
||||
) {
|
||||
IconSurfaceButton(
|
||||
title = stringResource(R.string.automatic),
|
||||
onClick = {
|
||||
viewModel.onThemeChange(Theme.AUTOMATIC)
|
||||
},
|
||||
selected = appUiState.generalState.theme == Theme.AUTOMATIC,
|
||||
)
|
||||
IconSurfaceButton(
|
||||
title = stringResource(R.string.light),
|
||||
onClick = { viewModel.onThemeChange(Theme.LIGHT) },
|
||||
selected = appUiState.generalState.theme == Theme.LIGHT,
|
||||
)
|
||||
IconSurfaceButton(
|
||||
title = stringResource(R.string.dark),
|
||||
onClick = { viewModel.onThemeChange(Theme.DARK) },
|
||||
selected = appUiState.generalState.theme == Theme.DARK,
|
||||
)
|
||||
IconSurfaceButton(
|
||||
title = stringResource(R.string.dynamic),
|
||||
onClick = { viewModel.onThemeChange(Theme.DYNAMIC) },
|
||||
selected = appUiState.generalState.theme == Theme.DYNAMIC,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.screens.settings.appearance.display
|
||||
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import com.zaneschepke.wireguardautotunnel.data.repository.AppStateRepository
|
||||
import com.zaneschepke.wireguardautotunnel.ui.theme.Theme
|
||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||
import kotlinx.coroutines.launch
|
||||
import javax.inject.Inject
|
||||
|
||||
@HiltViewModel
|
||||
class DisplayViewModel
|
||||
@Inject
|
||||
constructor(
|
||||
private val appStateRepository: AppStateRepository,
|
||||
) : ViewModel() {
|
||||
|
||||
fun onThemeChange(theme: Theme) = viewModelScope.launch {
|
||||
appStateRepository.setTheme(theme)
|
||||
}
|
||||
}
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.screens.settings.appearance.language
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.WindowInsets
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.navigationBars
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.windowInsetsPadding
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.zaneschepke.wireguardautotunnel.R
|
||||
import com.zaneschepke.wireguardautotunnel.data.datastore.LocaleStorage
|
||||
import com.zaneschepke.wireguardautotunnel.ui.Route
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.SelectedLabel
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.button.SelectionItemButton
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.navigation.LocalNavController
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.navigation.TopNavBar
|
||||
import com.zaneschepke.wireguardautotunnel.util.LocaleUtil
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.navigateAndForget
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.scaledHeight
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.scaledWidth
|
||||
import timber.log.Timber
|
||||
import java.text.Collator
|
||||
import java.util.Locale
|
||||
|
||||
@Composable
|
||||
fun LanguageScreen(localeStorage: LocaleStorage) {
|
||||
val navController = LocalNavController.current
|
||||
|
||||
val context = LocalContext.current
|
||||
|
||||
val collator = Collator.getInstance(Locale.getDefault())
|
||||
|
||||
val currentLocale = remember { mutableStateOf(LocaleUtil.OPTION_PHONE_LANGUAGE) }
|
||||
|
||||
val locales = LocaleUtil.supportedLocales.map {
|
||||
val tag = it.replace("_", "-")
|
||||
Locale.forLanguageTag(tag)
|
||||
}
|
||||
|
||||
val sortedLocales =
|
||||
remember(locales) {
|
||||
locales.sortedWith(compareBy(collator) { it.getDisplayName(it) }).toList()
|
||||
}
|
||||
|
||||
LaunchedEffect(Unit) {
|
||||
currentLocale.value = localeStorage.getPreferredLocale()
|
||||
}
|
||||
|
||||
fun onChangeLocale(locale: String) {
|
||||
Timber.d("Setting preferred locale: $locale")
|
||||
localeStorage.setPreferredLocale(locale)
|
||||
LocaleUtil.applyLocalizedContext(context, locale)
|
||||
navController.navigateAndForget(Route.Main)
|
||||
}
|
||||
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopNavBar(stringResource(R.string.language))
|
||||
},
|
||||
) {
|
||||
LazyColumn(
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.Top,
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxSize().padding(it)
|
||||
.padding(horizontal = 24.dp.scaledWidth()).windowInsetsPadding(WindowInsets.navigationBars),
|
||||
) {
|
||||
item {
|
||||
Box(modifier = Modifier.padding(top = 24.dp.scaledHeight())) {
|
||||
SelectionItemButton(
|
||||
buttonText = stringResource(R.string.automatic),
|
||||
onClick = {
|
||||
onChangeLocale(LocaleUtil.OPTION_PHONE_LANGUAGE)
|
||||
},
|
||||
trailing = {
|
||||
if (currentLocale.value == LocaleUtil.OPTION_PHONE_LANGUAGE) {
|
||||
SelectedLabel()
|
||||
}
|
||||
},
|
||||
ripple = false,
|
||||
)
|
||||
}
|
||||
}
|
||||
items(sortedLocales, key = { it }) { locale ->
|
||||
SelectionItemButton(
|
||||
buttonText = locale.getDisplayLanguage(locale).capitalize(locale) +
|
||||
if (locale.toLanguageTag().contains("-")) " (${locale.getDisplayCountry(locale).capitalize(locale)})" else "",
|
||||
onClick = {
|
||||
onChangeLocale(locale.toLanguageTag())
|
||||
},
|
||||
trailing = {
|
||||
if (locale.toLanguageTag() == currentLocale.value) {
|
||||
SelectedLabel()
|
||||
}
|
||||
},
|
||||
ripple = false,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+330
@@ -0,0 +1,330 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.screens.settings.autotunnel
|
||||
|
||||
import android.Manifest
|
||||
import android.os.Build
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.ExperimentalLayoutApi
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.WindowInsets
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.outlined.Code
|
||||
import androidx.compose.material.icons.outlined.Filter1
|
||||
import androidx.compose.material.icons.outlined.NetworkPing
|
||||
import androidx.compose.material.icons.outlined.Security
|
||||
import androidx.compose.material.icons.outlined.SettingsEthernet
|
||||
import androidx.compose.material.icons.outlined.SignalCellular4Bar
|
||||
import androidx.compose.material.icons.outlined.Wifi
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.hilt.navigation.compose.hiltViewModel
|
||||
import com.google.accompanist.permissions.ExperimentalPermissionsApi
|
||||
import com.google.accompanist.permissions.isGranted
|
||||
import com.google.accompanist.permissions.rememberPermissionState
|
||||
import com.zaneschepke.wireguardautotunnel.R
|
||||
import com.zaneschepke.wireguardautotunnel.ui.AppUiState
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.button.ScaledSwitch
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.button.surface.SelectionItem
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.button.surface.SurfaceSelectionGroupButton
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.navigation.TopNavBar
|
||||
import com.zaneschepke.wireguardautotunnel.ui.screens.settings.autotunnel.components.TrustedNetworkTextBox
|
||||
import com.zaneschepke.wireguardautotunnel.ui.screens.settings.autotunnel.components.WildcardsLabel
|
||||
import com.zaneschepke.wireguardautotunnel.ui.screens.settings.components.BackgroundLocationDialog
|
||||
import com.zaneschepke.wireguardautotunnel.ui.screens.settings.components.LearnMoreLinkLabel
|
||||
import com.zaneschepke.wireguardautotunnel.ui.screens.settings.components.LocationServicesDialog
|
||||
import com.zaneschepke.wireguardautotunnel.ui.theme.iconSize
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.isLocationServicesEnabled
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.isRunningOnTv
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.openWebUrl
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.scaledHeight
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.scaledWidth
|
||||
|
||||
@OptIn(ExperimentalPermissionsApi::class, ExperimentalLayoutApi::class)
|
||||
@Composable
|
||||
fun AutoTunnelScreen(uiState: AppUiState, viewModel: AutoTunnelViewModel = hiltViewModel()) {
|
||||
val context = LocalContext.current
|
||||
|
||||
val fineLocationState = rememberPermissionState(Manifest.permission.ACCESS_FINE_LOCATION)
|
||||
var currentText by remember { mutableStateOf("") }
|
||||
var isBackgroundLocationGranted by remember { mutableStateOf(true) }
|
||||
var showLocationServicesAlertDialog by remember { mutableStateOf(false) }
|
||||
var showLocationDialog by remember { mutableStateOf(false) }
|
||||
|
||||
fun checkFineLocationGranted() {
|
||||
isBackgroundLocationGranted = fineLocationState.status.isGranted
|
||||
}
|
||||
|
||||
fun onAutoTunnelWifiChecked() {
|
||||
if (uiState.settings.isTunnelOnWifiEnabled) viewModel.onToggleTunnelOnWifi().also { return }
|
||||
when (false) {
|
||||
isBackgroundLocationGranted -> showLocationDialog = true
|
||||
fineLocationState.status.isGranted -> showLocationDialog = true
|
||||
context.isLocationServicesEnabled() ->
|
||||
showLocationServicesAlertDialog = true
|
||||
else -> {
|
||||
viewModel.onToggleTunnelOnWifi()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P) checkFineLocationGranted()
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||
if (context.isRunningOnTv() && Build.VERSION.SDK_INT == Build.VERSION_CODES.Q) {
|
||||
checkFineLocationGranted()
|
||||
} else {
|
||||
val backgroundLocationState = rememberPermissionState(Manifest.permission.ACCESS_BACKGROUND_LOCATION)
|
||||
isBackgroundLocationGranted = backgroundLocationState.status.isGranted
|
||||
}
|
||||
}
|
||||
|
||||
LaunchedEffect(uiState.settings.trustedNetworkSSIDs) {
|
||||
currentText = ""
|
||||
}
|
||||
|
||||
LocationServicesDialog(
|
||||
showLocationServicesAlertDialog,
|
||||
onDismiss = { showLocationServicesAlertDialog = false },
|
||||
onAttest = {
|
||||
viewModel.onToggleTunnelOnWifi()
|
||||
},
|
||||
)
|
||||
|
||||
BackgroundLocationDialog(
|
||||
showLocationDialog,
|
||||
onDismiss = { showLocationDialog = false },
|
||||
onAttest = { showLocationDialog = false },
|
||||
)
|
||||
|
||||
Scaffold(
|
||||
contentWindowInsets = WindowInsets(0.dp),
|
||||
topBar = {
|
||||
TopNavBar(stringResource(R.string.auto_tunneling))
|
||||
},
|
||||
) {
|
||||
Column(
|
||||
horizontalAlignment = Alignment.Start,
|
||||
verticalArrangement = Arrangement.spacedBy(24.dp.scaledHeight(), Alignment.Top),
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.padding(it)
|
||||
.padding(top = 24.dp.scaledHeight())
|
||||
.padding(horizontal = 24.dp.scaledWidth()),
|
||||
) {
|
||||
SurfaceSelectionGroupButton(
|
||||
buildList {
|
||||
addAll(
|
||||
listOf(
|
||||
SelectionItem(
|
||||
Icons.Outlined.Wifi,
|
||||
title = {
|
||||
Text(
|
||||
stringResource(R.string.tunnel_on_wifi),
|
||||
style = MaterialTheme.typography.bodyMedium.copy(MaterialTheme.colorScheme.onSurface),
|
||||
)
|
||||
},
|
||||
description = {
|
||||
},
|
||||
trailing = {
|
||||
ScaledSwitch(
|
||||
enabled = !uiState.settings.isAlwaysOnVpnEnabled,
|
||||
checked = uiState.settings.isTunnelOnWifiEnabled,
|
||||
onClick = {
|
||||
if (uiState.settings.isWifiNameByShellEnabled) viewModel.onToggleTunnelOnWifi().also { return@ScaledSwitch }
|
||||
onAutoTunnelWifiChecked()
|
||||
},
|
||||
)
|
||||
},
|
||||
onClick = {
|
||||
if (uiState.settings.isWifiNameByShellEnabled) viewModel.onToggleTunnelOnWifi().also { return@SelectionItem }
|
||||
onAutoTunnelWifiChecked()
|
||||
},
|
||||
),
|
||||
SelectionItem(
|
||||
Icons.Outlined.Code,
|
||||
title = {
|
||||
Text(
|
||||
stringResource(R.string.wifi_name_via_shell),
|
||||
style = MaterialTheme.typography.bodyMedium.copy(MaterialTheme.colorScheme.onSurface),
|
||||
)
|
||||
},
|
||||
description = {
|
||||
Text(
|
||||
stringResource(R.string.use_root_shell_for_wifi),
|
||||
style = MaterialTheme.typography.bodySmall.copy(MaterialTheme.colorScheme.outline),
|
||||
)
|
||||
},
|
||||
trailing = {
|
||||
ScaledSwitch(
|
||||
checked = uiState.settings.isWifiNameByShellEnabled,
|
||||
onClick = {
|
||||
viewModel.onRootShellWifiToggle()
|
||||
},
|
||||
)
|
||||
},
|
||||
onClick = {
|
||||
viewModel.onRootShellWifiToggle()
|
||||
},
|
||||
),
|
||||
),
|
||||
)
|
||||
if (uiState.settings.isTunnelOnWifiEnabled) {
|
||||
addAll(
|
||||
listOf(
|
||||
SelectionItem(
|
||||
Icons.Outlined.Filter1,
|
||||
title = {
|
||||
Text(
|
||||
stringResource(R.string.use_wildcards),
|
||||
style = MaterialTheme.typography.bodyMedium.copy(MaterialTheme.colorScheme.onSurface),
|
||||
)
|
||||
},
|
||||
description = {
|
||||
LearnMoreLinkLabel({ context.openWebUrl(it) }, stringResource(id = R.string.docs_wildcards))
|
||||
},
|
||||
trailing = {
|
||||
ScaledSwitch(
|
||||
checked = uiState.settings.isWildcardsEnabled,
|
||||
onClick = {
|
||||
viewModel.onToggleWildcards()
|
||||
},
|
||||
)
|
||||
},
|
||||
onClick = {
|
||||
viewModel.onToggleWildcards()
|
||||
},
|
||||
),
|
||||
SelectionItem(
|
||||
title = {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp.scaledHeight()),
|
||||
) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier
|
||||
.weight(4f, false)
|
||||
.fillMaxWidth(),
|
||||
) {
|
||||
val icon = Icons.Outlined.Security
|
||||
Icon(
|
||||
icon,
|
||||
icon.name,
|
||||
modifier = Modifier.size(iconSize),
|
||||
)
|
||||
Column(
|
||||
horizontalAlignment = Alignment.Start,
|
||||
verticalArrangement = Arrangement.spacedBy(2.dp, Alignment.CenterVertically),
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(start = 16.dp.scaledWidth())
|
||||
.padding(vertical = 6.dp.scaledHeight()),
|
||||
) {
|
||||
Text(
|
||||
stringResource(R.string.trusted_wifi_names),
|
||||
style = MaterialTheme.typography.bodyMedium.copy(MaterialTheme.colorScheme.onSurface),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
description = {
|
||||
TrustedNetworkTextBox(
|
||||
uiState.settings.trustedNetworkSSIDs,
|
||||
onDelete = viewModel::onDeleteTrustedSSID,
|
||||
currentText = currentText,
|
||||
onSave = viewModel::onSaveTrustedSSID,
|
||||
onValueChange = { currentText = it },
|
||||
supporting = {
|
||||
if (uiState.settings.isWildcardsEnabled) {
|
||||
WildcardsLabel()
|
||||
}
|
||||
},
|
||||
)
|
||||
},
|
||||
),
|
||||
),
|
||||
)
|
||||
}
|
||||
},
|
||||
)
|
||||
SurfaceSelectionGroupButton(
|
||||
listOf(
|
||||
SelectionItem(
|
||||
Icons.Outlined.SignalCellular4Bar,
|
||||
title = {
|
||||
Text(
|
||||
stringResource(R.string.tunnel_mobile_data),
|
||||
style = MaterialTheme.typography.bodyMedium.copy(MaterialTheme.colorScheme.onSurface),
|
||||
)
|
||||
},
|
||||
trailing = {
|
||||
ScaledSwitch(
|
||||
enabled = !uiState.settings.isAlwaysOnVpnEnabled,
|
||||
checked = uiState.settings.isTunnelOnMobileDataEnabled,
|
||||
onClick = { viewModel.onToggleTunnelOnMobileData() },
|
||||
)
|
||||
},
|
||||
onClick = {
|
||||
viewModel.onToggleTunnelOnMobileData()
|
||||
},
|
||||
),
|
||||
SelectionItem(
|
||||
Icons.Outlined.SettingsEthernet,
|
||||
title = {
|
||||
Text(
|
||||
stringResource(R.string.tunnel_on_ethernet),
|
||||
style = MaterialTheme.typography.bodyMedium.copy(MaterialTheme.colorScheme.onSurface),
|
||||
)
|
||||
},
|
||||
trailing = {
|
||||
ScaledSwitch(
|
||||
enabled = !uiState.settings.isAlwaysOnVpnEnabled,
|
||||
checked = uiState.settings.isTunnelOnEthernetEnabled,
|
||||
onClick = { viewModel.onToggleTunnelOnEthernet() },
|
||||
)
|
||||
},
|
||||
onClick = {
|
||||
viewModel.onToggleTunnelOnEthernet()
|
||||
},
|
||||
),
|
||||
SelectionItem(
|
||||
Icons.Outlined.NetworkPing,
|
||||
title = {
|
||||
Text(
|
||||
stringResource(R.string.restart_on_ping),
|
||||
style = MaterialTheme.typography.bodyMedium.copy(MaterialTheme.colorScheme.onSurface),
|
||||
)
|
||||
},
|
||||
trailing = {
|
||||
ScaledSwitch(
|
||||
checked = uiState.settings.isPingEnabled,
|
||||
onClick = { viewModel.onToggleRestartOnPing() },
|
||||
)
|
||||
},
|
||||
onClick = {
|
||||
viewModel.onToggleRestartOnPing()
|
||||
},
|
||||
),
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
+131
@@ -0,0 +1,131 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.screens.settings.autotunnel
|
||||
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import com.wireguard.android.util.RootShell
|
||||
import com.zaneschepke.wireguardautotunnel.R
|
||||
import com.zaneschepke.wireguardautotunnel.data.domain.Settings
|
||||
import com.zaneschepke.wireguardautotunnel.data.repository.AppDataRepository
|
||||
import com.zaneschepke.wireguardautotunnel.module.AppShell
|
||||
import com.zaneschepke.wireguardautotunnel.module.IoDispatcher
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.snackbar.SnackbarController
|
||||
import com.zaneschepke.wireguardautotunnel.util.StringValue
|
||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||
import kotlinx.coroutines.CoroutineDispatcher
|
||||
import kotlinx.coroutines.flow.SharingStarted
|
||||
import kotlinx.coroutines.flow.stateIn
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Provider
|
||||
|
||||
@HiltViewModel
|
||||
class AutoTunnelViewModel
|
||||
@Inject
|
||||
constructor(
|
||||
private val appDataRepository: AppDataRepository,
|
||||
@AppShell private val rootShell: Provider<RootShell>,
|
||||
@IoDispatcher private val ioDispatcher: CoroutineDispatcher,
|
||||
) : ViewModel() {
|
||||
|
||||
private val settings = appDataRepository.settings.getSettingsFlow()
|
||||
.stateIn(viewModelScope, SharingStarted.Eagerly, Settings())
|
||||
|
||||
fun onToggleTunnelOnWifi() = viewModelScope.launch {
|
||||
with(settings.value) {
|
||||
appDataRepository.settings.save(
|
||||
copy(
|
||||
isTunnelOnWifiEnabled = !isTunnelOnWifiEnabled,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun onToggleTunnelOnMobileData() = viewModelScope.launch {
|
||||
with(settings.value) {
|
||||
appDataRepository.settings.save(
|
||||
copy(
|
||||
isTunnelOnMobileDataEnabled = !isTunnelOnMobileDataEnabled,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun onToggleWildcards() = viewModelScope.launch {
|
||||
with(settings.value) {
|
||||
appDataRepository.settings.save(
|
||||
copy(
|
||||
isWildcardsEnabled = !isWildcardsEnabled,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun onDeleteTrustedSSID(ssid: String) = viewModelScope.launch {
|
||||
with(settings.value) {
|
||||
appDataRepository.settings.save(
|
||||
copy(
|
||||
trustedNetworkSSIDs = (trustedNetworkSSIDs - ssid).toMutableList(),
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun onRootShellWifiToggle() = viewModelScope.launch {
|
||||
requestRoot().onSuccess {
|
||||
with(settings.value) {
|
||||
appDataRepository.settings.save(
|
||||
copy(isWifiNameByShellEnabled = !isWifiNameByShellEnabled),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun requestRoot(): Result<Unit> {
|
||||
return withContext(ioDispatcher) {
|
||||
kotlin.runCatching {
|
||||
rootShell.get().start()
|
||||
SnackbarController.showMessage(StringValue.StringResource(R.string.root_accepted))
|
||||
}.onFailure {
|
||||
SnackbarController.showMessage(StringValue.StringResource(R.string.error_root_denied))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun onToggleTunnelOnEthernet() = viewModelScope.launch {
|
||||
with(settings.value) {
|
||||
appDataRepository.settings.save(
|
||||
copy(
|
||||
isTunnelOnEthernetEnabled = !isTunnelOnEthernetEnabled,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun onSaveTrustedSSID(ssid: String) = viewModelScope.launch {
|
||||
if (ssid.isEmpty()) return@launch
|
||||
val trimmed = ssid.trim()
|
||||
with(settings.value) {
|
||||
if (!trustedNetworkSSIDs.contains(trimmed)) {
|
||||
this.trustedNetworkSSIDs.add(ssid)
|
||||
appDataRepository.settings.save(this)
|
||||
} else {
|
||||
SnackbarController.showMessage(
|
||||
StringValue.StringResource(
|
||||
R.string.error_ssid_exists,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun onToggleRestartOnPing() = viewModelScope.launch {
|
||||
with(settings.value) {
|
||||
appDataRepository.settings.save(
|
||||
copy(
|
||||
isPingEnabled = !isPingEnabled,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.screens.settings.autotunnel.components
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.ExperimentalLayoutApi
|
||||
import androidx.compose.foundation.layout.FlowRow
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.text.KeyboardActions
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.outlined.Add
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.input.ImeAction
|
||||
import androidx.compose.ui.text.input.KeyboardCapitalization
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.zaneschepke.wireguardautotunnel.R
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.ClickableIconButton
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.textbox.CustomTextField
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.isRunningOnTv
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.scaledHeight
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.scaledWidth
|
||||
|
||||
@OptIn(ExperimentalLayoutApi::class)
|
||||
@Composable
|
||||
fun TrustedNetworkTextBox(
|
||||
trustedNetworks: List<String>,
|
||||
onDelete: (ssid: String) -> Unit,
|
||||
currentText: String,
|
||||
onSave: (ssid: String) -> Unit,
|
||||
onValueChange: (network: String) -> Unit,
|
||||
supporting: @Composable () -> Unit,
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
Column(verticalArrangement = Arrangement.spacedBy(10.dp.scaledHeight())) {
|
||||
FlowRow(
|
||||
modifier =
|
||||
Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.spacedBy(5.dp, Alignment.CenterHorizontally),
|
||||
) {
|
||||
trustedNetworks.forEach { ssid ->
|
||||
ClickableIconButton(
|
||||
onClick = {
|
||||
if (context.isRunningOnTv()) {
|
||||
onDelete(ssid)
|
||||
}
|
||||
},
|
||||
onIconClick = {
|
||||
onDelete(ssid)
|
||||
},
|
||||
text = ssid,
|
||||
icon = Icons.Filled.Close,
|
||||
)
|
||||
}
|
||||
}
|
||||
CustomTextField(
|
||||
textStyle = MaterialTheme.typography.bodySmall,
|
||||
value = currentText,
|
||||
onValueChange = onValueChange,
|
||||
label = { Text(stringResource(R.string.add_wifi_name)) },
|
||||
containerColor = MaterialTheme.colorScheme.surface,
|
||||
supportingText = supporting,
|
||||
modifier =
|
||||
Modifier
|
||||
.padding(
|
||||
top = 5.dp,
|
||||
bottom = 10.dp,
|
||||
).fillMaxWidth().padding(end = 16.dp.scaledWidth()),
|
||||
singleLine = true,
|
||||
keyboardOptions =
|
||||
KeyboardOptions(
|
||||
capitalization = KeyboardCapitalization.None,
|
||||
imeAction = ImeAction.Done,
|
||||
),
|
||||
keyboardActions = KeyboardActions(onDone = { onSave(currentText) }),
|
||||
trailing = {
|
||||
if (currentText != "") {
|
||||
IconButton(onClick = {
|
||||
onSave(currentText)
|
||||
}) {
|
||||
val icon = Icons.Outlined.Add
|
||||
Icon(
|
||||
imageVector = icon,
|
||||
contentDescription = stringResource(
|
||||
R.string
|
||||
.trusted_ssid_value_description,
|
||||
),
|
||||
tint = MaterialTheme.colorScheme.primary,
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.screens.settings.autotunnel.components
|
||||
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontStyle
|
||||
import com.zaneschepke.wireguardautotunnel.R
|
||||
|
||||
@Composable
|
||||
fun WildcardsLabel() {
|
||||
Text(
|
||||
stringResource(R.string.wildcards_active),
|
||||
style = MaterialTheme.typography.bodySmall.copy(MaterialTheme.colorScheme.outline, fontStyle = FontStyle.Italic),
|
||||
)
|
||||
}
|
||||
-88
@@ -1,88 +0,0 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.screens.settings.components
|
||||
|
||||
import androidx.compose.foundation.ScrollState
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.rounded.LocationOff
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.zaneschepke.wireguardautotunnel.R
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.isRunningOnTv
|
||||
|
||||
@Composable
|
||||
fun BackgroundLocationDisclosure(onDismiss: () -> Unit, onAttest: () -> Unit, scrollState: ScrollState, focusRequester: FocusRequester) {
|
||||
val context = LocalContext.current
|
||||
Column(
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.Top,
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.verticalScroll(scrollState),
|
||||
) {
|
||||
Icon(
|
||||
Icons.Rounded.LocationOff,
|
||||
contentDescription = stringResource(id = R.string.map),
|
||||
modifier =
|
||||
Modifier
|
||||
.padding(30.dp)
|
||||
.size(128.dp),
|
||||
)
|
||||
Text(
|
||||
stringResource(R.string.prominent_background_location_title),
|
||||
textAlign = TextAlign.Center,
|
||||
modifier = Modifier.padding(30.dp),
|
||||
fontSize = 20.sp,
|
||||
)
|
||||
Text(
|
||||
stringResource(R.string.prominent_background_location_message),
|
||||
textAlign = TextAlign.Center,
|
||||
modifier = Modifier.padding(30.dp),
|
||||
fontSize = 15.sp,
|
||||
)
|
||||
Row(
|
||||
modifier =
|
||||
if (context.isRunningOnTv()) {
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(10.dp)
|
||||
} else {
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(30.dp)
|
||||
},
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.SpaceEvenly,
|
||||
) {
|
||||
TextButton(onClick = { onDismiss() }) {
|
||||
Text(stringResource(id = R.string.no_thanks))
|
||||
}
|
||||
TextButton(
|
||||
modifier = Modifier.focusRequester(focusRequester),
|
||||
onClick = {
|
||||
onAttest()
|
||||
},
|
||||
) {
|
||||
Text(stringResource(id = R.string.turn_on))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.screens.settings.components
|
||||
|
||||
import androidx.compose.foundation.focusable
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.outlined.ArrowForward
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import com.zaneschepke.wireguardautotunnel.ui.theme.iconSize
|
||||
|
||||
@Composable
|
||||
fun ForwardButton(modifier: Modifier = Modifier.focusable(), onClick: () -> Unit) {
|
||||
IconButton(
|
||||
modifier = modifier,
|
||||
onClick = onClick,
|
||||
) {
|
||||
val icon = Icons.AutoMirrored.Outlined.ArrowForward
|
||||
Icon(icon, icon.name, Modifier.size(iconSize))
|
||||
}
|
||||
}
|
||||
+3
-3
@@ -12,18 +12,18 @@ import androidx.compose.ui.text.withStyle
|
||||
import com.zaneschepke.wireguardautotunnel.R
|
||||
|
||||
@Composable
|
||||
fun WildcardSupportingLabel(onClick: (url: String) -> Unit) {
|
||||
fun LearnMoreLinkLabel(onClick: (url: String) -> Unit, url: String) {
|
||||
// TODO update link when docs are fully updated
|
||||
val gettingStarted =
|
||||
buildAnnotatedString {
|
||||
pushStringAnnotation(
|
||||
tag = "details",
|
||||
annotation = stringResource(id = R.string.docs_wildcards),
|
||||
annotation = url,
|
||||
)
|
||||
withStyle(
|
||||
style = SpanStyle(color = MaterialTheme.colorScheme.primary),
|
||||
) {
|
||||
append(stringResource(id = R.string.wildcard_supported))
|
||||
append(stringResource(id = R.string.learn_more))
|
||||
}
|
||||
pop()
|
||||
}
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.screens.settings.disclosure
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.outlined.LocationOn
|
||||
import androidx.compose.material.icons.rounded.PermScanWifi
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.zaneschepke.wireguardautotunnel.R
|
||||
import com.zaneschepke.wireguardautotunnel.ui.AppUiState
|
||||
import com.zaneschepke.wireguardautotunnel.ui.AppViewModel
|
||||
import com.zaneschepke.wireguardautotunnel.ui.Route
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.button.surface.SelectionItem
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.button.surface.SurfaceSelectionGroupButton
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.navigation.LocalNavController
|
||||
import com.zaneschepke.wireguardautotunnel.ui.screens.settings.components.ForwardButton
|
||||
import com.zaneschepke.wireguardautotunnel.ui.theme.topPadding
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.goFromRoot
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.launchAppSettings
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.scaledHeight
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.scaledWidth
|
||||
|
||||
@Composable
|
||||
fun LocationDisclosureScreen(appViewModel: AppViewModel, appUiState: AppUiState) {
|
||||
val context = LocalContext.current
|
||||
val navController = LocalNavController.current
|
||||
|
||||
LaunchedEffect(Unit, appUiState) {
|
||||
if (appUiState.generalState.isLocationDisclosureShown) navController.goFromRoot(Route.AutoTunnel)
|
||||
}
|
||||
|
||||
Column(
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.spacedBy(24.dp.scaledHeight(), Alignment.Top),
|
||||
modifier =
|
||||
Modifier.fillMaxSize().padding(top = topPadding).padding(horizontal = 24.dp.scaledWidth()),
|
||||
) {
|
||||
val icon = Icons.Rounded.PermScanWifi
|
||||
Icon(
|
||||
icon,
|
||||
contentDescription = icon.name,
|
||||
modifier = Modifier
|
||||
.padding(30.dp.scaledHeight())
|
||||
.size(128.dp.scaledHeight()),
|
||||
)
|
||||
Text(
|
||||
stringResource(R.string.prominent_background_location_title),
|
||||
style = MaterialTheme.typography.titleLarge.copy(fontWeight = FontWeight.Bold),
|
||||
)
|
||||
Text(
|
||||
stringResource(R.string.prominent_background_location_message),
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
)
|
||||
SurfaceSelectionGroupButton(
|
||||
listOf(
|
||||
SelectionItem(
|
||||
Icons.Outlined.LocationOn,
|
||||
title = {
|
||||
Text(
|
||||
stringResource(R.string.launch_app_settings),
|
||||
style = MaterialTheme.typography.bodyLarge.copy(MaterialTheme.colorScheme.onSurface),
|
||||
)
|
||||
},
|
||||
onClick = {
|
||||
context.launchAppSettings().also {
|
||||
appViewModel.setLocationDisclosureShown()
|
||||
}
|
||||
},
|
||||
trailing = {
|
||||
ForwardButton {
|
||||
context.launchAppSettings().also {
|
||||
appViewModel.setLocationDisclosureShown()
|
||||
}
|
||||
}
|
||||
},
|
||||
),
|
||||
),
|
||||
)
|
||||
SurfaceSelectionGroupButton(
|
||||
listOf(
|
||||
SelectionItem(
|
||||
title = { Text(stringResource(R.string.skip), style = MaterialTheme.typography.bodyLarge.copy(MaterialTheme.colorScheme.onSurface)) },
|
||||
onClick = { appViewModel.setLocationDisclosureShown() },
|
||||
trailing = {
|
||||
ForwardButton { appViewModel.setLocationDisclosureShown() }
|
||||
},
|
||||
),
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
+113
-267
@@ -1,309 +1,155 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.screens.support
|
||||
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.focusable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.IntrinsicSize
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.rounded.ArrowForward
|
||||
import androidx.compose.material.icons.rounded.Book
|
||||
import androidx.compose.material.icons.rounded.FormatListNumbered
|
||||
import androidx.compose.material.icons.rounded.Mail
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material.icons.filled.Book
|
||||
import androidx.compose.material.icons.filled.LineStyle
|
||||
import androidx.compose.material.icons.filled.Mail
|
||||
import androidx.compose.material.icons.filled.Policy
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.res.vectorResource
|
||||
import androidx.compose.ui.text.TextStyle
|
||||
import androidx.compose.ui.text.buildAnnotatedString
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.text.style.TextDecoration
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.navigation.NavController
|
||||
import com.zaneschepke.wireguardautotunnel.BuildConfig
|
||||
import com.zaneschepke.wireguardautotunnel.R
|
||||
import com.zaneschepke.wireguardautotunnel.ui.AppUiState
|
||||
import com.zaneschepke.wireguardautotunnel.ui.Route
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.isRunningOnTv
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.button.surface.SelectionItem
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.button.surface.SurfaceSelectionGroupButton
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.label.GroupLabel
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.label.VersionLabel
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.navigation.LocalNavController
|
||||
import com.zaneschepke.wireguardautotunnel.ui.screens.settings.components.ForwardButton
|
||||
import com.zaneschepke.wireguardautotunnel.ui.theme.topPadding
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.launchSupportEmail
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.openWebUrl
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.scaledHeight
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.scaledWidth
|
||||
|
||||
@Composable
|
||||
fun SupportScreen(navController: NavController, focusRequester: FocusRequester, appUiState: AppUiState) {
|
||||
fun SupportScreen() {
|
||||
val context = LocalContext.current
|
||||
val fillMaxWidth = .85f
|
||||
val navController = LocalNavController.current
|
||||
|
||||
Column(
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.Top,
|
||||
horizontalAlignment = Alignment.Start,
|
||||
verticalArrangement = Arrangement.spacedBy(24.dp.scaledHeight(), Alignment.Top),
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.verticalScroll(rememberScrollState())
|
||||
.focusable(),
|
||||
.padding(top = topPadding)
|
||||
.padding(horizontal = 24.dp.scaledWidth()),
|
||||
) {
|
||||
Surface(
|
||||
tonalElevation = 2.dp,
|
||||
shadowElevation = 2.dp,
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
color = MaterialTheme.colorScheme.surface,
|
||||
modifier =
|
||||
(
|
||||
if (context.isRunningOnTv()) {
|
||||
Modifier
|
||||
.height(IntrinsicSize.Min)
|
||||
.fillMaxWidth(fillMaxWidth)
|
||||
.padding(top = 10.dp)
|
||||
} else {
|
||||
Modifier
|
||||
.fillMaxWidth(fillMaxWidth)
|
||||
.padding(top = 20.dp)
|
||||
}
|
||||
)
|
||||
.padding(bottom = 25.dp),
|
||||
) {
|
||||
Column(modifier = Modifier.padding(20.dp)) {
|
||||
val forwardIcon = Icons.AutoMirrored.Rounded.ArrowForward
|
||||
Text(
|
||||
stringResource(R.string.thank_you),
|
||||
textAlign = TextAlign.Start,
|
||||
fontWeight = FontWeight.Bold,
|
||||
modifier = Modifier.padding(bottom = 20.dp),
|
||||
fontSize = 16.sp,
|
||||
)
|
||||
Text(
|
||||
stringResource(id = R.string.support_help_text),
|
||||
textAlign = TextAlign.Start,
|
||||
fontSize = 16.sp,
|
||||
modifier = Modifier.padding(bottom = 20.dp),
|
||||
)
|
||||
TextButton(
|
||||
onClick = {
|
||||
context.openWebUrl(
|
||||
context.resources.getString(R.string.docs_url),
|
||||
GroupLabel(stringResource(R.string.thank_you))
|
||||
SurfaceSelectionGroupButton(
|
||||
listOf(
|
||||
SelectionItem(
|
||||
Icons.Filled.Book,
|
||||
title = {
|
||||
Text(
|
||||
stringResource(R.string.docs_description),
|
||||
style = MaterialTheme.typography.bodyMedium.copy(MaterialTheme.colorScheme.onSurface),
|
||||
)
|
||||
},
|
||||
modifier =
|
||||
Modifier
|
||||
.padding(vertical = 5.dp)
|
||||
.focusRequester(focusRequester),
|
||||
) {
|
||||
Row(
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Row {
|
||||
val icon = Icons.Rounded.Book
|
||||
Icon(icon, icon.name)
|
||||
Text(
|
||||
stringResource(id = R.string.docs_description),
|
||||
textAlign = TextAlign.Justify,
|
||||
modifier =
|
||||
Modifier
|
||||
.padding(start = 10.dp)
|
||||
.weight(
|
||||
weight = 1.0f,
|
||||
fill = false,
|
||||
),
|
||||
softWrap = true,
|
||||
)
|
||||
}
|
||||
Icon(
|
||||
forwardIcon,
|
||||
forwardIcon.name,
|
||||
)
|
||||
}
|
||||
}
|
||||
HorizontalDivider(
|
||||
thickness = 0.5.dp,
|
||||
color = MaterialTheme.colorScheme.onBackground,
|
||||
)
|
||||
TextButton(
|
||||
trailing = {
|
||||
ForwardButton { context.openWebUrl(context.getString(R.string.docs_url)) }
|
||||
},
|
||||
onClick = {
|
||||
context.openWebUrl(
|
||||
context.resources.getString(R.string.telegram_url),
|
||||
context.openWebUrl(context.getString(R.string.docs_url))
|
||||
},
|
||||
),
|
||||
SelectionItem(
|
||||
Icons.Filled.LineStyle,
|
||||
title = {
|
||||
Text(
|
||||
stringResource(R.string.read_logs),
|
||||
style = MaterialTheme.typography.bodyMedium.copy(MaterialTheme.colorScheme.onSurface),
|
||||
)
|
||||
},
|
||||
modifier = Modifier.padding(vertical = 5.dp),
|
||||
) {
|
||||
Row(
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Row {
|
||||
val icon = ImageVector.vectorResource(R.drawable.telegram)
|
||||
Icon(
|
||||
icon,
|
||||
icon.name,
|
||||
Modifier.size(25.dp),
|
||||
)
|
||||
Text(
|
||||
stringResource(id = R.string.chat_description),
|
||||
textAlign = TextAlign.Justify,
|
||||
modifier = Modifier.padding(start = 10.dp),
|
||||
)
|
||||
trailing = {
|
||||
ForwardButton {
|
||||
navController.navigate(Route.Logs)
|
||||
}
|
||||
Icon(
|
||||
forwardIcon,
|
||||
forwardIcon.name,
|
||||
)
|
||||
}
|
||||
}
|
||||
HorizontalDivider(
|
||||
thickness = 0.5.dp,
|
||||
color = MaterialTheme.colorScheme.onBackground,
|
||||
)
|
||||
TextButton(
|
||||
},
|
||||
onClick = {
|
||||
context.openWebUrl(
|
||||
context.resources.getString(R.string.github_url),
|
||||
navController.navigate(Route.Logs)
|
||||
},
|
||||
),
|
||||
SelectionItem(
|
||||
Icons.Filled.Policy,
|
||||
title = {
|
||||
Text(
|
||||
stringResource(R.string.privacy_policy),
|
||||
style = MaterialTheme.typography.bodyMedium.copy(MaterialTheme.colorScheme.onSurface),
|
||||
)
|
||||
},
|
||||
modifier = Modifier.padding(vertical = 5.dp),
|
||||
) {
|
||||
Row(
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Row {
|
||||
val icon = ImageVector.vectorResource(R.drawable.github)
|
||||
Icon(
|
||||
imageVector = icon,
|
||||
icon.name,
|
||||
Modifier.size(25.dp),
|
||||
)
|
||||
Text(
|
||||
stringResource(id = R.string.open_issue),
|
||||
textAlign = TextAlign.Justify,
|
||||
modifier = Modifier.padding(start = 10.dp),
|
||||
)
|
||||
}
|
||||
Icon(
|
||||
forwardIcon,
|
||||
forwardIcon.name,
|
||||
)
|
||||
}
|
||||
}
|
||||
HorizontalDivider(
|
||||
thickness = 0.5.dp,
|
||||
color = MaterialTheme.colorScheme.onBackground,
|
||||
)
|
||||
TextButton(
|
||||
onClick = { context.launchSupportEmail() },
|
||||
modifier = Modifier.padding(vertical = 5.dp),
|
||||
) {
|
||||
Row(
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Row {
|
||||
val icon = Icons.Rounded.Mail
|
||||
Icon(icon, icon.name)
|
||||
Text(
|
||||
stringResource(id = R.string.email_description),
|
||||
textAlign = TextAlign.Justify,
|
||||
modifier = Modifier.padding(start = 10.dp),
|
||||
)
|
||||
}
|
||||
Icon(
|
||||
forwardIcon,
|
||||
forwardIcon.name,
|
||||
)
|
||||
}
|
||||
}
|
||||
if (!context.isRunningOnTv()) {
|
||||
HorizontalDivider(
|
||||
thickness = 0.5.dp,
|
||||
color = MaterialTheme.colorScheme.onBackground,
|
||||
)
|
||||
TextButton(
|
||||
onClick = { navController.navigate(Route.Logs) },
|
||||
modifier = Modifier.padding(vertical = 5.dp),
|
||||
) {
|
||||
Row(
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Row {
|
||||
val icon = Icons.Rounded.FormatListNumbered
|
||||
Icon(icon, icon.name)
|
||||
Text(
|
||||
stringResource(id = R.string.read_logs),
|
||||
textAlign = TextAlign.Justify,
|
||||
modifier = Modifier.padding(start = 10.dp),
|
||||
)
|
||||
}
|
||||
Icon(
|
||||
Icons.AutoMirrored.Rounded.ArrowForward,
|
||||
stringResource(id = R.string.go),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Spacer(modifier = Modifier.weight(1f))
|
||||
Text(
|
||||
stringResource(id = R.string.privacy_policy),
|
||||
style = TextStyle(textDecoration = TextDecoration.Underline),
|
||||
fontSize = 16.sp,
|
||||
modifier =
|
||||
Modifier.clickable {
|
||||
context.openWebUrl(
|
||||
context.resources.getString(R.string.privacy_policy_url),
|
||||
)
|
||||
},
|
||||
trailing = {
|
||||
ForwardButton { context.openWebUrl(context.getString(R.string.privacy_policy_url)) }
|
||||
},
|
||||
onClick = {
|
||||
context.openWebUrl(context.getString(R.string.privacy_policy_url))
|
||||
},
|
||||
),
|
||||
|
||||
),
|
||||
)
|
||||
Row(
|
||||
horizontalArrangement = Arrangement.spacedBy(25.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.padding(25.dp),
|
||||
) {
|
||||
val version =
|
||||
buildAnnotatedString {
|
||||
append(stringResource(id = R.string.version))
|
||||
append(": ")
|
||||
append(BuildConfig.VERSION_NAME)
|
||||
}
|
||||
val mode =
|
||||
buildAnnotatedString {
|
||||
append(stringResource(R.string.mode))
|
||||
append(": ")
|
||||
when (appUiState.settings.isKernelEnabled) {
|
||||
true -> append(stringResource(id = R.string.kernel))
|
||||
false -> append(stringResource(id = R.string.userspace))
|
||||
}
|
||||
}
|
||||
Text(version.text, modifier = Modifier.focusable())
|
||||
Text(mode.text)
|
||||
}
|
||||
SurfaceSelectionGroupButton(
|
||||
listOf(
|
||||
SelectionItem(
|
||||
ImageVector.vectorResource(R.drawable.telegram),
|
||||
title = {
|
||||
Text(
|
||||
stringResource(R.string.chat_description),
|
||||
style = MaterialTheme.typography.bodyMedium.copy(MaterialTheme.colorScheme.onSurface),
|
||||
)
|
||||
},
|
||||
trailing = {
|
||||
ForwardButton {
|
||||
context.openWebUrl(context.getString(R.string.telegram_url))
|
||||
}
|
||||
},
|
||||
onClick = {
|
||||
context.openWebUrl(context.getString(R.string.telegram_url))
|
||||
},
|
||||
),
|
||||
SelectionItem(
|
||||
ImageVector.vectorResource(R.drawable.github),
|
||||
title = { Text(stringResource(R.string.open_issue), style = MaterialTheme.typography.bodyMedium.copy(MaterialTheme.colorScheme.onSurface)) },
|
||||
trailing = {
|
||||
ForwardButton {
|
||||
context.openWebUrl(context.getString(R.string.github_url))
|
||||
}
|
||||
},
|
||||
onClick = {
|
||||
context.openWebUrl(context.getString(R.string.github_url))
|
||||
},
|
||||
),
|
||||
SelectionItem(
|
||||
Icons.Filled.Mail,
|
||||
title = {
|
||||
Text(
|
||||
stringResource(R.string.email_description),
|
||||
style = MaterialTheme.typography.bodyMedium.copy(MaterialTheme.colorScheme.onSurface),
|
||||
)
|
||||
},
|
||||
trailing = {
|
||||
ForwardButton {
|
||||
context.launchSupportEmail()
|
||||
}
|
||||
},
|
||||
onClick = {
|
||||
context.launchSupportEmail()
|
||||
},
|
||||
),
|
||||
),
|
||||
)
|
||||
VersionLabel()
|
||||
}
|
||||
}
|
||||
|
||||
+43
-21
@@ -1,7 +1,5 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.screens.support.logs
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.widget.Toast
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
@@ -13,7 +11,7 @@ import androidx.compose.foundation.lazy.itemsIndexed
|
||||
import androidx.compose.foundation.lazy.rememberLazyListState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Save
|
||||
import androidx.compose.material.icons.filled.Share
|
||||
import androidx.compose.material3.FloatingActionButton
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
@@ -21,14 +19,19 @@ import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.runtime.snapshotFlow
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.platform.ClipboardManager
|
||||
import androidx.compose.ui.platform.LocalClipboardManager
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.AnnotatedString
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.dp
|
||||
@@ -36,44 +39,63 @@ import androidx.compose.ui.unit.sp
|
||||
import androidx.hilt.navigation.compose.hiltViewModel
|
||||
import com.zaneschepke.logcatter.model.LogMessage
|
||||
import com.zaneschepke.wireguardautotunnel.R
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.navigation.TopNavBar
|
||||
import com.zaneschepke.wireguardautotunnel.ui.common.text.LogTypeLabel
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
|
||||
@Composable
|
||||
fun LogsScreen(viewModel: LogsViewModel = hiltViewModel()) {
|
||||
val logs = viewModel.logs
|
||||
|
||||
val context = LocalContext.current
|
||||
val clipboardManager: ClipboardManager = LocalClipboardManager.current
|
||||
|
||||
val lazyColumnListState = rememberLazyListState()
|
||||
val clipboardManager: ClipboardManager = LocalClipboardManager.current
|
||||
val scope = rememberCoroutineScope()
|
||||
var isAutoScrolling by remember { mutableStateOf(true) }
|
||||
var lastScrollPosition by remember { mutableIntStateOf(0) }
|
||||
|
||||
LaunchedEffect(logs.size) {
|
||||
scope.launch {
|
||||
LaunchedEffect(isAutoScrolling) {
|
||||
if (isAutoScrolling) {
|
||||
lazyColumnListState.animateScrollToItem(logs.size)
|
||||
}
|
||||
}
|
||||
|
||||
LaunchedEffect(logs.size) {
|
||||
if (isAutoScrolling) {
|
||||
lazyColumnListState.animateScrollToItem(logs.size)
|
||||
}
|
||||
}
|
||||
|
||||
LaunchedEffect(lazyColumnListState) {
|
||||
snapshotFlow { lazyColumnListState.firstVisibleItemIndex }
|
||||
.collect { currentScrollPosition ->
|
||||
if (currentScrollPosition < lastScrollPosition && isAutoScrolling) {
|
||||
isAutoScrolling = false
|
||||
}
|
||||
val visible = lazyColumnListState.layoutInfo.visibleItemsInfo
|
||||
if (visible.isNotEmpty()) {
|
||||
if (visible.last().index
|
||||
== lazyColumnListState.layoutInfo.totalItemsCount - 1 && !isAutoScrolling
|
||||
) {
|
||||
isAutoScrolling = true
|
||||
}
|
||||
}
|
||||
lastScrollPosition = currentScrollPosition
|
||||
}
|
||||
}
|
||||
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopNavBar(stringResource(R.string.logs))
|
||||
},
|
||||
floatingActionButton = {
|
||||
FloatingActionButton(
|
||||
onClick = {
|
||||
scope.launch {
|
||||
viewModel.saveLogsToFile().onSuccess {
|
||||
Toast.makeText(
|
||||
context,
|
||||
context.getString(R.string.logs_saved),
|
||||
Toast.LENGTH_SHORT,
|
||||
).show()
|
||||
}
|
||||
}
|
||||
viewModel.shareLogs(context)
|
||||
},
|
||||
shape = RoundedCornerShape(16.dp),
|
||||
containerColor = MaterialTheme.colorScheme.primary,
|
||||
) {
|
||||
val icon = Icons.Filled.Save
|
||||
val icon = Icons.Filled.Share
|
||||
Icon(
|
||||
imageVector = icon,
|
||||
contentDescription = icon.name,
|
||||
@@ -89,7 +111,7 @@ fun LogsScreen(viewModel: LogsViewModel = hiltViewModel()) {
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.padding(horizontal = 24.dp),
|
||||
.padding(horizontal = 24.dp).padding(it),
|
||||
) {
|
||||
itemsIndexed(
|
||||
logs,
|
||||
|
||||
+17
-10
@@ -1,19 +1,25 @@
|
||||
package com.zaneschepke.wireguardautotunnel.ui.screens.support.logs
|
||||
|
||||
import android.content.Context
|
||||
import androidx.compose.runtime.mutableStateListOf
|
||||
import androidx.core.content.FileProvider
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import com.zaneschepke.logcatter.LocalLogCollector
|
||||
import com.zaneschepke.logcatter.LogReader
|
||||
import com.zaneschepke.logcatter.model.LogMessage
|
||||
import com.zaneschepke.wireguardautotunnel.R
|
||||
import com.zaneschepke.wireguardautotunnel.module.IoDispatcher
|
||||
import com.zaneschepke.wireguardautotunnel.module.MainDispatcher
|
||||
import com.zaneschepke.wireguardautotunnel.util.Constants
|
||||
import com.zaneschepke.wireguardautotunnel.util.FileUtils
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.chunked
|
||||
import com.zaneschepke.wireguardautotunnel.util.extensions.launchShareFile
|
||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||
import kotlinx.coroutines.CoroutineDispatcher
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import timber.log.Timber
|
||||
import java.time.Duration
|
||||
import java.time.Instant
|
||||
import javax.inject.Inject
|
||||
@@ -22,7 +28,7 @@ import javax.inject.Inject
|
||||
class LogsViewModel
|
||||
@Inject
|
||||
constructor(
|
||||
private val localLogCollector: LocalLogCollector,
|
||||
private val localLogCollector: LogReader,
|
||||
private val fileUtils: FileUtils,
|
||||
@IoDispatcher private val ioDispatcher: CoroutineDispatcher,
|
||||
@MainDispatcher private val mainDispatcher: CoroutineDispatcher,
|
||||
@@ -44,13 +50,14 @@ constructor(
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun saveLogsToFile(): Result<Unit> {
|
||||
val file =
|
||||
localLogCollector.getLogFile().getOrElse {
|
||||
return Result.failure(it)
|
||||
}
|
||||
val fileContent = fileUtils.readBytesFromFile(file)
|
||||
val fileName = "${Constants.BASE_LOG_FILE_NAME}-${Instant.now().epochSecond}.txt"
|
||||
return fileUtils.saveByteArrayToDownloads(fileContent, fileName)
|
||||
fun shareLogs(context: Context): Job = viewModelScope.launch(ioDispatcher) {
|
||||
runCatching {
|
||||
val file = fileUtils.createNewShareFile("${Constants.BASE_LOG_FILE_NAME}-${Instant.now().epochSecond}.zip")
|
||||
localLogCollector.zipLogFiles(file.absolutePath)
|
||||
val uri = FileProvider.getUriForFile(context, context.getString(R.string.provider), file)
|
||||
context.launchShareFile(uri)
|
||||
}.onFailure {
|
||||
Timber.e(it)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,17 +2,37 @@ package com.zaneschepke.wireguardautotunnel.ui.theme
|
||||
|
||||
import androidx.compose.ui.graphics.Color
|
||||
|
||||
val Purple80 = Color(0xFFD0BCFF)
|
||||
val PurpleGrey80 = Color(0xFFCCC2DC)
|
||||
val Pink80 = Color(0xFF492532)
|
||||
val virdigris = Color(0xFF5BC0BE)
|
||||
val OffWhite = Color(0xFFE5E1E5)
|
||||
val LightGrey = Color(0xFFCAC4D0)
|
||||
val Aqua = Color(0xFF76BEBD)
|
||||
val SilverTree = Color(0xFF6DB58B)
|
||||
val Plantation = Color(0xFF264A49)
|
||||
val Shark = Color(0xFF21272A)
|
||||
val BalticSea = Color(0xFF1C1B1F)
|
||||
val Brick = Color(0xFFCE4257)
|
||||
val Straw = Color(0xFFD4C483)
|
||||
|
||||
val Purple40 = Color(0xFF6650a4)
|
||||
val PurpleGrey40 = Color(0xFF625b71)
|
||||
val Pink40 = Color(0xFFFFFFFF)
|
||||
sealed class ThemeColors(
|
||||
val background: Color,
|
||||
val surface: Color,
|
||||
val primary: Color,
|
||||
val secondary: Color,
|
||||
val onSurface: Color,
|
||||
) {
|
||||
|
||||
// status colors
|
||||
val brickRed = Color(0xFFCE4257)
|
||||
val corn = Color(0xFFFBEC5D)
|
||||
val pinkRed = Color(0xFFEF476F)
|
||||
val mint = Color(0xFF52B788)
|
||||
data object Light : ThemeColors(
|
||||
background = LightGrey,
|
||||
surface = OffWhite,
|
||||
primary = Plantation,
|
||||
secondary = OffWhite,
|
||||
onSurface = BalticSea,
|
||||
)
|
||||
|
||||
data object Dark : ThemeColors(
|
||||
background = BalticSea,
|
||||
surface = Shark,
|
||||
primary = Aqua,
|
||||
secondary = Plantation,
|
||||
onSurface = OffWhite,
|
||||
)
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user