Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Battery widget #1

Merged
merged 6 commits into from
Nov 3, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
<activity
android:name="eu.darken.octi.main.ui.MainActivity"
android:exported="true"
android:launchMode="singleTask"
android:label="@string/app_name"
android:theme="@style/AppThemeSplash">
<intent-filter>
Expand Down Expand Up @@ -49,6 +50,17 @@
android:screenOrientation="sensor"
tools:replace="screenOrientation" />

<receiver
android:name=".modules.power.ui.widget.BatteryWidgetProvider"
android:exported="false">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="@xml/battery_widget_info" />
</receiver>

<!-- Debug stuff-->
<activity
android:name="eu.darken.octi.common.debug.recording.ui.RecorderActivity"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,8 @@ class AppsListVM @Inject constructor(
metaRepo.state,
appsRepo.state
) { metaState, appsState ->
val metaData = (metaState.others + metaState.self).firstOrNull { it?.deviceId == navArgs.deviceId }
val moduleData = (appsState.others + appsState.self).firstOrNull { it?.deviceId == navArgs.deviceId }
val metaData = metaState.all.firstOrNull { it.deviceId == navArgs.deviceId }
val moduleData = appsState.all.firstOrNull { it.deviceId == navArgs.deviceId }

if (metaData == null || moduleData == null) {
log(TAG, ERROR) { "No module data found for ${navArgs.deviceId}" }
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package eu.darken.octi.modules.power.ui.widget

import android.appwidget.AppWidgetManager
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import dagger.hilt.android.qualifiers.ApplicationContext
import eu.darken.octi.common.debug.logging.Logging.Priority.VERBOSE
import eu.darken.octi.common.debug.logging.log
import eu.darken.octi.common.debug.logging.logTag
import javax.inject.Inject
import javax.inject.Singleton


@Singleton
class BatteryWidgetManager @Inject constructor(
@ApplicationContext private val context: Context,
) {

private val widgetManager by lazy { AppWidgetManager.getInstance(context) }

private val currentWidgetIds: IntArray
get() = widgetManager.getAppWidgetIds(ComponentName(context, PROVIDER_CLASS))

suspend fun refreshWidgets() {
log(TAG) { "updateWidgets()" }

log(TAG, VERBOSE) { "Notifying these widget IDs: ${currentWidgetIds.toList()}" }

val intent = Intent(context, PROVIDER_CLASS).apply {
action = AppWidgetManager.ACTION_APPWIDGET_UPDATE
putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, currentWidgetIds)
}
context.sendBroadcast(intent)
}

companion object {
val PROVIDER_CLASS = BatteryWidgetProvider::class.java
val TAG = logTag("Module", "Power", "Widget", "Manager")
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
package eu.darken.octi.modules.power.ui.widget

import android.app.PendingIntent
import android.appwidget.AppWidgetManager
import android.appwidget.AppWidgetProvider
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.format.DateUtils
import android.widget.RemoteViews
import dagger.hilt.android.AndroidEntryPoint
import eu.darken.octi.R
import eu.darken.octi.common.coroutine.AppScope
import eu.darken.octi.common.debug.logging.Logging.Priority.ERROR
import eu.darken.octi.common.debug.logging.Logging.Priority.VERBOSE
import eu.darken.octi.common.debug.logging.asLog
import eu.darken.octi.common.debug.logging.log
import eu.darken.octi.common.debug.logging.logTag
import eu.darken.octi.main.ui.MainActivity
import eu.darken.octi.module.core.BaseModuleRepo
import eu.darken.octi.modules.meta.core.MetaInfo
import eu.darken.octi.modules.meta.core.MetaRepo
import eu.darken.octi.modules.power.core.PowerInfo
import eu.darken.octi.modules.power.core.PowerRepo
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import kotlinx.coroutines.withTimeout
import java.time.Duration
import java.time.Instant
import javax.inject.Inject

@AndroidEntryPoint
class BatteryWidgetProvider : AppWidgetProvider() {

@Inject lateinit var metaRepo: MetaRepo
@Inject lateinit var powerRepo: PowerRepo
@AppScope @Inject lateinit var appScope: CoroutineScope

private var asyncBarrier: PendingResult? = null

private fun executeAsync(
tag: String,
timeout: Duration = Duration.ofSeconds(10),
block: suspend () -> Unit
) {
val start = System.currentTimeMillis()
asyncBarrier = goAsync()
log(TAG, VERBOSE) { "executeAsync($tag) starting asyncBarrier=$asyncBarrier " }

appScope.launch {
try {
withTimeout(timeout.toMillis()) { block() }
} catch (e: Exception) {
log(TAG, ERROR) { "executeAsync($tag) failed: ${e.asLog()}" }
} finally {
asyncBarrier?.finish()
val stop = System.currentTimeMillis()
log(TAG, VERBOSE) { "executeAsync($tag) DONE (${stop - start}ms) " }
}
}

log(TAG, VERBOSE) { "executeAsync($block) leaving" }
}

override fun onUpdate(context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray) {
log(TAG) { "onUpdate(appWidgetIds=${appWidgetIds.toList()})" }
executeAsync("onUpdate") {
appWidgetIds.forEach { appWidgetId ->
updateWidget(context, appWidgetManager, appWidgetId, null)
}
}
}

override fun onAppWidgetOptionsChanged(
context: Context,
appWidgetManager: AppWidgetManager,
appWidgetId: Int,
newOptions: Bundle?
) {
log(TAG) { "onAppWidgetOptionsChanged(appWidgetId=$appWidgetId, newOptions=$newOptions)" }
executeAsync("onAppWidgetOptionsChanged") {
updateWidget(context, appWidgetManager, appWidgetId, newOptions)
}
}

private suspend fun updateWidget(
context: Context,
widgetManager: AppWidgetManager,
widgetId: Int,
options: Bundle?
) {
log(TAG) { "updateWidget(widgetId=$widgetId, options=$options)" }

val metaState = metaRepo.state.first()
val powerState = powerRepo.state.first()

val layout = createLayout(context, metaState, powerState)
widgetManager.updateAppWidget(widgetId, layout)
}

private fun createLayout(
context: Context,
metaStates: BaseModuleRepo.State<MetaInfo>,
powerStates: BaseModuleRepo.State<PowerInfo>
): RemoteViews {
log(TAG, VERBOSE) { "createLayout(context=$context, metaStates=$metaStates, powerStates=$powerStates)" }
val pendingIntent: PendingIntent = PendingIntent.getActivity(
context,
0,
Intent(context, MainActivity::class.java),
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)

val rows = powerStates.others.mapNotNull { powerInfo ->
val metaInfo = metaStates.all.firstOrNull { it.deviceId == powerInfo.deviceId } ?: return@mapNotNull null

log(TAG) { "Generating info row for ${metaInfo.data.labelOrFallback}" }
RemoteViews(context.packageName, R.layout.module_power_widget_row).apply {
val lastSeen = DateUtils.getRelativeTimeSpanString(metaInfo.modifiedAt.toEpochMilli())
val labelText = if (Duration.between(metaInfo.modifiedAt, Instant.now()).toHours() > 1) {
"${metaInfo.data.labelOrFallback} ($lastSeen)"
} else {
metaInfo.data.labelOrFallback
}
setTextViewText(R.id.device_label, labelText)

setImageViewResource(
R.id.battery_icon,
if (powerInfo.data.isCharging) R.drawable.widget_battery_charging_full_24
else R.drawable.widget_battery_full_24
)

setProgressBar(
R.id.battery_progressbar,
100,
(powerInfo.data.battery.percent * 100).toInt(),
false,
)
}
}

return RemoteViews(context.packageName, R.layout.module_power_widget).apply {
setOnClickPendingIntent(R.id.widget_root, pendingIntent)
removeAllViews(R.id.widget_root)
rows.forEach { addView(R.id.widget_root, it) }
}
}

companion object {
val TAG = logTag("Module", "Power", "Widget", "Provider")
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import eu.darken.octi.common.debug.logging.Logging.Priority.VERBOSE
import eu.darken.octi.common.debug.logging.log
import eu.darken.octi.common.debug.logging.logTag
import eu.darken.octi.module.core.ModuleManager
import eu.darken.octi.modules.power.ui.widget.BatteryWidgetManager
import eu.darken.octi.sync.core.SyncManager
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.cancel
Expand All @@ -24,6 +25,7 @@ class SyncWorker @AssistedInject constructor(
// syncWorkerComponentBuilder: SyncWorkerComponent.Builder,
private val syncManager: SyncManager,
private val moduleManager: ModuleManager,
private val batteryWidgetManager: BatteryWidgetManager,
) : CoroutineWorker(context, params) {

private val workerScope = SyncWorkerCoroutineScope()
Expand Down Expand Up @@ -68,6 +70,7 @@ class SyncWorker @AssistedInject constructor(
moduleManager.refresh()
delay(3000)
syncManager.sync()
batteryWidgetManager.refreshWidgets()
}

companion object {
Expand Down
9 changes: 9 additions & 0 deletions app/src/main/res/drawable/widget_battery_charging_full_24.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="@color/widgetOnBackground"
android:pathData="M15.67,4H14V2h-4v2H8.33C7.6,4 7,4.6 7,5.33v15.33C7,21.4 7.6,22 8.33,22h7.33c0.74,0 1.34,-0.6 1.34,-1.33V5.33C17,4.6 16.4,4 15.67,4zM11,20v-5.5H9L13,7v5.5h2L11,20z" />
</vector>
9 changes: 9 additions & 0 deletions app/src/main/res/drawable/widget_battery_full_24.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="@color/widgetOnBackground"
android:pathData="M15.67,4H14V2h-4v2H8.33C7.6,4 7,4.6 7,5.33v15.33C7,21.4 7.6,22 8.33,22h7.33c0.74,0 1.34,-0.6 1.34,-1.33V5.33C17,4.6 16.4,4 15.67,4z" />
</vector>
9 changes: 9 additions & 0 deletions app/src/main/res/layout/module_power_widget.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
style="@style/BatteryWidget.Container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/widget_root"
android:orientation="vertical">

</LinearLayout>
13 changes: 13 additions & 0 deletions app/src/main/res/layout/module_power_widget_initial.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
style="@style/BatteryWidget.Container"
android:layout_width="match_parent"
android:layout_height="match_parent">

<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:indeterminate="true" />

</FrameLayout>
13 changes: 13 additions & 0 deletions app/src/main/res/layout/module_power_widget_preview.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
style="@style/BatteryWidget.Container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<include layout="@layout/module_power_widget_row" />

<include layout="@layout/module_power_widget_row" />

<include layout="@layout/module_power_widget_row" />
</LinearLayout>
38 changes: 38 additions & 0 deletions app/src/main/res/layout/module_power_widget_row.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<ImageView
android:id="@+id/battery_icon"
android:layout_width="20dp"
android:layout_height="20dp"
android:layout_alignTop="@id/device_label"
android:layout_alignBottom="@id/battery_progressbar"
android:layout_alignParentStart="true"
android:src="@drawable/widget_battery_full_24" />

<TextView
android:id="@+id/device_label"
style="@style/BatteryWidget.Text"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_alignStart="@id/battery_progressbar"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:text="Pixel 6"
android:textStyle="bold" />

<ProgressBar
android:id="@+id/battery_progressbar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="8dp"
android:layout_below="@id/device_label"
android:layout_alignParentEnd="true"
android:layout_marginEnd="8dp"
android:layout_toEndOf="@id/battery_icon"
android:indeterminate="false"
android:max="100"
android:progress="60" />
</RelativeLayout>
5 changes: 5 additions & 0 deletions app/src/main/res/values-night/colors.xml
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
<resources>
<color name="colorUpgraded">#2962ff</color>

<color name="widgetBackground">@color/md_theme_dark_background</color>
<color name="widgetOnBackground">@color/md_theme_dark_onBackground</color>
<color name="widgetPrimary">@color/md_theme_dark_primary</color>
<color name="widgetOnPrimary">@color/md_theme_dark_onPrimary</color>
</resources>
5 changes: 5 additions & 0 deletions app/src/main/res/values/colors.xml
Original file line number Diff line number Diff line change
Expand Up @@ -63,4 +63,9 @@
<color name="CustomColor2">#009495</color>

<color name="colorUpgraded">#00b8d4</color>

<color name="widgetBackground">@color/md_theme_light_background</color>
<color name="widgetOnBackground">@color/md_theme_light_onBackground</color>
<color name="widgetPrimary">@color/md_theme_light_primary</color>
<color name="widgetOnPrimary">@color/md_theme_light_onPrimary</color>
</resources>
1 change: 1 addition & 0 deletions app/src/main/res/values/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -193,4 +193,5 @@

<string name="pro_device_limit_reached_title">Device limit reached</string>
<string name="pro_device_limit_reached_description">You currently have %1$d synced devices. To view more than %2$d devices, upgrade to Octi Pro or remove devices.</string>
<string name="module_power_widget_description">Display the battery status of your synced devices.</string>
</resources>
Loading