Widgets: fixes from the pre-release audit
Clock: - Weather requests send only "FlexeraLauncher" as their user agent, no longer Android's, which names the phone model and build. - Celsius or Fahrenheit follows Android's own temperature setting where there is one (Android 14 and newer), else the locale. - Failed weather requests back off (5, 10, 20, 40, then 45 minutes) instead of retrying every time the home screen returns. - The options sheet's segments switch to a list at large font sizes and read left to right for alignment in right-to-left languages; the spoken time says AM or PM in 12-hour mode. Pictures, and both widgets' data: - When Android restores widgets, the pictures and the clock's options move to the new ids instead of being deleted. - The setup screen survives being recreated while photos are copied; photos staged for a widget that never got set up are cleared after the home screens load. - Slides are decoded at about the frame's size, let go of in the background, and the slideshow pauses while the widget cannot be seen. - No "Tap to choose pictures" over the sample while a photo loads; the empty widget's hint stays readable at large font sizes, off the sun. - Canvas-drawn text follows Android's Bold text setting. The drop animation of another app's widget lands at the size the widget will have (the icon-aligned inset was added instead of taken off). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
ec7d3bc004
commit
42f728fd82
14 files changed
+893
-136
No files matched your search
@@ -3,8 +3,10 @@ package app.flexera.widget
|
||||
import android.content.Context
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.os.SystemClock
|
||||
import android.util.Log
|
||||
import androidx.annotation.WorkerThread
|
||||
import androidx.core.text.util.LocalePreferences
|
||||
import com.android.launcher3.R
|
||||
import com.android.launcher3.util.Executors
|
||||
import java.io.IOException
|
||||
@@ -23,7 +25,10 @@ import org.json.JSONObject
|
||||
* The data comes from Open-Meteo, a weather service that needs no account. It is asked only for
|
||||
* a place the owner picked by name in the clock's options, never for where the phone is, so the
|
||||
* launcher needs no location permission; and only while a clock with weather is in view, at most
|
||||
* every [FRESH_MS]. The place's coordinates, rounded to about a kilometre, are all that is sent.
|
||||
* every [FRESH_MS], or after a request that failed, at intervals that grow from [RETRY_MS] to
|
||||
* [RETRY_MAX_MS]. A search sends the name typed and the phone's language, and a forecast the
|
||||
* place's coordinates, rounded to about a kilometre, and the unit of temperature. Nothing else
|
||||
* goes out, as the privacy text in About and the clock's options say.
|
||||
* The last answer is kept, so that the line is there at once and survives a spell offline.
|
||||
*/
|
||||
object ClockWeather {
|
||||
@@ -31,7 +36,7 @@ object ClockWeather {
|
||||
/** A place found by name. [detail] tells places of one name apart: region and country. */
|
||||
data class Place(val name: String, val detail: String, val latitude: Double, val longitude: Double)
|
||||
|
||||
/** What the service said: degrees in the unit of the phone's country, and a WMO weather code. */
|
||||
/** What the service said: degrees in the unit the phone is set to, and a WMO weather code. */
|
||||
data class Reading(val degrees: Int, val code: Int, val fahrenheit: Boolean, val readAt: Long)
|
||||
|
||||
/** Told on the main thread that a new reading has come in. */
|
||||
@@ -48,16 +53,43 @@ object ClockWeather {
|
||||
/** A reading younger than this is not asked for again. */
|
||||
private const val FRESH_MS = 45 * 60 * 1000L
|
||||
|
||||
/**
|
||||
* How long a place waits for its next try after a request for it failed. The wait doubles
|
||||
* with each failure in a row, up to [RETRY_MAX_MS].
|
||||
*/
|
||||
private const val RETRY_MS = 5 * 60 * 1000L
|
||||
|
||||
/**
|
||||
* The longest wait after failures. Tries made while the phone is offline, on a flight say,
|
||||
* fail as well; with a short wait the weather is back soon once the phone is online again,
|
||||
* and a service that cannot be reached is still asked only a few times an hour.
|
||||
*/
|
||||
private const val RETRY_MAX_MS = 15 * 60 * 1000L
|
||||
|
||||
/** A reading older than this is no longer shown: stale weather is worse than none. */
|
||||
private const val SHOWN_MS = 3 * 60 * 60 * 1000L
|
||||
|
||||
/** The countries that count degrees in Fahrenheit. */
|
||||
private val fahrenheitCountries = setOf("US", "BS", "BZ", "KY", "PW", "FM", "MH", "LR")
|
||||
/**
|
||||
* When the last request for a place failed, on the [SystemClock.elapsedRealtime] clock, and
|
||||
* how many failed in a row.
|
||||
*/
|
||||
private class Failure(val at: Long, val inARow: Int)
|
||||
|
||||
private val listeners = CopyOnWriteArraySet<Listener>()
|
||||
private val asking = HashSet<String>()
|
||||
|
||||
/** The places whose last request failed. Guarded by [asking], like it. */
|
||||
private val failures = HashMap<String, Failure>()
|
||||
private val main = Handler(Looper.getMainLooper())
|
||||
|
||||
/**
|
||||
* The last answer of [usesFahrenheit], and the locale it is for. Unless a unit is picked in the
|
||||
* regional preferences, Android works it out from its tables of units, which it reads anew
|
||||
* each time: too slow to repeat on the main thread at every return to the home screen.
|
||||
*/
|
||||
@Volatile
|
||||
private var temperatureUnit: Pair<Locale, Boolean>? = null
|
||||
|
||||
fun addListener(listener: Listener) {
|
||||
listeners.add(listener)
|
||||
}
|
||||
@@ -70,8 +102,13 @@ object ClockWeather {
|
||||
@WorkerThread
|
||||
@Throws(IOException::class)
|
||||
fun search(name: String): List<Place> {
|
||||
// The language decides which names match, not only the names given back: without it,
|
||||
// "Wien" does not find Vienna, and a name in Cyrillic finds nothing.
|
||||
val language = Locale.getDefault().language.ifEmpty { "en" }
|
||||
val answer = get("$SEARCH?name=${URLEncoder.encode(name, "UTF-8")}&count=6&language=$language&format=json")
|
||||
// The service answered, so the places whose weather failed lately may be asked for again
|
||||
// at once, such as the one the owner picks from these results.
|
||||
synchronized(asking) { failures.clear() }
|
||||
val results = JSONObject(answer).optJSONArray("results") ?: return emptyList()
|
||||
return (0 until results.length()).map { index ->
|
||||
val place = results.getJSONObject(index)
|
||||
@@ -96,13 +133,20 @@ object ClockWeather {
|
||||
return if (age in 0..SHOWN_MS && reading.fahrenheit == usesFahrenheit()) reading else null
|
||||
}
|
||||
|
||||
/** Asks for a new reading in the background, unless the last one is fresh or one is on its way. */
|
||||
/**
|
||||
* Asks for a new reading in the background, unless the last one is fresh, one is on its way,
|
||||
* or the last request failed too recently to try again.
|
||||
*/
|
||||
fun refreshIfStale(context: Context, place: Place) {
|
||||
val app = context.applicationContext
|
||||
val key = key(place)
|
||||
val last = reading(app, place)
|
||||
if (last != null && System.currentTimeMillis() - last.readAt < FRESH_MS) return
|
||||
synchronized(asking) {
|
||||
// The widget asks at every return to the home screen. While the service cannot be
|
||||
// reached, that would be a new request each time.
|
||||
val failure = failures[key]
|
||||
if (failure != null && SystemClock.elapsedRealtime() - failure.at < retryAfter(failure.inARow)) return
|
||||
if (!asking.add(key)) return
|
||||
}
|
||||
Executors.THREAD_POOL_EXECUTOR.execute {
|
||||
@@ -119,16 +163,25 @@ object ClockWeather {
|
||||
prefs(app).edit()
|
||||
.putString(key, "$degrees|$code|${if (fahrenheit) "F" else "C"}|${System.currentTimeMillis()}")
|
||||
.apply()
|
||||
synchronized(asking) { failures.remove(key) }
|
||||
main.post { listeners.forEach { it.onWeatherChanged() } }
|
||||
} catch (e: Exception) {
|
||||
// Offline, or the service is down: the last reading stays until it is too old.
|
||||
// Offline, or the service is down: the last reading stays until it is too old,
|
||||
// and the next try waits (see RETRY_MS).
|
||||
Log.w(TAG, "No weather this time", e)
|
||||
synchronized(asking) {
|
||||
failures[key] = Failure(SystemClock.elapsedRealtime(), (failures[key]?.inARow ?: 0) + 1)
|
||||
}
|
||||
} finally {
|
||||
synchronized(asking) { asking.remove(key) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The wait after [inARow] failed requests: [RETRY_MS], doubled for each after the first, up to [RETRY_MAX_MS]. */
|
||||
private fun retryAfter(inARow: Int): Long =
|
||||
(RETRY_MS shl (inARow - 1).coerceIn(0, 8)).coerceAtMost(RETRY_MAX_MS)
|
||||
|
||||
/** The line as the widget shows it, such as "6° · Overcast". */
|
||||
fun line(context: Context, reading: Reading): String =
|
||||
context.getString(R.string.flexera_weather_line, reading.degrees, context.getString(word(reading.code)))
|
||||
@@ -150,7 +203,21 @@ object ClockWeather {
|
||||
else -> R.string.flexera_weather_overcast
|
||||
}
|
||||
|
||||
private fun usesFahrenheit(): Boolean = Locale.getDefault().country in fahrenheitCountries
|
||||
/**
|
||||
* True when the phone counts degrees in Fahrenheit: the unit the owner picked under Android's
|
||||
* regional preferences (Android 14 and newer), or else the one usual where the phone's
|
||||
* language is from, such as the United States for American English.
|
||||
*/
|
||||
private fun usesFahrenheit(): Boolean {
|
||||
// The locale LocalePreferences would read by itself. A unit picked in the regional
|
||||
// preferences is part of it, so a new choice is a new locale.
|
||||
val locale = Locale.getDefault(Locale.Category.FORMAT)
|
||||
val known = temperatureUnit
|
||||
if (known != null && known.first == locale) return known.second
|
||||
val fahrenheit = LocalePreferences.getTemperatureUnit(locale) == LocalePreferences.TemperatureUnit.FAHRENHEIT
|
||||
temperatureUnit = locale to fahrenheit
|
||||
return fahrenheit
|
||||
}
|
||||
|
||||
/** Two decimals, about a kilometre: all a forecast needs, and no more exact than that. */
|
||||
private fun coordinate(value: Double): String = String.format(Locale.ROOT, "%.2f", value)
|
||||
@@ -166,6 +233,9 @@ object ClockWeather {
|
||||
connection.connectTimeout = TIMEOUT_MS
|
||||
connection.readTimeout = TIMEOUT_MS
|
||||
connection.setRequestProperty("Accept", "application/json")
|
||||
// Android's own User-Agent would tell the service the phone's model and its exact
|
||||
// Android build. This one names only the app.
|
||||
connection.setRequestProperty("User-Agent", "FlexeraLauncher")
|
||||
if (connection.responseCode != HttpURLConnection.HTTP_OK) {
|
||||
throw IOException("The weather service answered HTTP ${connection.responseCode}")
|
||||
}
|
||||
|
||||
@@ -8,15 +8,19 @@ import androidx.activity.compose.setContent
|
||||
import androidx.activity.enableEdgeToEdge
|
||||
import androidx.annotation.StringRes
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.BoxWithConstraints
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.imePadding
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.selection.selectable
|
||||
import androidx.compose.foundation.selection.selectableGroup
|
||||
import androidx.compose.foundation.text.KeyboardActions
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
@@ -26,6 +30,7 @@ import androidx.compose.material3.LinearProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.ModalBottomSheet
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.RadioButton
|
||||
import androidx.compose.material3.SegmentedButton
|
||||
import androidx.compose.material3.SegmentedButtonDefaults
|
||||
import androidx.compose.material3.SingleChoiceSegmentedButtonRow
|
||||
@@ -33,7 +38,10 @@ import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.material3.rememberModalBottomSheetState
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.CompositionLocalProvider
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.key
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
@@ -42,10 +50,20 @@ import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.platform.LocalFocusManager
|
||||
import androidx.compose.ui.platform.LocalLayoutDirection
|
||||
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
|
||||
import androidx.compose.ui.res.pluralStringResource
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.LiveRegionMode
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.semantics.liveRegion
|
||||
import androidx.compose.ui.semantics.semantics
|
||||
import androidx.compose.ui.text.input.ImeAction
|
||||
import androidx.compose.ui.text.rememberTextMeasurer
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.LayoutDirection
|
||||
import androidx.compose.ui.unit.dp
|
||||
import app.flexera.widget.ClockWidgetStore.Align
|
||||
import app.flexera.widget.ClockWidgetStore.Size
|
||||
@@ -119,6 +137,7 @@ class ClockWidgetConfigActivity : ComponentActivity() {
|
||||
),
|
||||
chosen = options.align,
|
||||
onChoose = { change(options.copy(align = it)) },
|
||||
sides = true,
|
||||
)
|
||||
Spacer(modifier = Modifier.height(20.dp))
|
||||
Choice(
|
||||
@@ -165,7 +184,13 @@ private fun Heading(@StringRes text: Int) {
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
}
|
||||
|
||||
/** A heading with one row of choices under it, of which one is taken. */
|
||||
/**
|
||||
* A heading with one row of choices under it, of which one is taken. When a label does not fit
|
||||
* its segment, as at large font sizes, the choices are a list instead, one to a line.
|
||||
*
|
||||
* Choices that are [sides] of the widget are not a reading order: their row stays left to right
|
||||
* in right-to-left languages too, so that Left is on the left.
|
||||
*/
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
private fun <T> Choice(
|
||||
@@ -173,21 +198,67 @@ private fun <T> Choice(
|
||||
choices: List<Pair<T, Int>>,
|
||||
chosen: T,
|
||||
onChoose: (T) -> Unit,
|
||||
sides: Boolean = false,
|
||||
) {
|
||||
Heading(heading)
|
||||
SingleChoiceSegmentedButtonRow(modifier = Modifier.fillMaxWidth()) {
|
||||
choices.forEachIndexed { index, (value, label) ->
|
||||
SegmentedButton(
|
||||
selected = value == chosen,
|
||||
onClick = { onChoose(value) },
|
||||
shape = SegmentedButtonDefaults.itemShape(index = index, count = choices.size),
|
||||
) {
|
||||
Text(text = stringResource(id = label), maxLines = 1)
|
||||
val labels = choices.map { (_, label) -> stringResource(id = label) }
|
||||
BoxWithConstraints(modifier = Modifier.fillMaxWidth()) {
|
||||
if (fitInSegments(labels, maxWidth)) {
|
||||
val direction = if (sides) LayoutDirection.Ltr else LocalLayoutDirection.current
|
||||
CompositionLocalProvider(LocalLayoutDirection provides direction) {
|
||||
SingleChoiceSegmentedButtonRow(modifier = Modifier.fillMaxWidth()) {
|
||||
choices.forEachIndexed { index, (value, _) ->
|
||||
SegmentedButton(
|
||||
selected = value == chosen,
|
||||
onClick = { onChoose(value) },
|
||||
shape = SegmentedButtonDefaults.itemShape(index = index, count = choices.size),
|
||||
) {
|
||||
Text(text = labels[index], maxLines = 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
Column(modifier = Modifier.selectableGroup()) {
|
||||
choices.forEachIndexed { index, (value, _) ->
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.heightIn(min = 48.dp)
|
||||
.selectable(
|
||||
selected = value == chosen,
|
||||
onClick = { onChoose(value) },
|
||||
role = Role.RadioButton,
|
||||
),
|
||||
) {
|
||||
RadioButton(selected = value == chosen, onClick = null)
|
||||
Spacer(modifier = Modifier.width(12.dp))
|
||||
Text(text = labels[index], style = MaterialTheme.typography.bodyLarge)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* True when every label fits its segment of a row [width] wide, beside the check mark the chosen
|
||||
* one carries. Material measures a label against all the room in its segment and then adds the
|
||||
* check mark beside it, so a word that is too long is broken mid-word ("Regul") or runs into the
|
||||
* border.
|
||||
*/
|
||||
@Composable
|
||||
private fun fitInSegments(labels: List<String>, width: Dp): Boolean {
|
||||
val measurer = rememberTextMeasurer()
|
||||
val style = MaterialTheme.typography.labelLarge
|
||||
val room = with(LocalDensity.current) { (width / labels.size - CheckMarkRoom).toPx() }
|
||||
return labels.all { measurer.measure(it, style, softWrap = false, maxLines = 1).size.width <= room }
|
||||
}
|
||||
|
||||
/** What a chosen segment keeps beside its label: the check mark, the space after it, and its two borders. */
|
||||
private val CheckMarkRoom = SegmentedButtonDefaults.IconSize + 10.dp
|
||||
|
||||
private enum class Search { IDLE, RUNNING, NOTHING, FAILED }
|
||||
|
||||
/**
|
||||
@@ -200,6 +271,7 @@ private fun WeatherChoice(place: ClockWeather.Place?, onChoose: (ClockWeather.Pl
|
||||
var name by rememberSaveable { mutableStateOf(place?.name ?: timeZoneCity()) }
|
||||
var found by remember { mutableStateOf(emptyList<ClockWeather.Place>()) }
|
||||
var search by remember { mutableStateOf(Search.IDLE) }
|
||||
var searches by remember { mutableIntStateOf(0) }
|
||||
val keyboard = LocalSoftwareKeyboardController.current
|
||||
val focus = LocalFocusManager.current
|
||||
val look = {
|
||||
@@ -209,6 +281,7 @@ private fun WeatherChoice(place: ClockWeather.Place?, onChoose: (ClockWeather.Pl
|
||||
keyboard?.hide()
|
||||
focus.clearFocus()
|
||||
search = Search.RUNNING
|
||||
searches++
|
||||
scope.launch {
|
||||
val result = withContext(Dispatchers.IO) { runCatching { ClockWeather.search(wanted) } }
|
||||
found = result.getOrDefault(emptyList())
|
||||
@@ -246,18 +319,25 @@ private fun WeatherChoice(place: ClockWeather.Place?, onChoose: (ClockWeather.Pl
|
||||
Text(text = stringResource(id = R.string.flexera_clock_widget_weather_search))
|
||||
}
|
||||
}
|
||||
when (search) {
|
||||
Search.RUNNING -> LinearProgressIndicator(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(top = 12.dp),
|
||||
)
|
||||
// Each search gets a new note, which TalkBack reads out, also when it says what the last one
|
||||
// did: offline, a search can fail before the progress bar is ever drawn, and the note that
|
||||
// stayed would not be read again.
|
||||
key(searches) {
|
||||
when (search) {
|
||||
Search.RUNNING -> LinearProgressIndicator(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(top = 12.dp),
|
||||
)
|
||||
|
||||
Search.NOTHING -> Note(R.string.flexera_clock_widget_weather_nothing)
|
||||
Search.NOTHING -> Note(stringResource(id = R.string.flexera_clock_widget_weather_nothing))
|
||||
|
||||
Search.FAILED -> Note(R.string.flexera_clock_widget_weather_failed)
|
||||
Search.FAILED -> Note(stringResource(id = R.string.flexera_clock_widget_weather_failed))
|
||||
|
||||
Search.IDLE -> Unit
|
||||
Search.IDLE -> if (found.isNotEmpty()) {
|
||||
Note(pluralStringResource(id = R.plurals.flexera_clock_widget_weather_found, count = found.size, found.size))
|
||||
}
|
||||
}
|
||||
}
|
||||
found.forEach { candidate ->
|
||||
Text(
|
||||
@@ -286,13 +366,19 @@ private fun WeatherChoice(place: ClockWeather.Place?, onChoose: (ClockWeather.Pl
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* How a search went, under the search field. TalkBack reads it out as it appears: the answer
|
||||
* comes a moment after the owner asked, and nothing else would say that it is there.
|
||||
*/
|
||||
@Composable
|
||||
private fun Note(@StringRes text: Int) {
|
||||
private fun Note(text: String) {
|
||||
Text(
|
||||
text = stringResource(id = text),
|
||||
text = text,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.padding(top = 12.dp),
|
||||
modifier = Modifier
|
||||
.padding(top = 12.dp)
|
||||
.semantics { liveRegion = LiveRegionMode.Polite },
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -3,12 +3,15 @@ package app.flexera.widget
|
||||
import android.appwidget.AppWidgetProvider
|
||||
import android.content.ComponentName
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import com.android.launcher3.BuildConfig
|
||||
import com.android.launcher3.model.data.LauncherAppWidgetInfo
|
||||
|
||||
/**
|
||||
* The launcher's own clock widget: the time, large, with the date under it. Android knows it as
|
||||
* an ordinary app widget; the launcher draws it itself with a [ClockWidgetView]. It needs no
|
||||
* setting up; what the owner may choose for it is kept in [ClockWidgetStore]. See [FlexeraWidgets].
|
||||
* setting up; what the owner may choose for it is kept in [ClockWidgetStore], under the
|
||||
* widget's id, and goes with the widget when a restore gives it a new one. See [FlexeraWidgets].
|
||||
*/
|
||||
class ClockWidgetProvider : AppWidgetProvider() {
|
||||
|
||||
@@ -16,8 +19,50 @@ class ClockWidgetProvider : AppWidgetProvider() {
|
||||
appWidgetIds.forEach { ClockWidgetStore.delete(context, it) }
|
||||
}
|
||||
|
||||
/** After Android's own restore. */
|
||||
override fun onRestored(context: Context, oldWidgetIds: IntArray, newWidgetIds: IntArray) {
|
||||
ClockWidgetStore.move(context, oldWidgetIds, newWidgetIds)
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = "ClockWidgetProvider"
|
||||
|
||||
@JvmField
|
||||
val componentName = ComponentName(BuildConfig.APPLICATION_ID, ClockWidgetProvider::class.java.name)
|
||||
|
||||
/**
|
||||
* Told by Launcher3 (WidgetInflater) that a widget of the home screen got a new id
|
||||
* because the one it had is no longer valid, as after a restore of the launcher's
|
||||
* backup; [oldAppWidgetId] is the id it had. Android's onRestored does not come in that
|
||||
* case, and Launcher3 deletes the old id after the home screens are loaded, so the
|
||||
* clock's options go to the new id first, before onDeleted would forget them.
|
||||
*/
|
||||
@JvmStatic
|
||||
fun onNewAppWidgetId(context: Context, item: LauncherAppWidgetInfo, oldAppWidgetId: Int) {
|
||||
val newId = item.appWidgetId
|
||||
if (item.providerName != componentName || oldAppWidgetId <= 0 || newId <= 0) return
|
||||
try {
|
||||
ClockWidgetStore.move(context, intArrayOf(oldAppWidgetId), intArrayOf(newId))
|
||||
} catch (e: RuntimeException) {
|
||||
// Never in the way of loading the home screens.
|
||||
Log.w(TAG, "Options not handed to widget $newId", e)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Told by Launcher3 (LauncherWidgetHolder) that it deleted a widget id, of any widget.
|
||||
* Android calls onDeleted only for an id that was bound, and a clock removed while it
|
||||
* waited for "tap to set up" may have options under an id that was not
|
||||
* ([onNewAppWidgetId]); they go with it. For another widget's id there is nothing to remove.
|
||||
*/
|
||||
@JvmStatic
|
||||
fun onAppWidgetIdDeleted(context: Context, appWidgetId: Int) {
|
||||
if (appWidgetId <= 0) return
|
||||
try {
|
||||
ClockWidgetStore.delete(context, appWidgetId)
|
||||
} catch (e: RuntimeException) {
|
||||
Log.w(TAG, "Options of widget $appWidgetId not removed", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,8 @@ package app.flexera.widget
|
||||
|
||||
import android.content.Context
|
||||
import android.content.SharedPreferences
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import java.util.concurrent.CopyOnWriteArraySet
|
||||
|
||||
/**
|
||||
@@ -91,15 +93,47 @@ object ClockWidgetStore {
|
||||
/** Forgets the options of a widget that left the home screen. */
|
||||
fun delete(context: Context, appWidgetId: Int) {
|
||||
val edit = prefs(context).edit()
|
||||
for (key in listOf(ALIGN, SIZE, WEIGHT, PLACE, PLACE_DETAIL, LATITUDE, LONGITUDE)) {
|
||||
for (key in KEYS) {
|
||||
edit.remove(key + appWidgetId)
|
||||
}
|
||||
edit.apply()
|
||||
}
|
||||
|
||||
/**
|
||||
* Hands the options of each widget in [from] to the widget at the same place in [to]: the
|
||||
* ids that a restore gave the widgets in place of the ones they had. May be called on any
|
||||
* thread; listeners are told on the main thread.
|
||||
*/
|
||||
fun move(context: Context, from: IntArray, to: IntArray) {
|
||||
val prefs = prefs(context)
|
||||
val before = prefs.all
|
||||
val edit = prefs.edit()
|
||||
// The old ids are all cleared before the new ones are written, in one change, so that an
|
||||
// id that is one widget's old id and another's new one ends up with the right options.
|
||||
for (oldId in from) {
|
||||
for (key in KEYS) edit.remove(key + oldId)
|
||||
}
|
||||
val moved = ArrayList<Int>()
|
||||
for (i in from.indices) {
|
||||
val newId = to.getOrNull(i) ?: continue
|
||||
for (key in KEYS) {
|
||||
when (val value = before[key + from[i]]) {
|
||||
is String -> edit.putString(key + newId, value)
|
||||
is Float -> edit.putFloat(key + newId, value)
|
||||
else -> edit.remove(key + newId)
|
||||
}
|
||||
}
|
||||
moved.add(newId)
|
||||
}
|
||||
edit.apply()
|
||||
mainHandler.post { moved.forEach { id -> listeners.forEach { it.onClockOptionsChanged(id) } } }
|
||||
}
|
||||
|
||||
private fun prefs(context: Context): SharedPreferences =
|
||||
context.applicationContext.getSharedPreferences(FILE, Context.MODE_PRIVATE)
|
||||
|
||||
private val mainHandler = Handler(Looper.getMainLooper())
|
||||
|
||||
private const val FILE = "flexera_clock_widget"
|
||||
private const val ALIGN = "align_"
|
||||
private const val SIZE = "size_"
|
||||
@@ -108,4 +142,7 @@ object ClockWidgetStore {
|
||||
private const val PLACE_DETAIL = "place_detail_"
|
||||
private const val LATITUDE = "latitude_"
|
||||
private const val LONGITUDE = "longitude_"
|
||||
|
||||
/** Every option kept for a widget, each under its key followed by the widget's id. */
|
||||
private val KEYS = listOf(ALIGN, SIZE, WEIGHT, PLACE, PLACE_DETAIL, LATITUDE, LONGITUDE)
|
||||
}
|
||||
@@ -5,12 +5,14 @@ import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.IntentFilter
|
||||
import android.content.res.Configuration
|
||||
import android.graphics.Canvas
|
||||
import android.graphics.Color
|
||||
import android.graphics.Paint
|
||||
import android.graphics.Rect
|
||||
import android.graphics.RectF
|
||||
import android.graphics.Typeface
|
||||
import android.graphics.fonts.FontStyle
|
||||
import android.os.Build
|
||||
import android.provider.AlarmClock
|
||||
import android.text.TextPaint
|
||||
@@ -66,6 +68,9 @@ class ClockWidgetView @JvmOverloads constructor(
|
||||
private val ink = Rect()
|
||||
private val now = Calendar.getInstance()
|
||||
private var time = ""
|
||||
|
||||
/** The time as a screen reader says it: as drawn, but with "AM" or "PM" in 12-hour mode. */
|
||||
private var spokenTime = ""
|
||||
private var date = ""
|
||||
|
||||
/** The weather line; empty for a clock without weather or while none is known. */
|
||||
@@ -222,6 +227,17 @@ class ClockWidgetView @JvmOverloads constructor(
|
||||
}
|
||||
}
|
||||
|
||||
override fun onConfigurationChanged(newConfig: Configuration) {
|
||||
super.onConfigurationChanged(newConfig)
|
||||
// Android's Bold text setting is part of the configuration; the lines follow a new one
|
||||
// as a TextView does. Heavier lines are wider, so they are placed anew.
|
||||
timePaint.typeface = weight(options.weight.value)
|
||||
datePaint.typeface = weight(DATE_WEIGHT)
|
||||
weatherPaint.typeface = weight(WEATHER_WEIGHT)
|
||||
arrange()
|
||||
invalidate()
|
||||
}
|
||||
|
||||
override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
|
||||
super.onLayout(changed, left, top, right, bottom)
|
||||
val aligned = IconFrame.of(this)
|
||||
@@ -241,15 +257,18 @@ class ClockWidgetView @JvmOverloads constructor(
|
||||
private fun tell() {
|
||||
now.timeInMillis = System.currentTimeMillis()
|
||||
val locale = Locale.getDefault()
|
||||
// The phone's own choice of 12 or 24 hours, without "AM" and "PM": the date line and
|
||||
// the daylight say which half of the day it is.
|
||||
// The phone's own choice of 12 or 24 hours, drawn without "AM" and "PM": the date line and
|
||||
// the daylight say which half of the day it is. Spoken, the time keeps them.
|
||||
val hours = if (DateFormat.is24HourFormat(context)) "Hm" else "hm"
|
||||
val timePattern = DateFormat.getBestDateTimePattern(locale, hours).replace("a", "").trim()
|
||||
val spokenPattern = DateFormat.getBestDateTimePattern(locale, hours)
|
||||
val timePattern = spokenPattern.replace("a", "").trim()
|
||||
val datePattern = DateFormat.getBestDateTimePattern(locale, "EEEEdMMMM")
|
||||
val newTime = DateFormat.format(timePattern, now).toString()
|
||||
val newSpokenTime = DateFormat.format(spokenPattern, now).toString()
|
||||
val newDate = DateFormat.format(datePattern, now).toString()
|
||||
if (newTime == time && newDate == date) return
|
||||
if (newTime == time && newSpokenTime == spokenTime && newDate == date) return
|
||||
time = newTime
|
||||
spokenTime = newSpokenTime
|
||||
date = newDate
|
||||
describe()
|
||||
arrange()
|
||||
@@ -258,7 +277,7 @@ class ClockWidgetView @JvmOverloads constructor(
|
||||
|
||||
/** What a screen reader says for the widget: everything it shows. */
|
||||
private fun describe() {
|
||||
contentDescription = listOf(time, date, weather).filter { it.isNotEmpty() }.joinToString(", ")
|
||||
contentDescription = listOf(spokenTime, date, weather).filter { it.isNotEmpty() }.joinToString(", ")
|
||||
}
|
||||
|
||||
/** Sizes the two lines for the frame and the owner's choices, and works out where they go. */
|
||||
@@ -357,10 +376,13 @@ class ClockWidgetView @JvmOverloads constructor(
|
||||
}
|
||||
}
|
||||
|
||||
/** The phone's own font at a weight from 100 (thin) to 900. Android 8 only knows a few. */
|
||||
/**
|
||||
* The phone's own font at a weight from 100 (thin) to 900, made heavier by Android's Bold
|
||||
* text setting (see withBoldText). Android 8 only knows a few.
|
||||
*/
|
||||
private fun weight(weight: Int): Typeface =
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
|
||||
Typeface.create(Typeface.DEFAULT, weight, false)
|
||||
withBoldText(Typeface.create(Typeface.DEFAULT, weight, false))
|
||||
} else {
|
||||
val family = when {
|
||||
weight <= 100 -> "sans-serif-thin"
|
||||
@@ -372,6 +394,18 @@ class ClockWidgetView @JvmOverloads constructor(
|
||||
Typeface.create(family, Typeface.NORMAL)
|
||||
}
|
||||
|
||||
/**
|
||||
* [typeface] made heavier by Android's Bold text setting (Android 12 and newer), as Android
|
||||
* does for the text of a TextView but not for text drawn on a canvas.
|
||||
*/
|
||||
private fun withBoldText(typeface: Typeface): Typeface {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) return typeface
|
||||
val adjustment = resources.configuration.fontWeightAdjustment
|
||||
if (adjustment == 0 || adjustment == Configuration.FONT_WEIGHT_ADJUSTMENT_UNDEFINED) return typeface
|
||||
val weight = (typeface.weight + adjustment).coerceIn(FontStyle.FONT_WEIGHT_MIN, FontStyle.FONT_WEIGHT_MAX)
|
||||
return Typeface.create(typeface, weight, typeface.isItalic)
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val TAG = "ClockWidgetView"
|
||||
|
||||
|
||||
@@ -37,11 +37,17 @@ object FlexeraWidgets {
|
||||
* [appWidgetPadding].
|
||||
*/
|
||||
@JvmStatic
|
||||
fun cellInset(child: View, profile: DeviceProfile, cellWidth: Int, cellHeight: Int): Rect {
|
||||
val info = child.tag as? LauncherAppWidgetInfo
|
||||
if (info != null && isOwn(info.providerName)) return noInset
|
||||
return appWidgetPadding(profile, cellWidth, cellHeight)
|
||||
}
|
||||
fun cellInset(child: View, profile: DeviceProfile, cellWidth: Int, cellHeight: Int): Rect =
|
||||
cellInset((child.tag as? LauncherAppWidgetInfo)?.providerName, profile, cellWidth, cellHeight)
|
||||
|
||||
/**
|
||||
* [cellInset] for a widget of [provider]. The drop animation asks this way, because a widget
|
||||
* dropped from the list of widgets is not tagged with its item until it is on the home screen;
|
||||
* asked about its view, the launcher's own Clock would get another app's room.
|
||||
*/
|
||||
@JvmStatic
|
||||
fun cellInset(provider: ComponentName?, profile: DeviceProfile, cellWidth: Int, cellHeight: Int): Rect =
|
||||
if (isOwn(provider)) noInset else appWidgetPadding(profile, cellWidth, cellHeight)
|
||||
|
||||
/** [appWidgetPadding] for the cells of [profile]'s home screen. */
|
||||
@JvmStatic
|
||||
@@ -57,6 +63,13 @@ object FlexeraWidgets {
|
||||
* same box the launcher's own widgets draw in ([IconFrame]), so that every widget's edges
|
||||
* meet the edges of the icons above, below and beside it. Otherwise it is Launcher3's own,
|
||||
* which the Widget padding setting scales.
|
||||
*
|
||||
* How many cells a widget takes is still worked out with Launcher3's own padding
|
||||
* (LauncherAppWidgetProviderInfo.initSpans), on purpose: lining widgets up with the icons
|
||||
* changes no widget's cell count, on the home screen or in the list of widgets. The cost is
|
||||
* that a widget can be laid out smaller than the minimum size it declares, by up to about a
|
||||
* cell less an icon each way; one that asks for 72dp of height on cells about 90dp tall,
|
||||
* say, gets one row and so the height of an icon.
|
||||
*/
|
||||
@JvmStatic
|
||||
fun appWidgetPadding(profile: DeviceProfile, cellWidth: Int, cellHeight: Int): Rect {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package app.flexera.widget
|
||||
|
||||
import android.appwidget.AppWidgetManager
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
@@ -12,14 +13,22 @@ import android.widget.FrameLayout
|
||||
import android.widget.ProgressBar
|
||||
import android.widget.Toast
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.OnBackPressedCallback
|
||||
import androidx.activity.result.PickVisualMediaRequest
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.annotation.WorkerThread
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import com.android.launcher3.LauncherAppState
|
||||
import com.android.launcher3.LauncherSettings.Favorites
|
||||
import com.android.launcher3.R
|
||||
import com.android.launcher3.model.data.LauncherAppWidgetInfo
|
||||
import kotlin.math.min
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.Deferred
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.MainScope
|
||||
import kotlinx.coroutines.async
|
||||
import kotlinx.coroutines.isActive
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
@@ -30,11 +39,19 @@ import kotlinx.coroutines.withContext
|
||||
* Android starts it when the widget is put on the home screen and from the widget's edit
|
||||
* button; the widget starts it itself when it has no pictures. The photo picker hands over
|
||||
* only the pictures the owner picks, so the launcher needs no access to the gallery.
|
||||
*
|
||||
* Android may make this screen anew at any moment, as it does when the dark theme comes on: the
|
||||
* picker then answers the new screen, and a copy under way goes on and is waited for by it. A
|
||||
* copy goes on, too, when the owner leaves for the home screen while it is made; only Back stops
|
||||
* it.
|
||||
*/
|
||||
class PictureWidgetConfigActivity : ComponentActivity() {
|
||||
|
||||
private var appWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID
|
||||
|
||||
/** True from asking the photo picker until it answers; kept when the screen is made anew. */
|
||||
private var picking = false
|
||||
|
||||
private val picker = registerForActivityResult(
|
||||
ActivityResultContracts.PickMultipleVisualMedia(mostPictures()),
|
||||
) { chosen -> onChosen(chosen) }
|
||||
@@ -51,52 +68,97 @@ class PictureWidgetConfigActivity : ComponentActivity() {
|
||||
finish()
|
||||
return
|
||||
}
|
||||
// After Android has restarted this screen, the picker is already open and answers here.
|
||||
if (savedInstanceState != null) return
|
||||
val underWay = copies[appWidgetId]
|
||||
when {
|
||||
// The pictures are still being copied, as when Android made this screen anew.
|
||||
underWay != null -> waitFor(underWay)
|
||||
// The picker is open and answers here.
|
||||
savedInstanceState?.getBoolean(STATE_PICKING) == true -> picking = true
|
||||
else -> start()
|
||||
}
|
||||
}
|
||||
|
||||
override fun onSaveInstanceState(outState: Bundle) {
|
||||
super.onSaveInstanceState(outState)
|
||||
outState.putBoolean(STATE_PICKING, picking)
|
||||
}
|
||||
|
||||
private fun start() {
|
||||
val widget = appWidgetId
|
||||
lifecycleScope.launch {
|
||||
// A widget that came with an import already has its pictures waiting.
|
||||
val adopted = withContext(Dispatchers.IO) { adoptImported(widget) }
|
||||
if (adopted) {
|
||||
val ready = withContext(Dispatchers.IO) { hasPicturesWaiting(widget) }
|
||||
if (ready) {
|
||||
setResult(RESULT_OK, result())
|
||||
finish()
|
||||
} else {
|
||||
picking = true
|
||||
picker.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Hands the widget the pictures an import kept for its place on the home screen, if this is
|
||||
* such a widget and it has none yet. The launcher's database knows where the widget sits,
|
||||
* and an import keeps its pictures under that place.
|
||||
* True if this widget is waiting to be set up and already has its pictures, so that there
|
||||
* is nothing to choose: a widget that came back from a restore with them, or that an import
|
||||
* brought along with its photos (see [PictureWidgetProvider.onNewAppWidgetId]). The launcher's
|
||||
* database knows which widgets wait to be set up. The edit button, and a widget that has no
|
||||
* pictures, open the photo picker as ever.
|
||||
*/
|
||||
private fun adoptImported(widget: Int): Boolean {
|
||||
private fun hasPicturesWaiting(widget: Int): Boolean {
|
||||
val context = applicationContext
|
||||
if (!PictureWidgetStore.hasImports(context)) return false
|
||||
if (PictureWidgetStore.pictures(context, widget).isNotEmpty()) return false
|
||||
if (PictureWidgetStore.pictures(context, widget).isEmpty()) return false
|
||||
return try {
|
||||
LauncherAppState.getInstance(context).model.modelDbController.query(
|
||||
arrayOf(Favorites.SCREEN, Favorites.CELLX, Favorites.CELLY),
|
||||
"${Favorites.APPWIDGET_ID} = ? AND ${Favorites.ITEM_TYPE} = ${Favorites.ITEM_TYPE_APPWIDGET} " +
|
||||
"AND ${Favorites.CONTAINER} = ${Favorites.CONTAINER_DESKTOP}",
|
||||
arrayOf(Favorites.RESTORED),
|
||||
"${Favorites.APPWIDGET_ID} = ? AND ${Favorites.ITEM_TYPE} = ${Favorites.ITEM_TYPE_APPWIDGET}",
|
||||
arrayOf(widget.toString()),
|
||||
null,
|
||||
).use { row ->
|
||||
row.moveToFirst() &&
|
||||
PictureWidgetStore.adoptImport(context, widget, row.getInt(0), row.getInt(1), row.getInt(2))
|
||||
row.moveToFirst() && row.getInt(0) != LauncherAppWidgetInfo.RESTORE_COMPLETED
|
||||
}
|
||||
} catch (e: RuntimeException) {
|
||||
Log.w(TAG, "Could not look for imported pictures", e)
|
||||
Log.w(TAG, "Could not look the widget up", e)
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
private fun onChosen(chosen: List<Uri>) {
|
||||
picking = false
|
||||
if (chosen.isEmpty()) {
|
||||
finish()
|
||||
return
|
||||
}
|
||||
val widget = appWidgetId
|
||||
val context = applicationContext
|
||||
// Not tied to this screen, which Android may make anew while the copies are made, and
|
||||
// which the owner may leave for the home screen without waiting for them.
|
||||
val started = copying.async(Dispatchers.IO) {
|
||||
val saved = PictureWidgetStore.replace(context, widget, chosen) { isActive }
|
||||
// A widget that was being added is dropped when its screen is left before the copies
|
||||
// are done, and they go with it.
|
||||
if (isRemoved(context, widget)) PictureWidgetStore.delete(context, widget)
|
||||
saved
|
||||
}
|
||||
copies[widget] = started
|
||||
copying.launch {
|
||||
started.join()
|
||||
if (copies[widget] === started) copies.remove(widget)
|
||||
}
|
||||
waitFor(started)
|
||||
}
|
||||
|
||||
private fun waitFor(underWay: Deferred<Int>) {
|
||||
// Back while the pictures are copied means no: the copy stops, and the widget keeps what
|
||||
// it had. Any other way out, as to the home screen, lets the copy finish.
|
||||
onBackPressedDispatcher.addCallback(
|
||||
this,
|
||||
object : OnBackPressedCallback(true) {
|
||||
override fun handleOnBackPressed() {
|
||||
underWay.cancel()
|
||||
finish()
|
||||
}
|
||||
},
|
||||
)
|
||||
// Copying a few large photos takes a moment.
|
||||
setContentView(
|
||||
FrameLayout(this).apply {
|
||||
@@ -110,10 +172,16 @@ class PictureWidgetConfigActivity : ComponentActivity() {
|
||||
)
|
||||
},
|
||||
)
|
||||
val widget = appWidgetId
|
||||
lifecycleScope.launch {
|
||||
val saved = withContext(Dispatchers.IO) {
|
||||
PictureWidgetStore.replace(applicationContext, widget, chosen)
|
||||
val saved = try {
|
||||
underWay.await()
|
||||
} catch (e: CancellationException) {
|
||||
// Back stopped the copy, or this screen is gone; if it was made anew, the new one
|
||||
// waits for the copy.
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "The chosen pictures were not copied", e)
|
||||
0
|
||||
}
|
||||
if (saved > 0) {
|
||||
setResult(RESULT_OK, result())
|
||||
@@ -132,6 +200,22 @@ class PictureWidgetConfigActivity : ComponentActivity() {
|
||||
|
||||
private companion object {
|
||||
const val TAG = "PictureWidgetConfig"
|
||||
const val STATE_PICKING = "picking"
|
||||
|
||||
/** Copies of chosen pictures under way, by widget, each until it is done; used on the main thread only. */
|
||||
val copies = HashMap<Int, Deferred<Int>>()
|
||||
|
||||
/** Where those copies run: outside any one screen, so that they outlast it. */
|
||||
val copying = MainScope()
|
||||
|
||||
/** True if the widget has left the home screen, which takes its id away. */
|
||||
@WorkerThread
|
||||
fun isRemoved(context: Context, widget: Int): Boolean = try {
|
||||
AppWidgetManager.getInstance(context).getAppWidgetInfo(widget) == null
|
||||
} catch (e: RuntimeException) {
|
||||
Log.w(TAG, "Could not look the widget up", e)
|
||||
false
|
||||
}
|
||||
|
||||
/** How many pictures the photo picker lets the owner tick. */
|
||||
fun mostPictures(): Int = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
||||
|
||||
@@ -3,7 +3,10 @@ package app.flexera.widget
|
||||
import android.appwidget.AppWidgetProvider
|
||||
import android.content.ComponentName
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import com.android.launcher3.BuildConfig
|
||||
import com.android.launcher3.LauncherSettings.Favorites
|
||||
import com.android.launcher3.model.data.LauncherAppWidgetInfo
|
||||
|
||||
/**
|
||||
* The launcher's own picture widget: one picture, or several that take turns.
|
||||
@@ -11,7 +14,9 @@ import com.android.launcher3.BuildConfig
|
||||
* Android knows it as an ordinary app widget, so it is added, moved, resized and removed like
|
||||
* any other. What it shows is not sent through Android, though: the launcher draws it itself
|
||||
* with a [PictureWidgetView], which is what lets it line up with the icons around it. Its
|
||||
* pictures live in [PictureWidgetStore]. See [FlexeraWidgets].
|
||||
* pictures live in [PictureWidgetStore], under the widget's id; they leave only with the widget,
|
||||
* and a widget that comes back from a restore under a new id takes them along.
|
||||
* See [FlexeraWidgets].
|
||||
*/
|
||||
class PictureWidgetProvider : AppWidgetProvider() {
|
||||
|
||||
@@ -19,15 +24,72 @@ class PictureWidgetProvider : AppWidgetProvider() {
|
||||
appWidgetIds.forEach { PictureWidgetStore.delete(context, it) }
|
||||
}
|
||||
|
||||
/** After Android's own restore. */
|
||||
override fun onRestored(context: Context, oldWidgetIds: IntArray, newWidgetIds: IntArray) {
|
||||
for (i in oldWidgetIds.indices) {
|
||||
val newId = newWidgetIds.getOrNull(i) ?: continue
|
||||
PictureWidgetStore.move(context, oldWidgetIds[i], newId)
|
||||
}
|
||||
PictureWidgetStore.move(context, oldWidgetIds, newWidgetIds)
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = "PictureWidgetProvider"
|
||||
|
||||
@JvmField
|
||||
val componentName = ComponentName(BuildConfig.APPLICATION_ID, PictureWidgetProvider::class.java.name)
|
||||
|
||||
/**
|
||||
* Told by Launcher3 (WidgetInflater) that a widget of the home screen got a new id
|
||||
* because the one it had is no longer valid: after a restore of the launcher's backup or
|
||||
* an import. [oldAppWidgetId] is the id it had; an import's widgets had none.
|
||||
*
|
||||
* Android's onRestored does not come in that case. Launcher3 deletes the old id after
|
||||
* the home screens are loaded, and onDeleted would take the pictures with it, so they go
|
||||
* to the new id first. A picture widget of an import takes the pictures the import kept
|
||||
* for the place it was put in.
|
||||
*/
|
||||
@JvmStatic
|
||||
fun onNewAppWidgetId(context: Context, item: LauncherAppWidgetInfo, oldAppWidgetId: Int) {
|
||||
val newId = item.appWidgetId
|
||||
if (item.providerName != componentName || newId <= 0 || newId == oldAppWidgetId) return
|
||||
try {
|
||||
if (oldAppWidgetId > 0) {
|
||||
PictureWidgetStore.move(context, intArrayOf(oldAppWidgetId), intArrayOf(newId))
|
||||
} else if (item.container == Favorites.CONTAINER_DESKTOP) {
|
||||
PictureWidgetStore.adoptImport(context, newId, item.screenId, item.cellX, item.cellY)
|
||||
}
|
||||
} catch (e: RuntimeException) {
|
||||
// Never in the way of loading the home screens.
|
||||
Log.w(TAG, "Pictures not handed to widget $newId", e)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Told by Launcher3 (LoaderTask) that the home screens are loaded. Each picture widget an
|
||||
* import brought along has had its id by then, and with it the pictures the import kept
|
||||
* for it ([onNewAppWidgetId]). Pictures still kept are for a widget that did not come,
|
||||
* and no widget can take them later, so they go.
|
||||
*/
|
||||
@JvmStatic
|
||||
fun onHomeScreensLoaded(context: Context) {
|
||||
try {
|
||||
PictureWidgetStore.clearImports(context)
|
||||
} catch (e: RuntimeException) {
|
||||
Log.w(TAG, "Pictures of an import not removed", e)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Told by Launcher3 (LauncherWidgetHolder) that it deleted a widget id, of any widget.
|
||||
* Android calls onDeleted only for an id that was bound, and a widget removed while it
|
||||
* waited for "tap to set up" may have pictures under an id that was not
|
||||
* ([onNewAppWidgetId]); they go with it. For another widget's id there is nothing to remove.
|
||||
*/
|
||||
@JvmStatic
|
||||
fun onAppWidgetIdDeleted(context: Context, appWidgetId: Int) {
|
||||
if (appWidgetId <= 0) return
|
||||
try {
|
||||
PictureWidgetStore.delete(context, appWidgetId)
|
||||
} catch (e: RuntimeException) {
|
||||
Log.w(TAG, "Pictures of widget $appWidgetId not removed", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,9 @@ package app.flexera.widget
|
||||
import android.content.Context
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.BitmapFactory
|
||||
import android.graphics.BitmapRegionDecoder
|
||||
import android.graphics.ImageDecoder
|
||||
import android.graphics.Rect
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.os.Handler
|
||||
@@ -11,6 +13,7 @@ import android.os.Looper
|
||||
import android.util.Log
|
||||
import androidx.annotation.WorkerThread
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
import java.util.Locale
|
||||
import java.util.concurrent.CopyOnWriteArraySet
|
||||
import kotlin.math.max
|
||||
@@ -49,12 +52,13 @@ object PictureWidgetStore {
|
||||
/**
|
||||
* Gives a widget copies of [sources] in place of the pictures it had, and returns how many
|
||||
* were saved. A source that cannot be read is left out; when none can be read the widget
|
||||
* keeps what it had and the result is 0.
|
||||
* keeps what it had and the result is 0. So it does when [keepGoing] turns false before the
|
||||
* copies are done, as when the owner presses Back while they are being made.
|
||||
*/
|
||||
@WorkerThread
|
||||
fun replace(context: Context, appWidgetId: Int, sources: List<Uri>): Int {
|
||||
fun replace(context: Context, appWidgetId: Int, sources: List<Uri>, keepGoing: () -> Boolean = { true }): Int {
|
||||
val incoming = File(root(context), "$appWidgetId$INCOMING_SUFFIX")
|
||||
var saved = saveCopies(context, incoming, sources)
|
||||
var saved = saveCopies(context, incoming, sources, keepGoing)
|
||||
if (saved == 0) return 0
|
||||
val folder = folder(context, appWidgetId)
|
||||
folder.deleteRecursively()
|
||||
@@ -68,27 +72,27 @@ object PictureWidgetStore {
|
||||
|
||||
/**
|
||||
* Keeps copies of [sources] for a picture widget that an import has put at a place on a
|
||||
* home screen. Such a widget has no id yet: Android gives it one when the owner taps it to
|
||||
* set it up, and [adoptImport] then hands it these pictures. Returns how many were saved.
|
||||
* home screen. Such a widget has no id yet: the launcher gives it one when it first loads
|
||||
* the imported home screens, and [adoptImport] then hands it these pictures, which from then
|
||||
* on go with the widget wherever it is moved and leave with it. Returns how many were saved.
|
||||
*/
|
||||
@WorkerThread
|
||||
fun stageImport(context: Context, screen: Int, cellX: Int, cellY: Int, sources: List<Uri>): Int =
|
||||
saveCopies(context, importFolder(context, screen, cellX, cellY), sources)
|
||||
saveCopies(context, importFolder(context, screen, cellX, cellY), sources) { true }
|
||||
|
||||
/** True while pictures of an import wait for their widgets. */
|
||||
fun hasImports(context: Context): Boolean =
|
||||
root(context).listFiles { file -> file.isDirectory && file.name.startsWith(IMPORT_PREFIX) }
|
||||
?.isNotEmpty() == true
|
||||
|
||||
/** Forgets the pictures of an earlier import that were never claimed. */
|
||||
/**
|
||||
* Forgets the pictures an import kept that no widget took: when another import keeps its own,
|
||||
* and once the home screens are loaded ([PictureWidgetProvider.onHomeScreensLoaded]).
|
||||
*/
|
||||
fun clearImports(context: Context) {
|
||||
root(context).listFiles { file -> file.isDirectory && file.name.startsWith(IMPORT_PREFIX) }
|
||||
?.forEach { it.deleteRecursively() }
|
||||
}
|
||||
|
||||
/**
|
||||
* Gives a widget the pictures an import kept for the place it sits at. True if there were
|
||||
* any; the widget then needs no pictures chosen for it.
|
||||
* Gives a widget the pictures an import kept for the place it was imported to, when the
|
||||
* widget gets its id (see [PictureWidgetProvider.onNewAppWidgetId]). True if there were any.
|
||||
* Asked only then, so that a widget put in that place later never gets them.
|
||||
*/
|
||||
@WorkerThread
|
||||
fun adoptImport(context: Context, appWidgetId: Int, screen: Int, cellX: Int, cellY: Int): Boolean {
|
||||
@@ -101,13 +105,17 @@ object PictureWidgetStore {
|
||||
return true
|
||||
}
|
||||
|
||||
/** Fills [into] with copies of [sources], replacing what it held. Returns how many were saved. */
|
||||
private fun saveCopies(context: Context, into: File, sources: List<Uri>): Int {
|
||||
/**
|
||||
* Fills [into] with copies of [sources], replacing what it held. Returns how many were saved;
|
||||
* none, with nothing kept, if [keepGoing] turns false on the way.
|
||||
*/
|
||||
private fun saveCopies(context: Context, into: File, sources: List<Uri>, keepGoing: () -> Boolean): Int {
|
||||
into.deleteRecursively()
|
||||
if (!into.mkdirs()) return 0
|
||||
|
||||
var saved = 0
|
||||
for (source in sources.take(MAX_PICTURES)) {
|
||||
if (!keepGoing()) break
|
||||
val bitmap = try {
|
||||
decode(context, source)
|
||||
} catch (e: Exception) {
|
||||
@@ -134,7 +142,10 @@ object PictureWidgetStore {
|
||||
if (written) saved++ else file.delete()
|
||||
}
|
||||
|
||||
if (saved == 0) into.deleteRecursively()
|
||||
if (saved == 0 || !keepGoing()) {
|
||||
into.deleteRecursively()
|
||||
return 0
|
||||
}
|
||||
return saved
|
||||
}
|
||||
|
||||
@@ -145,22 +156,88 @@ object PictureWidgetStore {
|
||||
notifyChanged(appWidgetId)
|
||||
}
|
||||
|
||||
/** Hands the pictures of a widget to the id Android gave it after a restore. */
|
||||
fun move(context: Context, fromAppWidgetId: Int, toAppWidgetId: Int) {
|
||||
val from = folder(context, fromAppWidgetId)
|
||||
if (!from.isDirectory || fromAppWidgetId == toAppWidgetId) return
|
||||
val to = folder(context, toAppWidgetId)
|
||||
to.deleteRecursively()
|
||||
from.renameTo(to)
|
||||
notifyChanged(toAppWidgetId)
|
||||
/**
|
||||
* Hands the pictures of each widget in [from] to the widget at the same place in [to]: the
|
||||
* ids that a restore gave the widgets in place of the ones they had.
|
||||
*/
|
||||
fun move(context: Context, from: IntArray, to: IntArray) {
|
||||
// In two steps, so that an id that is one widget's old id and another's new one ends up
|
||||
// with the right pictures.
|
||||
val moving = ArrayList<Pair<File, Int>>()
|
||||
for (i in from.indices) {
|
||||
val newId = to.getOrNull(i) ?: continue
|
||||
val folder = folder(context, from[i])
|
||||
if (newId == from[i] || !folder.isDirectory) continue
|
||||
val aside = File(root(context), "${from[i]}$MOVING_SUFFIX")
|
||||
aside.deleteRecursively()
|
||||
if (folder.renameTo(aside)) moving.add(aside to newId)
|
||||
}
|
||||
for ((aside, newId) in moving) {
|
||||
val target = folder(context, newId)
|
||||
target.deleteRecursively()
|
||||
if (!aside.renameTo(target)) aside.deleteRecursively()
|
||||
notifyChanged(newId)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads a stored picture for a frame of [width] by [height] pixels: at the smallest size
|
||||
* that still covers the frame, so that no more memory is used than the screen can show.
|
||||
* Reads a stored picture for a frame of [width] by [height] pixels: only the part the frame
|
||||
* shows, which is the middle of the picture in the frame's shape, at the frame's size. A
|
||||
* picture smaller than the frame comes at its own size and is stretched when drawn.
|
||||
*/
|
||||
@WorkerThread
|
||||
fun load(file: File, width: Int, height: Int): Bitmap? {
|
||||
if (width <= 0 || height <= 0) return null
|
||||
val decoder = openInParts(file) ?: return loadWhole(file, width, height)
|
||||
try {
|
||||
val pictureWidth = decoder.width
|
||||
val pictureHeight = decoder.height
|
||||
if (pictureWidth <= 0 || pictureHeight <= 0) return null
|
||||
val part = if (pictureWidth.toLong() * height > pictureHeight.toLong() * width) {
|
||||
// Wider than the frame: its sides are cut off.
|
||||
val partWidth = (pictureHeight.toLong() * width / height).toInt().coerceIn(1, pictureWidth)
|
||||
val left = (pictureWidth - partWidth) / 2
|
||||
Rect(left, 0, left + partWidth, pictureHeight)
|
||||
} else {
|
||||
// Taller than the frame: its top and bottom are cut off.
|
||||
val partHeight = (pictureWidth.toLong() * height / width).toInt().coerceIn(1, pictureHeight)
|
||||
val top = (pictureHeight - partHeight) / 2
|
||||
Rect(0, top, pictureWidth, top + partHeight)
|
||||
}
|
||||
var sample = 1
|
||||
while (part.width() / (sample * 2) >= width && part.height() / (sample * 2) >= height) {
|
||||
sample *= 2
|
||||
}
|
||||
val read = decoder.decodeRegion(part, BitmapFactory.Options().apply { inSampleSize = sample })
|
||||
?: return loadWhole(file, width, height)
|
||||
// Read at a power of two, the part can still be up to twice the frame's size each way.
|
||||
if (read.width <= width && read.height <= height) return read
|
||||
val scaled = Bitmap.createScaledBitmap(read, width, height, true)
|
||||
if (scaled !== read) read.recycle()
|
||||
return scaled
|
||||
} finally {
|
||||
decoder.recycle()
|
||||
}
|
||||
}
|
||||
|
||||
/** Opens a stored picture for reading in parts; null if Android cannot read it that way. */
|
||||
@Suppress("DEPRECATION") // The only way before Android 12.
|
||||
private fun openInParts(file: File): BitmapRegionDecoder? = try {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
|
||||
BitmapRegionDecoder.newInstance(file.path)
|
||||
} else {
|
||||
BitmapRegionDecoder.newInstance(file.path, false)
|
||||
}
|
||||
} catch (e: IOException) {
|
||||
null
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads a whole stored picture, at the smallest size that still covers the frame; for a
|
||||
* picture that cannot be read in parts, or whose part could not be read. The frame then crops
|
||||
* it when it is drawn.
|
||||
*/
|
||||
private fun loadWhole(file: File, width: Int, height: Int): Bitmap? {
|
||||
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
|
||||
BitmapFactory.decodeFile(file.path, bounds)
|
||||
if (bounds.outWidth <= 0 || bounds.outHeight <= 0) return null
|
||||
@@ -227,6 +304,7 @@ object PictureWidgetStore {
|
||||
private const val TAG = "PictureWidgetStore"
|
||||
private const val FOLDER = "flexera_picture_widget"
|
||||
private const val INCOMING_SUFFIX = ".incoming"
|
||||
private const val MOVING_SUFFIX = ".moving"
|
||||
private const val IMPORT_PREFIX = "import-"
|
||||
|
||||
/** The most pictures one widget holds. */
|
||||
|
||||
@@ -8,6 +8,7 @@ import android.appwidget.AppWidgetManager
|
||||
import android.content.Context
|
||||
import android.content.ContextWrapper
|
||||
import android.content.Intent
|
||||
import android.content.res.Configuration
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.BitmapShader
|
||||
import android.graphics.Canvas
|
||||
@@ -17,20 +18,31 @@ import android.graphics.Paint
|
||||
import android.graphics.Path
|
||||
import android.graphics.RectF
|
||||
import android.graphics.Shader
|
||||
import android.graphics.Typeface
|
||||
import android.graphics.fonts.FontStyle
|
||||
import android.os.Build
|
||||
import android.text.Layout
|
||||
import android.text.StaticLayout
|
||||
import android.text.TextPaint
|
||||
import android.util.AttributeSet
|
||||
import android.util.Log
|
||||
import android.view.View
|
||||
import android.view.animation.LinearInterpolator
|
||||
import android.widget.FrameLayout
|
||||
import app.lawnchair.icons.shape.CornerShapeCompat
|
||||
import app.lawnchair.icons.shape.IconShape
|
||||
import app.lawnchair.preferences2.PreferenceManager2
|
||||
import app.lawnchair.preferences2.firstCached
|
||||
import com.android.launcher3.CellLayout
|
||||
import com.android.launcher3.Launcher
|
||||
import com.android.launcher3.LauncherState
|
||||
import com.android.launcher3.R
|
||||
import com.android.launcher3.ShortcutAndWidgetContainer
|
||||
import com.android.launcher3.Workspace
|
||||
import com.android.launcher3.folder.Folder
|
||||
import com.android.launcher3.util.Executors
|
||||
import java.io.File
|
||||
import java.text.BreakIterator
|
||||
import kotlin.math.max
|
||||
import kotlin.math.min
|
||||
import kotlin.math.roundToInt
|
||||
@@ -44,6 +56,10 @@ import kotlin.math.roundToInt
|
||||
* in use, so the picture lines up with the icons beside, above and below it. The view itself is
|
||||
* larger than the frame: it fills the widget's cells and draws nothing outside the frame.
|
||||
*
|
||||
* The pictures take turns only while the widget can be seen ([isSeen]). Each is read at the
|
||||
* size of the frame, which keeps the one shown small enough to stay in memory while the launcher
|
||||
* is out of sight, so that it is there at once on the way back.
|
||||
*
|
||||
* In the list of widgets and while it is dragged from there, the same view shows a sample.
|
||||
*/
|
||||
class PictureWidgetView @JvmOverloads constructor(
|
||||
@@ -82,6 +98,15 @@ class PictureWidgetView @JvmOverloads constructor(
|
||||
|
||||
private var onScreen = false
|
||||
|
||||
/**
|
||||
* True when none of the pictures could be read: the widget then shows and acts as if it had
|
||||
* none, until they are read anew ([reload]).
|
||||
*/
|
||||
private var unreadable = false
|
||||
|
||||
/** True while the slideshow waits for the widget to be seen again ([isSeen]). */
|
||||
private var waitingToBeSeen = false
|
||||
|
||||
private val frame = RectF()
|
||||
private val shape = Path()
|
||||
private val farHill = Path()
|
||||
@@ -90,6 +115,10 @@ class PictureWidgetView @JvmOverloads constructor(
|
||||
private val scratch = Path()
|
||||
private val cropMatrix = Matrix()
|
||||
private var hint: StaticLayout? = null
|
||||
private var hintTop = 0f
|
||||
|
||||
/** False when the hint needs the whole frame and the sun is left out of the drawing. */
|
||||
private var drawsSun = true
|
||||
private var sampleShader: Shader? = null
|
||||
|
||||
private val picturePaint = Paint(Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG)
|
||||
@@ -98,6 +127,11 @@ class PictureWidgetView @JvmOverloads constructor(
|
||||
private val hintPaint = TextPaint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
color = HINT_COLOR
|
||||
textSize = resources.getDimension(R.dimen.flexera_picture_widget_hint_text_size)
|
||||
// Heavier with Android's Bold text setting, like the icon labels.
|
||||
typeface = withBoldText(Typeface.DEFAULT)
|
||||
// The soft shadow of the icon labels, for the words over the light parts of the drawing.
|
||||
val density = resources.displayMetrics.density
|
||||
setShadowLayer(HINT_SHADOW_RADIUS_DP * density, 0f, HINT_SHADOW_DROP_DP * density, HINT_SHADOW_COLOR)
|
||||
}
|
||||
|
||||
private val advance = Runnable { showNext() }
|
||||
@@ -187,6 +221,15 @@ class PictureWidgetView @JvmOverloads constructor(
|
||||
}
|
||||
}
|
||||
|
||||
override fun onConfigurationChanged(newConfig: Configuration) {
|
||||
super.onConfigurationChanged(newConfig)
|
||||
// Android's Bold text setting is part of the configuration; the hint follows a new one
|
||||
// as a TextView does. Heavier words take more room, so it is laid out anew.
|
||||
hintPaint.typeface = withBoldText(Typeface.DEFAULT)
|
||||
if (!frame.isEmpty) buildSample()
|
||||
invalidate()
|
||||
}
|
||||
|
||||
/** Reads the widget's pictures anew and shows the one whose turn it is. */
|
||||
private fun reload() {
|
||||
fadeAnimator?.cancel()
|
||||
@@ -194,6 +237,7 @@ class PictureWidgetView @JvmOverloads constructor(
|
||||
removeCallbacks(reloadForSize)
|
||||
incoming = null
|
||||
pictures = if (sample) emptyList() else PictureWidgetStore.pictures(context, appWidgetId)
|
||||
unreadable = false
|
||||
updateDescription()
|
||||
if (pictures.isEmpty()) {
|
||||
loadGeneration++
|
||||
@@ -213,10 +257,34 @@ class PictureWidgetView @JvmOverloads constructor(
|
||||
index = index.coerceIn(0, pictures.lastIndex)
|
||||
loadedWidth = frame.width().roundToInt()
|
||||
loadedHeight = frame.height().roundToInt()
|
||||
load(index) { slide ->
|
||||
shown = slide
|
||||
invalidate()
|
||||
scheduleNext()
|
||||
showFirstReadable(index, pictures.size)
|
||||
}
|
||||
|
||||
/**
|
||||
* Shows the picture at [position], or the first after it that can be read, trying [tries]
|
||||
* pictures at most. When none can be read the widget looks and acts as if it had none, so
|
||||
* that a tap asks for new ones.
|
||||
*/
|
||||
private fun showFirstReadable(position: Int, tries: Int) {
|
||||
load(position) { slide ->
|
||||
when {
|
||||
slide != null -> {
|
||||
index = position
|
||||
shown = slide
|
||||
updateDescription()
|
||||
invalidate()
|
||||
scheduleNext()
|
||||
}
|
||||
|
||||
tries > 1 -> showFirstReadable((position + 1) % pictures.size, tries - 1)
|
||||
|
||||
else -> {
|
||||
shown = null
|
||||
unreadable = true
|
||||
updateDescription()
|
||||
invalidate()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -249,13 +317,32 @@ class PictureWidgetView @JvmOverloads constructor(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gives the shown picture a whole turn from now. With none that can be read there are no
|
||||
* turns: the widget asks for new pictures instead.
|
||||
*/
|
||||
private fun scheduleNext() {
|
||||
removeCallbacks(advance)
|
||||
if (onScreen && !sample && pictures.size > 1) postDelayed(advance, INTERVAL_MS)
|
||||
waitingToBeSeen = false
|
||||
if (onScreen && !sample && !unreadable && pictures.size > 1) postDelayed(advance, INTERVAL_MS)
|
||||
}
|
||||
|
||||
private fun showNext() {
|
||||
/** Brings in the next picture; at once for [now], as for a tap, else only if it can be seen. */
|
||||
private fun showNext(now: Boolean = false) {
|
||||
if (pictures.size < 2 || loading || incoming != null) return
|
||||
if (!now && !isSeen()) {
|
||||
// Nobody can see it, so nothing is read or faded in. It is looked at again shortly;
|
||||
// seen again, the picture it shows gets a whole turn first.
|
||||
waitingToBeSeen = true
|
||||
removeCallbacks(advance)
|
||||
if (onScreen) postDelayed(advance, SEEN_CHECK_MS)
|
||||
return
|
||||
}
|
||||
if (!now && waitingToBeSeen) {
|
||||
scheduleNext()
|
||||
return
|
||||
}
|
||||
waitingToBeSeen = false
|
||||
val next = (index + 1) % pictures.size
|
||||
load(next) { slide ->
|
||||
if (slide == null) {
|
||||
@@ -302,14 +389,48 @@ class PictureWidgetView @JvmOverloads constructor(
|
||||
scheduleNext()
|
||||
}
|
||||
|
||||
/**
|
||||
* True while the widget can really be seen. Its window being on the screen is not enough:
|
||||
* Launcher3 leaves every home screen page shown, and covers them with the app drawer, Recents
|
||||
* or a folder without hiding them.
|
||||
*/
|
||||
private fun isSeen(): Boolean {
|
||||
if (!onScreen || !isShown) return false
|
||||
val launcher = launcher() ?: return true
|
||||
if (!launcher.isInState(LauncherState.NORMAL) &&
|
||||
!launcher.isInState(LauncherState.SPRING_LOADED) &&
|
||||
!launcher.isInState(LauncherState.EDIT_MODE)
|
||||
) {
|
||||
return false
|
||||
}
|
||||
if (Folder.getOpen(launcher) != null) return false
|
||||
// On the home screen: the page the widget is on has to be one of those on the screen,
|
||||
// and not faded out.
|
||||
val cells = (parent as? View)?.parent as? ShortcutAndWidgetContainer ?: return true
|
||||
if (cells.alpha <= 0f) return false
|
||||
val page = cells.parent as? CellLayout ?: return true
|
||||
val pages = page.parent as? Workspace<*> ?: return true
|
||||
return pages.isVisible(page)
|
||||
}
|
||||
|
||||
private fun launcher(): Launcher? {
|
||||
var current: Context? = context
|
||||
while (current != null) {
|
||||
if (current is Launcher) return current
|
||||
current = (current as? ContextWrapper)?.baseContext
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
private fun onTap() {
|
||||
when {
|
||||
// Nothing to show yet, as after a restore on a new phone: ask for pictures.
|
||||
pictures.isEmpty() -> choosePictures()
|
||||
// Nothing to show yet, as after a restore on a new phone, or nothing that can be
|
||||
// read: ask for pictures.
|
||||
pictures.isEmpty() || unreadable -> choosePictures()
|
||||
// A tap does not wait for the picture's turn to end.
|
||||
pictures.size > 1 -> {
|
||||
removeCallbacks(advance)
|
||||
showNext()
|
||||
showNext(now = true)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -335,7 +456,7 @@ class PictureWidgetView @JvmOverloads constructor(
|
||||
private fun updateDescription() {
|
||||
contentDescription = when {
|
||||
sample -> resources.getString(R.string.flexera_picture_widget)
|
||||
pictures.isEmpty() -> resources.getString(R.string.flexera_picture_widget_empty)
|
||||
pictures.isEmpty() || unreadable -> resources.getString(R.string.flexera_picture_widget_empty)
|
||||
pictures.size == 1 -> resources.getString(R.string.flexera_picture_widget)
|
||||
else -> resources.getString(
|
||||
R.string.flexera_picture_widget_position,
|
||||
@@ -412,7 +533,12 @@ class PictureWidgetView @JvmOverloads constructor(
|
||||
nearHill.op(scratch, shape, Path.Op.INTERSECT)
|
||||
|
||||
scratch.reset()
|
||||
scratch.addCircle(frame.right - unit * 0.30f, frame.top + unit * 0.30f, unit * 0.10f, Path.Direction.CW)
|
||||
scratch.addCircle(
|
||||
frame.right - unit * SUN_CENTRE_SHARE,
|
||||
frame.top + unit * SUN_CENTRE_SHARE,
|
||||
unit * SUN_RADIUS_SHARE,
|
||||
Path.Direction.CW,
|
||||
)
|
||||
sun.op(scratch, shape, Path.Op.INTERSECT)
|
||||
|
||||
sampleShader = LinearGradient(
|
||||
@@ -426,16 +552,78 @@ class PictureWidgetView @JvmOverloads constructor(
|
||||
)
|
||||
|
||||
hint = null
|
||||
val hintWidth = (width - 2 * resources.getDimension(R.dimen.flexera_picture_widget_hint_margin)).toInt()
|
||||
if (!sample && hintWidth > 0) {
|
||||
val text = resources.getString(R.string.flexera_picture_widget_empty)
|
||||
val layout = StaticLayout.Builder.obtain(text, 0, text.length, hintPaint, hintWidth)
|
||||
.setAlignment(Layout.Alignment.ALIGN_CENTER)
|
||||
.build()
|
||||
// Too small a widget for the words gets the drawing alone.
|
||||
val fits = layout.lineCount <= HINT_MAX_LINES && layout.height <= height * HINT_MAX_HEIGHT_SHARE
|
||||
if (fits) hint = layout
|
||||
drawsSun = true
|
||||
if (!sample) layOutHint(unit)
|
||||
}
|
||||
|
||||
/**
|
||||
* Lays out the hint of a widget without pictures. It goes below the sun, so that the white
|
||||
* of the sun is never behind the words, at the size the owner has text at. Where they need
|
||||
* more room, at a large font size, they take the whole frame and the sun is left out; where
|
||||
* that is still too little they get smaller, though never smaller than at Android's standard
|
||||
* font size. Too small a widget for the words gets the drawing alone.
|
||||
*/
|
||||
private fun layOutHint(unit: Float) {
|
||||
val margin = resources.getDimension(R.dimen.flexera_picture_widget_hint_margin)
|
||||
val width = (frame.width() - 2 * margin).toInt()
|
||||
if (width <= 0) return
|
||||
val text = resources.getString(R.string.flexera_picture_widget_empty)
|
||||
val bottom = frame.bottom - margin
|
||||
val belowSun = frame.top + unit * (SUN_CENTRE_SHARE + SUN_RADIUS_SHARE) + margin
|
||||
|
||||
val wanted = hintPaint.textSize
|
||||
layHint(text, width, wanted, bottom - belowSun)?.let { layout ->
|
||||
hint = layout
|
||||
hintTop = belowSun + (bottom - belowSun - layout.height) / 2f
|
||||
return
|
||||
}
|
||||
val top = frame.top + margin
|
||||
val smallest = wanted / max(1f, resources.configuration.fontScale)
|
||||
var size = wanted
|
||||
while (true) {
|
||||
val layout = layHint(text, width, size, bottom - top)
|
||||
if (layout != null) {
|
||||
hint = layout
|
||||
hintTop = top + (bottom - top - layout.height) / 2f
|
||||
drawsSun = false
|
||||
return
|
||||
}
|
||||
if (size <= smallest) return
|
||||
size = max(smallest, size * HINT_SHRINK)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The hint at a text [size], or null if it is taller than [room], or if a word of it is wider
|
||||
* than [width] and would be split.
|
||||
*/
|
||||
private fun layHint(text: String, width: Int, size: Float, room: Float): StaticLayout? {
|
||||
if (room <= 0f) return null
|
||||
val paint = TextPaint(hintPaint).apply { textSize = size }
|
||||
val words = BreakIterator.getLineInstance().apply { setText(text) }
|
||||
var start = words.first()
|
||||
var end = words.next()
|
||||
while (end != BreakIterator.DONE) {
|
||||
if (paint.measureText(text.substring(start, end).trimEnd()) > width) return null
|
||||
start = end
|
||||
end = words.next()
|
||||
}
|
||||
val layout = StaticLayout.Builder.obtain(text, 0, text.length, paint, width)
|
||||
.setAlignment(Layout.Alignment.ALIGN_CENTER)
|
||||
.build()
|
||||
return layout.takeIf { it.height <= room }
|
||||
}
|
||||
|
||||
/**
|
||||
* [typeface] made heavier by Android's Bold text setting (Android 12 and newer), as Android
|
||||
* does for the text of a TextView but not for text drawn on a canvas.
|
||||
*/
|
||||
private fun withBoldText(typeface: Typeface): Typeface {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) return typeface
|
||||
val adjustment = resources.configuration.fontWeightAdjustment
|
||||
if (adjustment == 0 || adjustment == Configuration.FONT_WEIGHT_ADJUSTMENT_UNDEFINED) return typeface
|
||||
val weight = (typeface.weight + adjustment).coerceIn(FontStyle.FONT_WEIGHT_MIN, FontStyle.FONT_WEIGHT_MAX)
|
||||
return Typeface.create(typeface, weight, typeface.isItalic)
|
||||
}
|
||||
|
||||
override fun onDraw(canvas: Canvas) {
|
||||
@@ -443,7 +631,13 @@ class PictureWidgetView @JvmOverloads constructor(
|
||||
if (frame.isEmpty) return
|
||||
val current = shown
|
||||
if (current == null) {
|
||||
drawSample(canvas)
|
||||
if (pictures.isEmpty() || unreadable) {
|
||||
drawSample(canvas)
|
||||
} else {
|
||||
// A picture is on its way from storage. Until it comes there is the plate alone:
|
||||
// the drawing and its hint are for a widget that has no pictures.
|
||||
canvas.drawPath(shape, platePaint)
|
||||
}
|
||||
return
|
||||
}
|
||||
// The plate carries the shadow. A picture with see-through parts goes without, so
|
||||
@@ -474,8 +668,10 @@ class PictureWidgetView @JvmOverloads constructor(
|
||||
canvas.drawPath(shape, platePaint)
|
||||
platePaint.shader = null
|
||||
|
||||
sceneryPaint.alpha = SUN_ALPHA
|
||||
canvas.drawPath(sun, sceneryPaint)
|
||||
if (drawsSun) {
|
||||
sceneryPaint.alpha = SUN_ALPHA
|
||||
canvas.drawPath(sun, sceneryPaint)
|
||||
}
|
||||
sceneryPaint.alpha = FAR_HILL_ALPHA
|
||||
canvas.drawPath(farHill, sceneryPaint)
|
||||
sceneryPaint.alpha = NEAR_HILL_ALPHA
|
||||
@@ -483,10 +679,7 @@ class PictureWidgetView @JvmOverloads constructor(
|
||||
|
||||
val layout = hint ?: return
|
||||
canvas.save()
|
||||
canvas.translate(
|
||||
frame.left + (frame.width() - layout.width) / 2f,
|
||||
frame.top + frame.height() * HINT_CENTRE_SHARE - layout.height / 2f,
|
||||
)
|
||||
canvas.translate(frame.left + (frame.width() - layout.width) / 2f, hintTop)
|
||||
layout.draw(canvas)
|
||||
canvas.restore()
|
||||
}
|
||||
@@ -505,6 +698,9 @@ class PictureWidgetView @JvmOverloads constructor(
|
||||
/** How long the size has to stay put during a resize before the picture is read anew. */
|
||||
const val RESIZE_SETTLE_MS = 200L
|
||||
|
||||
/** How often a slideshow that nobody can see looks whether it can be seen again. */
|
||||
const val SEEN_CHECK_MS = 2_000L
|
||||
|
||||
/** Corner radius, as a share of the shorter side, where there are no icons to match. */
|
||||
const val LOOSE_CORNER_SHARE = 0.18f
|
||||
|
||||
@@ -521,11 +717,20 @@ class PictureWidgetView @JvmOverloads constructor(
|
||||
const val SAMPLE_COLOR_END = 0xFF2B3350.toInt()
|
||||
const val SCENERY_COLOR = 0xFFFFFFFF.toInt()
|
||||
const val SUN_ALPHA = 150
|
||||
|
||||
/** Where the sun's middle is from the top right corner, and its radius, as shares of the shorter side. */
|
||||
const val SUN_CENTRE_SHARE = 0.30f
|
||||
const val SUN_RADIUS_SHARE = 0.10f
|
||||
const val FAR_HILL_ALPHA = 40
|
||||
const val NEAR_HILL_ALPHA = 64
|
||||
const val HINT_COLOR = 0xF2FFFFFF.toInt()
|
||||
const val HINT_MAX_LINES = 2
|
||||
const val HINT_MAX_HEIGHT_SHARE = 0.4f
|
||||
const val HINT_CENTRE_SHARE = 0.36f
|
||||
|
||||
/** The step by which a hint that does not fit gets smaller. */
|
||||
const val HINT_SHRINK = 0.9f
|
||||
|
||||
// The soft shadow of light text on the wallpaper, as the clock widget has it.
|
||||
const val HINT_SHADOW_RADIUS_DP = 3f
|
||||
const val HINT_SHADOW_DROP_DP = 1f
|
||||
const val HINT_SHADOW_COLOR = 0x59000000
|
||||
}
|
||||
}
|
||||
@@ -3275,6 +3275,20 @@ public class Workspace<T extends View & PageIndicator> extends PagedView<T>
|
||||
|
||||
private Drawable createWidgetDrawable(ItemInfo widgetInfo, View layout) {
|
||||
int[] unScaledSize = estimateItemSize(widgetInfo);
|
||||
if (widgetInfo.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET
|
||||
&& getChildCount() > 0) {
|
||||
// Flexera Launcher: the widget is drawn for the drop animation at the size it is
|
||||
// laid out at, its cells less the room it keeps in them, which is where the
|
||||
// animation lands it (getFinalPositionForDropAnimation). Drawn at its cells whole,
|
||||
// as Launcher3 draws it, the picture is squeezed into that box and then gives way
|
||||
// to the widget's own layout, so its text and pictures jump as the animation ends.
|
||||
CellLayout cl = (CellLayout) getChildAt(0);
|
||||
Rect inset = app.flexera.widget.FlexeraWidgets.cellInset(
|
||||
widgetInfo.getTargetComponent(), mLauncher.getDeviceProfile(),
|
||||
cl.getCellWidth(), cl.getCellHeight());
|
||||
unScaledSize[0] = Math.max(1, unScaledSize[0] - inset.left - inset.right);
|
||||
unScaledSize[1] = Math.max(1, unScaledSize[1] - inset.top - inset.bottom);
|
||||
}
|
||||
int visibility = layout.getVisibility();
|
||||
layout.setVisibility(VISIBLE);
|
||||
|
||||
@@ -3299,16 +3313,21 @@ public class Workspace<T extends View & PageIndicator> extends PagedView<T>
|
||||
Rect r = estimateItemPosition(layout, targetCell[0], targetCell[1], spanX, spanY);
|
||||
if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET) {
|
||||
DeviceProfile profile = mLauncher.getDeviceProfile();
|
||||
if (finalView instanceof NavigableAppWidgetHostView) {
|
||||
// Flexera Launcher: the room this widget keeps in its cells.
|
||||
Point cell = profile.getCellSize();
|
||||
Rect widgetPadding = app.flexera.widget.FlexeraWidgets.cellInset(
|
||||
finalView, profile, cell.x, cell.y);
|
||||
r.left -= widgetPadding.left;
|
||||
r.right += widgetPadding.right;
|
||||
r.top -= widgetPadding.top;
|
||||
r.bottom += widgetPadding.bottom;
|
||||
}
|
||||
// Flexera Launcher: the drop lands on the box the widget is laid out in, its cells
|
||||
// less the room it keeps in them, worked out from the cells of the page it lands on
|
||||
// as ShortcutAndWidgetContainer does. Launcher3 added that room on instead of taking
|
||||
// it off, and left it out when the widget had no view yet (one that has to be set up
|
||||
// first); with the room that lines other apps' widgets up with the icons, a dropped
|
||||
// widget grew past its cells and then jumped to its real size. Whose widget it is
|
||||
// comes from the item, because one dropped from the list of widgets is not tagged
|
||||
// with it yet.
|
||||
Rect widgetPadding = app.flexera.widget.FlexeraWidgets.cellInset(
|
||||
info.getTargetComponent(), profile,
|
||||
layout.getCellWidth(), layout.getCellHeight());
|
||||
r.left += widgetPadding.left;
|
||||
r.right -= widgetPadding.right;
|
||||
r.top += widgetPadding.top;
|
||||
r.bottom -= widgetPadding.bottom;
|
||||
PointF appWidgetScale = profile.getAppWidgetScale(null);
|
||||
Utilities.shrinkRect(r, appWidgetScale.x, appWidgetScale.y);
|
||||
}
|
||||
|
||||
@@ -592,6 +592,11 @@ public class LoaderTask implements Runnable {
|
||||
private void sanitizeWidgetsShortcutsAndPackages() {
|
||||
// Remove any ghost widgets
|
||||
mModel.getModelDbController().removeGhostWidgets();
|
||||
// Flexera Launcher: and the pictures an import kept for photo widgets that did not come.
|
||||
// Not in safe mode, where widgets get no ids and so have not taken theirs yet.
|
||||
if (!mIsSafeModeEnabled) {
|
||||
app.flexera.widget.PictureWidgetProvider.onHomeScreensLoaded(mContext);
|
||||
}
|
||||
|
||||
// Update pinned state of model shortcuts
|
||||
mBgDataModel.updateShortcutPinnedState(mContext);
|
||||
|
||||
@@ -194,6 +194,11 @@ public class LauncherWidgetHolder {
|
||||
public void deleteAppWidgetId(int appWidgetId) {
|
||||
mWidgetHost.deleteAppWidgetId(appWidgetId);
|
||||
mViews.remove(appWidgetId);
|
||||
// Flexera Launcher: Android tells a widget's provider that it was deleted (onDeleted) only
|
||||
// if its id was bound. The id of a widget removed while it waited for "tap to set up" was
|
||||
// not, and the launcher's own widgets may already keep pictures or options under it.
|
||||
app.flexera.widget.PictureWidgetProvider.onAppWidgetIdDeleted(mContext, appWidgetId);
|
||||
app.flexera.widget.ClockWidgetProvider.onAppWidgetIdDeleted(mContext, appWidgetId);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -111,14 +111,28 @@ constructor(
|
||||
)
|
||||
}
|
||||
|
||||
// Flexera Launcher: a widget whose setting up is optional is never set up by a tap on
|
||||
// "tap to set up" (WidgetAddFlowHandler.needsConfigure), so after a restore it is ready
|
||||
// as it is, like one without a setting up; waiting for one left it there for good.
|
||||
// That goes for the widgets of every app, the launcher's own Clock among them, and for
|
||||
// Android's own restore too: there such a widget no longer waits for its app to say
|
||||
// the restore is done (isAppWidgetRestored), and shows what its app gives it.
|
||||
val needsSetUp = WidgetAddFlowHandler(appWidgetInfo).needsConfigure()
|
||||
|
||||
// If we do not have a valid id, try to bind an id.
|
||||
if (item.hasRestoreFlag(LauncherAppWidgetInfo.FLAG_ID_NOT_VALID)) {
|
||||
if (!item.hasRestoreFlag(LauncherAppWidgetInfo.FLAG_ID_ALLOCATED)) {
|
||||
// Id has not been allocated yet. Allocate a new id.
|
||||
val oldAppWidgetId = item.appWidgetId // Flexera Launcher: see below.
|
||||
LauncherWidgetHolder.newInstance(context).let {
|
||||
item.appWidgetId = it.allocateAppWidgetId()
|
||||
it.destroy()
|
||||
}
|
||||
// Flexera Launcher: the launcher's own widgets keep their pictures and options
|
||||
// under the widget's id. Launcher3 deletes the old id once the home screens are
|
||||
// loaded, which would delete those too, so they go to the new id first.
|
||||
app.flexera.widget.PictureWidgetProvider.onNewAppWidgetId(context, item, oldAppWidgetId)
|
||||
app.flexera.widget.ClockWidgetProvider.onNewAppWidgetId(context, item, oldAppWidgetId)
|
||||
item.restoreStatus =
|
||||
item.restoreStatus or LauncherAppWidgetInfo.FLAG_ID_ALLOCATED
|
||||
|
||||
@@ -158,7 +172,7 @@ constructor(
|
||||
// If the widget has a configure activity, it is still needs to set it
|
||||
// up, otherwise the widget is ready to go.
|
||||
item.restoreStatus =
|
||||
if ((appWidgetInfo.configure == null) || isDirectConfig)
|
||||
if (!needsSetUp || isDirectConfig) // Flexera Launcher: see needsSetUp.
|
||||
LauncherAppWidgetInfo.RESTORE_COMPLETED
|
||||
else LauncherAppWidgetInfo.FLAG_UI_NOT_READY
|
||||
}
|
||||
@@ -166,7 +180,7 @@ constructor(
|
||||
}
|
||||
} else if (
|
||||
(item.hasRestoreFlag(LauncherAppWidgetInfo.FLAG_UI_NOT_READY) &&
|
||||
(appWidgetInfo.configure == null))
|
||||
!needsSetUp) // Flexera Launcher: see needsSetUp.
|
||||
) {
|
||||
// The widget was marked as UI not ready, but there is no configure activity to
|
||||
// update the UI.
|
||||
|
||||
Reference in new issue
Block a user