VancedMicroG/play-services-core/src/main/kotlin/org/microg/gms/ui/Utils.kt

85 lines
3.1 KiB
Kotlin

/*
* SPDX-FileCopyrightText: 2020, microG Project Team
* SPDX-License-Identifier: Apache-2.0
*/
package org.microg.gms.ui
import android.content.ComponentName
import android.content.Context
import android.content.pm.ApplicationInfo
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.util.Log
import android.util.TypedValue
import android.view.View
import androidx.annotation.AttrRes
import androidx.annotation.ColorInt
import androidx.annotation.IdRes
import androidx.annotation.RequiresApi
import androidx.core.content.ContextCompat
import androidx.databinding.BindingAdapter
import androidx.navigation.NavController
import androidx.navigation.navOptions
import androidx.navigation.ui.R
fun PackageManager.getApplicationInfoIfExists(packageName: String?, flags: Int = 0): ApplicationInfo? = packageName?.let {
try {
getApplicationInfo(it, flags)
} catch (e: Exception) {
Log.w(TAG, "Package $packageName not installed.")
null
}
}
fun NavController.navigate(context: Context, @IdRes resId: Int, args: Bundle? = null) {
navigate(resId, args, if (context.systemAnimationsEnabled) navOptions {
anim {
enter = R.anim.nav_default_enter_anim
exit = R.anim.nav_default_exit_anim
popEnter = R.anim.nav_default_pop_enter_anim
popExit = R.anim.nav_default_pop_exit_anim
}
} else null)
}
@RequiresApi(Build.VERSION_CODES.M)
fun Context.hideIcon(hide: Boolean) {
packageManager.setComponentEnabledSetting(
ComponentName.createRelative(this, "org.microg.gms.ui.SettingsActivityLauncher"),
when (hide) {
true -> PackageManager.COMPONENT_ENABLED_STATE_DISABLED
false -> PackageManager.COMPONENT_ENABLED_STATE_ENABLED
},
PackageManager.DONT_KILL_APP
)
}
val Context.systemAnimationsEnabled: Boolean
get() {
val duration: Float
val transition: Float
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
duration = Settings.Global.getFloat(contentResolver, Settings.Global.ANIMATOR_DURATION_SCALE, 1f)
transition = Settings.Global.getFloat(contentResolver, Settings.Global.TRANSITION_ANIMATION_SCALE, 1f)
} else {
duration = Settings.System.getFloat(contentResolver, Settings.System.ANIMATOR_DURATION_SCALE, 1f)
transition = Settings.System.getFloat(contentResolver, Settings.System.TRANSITION_ANIMATION_SCALE, 1f)
}
return duration != 0f && transition != 0f
}
@ColorInt
fun Context.resolveColor(@AttrRes resid: Int): Int? {
val typedValue = TypedValue()
if (!theme.resolveAttribute(resid, typedValue, true)) return null
val colorRes = if (typedValue.resourceId != 0) typedValue.resourceId else typedValue.data
return ContextCompat.getColor(this, colorRes)
}
@BindingAdapter("app:backgroundColorAttr")
fun View.setBackgroundColorAttribute(@AttrRes resId: Int) = context.resolveColor(resId)?.let { setBackgroundColor(it) }