feat(widget): виджет запуска прокси с dynamic-цветами и потоками

Плитка на домашний экран: статус, активный сервер + потоки, кнопка
play/stop через ProxyReceiver. Material You (system_* с фолбэком <31),
перерисовка из App-scope collector по isRunning/статистике/серверу.
This commit is contained in:
samosvalishe committed 2026-07-03 13:49:58 +03:00
1 parent adec486bbb
commit ea19c091b2
11 files changed
+298 -2

No files matched your search

+12
View File
@@ -115,6 +115,18 @@
android:name=".service.ProxyReceiver"
android:exported="false" />
<receiver
android:name=".service.ProxyWidgetProvider"
android:exported="true"
android:label="@string/widget_label">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="@xml/proxy_widget_info" />
</receiver>
<service
android:name=".service.ProxyTileService"
android:exported="true"
+32 -1
View File
@@ -1,12 +1,27 @@
package com.freeturn.app
import android.app.Application
import com.freeturn.app.data.AppPreferences
import com.freeturn.app.di.appModule
import com.freeturn.app.domain.proxy.ProxyServiceState
import com.freeturn.app.service.ProxyWidgetProvider
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import org.koin.android.ext.android.inject
import org.koin.android.ext.koin.androidContext
import org.koin.android.ext.koin.androidLogger
import org.koin.core.context.startKoin
import com.freeturn.app.di.appModule
class App : Application() {
private val appPreferences: AppPreferences by inject()
private val scope = CoroutineScope(Dispatchers.Main + SupervisorJob())
override fun onCreate() {
super.onCreate()
// ed25519/curve25519 работает через Bouncy Castle в classpath. jsch 2.x подхватывает его сам.
@@ -15,5 +30,21 @@ class App : Application() {
androidContext(this@App)
modules(appModule)
}
observeWidgetState()
}
// Перерисовывает виджет при смене статуса прокси или активного сервера
// (RemoteViews не реактивны - их надо толкать вручную).
private fun observeWidgetState() {
combine(
ProxyServiceState.isRunning,
ProxyServiceState.connectionStats,
appPreferences.serversSnapshot
) { running, stats, snap ->
listOf(running, stats.active, stats.total, snap.active?.name)
}
.distinctUntilChanged()
.onEach { ProxyWidgetProvider.refresh(this) }
.launchIn(scope)
}
}
@@ -0,0 +1,131 @@
package com.freeturn.app.service
import android.app.PendingIntent
import android.appwidget.AppWidgetManager
import android.appwidget.AppWidgetProvider
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.widget.RemoteViews
import com.freeturn.app.MainActivity
import com.freeturn.app.R
import com.freeturn.app.data.AppPreferences
import com.freeturn.app.domain.proxy.ProxyServiceState
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import org.koin.core.component.KoinComponent
import org.koin.core.component.inject
/**
* Виджет домашнего экрана: статус прокси + имя активного сервера + кнопка-тумблер.
* RemoteViews не реактивны - перерисовку двигает [refresh] из App-scope collector'а
* (смена isRunning или активного сервера), плюс системный onUpdate при добавлении/ребуте.
*/
class ProxyWidgetProvider : AppWidgetProvider(), KoinComponent {
private val appPreferences: AppPreferences by inject()
override fun onUpdate(context: Context, manager: AppWidgetManager, ids: IntArray) {
// goAsync: чтение имени сервера из DataStore асинхронно, держим процесс живым.
val pending = goAsync()
CoroutineScope(Dispatchers.Main + SupervisorJob()).launch {
try {
val serverName = appPreferences.serversSnapshot.first().active?.name
val views = buildViews(context, ProxyServiceState.isRunning.value, serverName)
manager.updateAppWidget(ids, views)
} finally {
pending.finish()
}
}
}
companion object {
fun refresh(context: Context) {
val manager = AppWidgetManager.getInstance(context)
val ids = manager.getAppWidgetIds(
ComponentName(context, ProxyWidgetProvider::class.java)
)
if (ids.isEmpty()) return
context.sendBroadcast(
Intent(context, ProxyWidgetProvider::class.java)
.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE)
.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids)
)
}
private fun buildViews(
context: Context,
running: Boolean,
serverName: String?
): RemoteViews {
val views = RemoteViews(context.packageName, R.layout.widget_proxy)
// Прокси стартует не мгновенно: active>0 = каналы подняты, иначе ещё коннектится.
val stats = ProxyServiceState.connectionStats.value
val connecting = running && stats.active == 0
val statusRes = when {
!running -> R.string.widget_status_off
connecting -> R.string.widget_status_connecting
else -> R.string.widget_status_on
}
views.setTextViewText(R.id.widget_status_text, context.getString(statusRes))
// Потоки в подзаголовке рядом с сервером: "Amsterdam · 3/12" (формат главного экрана).
val counts = when {
!running -> null
stats.total > 0 -> "${stats.active}/${stats.total}"
else -> stats.active.toString()
}
val subtitle = listOfNotNull(
serverName ?: context.getString(R.string.widget_server_none),
counts
).joinToString(" · ")
views.setTextViewText(R.id.widget_server_name, subtitle)
// nearby-иконка кодирует статус тоном динамической палитры.
val statusColor = when {
!running -> R.color.widget_outline
connecting -> R.color.widget_tertiary
else -> R.color.widget_primary
}
views.setInt(R.id.widget_status_icon, "setColorFilter", context.getColor(statusColor))
// Кнопка play/stop - тон primary, состояние читается формой иконки.
views.setInt(R.id.widget_toggle, "setColorFilter", context.getColor(R.color.widget_primary))
if (running) {
views.setImageViewResource(R.id.widget_toggle, R.drawable.stop_24px)
views.setContentDescription(R.id.widget_toggle, context.getString(R.string.widget_action_stop))
} else {
views.setImageViewResource(R.id.widget_toggle, R.drawable.play_arrow_24px)
views.setContentDescription(R.id.widget_toggle, context.getString(R.string.widget_action_start))
}
val toggleAction = if (running) ProxyActions.STOP else ProxyActions.START
views.setOnClickPendingIntent(
R.id.widget_toggle,
PendingIntent.getBroadcast(
context,
if (running) 1 else 2,
Intent(context, ProxyReceiver::class.java).setAction(toggleAction),
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
)
views.setOnClickPendingIntent(
R.id.widget_body,
PendingIntent.getActivity(
context,
0,
Intent(context, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
)
return views
}
}
}
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="@color/widget_surface" />
<corners android:radius="24dp" />
</shape>
+57
View File
@@ -0,0 +1,57 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/widget_body"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:gravity="center_vertical"
android:background="@drawable/widget_background"
android:paddingHorizontal="14dp"
android:paddingVertical="10dp">
<ImageView
android:id="@+id/widget_status_icon"
android:layout_width="36dp"
android:layout_height="36dp"
android:src="@drawable/ic_qs_tile_nearby"
android:contentDescription="@null" />
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_marginStart="12dp"
android:orientation="vertical">
<TextView
android:id="@+id/widget_status_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:textSize="15sp"
android:textColor="@color/widget_on_surface"
android:maxLines="1"
android:ellipsize="end"
tools:text="Подключение…" />
<TextView
android:id="@+id/widget_server_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="13sp"
android:textColor="@color/widget_on_surface_variant"
android:maxLines="1"
android:ellipsize="end"
tools:text="Amsterdam #1" />
</LinearLayout>
<ImageView
android:id="@+id/widget_toggle"
android:layout_width="44dp"
android:layout_height="44dp"
android:layout_marginStart="8dp"
android:padding="8dp"
android:src="@drawable/play_arrow_24px"
android:contentDescription="@string/widget_action_start" />
</LinearLayout>
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Material You: динамическая палитра системы (API 31+), тёмная. -->
<resources>
<color name="widget_surface">@android:color/system_neutral1_800</color>
<color name="widget_on_surface">@android:color/system_neutral1_50</color>
<color name="widget_on_surface_variant">@android:color/system_neutral2_200</color>
<color name="widget_primary">@android:color/system_accent1_200</color>
<color name="widget_tertiary">@android:color/system_accent3_200</color>
<color name="widget_outline">@android:color/system_neutral2_400</color>
</resources>
+10
View File
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Фолбэк для API < 31, тёмная. -->
<resources>
<color name="widget_surface">#FF141218</color>
<color name="widget_on_surface">#FFE6E0E9</color>
<color name="widget_on_surface_variant">#FFCAC4D0</color>
<color name="widget_primary">#FFD0BCFF</color>
<color name="widget_tertiary">#FFEFB8C8</color>
<color name="widget_outline">#FF938F99</color>
</resources>
+10
View File
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Material You: динамическая палитра системы (API 31+), светлая. -->
<resources>
<color name="widget_surface">@android:color/system_neutral1_50</color>
<color name="widget_on_surface">@android:color/system_neutral1_900</color>
<color name="widget_on_surface_variant">@android:color/system_neutral2_700</color>
<color name="widget_primary">@android:color/system_accent1_600</color>
<color name="widget_tertiary">@android:color/system_accent3_600</color>
<color name="widget_outline">@android:color/system_neutral2_500</color>
</resources>
+9 -1
View File
@@ -1,2 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<resources />
<!-- Фолбэк для API < 31 (нет динамической палитры). Material 3 baseline, светлая. -->
<resources>
<color name="widget_surface">#FFFEF7FF</color>
<color name="widget_on_surface">#FF1D1B20</color>
<color name="widget_on_surface_variant">#FF49454F</color>
<color name="widget_primary">#FF6750A4</color>
<color name="widget_tertiary">#FF7D5260</color>
<color name="widget_outline">#FF79747E</color>
</resources>
+9
View File
@@ -353,6 +353,15 @@
<string name="tile_service_label">Free Turn</string>
<string name="proxy_active_wireguard">Прокси и WireGuard активны</string>
<!-- Виджет домашнего экрана -->
<string name="widget_label">FreeTurn - прокси</string>
<string name="widget_status_on">Подключено</string>
<string name="widget_status_connecting">Подключение…</string>
<string name="widget_status_off">Отключено</string>
<string name="widget_server_none">Нет активного сервера</string>
<string name="widget_action_start">Запустить</string>
<string name="widget_action_stop">Остановить</string>
<!-- App Shortcuts (long-press иконки) -->
<string name="shortcut_start_short">Запуск</string>
<string name="shortcut_start_long">Запустить прокси</string>
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:minWidth="220dp"
android:minHeight="40dp"
android:targetCellWidth="4"
android:targetCellHeight="1"
android:description="@string/widget_label"
android:initialLayout="@layout/widget_proxy"
android:previewLayout="@layout/widget_proxy"
android:resizeMode="horizontal"
android:updatePeriodMillis="0"
android:widgetCategory="home_screen" />