content
stringlengths 0
13M
| path
stringlengths 4
263
| contentHash
stringlengths 1
10
|
---|---|---|
package com.simplemobiletools.commons.compose.settings
import androidx.compose.foundation.layout.*
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ProvideTextStyle
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.simplemobiletools.commons.compose.extensions.MyDevices
import com.simplemobiletools.commons.compose.theme.SimpleTheme
@Composable
fun SettingsGroup(
modifier: Modifier = Modifier,
title: @Composable (() -> Unit)? = null,
content: @Composable ColumnScope.() -> Unit,
) {
Column(
modifier = modifier.fillMaxWidth(),
) {
if (title != null) {
SettingsGroupTitle(title = title)
}
content()
}
}
@Composable
fun SettingsGroupTitle(
modifier: Modifier = Modifier,
title: @Composable () -> Unit
) {
Box(
modifier = modifier
.fillMaxWidth()
.padding(horizontal = SimpleTheme.dimens.padding.extraLarge),
contentAlignment = Alignment.CenterStart
) {
val primary = SimpleTheme.colorScheme.primary
val titleStyle = SimpleTheme.typography.headlineMedium.copy(color = primary)
ProvideTextStyle(value = titleStyle) { title() }
}
}
@MyDevices
@Composable
private fun SettingsGroupPreview() {
MaterialTheme {
SettingsGroup(
title = { Text(text = "Title") }
) {
Box(
modifier = Modifier
.height(64.dp)
.fillMaxWidth(),
contentAlignment = Alignment.Center,
) {
Text(text = "Settings group")
}
}
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/compose/settings/SettingsGroup.kt | 2009836403 |
package com.simplemobiletools.commons.compose.settings
import androidx.compose.material3.DividerDefaults
import androidx.compose.material3.HorizontalDivider
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.Dp
import com.simplemobiletools.commons.compose.extensions.MyDevices
import com.simplemobiletools.commons.compose.theme.AppThemeSurface
import com.simplemobiletools.commons.compose.theme.divider_grey
@Composable
fun SettingsHorizontalDivider(
modifier: Modifier = Modifier,
color: Color = divider_grey,
thickness: Dp = DividerDefaults.Thickness,
) {
HorizontalDivider(modifier = modifier, color = color, thickness = thickness)
}
@Composable
@MyDevices
private fun SettingsHorizontalDividerPreview() {
AppThemeSurface {
SettingsHorizontalDivider()
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/compose/settings/SettingsDivider.kt | 4223932487 |
package com.simplemobiletools.commons.compose.settings
import androidx.annotation.DrawableRes
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material3.Icon
import androidx.compose.material3.ListItem
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.PreviewParameter
import androidx.compose.ui.unit.TextUnit
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.compose.extensions.BooleanPreviewParameterProvider
import com.simplemobiletools.commons.compose.extensions.MyDevices
import com.simplemobiletools.commons.compose.theme.AppThemeSurface
import com.simplemobiletools.commons.compose.theme.SimpleTheme
@Composable
fun SettingsListItem(
modifier: Modifier = Modifier,
text: String,
fontSize: TextUnit = TextUnit.Unspecified,
maxLines: Int = Int.MAX_VALUE,
overflow: TextOverflow = TextOverflow.Clip,
@DrawableRes icon: Int? = null,
isImage: Boolean = false,
click: (() -> Unit)? = null,
tint: Color? = null
) {
ListItem(
headlineContent = {
Text(
text = text,
modifier = Modifier
.fillMaxWidth()
.then(modifier),
fontSize = fontSize,
maxLines = maxLines,
overflow = overflow
)
},
leadingContent = {
val imageSize = Modifier
.size(SimpleTheme.dimens.icon.medium)
.padding(SimpleTheme.dimens.padding.medium)
when {
icon != null && isImage && tint != null -> Image(
modifier = imageSize,
painter = painterResource(id = icon),
contentDescription = text,
colorFilter = ColorFilter.tint(tint)
)
icon != null && isImage && tint == null -> Image(
modifier = imageSize,
painter = painterResource(id = icon),
contentDescription = text,
)
icon != null && !isImage && tint == null -> Icon(
modifier = imageSize,
painter = painterResource(id = icon),
contentDescription = text,
)
icon != null && !isImage && tint != null -> Icon(
modifier = imageSize,
painter = painterResource(id = icon),
contentDescription = text,
tint = tint
)
else -> Box(
modifier = imageSize,
)
}
},
modifier = Modifier
.fillMaxWidth()
.clickable(enabled = click != null) { click?.invoke() }
)
}
@Composable
fun SettingsListItem(
modifier: Modifier = Modifier,
text: @Composable () -> Unit,
@DrawableRes icon: Int? = null,
isImage: Boolean = false,
click: (() -> Unit)? = null,
tint: Color? = null
) {
ListItem(
headlineContent = {
text()
},
leadingContent = {
val imageSize = Modifier
.size(SimpleTheme.dimens.icon.medium)
.padding(SimpleTheme.dimens.padding.medium)
when {
icon != null && isImage && tint != null -> Image(
modifier = imageSize,
painter = painterResource(id = icon),
contentDescription = null,
colorFilter = ColorFilter.tint(tint)
)
icon != null && isImage && tint == null -> Image(
modifier = imageSize,
painter = painterResource(id = icon),
contentDescription = null,
)
icon != null && !isImage && tint == null -> Icon(
modifier = imageSize,
painter = painterResource(id = icon),
contentDescription = null,
)
icon != null && !isImage && tint != null -> Icon(
modifier = imageSize,
painter = painterResource(id = icon),
contentDescription = null,
tint = tint
)
else -> Box(
modifier = imageSize,
)
}
},
modifier = modifier
.fillMaxWidth()
.clickable(enabled = click != null) { click?.invoke() }
)
}
@MyDevices
@Composable
private fun SettingsListItem(@PreviewParameter(BooleanPreviewParameterProvider::class) isImage: Boolean) {
AppThemeSurface {
SettingsListItem(
click = {},
text = "Simple Mobile Tools",
icon = if (isImage) R.drawable.ic_telegram_vector else R.drawable.ic_dollar_vector,
isImage = isImage
)
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/compose/settings/SettingsListItem.kt | 1013277445 |
package com.simplemobiletools.commons.compose.lists
import androidx.compose.foundation.gestures.FlingBehavior
import androidx.compose.foundation.gestures.ScrollableDefaults
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListScope
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.AccessTime
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import com.simplemobiletools.commons.compose.extensions.AdjustNavigationBarColors
import com.simplemobiletools.commons.compose.extensions.MyDevices
import com.simplemobiletools.commons.compose.extensions.plus
import com.simplemobiletools.commons.compose.extensions.rememberMutableInteractionSource
import com.simplemobiletools.commons.compose.theme.AppThemeSurface
@Composable
fun SimpleLazyListScaffold(
title: String,
goBack: () -> Unit,
modifier: Modifier = Modifier,
contentPadding: PaddingValues = PaddingValues(0.dp),
reverseLayout: Boolean = false,
verticalArrangement: Arrangement.Vertical =
if (!reverseLayout) Arrangement.Top else Arrangement.Bottom,
horizontalAlignment: Alignment.Horizontal = Alignment.Start,
flingBehavior: FlingBehavior = ScrollableDefaults.flingBehavior(),
userScrollEnabled: Boolean = true,
state: LazyListState = rememberLazyListState(),
lazyContent: LazyListScope.(PaddingValues) -> Unit
) {
val context = LocalContext.current
val (statusBarColor, contrastColor) = statusBarAndContrastColor(context)
val scrollBehavior = TopAppBarDefaults.pinnedScrollBehavior(rememberTopAppBarState())
val (colorTransitionFraction, scrolledColor) = transitionFractionAndScrolledColor(scrollBehavior, contrastColor)
SystemUISettingsScaffoldStatusBarColor(scrolledColor)
val navigationIconInteractionSource = rememberMutableInteractionSource()
AdjustNavigationBarColors()
Scaffold(
modifier = modifier
.fillMaxSize()
.nestedScroll(scrollBehavior.nestedScrollConnection),
topBar = {
SimpleScaffoldTopBar(
title = title,
scrolledColor = scrolledColor,
navigationIconInteractionSource = navigationIconInteractionSource,
goBack = goBack,
scrollBehavior = scrollBehavior,
statusBarColor = statusBarColor,
colorTransitionFraction = colorTransitionFraction,
contrastColor = contrastColor
)
}
) { paddingValues ->
ScreenBoxSettingsScaffold(paddingValues) {
LazyColumn(
modifier = Modifier
.matchParentSize(),
state = state,
contentPadding = contentPadding.plus(PaddingValues(bottom = paddingValues.calculateBottomPadding())),
reverseLayout = reverseLayout,
verticalArrangement = verticalArrangement,
horizontalAlignment = horizontalAlignment,
flingBehavior = flingBehavior,
userScrollEnabled = userScrollEnabled
) {
lazyContent(paddingValues)
}
}
}
}
@Composable
fun SimpleLazyListScaffold(
modifier: Modifier = Modifier,
title: @Composable (scrolledColor: Color) -> Unit,
goBack: () -> Unit,
contentPadding: PaddingValues = PaddingValues(0.dp),
reverseLayout: Boolean = false,
verticalArrangement: Arrangement.Vertical =
if (!reverseLayout) Arrangement.Top else Arrangement.Bottom,
horizontalAlignment: Alignment.Horizontal = Alignment.Start,
flingBehavior: FlingBehavior = ScrollableDefaults.flingBehavior(),
userScrollEnabled: Boolean = true,
state: LazyListState = rememberLazyListState(),
lazyContent: LazyListScope.(PaddingValues) -> Unit
) {
val context = LocalContext.current
val (statusBarColor, contrastColor) = statusBarAndContrastColor(context)
val scrollBehavior = TopAppBarDefaults.pinnedScrollBehavior(rememberTopAppBarState())
val (colorTransitionFraction, scrolledColor) = transitionFractionAndScrolledColor(scrollBehavior, contrastColor)
SystemUISettingsScaffoldStatusBarColor(scrolledColor)
val navigationIconInteractionSource = rememberMutableInteractionSource()
AdjustNavigationBarColors()
Scaffold(
modifier = modifier
.fillMaxSize()
.nestedScroll(scrollBehavior.nestedScrollConnection),
topBar = {
SimpleScaffoldTopBar(
title = title,
scrolledColor = scrolledColor,
navigationIconInteractionSource = navigationIconInteractionSource,
goBack = goBack,
scrollBehavior = scrollBehavior,
statusBarColor = statusBarColor,
colorTransitionFraction = colorTransitionFraction,
contrastColor = contrastColor
)
}
) { paddingValues ->
ScreenBoxSettingsScaffold(paddingValues) {
LazyColumn(
modifier = Modifier
.matchParentSize(),
state = state,
contentPadding = contentPadding.plus(PaddingValues(bottom = paddingValues.calculateBottomPadding())),
reverseLayout = reverseLayout,
verticalArrangement = verticalArrangement,
horizontalAlignment = horizontalAlignment,
flingBehavior = flingBehavior,
userScrollEnabled = userScrollEnabled,
) {
lazyContent(paddingValues)
}
}
}
}
@Composable
fun SimpleLazyListScaffold(
modifier: Modifier = Modifier,
title: @Composable (scrolledColor: Color) -> Unit,
actions: @Composable() (RowScope.() -> Unit),
goBack: () -> Unit,
contentPadding: PaddingValues = PaddingValues(0.dp),
reverseLayout: Boolean = false,
verticalArrangement: Arrangement.Vertical =
if (!reverseLayout) Arrangement.Top else Arrangement.Bottom,
horizontalAlignment: Alignment.Horizontal = Alignment.Start,
flingBehavior: FlingBehavior = ScrollableDefaults.flingBehavior(),
userScrollEnabled: Boolean = true,
state: LazyListState = rememberLazyListState(),
lazyContent: LazyListScope.(PaddingValues) -> Unit
) {
val context = LocalContext.current
val (statusBarColor, contrastColor) = statusBarAndContrastColor(context)
val scrollBehavior = TopAppBarDefaults.pinnedScrollBehavior(rememberTopAppBarState())
val (colorTransitionFraction, scrolledColor) = transitionFractionAndScrolledColor(scrollBehavior, contrastColor)
SystemUISettingsScaffoldStatusBarColor(scrolledColor)
val navigationIconInteractionSource = rememberMutableInteractionSource()
AdjustNavigationBarColors()
Scaffold(
modifier = modifier
.fillMaxSize()
.nestedScroll(scrollBehavior.nestedScrollConnection),
topBar = {
SimpleScaffoldTopBar(
title = title,
scrolledColor = scrolledColor,
navigationIconInteractionSource = navigationIconInteractionSource,
goBack = goBack,
scrollBehavior = scrollBehavior,
statusBarColor = statusBarColor,
colorTransitionFraction = colorTransitionFraction,
contrastColor = contrastColor,
actions = actions
)
}
) { paddingValues ->
ScreenBoxSettingsScaffold(paddingValues) {
LazyColumn(
modifier = Modifier
.matchParentSize(),
state = state,
contentPadding = contentPadding.plus(PaddingValues(bottom = paddingValues.calculateBottomPadding())),
reverseLayout = reverseLayout,
verticalArrangement = verticalArrangement,
horizontalAlignment = horizontalAlignment,
flingBehavior = flingBehavior,
userScrollEnabled = userScrollEnabled
) {
lazyContent(paddingValues)
}
}
}
}
@Composable
fun SimpleLazyListScaffold(
modifier: Modifier = Modifier,
topBar: @Composable (scrolledColor: Color, navigationInteractionSource: MutableInteractionSource, scrollBehavior: TopAppBarScrollBehavior, statusBarColor: Int, colorTransitionFraction: Float, contrastColor: Color) -> Unit,
contentPadding: PaddingValues = PaddingValues(0.dp),
reverseLayout: Boolean = false,
verticalArrangement: Arrangement.Vertical =
if (!reverseLayout) Arrangement.Top else Arrangement.Bottom,
horizontalAlignment: Alignment.Horizontal = Alignment.Start,
flingBehavior: FlingBehavior = ScrollableDefaults.flingBehavior(),
userScrollEnabled: Boolean = true,
state: LazyListState = rememberLazyListState(),
lazyContent: LazyListScope.(PaddingValues) -> Unit
) {
val context = LocalContext.current
val (statusBarColor, contrastColor) = statusBarAndContrastColor(context)
val scrollBehavior = TopAppBarDefaults.pinnedScrollBehavior(rememberTopAppBarState())
val (colorTransitionFraction, scrolledColor) = transitionFractionAndScrolledColor(scrollBehavior, contrastColor)
SystemUISettingsScaffoldStatusBarColor(scrolledColor)
val navigationIconInteractionSource = rememberMutableInteractionSource()
AdjustNavigationBarColors()
Scaffold(
modifier = modifier
.fillMaxSize()
.nestedScroll(scrollBehavior.nestedScrollConnection),
topBar = {
topBar(scrolledColor, navigationIconInteractionSource, scrollBehavior, statusBarColor, colorTransitionFraction, contrastColor)
}
) { paddingValues ->
ScreenBoxSettingsScaffold(paddingValues) {
LazyColumn(
modifier = Modifier
.matchParentSize(),
state = state,
contentPadding = contentPadding.plus(PaddingValues(bottom = paddingValues.calculateBottomPadding())),
reverseLayout = reverseLayout,
verticalArrangement = verticalArrangement,
horizontalAlignment = horizontalAlignment,
flingBehavior = flingBehavior,
userScrollEnabled = userScrollEnabled
) {
lazyContent(paddingValues)
}
}
}
}
@Composable
fun SimpleScaffold(
modifier: Modifier = Modifier,
darkStatusBarIcons: Boolean = true,
customTopBar: @Composable (scrolledColor: Color, navigationInteractionSource: MutableInteractionSource, scrollBehavior: TopAppBarScrollBehavior, statusBarColor: Int, colorTransitionFraction: Float, contrastColor: Color) -> Unit,
customContent: @Composable (BoxScope.(PaddingValues) -> Unit)
) {
val context = LocalContext.current
val (statusBarColor, contrastColor) = statusBarAndContrastColor(context)
val scrollBehavior = TopAppBarDefaults.pinnedScrollBehavior(rememberTopAppBarState())
val (colorTransitionFraction, scrolledColor) = transitionFractionAndScrolledColor(scrollBehavior, contrastColor, darkStatusBarIcons)
SystemUISettingsScaffoldStatusBarColor(scrolledColor)
val navigationIconInteractionSource = rememberMutableInteractionSource()
AdjustNavigationBarColors()
Scaffold(
modifier = modifier
.fillMaxSize()
.nestedScroll(scrollBehavior.nestedScrollConnection),
topBar = {
customTopBar(scrolledColor, navigationIconInteractionSource, scrollBehavior, statusBarColor, colorTransitionFraction, contrastColor)
}
) { paddingValues ->
ScreenBoxSettingsScaffold(paddingValues) {
customContent(paddingValues)
}
}
}
@MyDevices
@Composable
private fun SimpleLazyListScaffoldPreview() {
AppThemeSurface {
SimpleLazyListScaffold(title = "About", goBack = {}) {
item {
ListItem(headlineContent = { Text(text = "Some text") },
leadingContent = {
Icon(imageVector = Icons.Filled.AccessTime, contentDescription = null)
})
}
}
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/compose/lists/SimpleLazyListScaffold.kt | 4244515812 |
package com.simplemobiletools.commons.compose.lists
import android.content.Context
import androidx.compose.foundation.background
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.layout.*
import androidx.compose.material3.TopAppBarScrollBehavior
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.lerp
import androidx.compose.ui.platform.LocalLayoutDirection
import com.simplemobiletools.commons.compose.extensions.onEventValue
import com.simplemobiletools.commons.compose.system_ui_controller.rememberSystemUiController
import com.simplemobiletools.commons.compose.theme.LocalTheme
import com.simplemobiletools.commons.compose.theme.SimpleTheme
import com.simplemobiletools.commons.compose.theme.isNotLitWell
import com.simplemobiletools.commons.compose.theme.isSurfaceLitWell
import com.simplemobiletools.commons.compose.theme.model.Theme
import com.simplemobiletools.commons.extensions.getColoredMaterialStatusBarColor
import com.simplemobiletools.commons.extensions.getContrastColor
@Composable
internal fun SystemUISettingsScaffoldStatusBarColor(scrolledColor: Color) {
val systemUiController = rememberSystemUiController()
DisposableEffect(systemUiController) {
systemUiController.statusBarDarkContentEnabled = scrolledColor.isNotLitWell()
onDispose { }
}
}
@Composable
internal fun ScreenBoxSettingsScaffold(paddingValues: PaddingValues, modifier: Modifier = Modifier, content: @Composable BoxScope.() -> Unit) {
val layoutDirection = LocalLayoutDirection.current
Box(
modifier = modifier
.fillMaxSize()
.background(SimpleTheme.colorScheme.surface)
.padding(
top = paddingValues.calculateTopPadding(),
start = paddingValues.calculateStartPadding(layoutDirection),
end = paddingValues.calculateEndPadding(layoutDirection)
)
) {
content()
}
}
@Composable
internal fun statusBarAndContrastColor(context: Context): Pair<Int, Color> {
val statusBarColor = onEventValue { context.getColoredMaterialStatusBarColor() }
val contrastColor by remember(statusBarColor) {
derivedStateOf { Color(statusBarColor.getContrastColor()) }
}
return Pair(statusBarColor, contrastColor)
}
@Composable
internal fun transitionFractionAndScrolledColor(
scrollBehavior: TopAppBarScrollBehavior,
contrastColor: Color,
darkIcons: Boolean = true,
): Pair<Float, Color> {
val systemUiController = rememberSystemUiController()
val colorTransitionFraction = scrollBehavior.state.overlappedFraction
val scrolledColor = lerp(
start = if (isSurfaceLitWell()) Color.Black else Color.White,
stop = contrastColor,
fraction = if (colorTransitionFraction > 0.01f) 1f else 0f
)
systemUiController.setStatusBarColor(
color = Color.Transparent,
darkIcons = scrolledColor.isNotLitWell() && darkIcons || (LocalTheme.current is Theme.SystemDefaultMaterialYou && !isSystemInDarkTheme())
)
return Pair(colorTransitionFraction, scrolledColor)
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/compose/lists/SettingsScaffoldExtensions.kt | 2195572578 |
package com.simplemobiletools.commons.compose.lists
import androidx.compose.foundation.ScrollState
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.AccessTime
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.platform.LocalContext
import com.simplemobiletools.commons.compose.extensions.AdjustNavigationBarColors
import com.simplemobiletools.commons.compose.extensions.MyDevices
import com.simplemobiletools.commons.compose.extensions.rememberMutableInteractionSource
import com.simplemobiletools.commons.compose.theme.AppThemeSurface
@Composable
fun SimpleColumnScaffold(
title: String,
goBack: () -> Unit,
modifier: Modifier = Modifier,
reverseLayout: Boolean = false,
verticalArrangement: Arrangement.Vertical =
if (!reverseLayout) Arrangement.Top else Arrangement.Bottom,
horizontalAlignment: Alignment.Horizontal = Alignment.Start,
scrollState: ScrollState = rememberScrollState(),
content: @Composable (ColumnScope.(PaddingValues) -> Unit)
) {
val context = LocalContext.current
val (statusBarColor, contrastColor) = statusBarAndContrastColor(context)
val scrollBehavior = TopAppBarDefaults.pinnedScrollBehavior(rememberTopAppBarState())
val (colorTransitionFraction, scrolledColor) = transitionFractionAndScrolledColor(scrollBehavior, contrastColor)
SystemUISettingsScaffoldStatusBarColor(scrolledColor)
val navigationIconInteractionSource = rememberMutableInteractionSource()
AdjustNavigationBarColors()
Scaffold(
modifier = modifier
.fillMaxSize()
.nestedScroll(scrollBehavior.nestedScrollConnection),
topBar = {
SimpleScaffoldTopBar(
title = title,
scrolledColor = scrolledColor,
navigationIconInteractionSource = navigationIconInteractionSource,
goBack = goBack,
scrollBehavior = scrollBehavior,
statusBarColor = statusBarColor,
colorTransitionFraction = colorTransitionFraction,
contrastColor = contrastColor
)
},
) { paddingValues ->
ScreenBoxSettingsScaffold(paddingValues) {
Column(
Modifier
.matchParentSize()
.verticalScroll(scrollState),
horizontalAlignment = horizontalAlignment,
verticalArrangement = verticalArrangement
) {
content(paddingValues)
Spacer(modifier = Modifier.padding(bottom = paddingValues.calculateBottomPadding()))
}
}
}
}
@Composable
fun SimpleColumnScaffold(
modifier: Modifier = Modifier,
title: @Composable (scrolledColor: Color) -> Unit,
goBack: () -> Unit,
reverseLayout: Boolean = false,
verticalArrangement: Arrangement.Vertical =
if (!reverseLayout) Arrangement.Top else Arrangement.Bottom,
horizontalAlignment: Alignment.Horizontal = Alignment.Start,
scrollState: ScrollState = rememberScrollState(),
content: @Composable (ColumnScope.(PaddingValues) -> Unit)
) {
val context = LocalContext.current
val (statusBarColor, contrastColor) = statusBarAndContrastColor(context)
val scrollBehavior = TopAppBarDefaults.pinnedScrollBehavior(rememberTopAppBarState())
val (colorTransitionFraction, scrolledColor) = transitionFractionAndScrolledColor(scrollBehavior, contrastColor)
SystemUISettingsScaffoldStatusBarColor(scrolledColor)
val navigationIconInteractionSource = rememberMutableInteractionSource()
AdjustNavigationBarColors()
Scaffold(
modifier = modifier
.fillMaxSize()
.nestedScroll(scrollBehavior.nestedScrollConnection),
topBar = {
SimpleScaffoldTopBar(
title = title,
scrolledColor = scrolledColor,
navigationIconInteractionSource = navigationIconInteractionSource,
goBack = goBack,
scrollBehavior = scrollBehavior,
statusBarColor = statusBarColor,
colorTransitionFraction = colorTransitionFraction,
contrastColor = contrastColor
)
}
) { paddingValues ->
ScreenBoxSettingsScaffold(paddingValues) {
Column(
modifier = Modifier
.matchParentSize()
.verticalScroll(scrollState),
verticalArrangement = verticalArrangement,
horizontalAlignment = horizontalAlignment,
) {
content(paddingValues)
Spacer(modifier = Modifier.padding(bottom = paddingValues.calculateBottomPadding()))
}
}
}
}
@Composable
fun SimpleColumnScaffold(
modifier: Modifier = Modifier,
title: @Composable (scrolledColor: Color) -> Unit,
actions: @Composable() (RowScope.() -> Unit),
goBack: () -> Unit,
reverseLayout: Boolean = false,
verticalArrangement: Arrangement.Vertical =
if (!reverseLayout) Arrangement.Top else Arrangement.Bottom,
horizontalAlignment: Alignment.Horizontal = Alignment.Start,
scrollState: ScrollState = rememberScrollState(),
content: @Composable (ColumnScope.(PaddingValues) -> Unit)
) {
val context = LocalContext.current
val (statusBarColor, contrastColor) = statusBarAndContrastColor(context)
val scrollBehavior = TopAppBarDefaults.pinnedScrollBehavior(rememberTopAppBarState())
val (colorTransitionFraction, scrolledColor) = transitionFractionAndScrolledColor(scrollBehavior, contrastColor)
SystemUISettingsScaffoldStatusBarColor(scrolledColor)
val navigationIconInteractionSource = rememberMutableInteractionSource()
AdjustNavigationBarColors()
Scaffold(
modifier = modifier
.fillMaxSize()
.nestedScroll(scrollBehavior.nestedScrollConnection),
topBar = {
SimpleScaffoldTopBar(
title = title,
scrolledColor = scrolledColor,
navigationIconInteractionSource = navigationIconInteractionSource,
goBack = goBack,
scrollBehavior = scrollBehavior,
statusBarColor = statusBarColor,
colorTransitionFraction = colorTransitionFraction,
contrastColor = contrastColor,
actions = actions
)
}
) { paddingValues ->
ScreenBoxSettingsScaffold(paddingValues) {
Column(
modifier = Modifier
.matchParentSize()
.verticalScroll(scrollState),
verticalArrangement = verticalArrangement,
horizontalAlignment = horizontalAlignment,
) {
content(paddingValues)
Spacer(modifier = Modifier.padding(bottom = paddingValues.calculateBottomPadding()))
}
}
}
}
@Composable
fun SimpleColumnScaffold(
modifier: Modifier = Modifier,
customTopBar: @Composable (scrolledColor: Color, navigationInteractionSource: MutableInteractionSource, scrollBehavior: TopAppBarScrollBehavior, statusBarColor: Int, colorTransitionFraction: Float, contrastColor: Color) -> Unit,
goBack: () -> Unit,
reverseLayout: Boolean = false,
verticalArrangement: Arrangement.Vertical =
if (!reverseLayout) Arrangement.Top else Arrangement.Bottom,
horizontalAlignment: Alignment.Horizontal = Alignment.Start,
scrollState: ScrollState = rememberScrollState(),
content: @Composable() (ColumnScope.(PaddingValues) -> Unit)
) {
val context = LocalContext.current
val (statusBarColor, contrastColor) = statusBarAndContrastColor(context)
val scrollBehavior = TopAppBarDefaults.pinnedScrollBehavior(rememberTopAppBarState())
val (colorTransitionFraction, scrolledColor) = transitionFractionAndScrolledColor(scrollBehavior, contrastColor)
SystemUISettingsScaffoldStatusBarColor(scrolledColor)
val navigationIconInteractionSource = rememberMutableInteractionSource()
AdjustNavigationBarColors()
Scaffold(
modifier = modifier
.fillMaxSize()
.nestedScroll(scrollBehavior.nestedScrollConnection),
topBar = {
customTopBar(scrolledColor, navigationIconInteractionSource, scrollBehavior, statusBarColor, colorTransitionFraction, contrastColor)
}
) { paddingValues ->
ScreenBoxSettingsScaffold(paddingValues) {
Column(
modifier = Modifier
.matchParentSize()
.verticalScroll(scrollState),
verticalArrangement = verticalArrangement,
horizontalAlignment = horizontalAlignment,
) {
content(paddingValues)
Spacer(modifier = Modifier.padding(bottom = paddingValues.calculateBottomPadding()))
}
}
}
}
@MyDevices
@Composable
private fun SimpleColumnScaffoldPreview() {
AppThemeSurface {
SimpleColumnScaffold(title = "About", goBack = {}) {
ListItem(headlineContent = { Text(text = "Some text") },
leadingContent = {
Icon(imageVector = Icons.Filled.AccessTime, contentDescription = null)
})
}
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/compose/lists/SimpleColumnScaffold.kt | 3262412443 |
package com.simplemobiletools.commons.compose.lists
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.ripple.rememberRipple
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalLayoutDirection
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextOverflow
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.compose.extensions.MyDevices
import com.simplemobiletools.commons.compose.extensions.rememberMutableInteractionSource
import com.simplemobiletools.commons.compose.theme.AppThemeSurface
import com.simplemobiletools.commons.compose.theme.SimpleTheme
@Composable
fun SimpleScaffoldTopBar(
modifier: Modifier = Modifier,
title: String,
scrolledColor: Color,
navigationIconInteractionSource: MutableInteractionSource = rememberMutableInteractionSource(),
scrollBehavior: TopAppBarScrollBehavior = TopAppBarDefaults.pinnedScrollBehavior(rememberTopAppBarState()),
statusBarColor: Int,
colorTransitionFraction: Float,
contrastColor: Color,
goBack: () -> Unit,
) {
TopAppBar(
title = {
Text(
text = title,
modifier = Modifier
.padding(start = SimpleTheme.dimens.padding.medium)
.fillMaxWidth(),
color = scrolledColor,
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
},
navigationIcon = {
SimpleNavigationIcon(
goBack = goBack,
navigationIconInteractionSource = navigationIconInteractionSource,
iconColor = scrolledColor
)
},
scrollBehavior = scrollBehavior,
colors = simpleTopAppBarColors(statusBarColor, colorTransitionFraction, contrastColor),
modifier = modifier.topAppBarPaddings(),
windowInsets = topAppBarInsets()
)
}
@Composable
fun SimpleScaffoldTopBar(
modifier: Modifier = Modifier,
title: @Composable (scrolledColor: Color) -> Unit,
scrolledColor: Color,
navigationIconInteractionSource: MutableInteractionSource = rememberMutableInteractionSource(),
scrollBehavior: TopAppBarScrollBehavior = TopAppBarDefaults.pinnedScrollBehavior(rememberTopAppBarState()),
statusBarColor: Int,
colorTransitionFraction: Float,
contrastColor: Color,
goBack: () -> Unit,
) {
TopAppBar(
title = {
title(scrolledColor)
},
navigationIcon = {
SimpleNavigationIcon(
goBack = goBack,
navigationIconInteractionSource = navigationIconInteractionSource,
iconColor = scrolledColor
)
},
scrollBehavior = scrollBehavior,
colors = simpleTopAppBarColors(statusBarColor, colorTransitionFraction, contrastColor),
modifier = modifier.topAppBarPaddings(),
windowInsets = topAppBarInsets()
)
}
@Composable
fun SimpleScaffoldTopBar(
modifier: Modifier = Modifier,
title: @Composable (scrolledColor: Color) -> Unit,
actions: @Composable RowScope.() -> Unit,
scrolledColor: Color,
navigationIconInteractionSource: MutableInteractionSource = rememberMutableInteractionSource(),
scrollBehavior: TopAppBarScrollBehavior = TopAppBarDefaults.pinnedScrollBehavior(rememberTopAppBarState()),
statusBarColor: Int,
colorTransitionFraction: Float,
contrastColor: Color,
goBack: () -> Unit,
) {
TopAppBar(
title = {
title(scrolledColor)
},
navigationIcon = {
SimpleNavigationIcon(
goBack = goBack,
navigationIconInteractionSource = navigationIconInteractionSource,
iconColor = scrolledColor
)
},
actions = actions,
scrollBehavior = scrollBehavior,
colors = simpleTopAppBarColors(statusBarColor, colorTransitionFraction, contrastColor),
modifier = modifier.topAppBarPaddings(),
windowInsets = topAppBarInsets()
)
}
@Composable
fun simpleTopAppBarColors(
statusBarColor: Int,
colorTransitionFraction: Float,
contrastColor: Color
) = TopAppBarDefaults.topAppBarColors(
scrolledContainerColor = Color(statusBarColor),
containerColor = if (colorTransitionFraction == 1f) contrastColor else SimpleTheme.colorScheme.surface,
navigationIconContentColor = if (colorTransitionFraction == 1f) contrastColor else SimpleTheme.colorScheme.surface
)
@Composable
fun topAppBarInsets() = TopAppBarDefaults.windowInsets.exclude(WindowInsets.navigationBars)
@Composable
fun Modifier.topAppBarPaddings(
paddingValues: PaddingValues = WindowInsets.navigationBars.asPaddingValues()
): Modifier {
val layoutDirection = LocalLayoutDirection.current
return padding(
top = paddingValues.calculateTopPadding(),
start = paddingValues.calculateStartPadding(layoutDirection),
end = paddingValues.calculateEndPadding(layoutDirection)
)
}
@Composable
fun SimpleNavigationIcon(
modifier: Modifier = Modifier,
navigationIconInteractionSource: MutableInteractionSource = rememberMutableInteractionSource(),
goBack: () -> Unit,
iconColor: Color? = null
) {
Box(
modifier
.padding(start = SimpleTheme.dimens.padding.medium)
.clip(RoundedCornerShape(50))
.clickable(
navigationIconInteractionSource, rememberRipple(
color = SimpleTheme.colorScheme.onSurface,
bounded = true
)
) { goBack() }
) {
SimpleBackIcon(iconColor)
}
}
@Composable
fun SimpleBackIcon(iconColor: Color?) {
if (iconColor == null) {
Icon(
imageVector = Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(id = R.string.back),
modifier = Modifier.padding(SimpleTheme.dimens.padding.small)
)
} else {
Icon(
imageVector = Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(id = R.string.back),
tint = iconColor,
modifier = Modifier.padding(SimpleTheme.dimens.padding.small)
)
}
}
@Composable
@MyDevices
private fun SimpleScaffoldTopBarPreview() {
AppThemeSurface {
SimpleScaffoldTopBar(
title = "SettingsScaffoldTopBar",
scrolledColor = Color.Black,
navigationIconInteractionSource = rememberMutableInteractionSource(),
goBack = {},
statusBarColor = Color.Magenta.toArgb(),
colorTransitionFraction = 1.0f,
contrastColor = Color.Gray
)
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/compose/lists/SimpleScaffoldTopBar.kt | 3713168396 |
package com.simplemobiletools.commons.compose.system_ui_controller
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import android.app.Activity
import android.content.Context
import android.content.ContextWrapper
import android.os.Build
import android.view.View
import android.view.Window
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Stable
import androidx.compose.runtime.remember
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.compositeOver
import androidx.compose.ui.graphics.luminance
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.window.DialogWindowProvider
import androidx.core.view.ViewCompat
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.WindowInsetsControllerCompat
/**
* A class which provides easy-to-use utilities for updating the System UI bar
* colors within Jetpack Compose.
*
*/
@Stable
interface SystemUiController {
/**
* Control for the behavior of the system bars. This value should be one of the
* [WindowInsetsControllerCompat] behavior constants:
* [WindowInsetsControllerCompat.BEHAVIOR_SHOW_BARS_BY_TOUCH] (Deprecated),
* [WindowInsetsControllerCompat.BEHAVIOR_DEFAULT] and
* [WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE].
*/
var systemBarsBehavior: Int
/**
* Property which holds the status bar visibility. If set to true, show the status bar,
* otherwise hide the status bar.
*/
var isStatusBarVisible: Boolean
/**
* Property which holds the navigation bar visibility. If set to true, show the navigation bar,
* otherwise hide the navigation bar.
*/
var isNavigationBarVisible: Boolean
/**
* Property which holds the status & navigation bar visibility. If set to true, show both bars,
* otherwise hide both bars.
*/
var isSystemBarsVisible: Boolean
get() = isNavigationBarVisible && isStatusBarVisible
set(value) {
isStatusBarVisible = value
isNavigationBarVisible = value
}
/**
* Set the status bar color.
*
* @param color The **desired** [Color] to set. This may require modification if running on an
* API level that only supports white status bar icons.
* @param darkIcons Whether dark status bar icons would be preferable.
* @param transformColorForLightContent A lambda which will be invoked to transform [color] if
* dark icons were requested but are not available. Defaults to applying a black scrim.
*
* @see statusBarDarkContentEnabled
*/
fun setStatusBarColor(
color: Color,
darkIcons: Boolean = color.luminance() > 0.5f,
transformColorForLightContent: (Color) -> Color = BlackScrimmed
)
/**
* Set the navigation bar color.
*
* @param color The **desired** [Color] to set. This may require modification if running on an
* API level that only supports white navigation bar icons. Additionally this will be ignored
* and [Color.Transparent] will be used on API 29+ where gesture navigation is preferred or the
* system UI automatically applies background protection in other navigation modes.
* @param darkIcons Whether dark navigation bar icons would be preferable.
* @param navigationBarContrastEnforced Whether the system should ensure that the navigation
* bar has enough contrast when a fully transparent background is requested. Only supported on
* API 29+.
* @param transformColorForLightContent A lambda which will be invoked to transform [color] if
* dark icons were requested but are not available. Defaults to applying a black scrim.
*
* @see navigationBarDarkContentEnabled
* @see navigationBarContrastEnforced
*/
fun setNavigationBarColor(
color: Color,
darkIcons: Boolean = color.luminance() > 0.5f,
navigationBarContrastEnforced: Boolean = true,
transformColorForLightContent: (Color) -> Color = BlackScrimmed
)
/**
* Set the status and navigation bars to [color].
*
* @see setStatusBarColor
* @see setNavigationBarColor
*/
fun setSystemBarsColor(
color: Color,
darkIcons: Boolean = color.luminance() > 0.5f,
isNavigationBarContrastEnforced: Boolean = true,
transformColorForLightContent: (Color) -> Color = BlackScrimmed
) {
setStatusBarColor(color, darkIcons, transformColorForLightContent)
setNavigationBarColor(
color,
darkIcons,
isNavigationBarContrastEnforced,
transformColorForLightContent
)
}
/**
* Property which holds whether the status bar icons + content are 'dark' or not.
*/
var statusBarDarkContentEnabled: Boolean
/**
* Property which holds whether the navigation bar icons + content are 'dark' or not.
*/
var navigationBarDarkContentEnabled: Boolean
/**
* Property which holds whether the status & navigation bar icons + content are 'dark' or not.
*/
var systemBarsDarkContentEnabled: Boolean
get() = statusBarDarkContentEnabled && navigationBarDarkContentEnabled
set(value) {
statusBarDarkContentEnabled = value
navigationBarDarkContentEnabled = value
}
/**
* Property which holds whether the system is ensuring that the navigation bar has enough
* contrast when a fully transparent background is requested. Only has an affect when running
* on Android API 29+ devices.
*/
var isNavigationBarContrastEnforced: Boolean
}
/**
* Remembers a [SystemUiController] for the given [window].
*
* If no [window] is provided, an attempt to find the correct [Window] is made.
*
* First, if the [LocalView]'s parent is a [DialogWindowProvider], then that dialog's [Window] will
* be used.
*
* Second, we attempt to find [Window] for the [Activity] containing the [LocalView].
*
* If none of these are found (such as may happen in a preview), then the functionality of the
* returned [SystemUiController] will be degraded, but won't throw an exception.
*/
@Composable
fun rememberSystemUiController(
window: Window? = findWindow(),
): SystemUiController {
val view = LocalView.current
return remember(view, window) { AndroidSystemUiController(view, window) }
}
@Composable
private fun findWindow(): Window? =
(LocalView.current.parent as? DialogWindowProvider)?.window
?: LocalView.current.context.findWindow()
private tailrec fun Context.findWindow(): Window? =
when (this) {
is Activity -> window
is ContextWrapper -> baseContext.findWindow()
else -> null
}
/**
* A helper class for setting the navigation and status bar colors for a [View], gracefully
* degrading behavior based upon API level.
*
* Typically you would use [rememberSystemUiController] to remember an instance of this.
*/
internal class AndroidSystemUiController(
private val view: View,
private val window: Window?
) : SystemUiController {
private val windowInsetsController = window?.let {
WindowCompat.getInsetsController(it, view)
}
override fun setStatusBarColor(
color: Color,
darkIcons: Boolean,
transformColorForLightContent: (Color) -> Color
) {
statusBarDarkContentEnabled = darkIcons
window?.statusBarColor = when {
darkIcons && windowInsetsController?.isAppearanceLightStatusBars != true -> {
// If we're set to use dark icons, but our windowInsetsController call didn't
// succeed (usually due to API level), we instead transform the color to maintain
// contrast
transformColorForLightContent(color)
}
else -> color
}.toArgb()
}
override fun setNavigationBarColor(
color: Color,
darkIcons: Boolean,
navigationBarContrastEnforced: Boolean,
transformColorForLightContent: (Color) -> Color
) {
navigationBarDarkContentEnabled = darkIcons
isNavigationBarContrastEnforced = navigationBarContrastEnforced
window?.navigationBarColor = when {
darkIcons && windowInsetsController?.isAppearanceLightNavigationBars != true -> {
// If we're set to use dark icons, but our windowInsetsController call didn't
// succeed (usually due to API level), we instead transform the color to maintain
// contrast
transformColorForLightContent(color)
}
else -> color
}.toArgb()
}
override var systemBarsBehavior: Int
get() = windowInsetsController?.systemBarsBehavior ?: 0
set(value) {
windowInsetsController?.systemBarsBehavior = value
}
override var isStatusBarVisible: Boolean
get() {
return ViewCompat.getRootWindowInsets(view)
?.isVisible(WindowInsetsCompat.Type.statusBars()) == true
}
set(value) {
if (value) {
windowInsetsController?.show(WindowInsetsCompat.Type.statusBars())
} else {
windowInsetsController?.hide(WindowInsetsCompat.Type.statusBars())
}
}
override var isNavigationBarVisible: Boolean
get() {
return ViewCompat.getRootWindowInsets(view)
?.isVisible(WindowInsetsCompat.Type.navigationBars()) == true
}
set(value) {
if (value) {
windowInsetsController?.show(WindowInsetsCompat.Type.navigationBars())
} else {
windowInsetsController?.hide(WindowInsetsCompat.Type.navigationBars())
}
}
override var statusBarDarkContentEnabled: Boolean
get() = windowInsetsController?.isAppearanceLightStatusBars == true
set(value) {
windowInsetsController?.isAppearanceLightStatusBars = value
}
override var navigationBarDarkContentEnabled: Boolean
get() = windowInsetsController?.isAppearanceLightNavigationBars == true
set(value) {
windowInsetsController?.isAppearanceLightNavigationBars = value
}
override var isNavigationBarContrastEnforced: Boolean
get() = Build.VERSION.SDK_INT >= 29 && window?.isNavigationBarContrastEnforced == true
set(value) {
if (Build.VERSION.SDK_INT >= 29) {
window?.isNavigationBarContrastEnforced = value
}
}
}
private val BlackScrim = Color(0f, 0f, 0f, 0.3f) // 30% opaque black
private val BlackScrimmed: (Color) -> Color = { original ->
BlackScrim.compositeOver(original)
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/compose/system_ui_controller/SystemUIController.kt | 3109388959 |
package com.simplemobiletools.commons.compose.extensions
import android.content.res.Configuration
import androidx.compose.ui.tooling.preview.Devices
import androidx.compose.ui.tooling.preview.Preview
const val LIGHT = "Light"
const val DARK = "Dark"
@MyDevicesDarkOnly
@MyDevicesLightOnly
annotation class MyDevices
@Preview(showBackground = true, uiMode = Configuration.UI_MODE_NIGHT_YES, device = Devices.PIXEL_4_XL, name = "6.3 inches dark", group = DARK)
@Preview(showBackground = true, uiMode = Configuration.UI_MODE_NIGHT_YES, device = Devices.PIXEL_2, name = "5.0 inches dark", group = DARK)
@Preview(showBackground = true, uiMode = Configuration.UI_MODE_NIGHT_YES, device = Devices.PIXEL_2_XL, name = "6.0 inches dark", group = DARK)
@Preview(showBackground = true, uiMode = Configuration.UI_MODE_NIGHT_YES, device = Devices.PIXEL_4_XL, name = "5.5 inches dark", group = DARK)
@Preview(showBackground = true, uiMode = Configuration.UI_MODE_NIGHT_YES, device = Devices.PIXEL_4, name = "5.7 inches dark", group = DARK)
@Preview(showBackground = true, uiMode = Configuration.UI_MODE_NIGHT_YES, device = Devices.TABLET, name = "Tablet", group = DARK)
annotation class MyDevicesDarkOnly
@Preview(showBackground = true, device = Devices.PIXEL_4_XL, name = "6.3 inches light", group = LIGHT)
@Preview(showBackground = true, device = Devices.PIXEL_2, name = "5.0 inches light", group = LIGHT)
@Preview(showBackground = true, device = Devices.PIXEL_2_XL, name = "6.0 inches light", group = LIGHT)
@Preview(showBackground = true, device = Devices.PIXEL_XL, name = "5.5 inches light", group = LIGHT)
@Preview(showBackground = true, device = Devices.PIXEL_4, name = "5.7 inches light", group = LIGHT)
@Preview(showBackground = true, device = Devices.TABLET, name = "Tablet", group = DARK)
annotation class MyDevicesLightOnly
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/compose/extensions/PreviewExtensions.kt | 2376799186 |
package com.simplemobiletools.commons.compose.extensions
import androidx.compose.material.ripple.RippleAlpha
import androidx.compose.material.ripple.RippleTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Immutable
import androidx.compose.ui.graphics.Color
@Immutable
object NoRippleTheme : RippleTheme {
@Composable
override fun defaultColor(): Color = Color.Unspecified
@Composable
override fun rippleAlpha(): RippleAlpha = RippleAlpha(
draggedAlpha = 0f,
focusedAlpha = 0f,
hoveredAlpha = 0f,
pressedAlpha = 0f,
)
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/compose/extensions/NoRippleTheme.kt | 1709044608 |
package com.simplemobiletools.commons.compose.extensions
import android.app.Activity
import android.content.Context
import android.content.ContextWrapper
import androidx.activity.ComponentActivity
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.calculateEndPadding
import androidx.compose.foundation.layout.calculateStartPadding
import androidx.compose.runtime.*
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLayoutDirection
import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.unit.dp
import androidx.core.view.WindowCompat
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.compose.LifecycleEventEffect
import androidx.lifecycle.compose.LifecycleResumeEffect
import androidx.lifecycle.compose.LifecycleStartEffect
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.compose.system_ui_controller.rememberSystemUiController
import com.simplemobiletools.commons.compose.theme.SimpleTheme
import com.simplemobiletools.commons.compose.theme.isLitWell
import com.simplemobiletools.commons.extensions.darkenColor
import com.simplemobiletools.commons.extensions.launchViewIntent
fun Context.getActivity(): Activity {
return when (this) {
is Activity -> this
is ContextWrapper -> baseContext.getActivity()
else -> getActivity()
}
}
fun Context.getComponentActivity(): ComponentActivity = getActivity() as ComponentActivity
@Composable
fun rememberMutableInteractionSource() = remember { MutableInteractionSource() }
@Composable
fun AdjustNavigationBarColors() {
val systemUiController = rememberSystemUiController()
val isSystemInDarkTheme = isSystemInDarkTheme()
val isSurfaceLitWell = SimpleTheme.colorScheme.surface.isLitWell()
val navigationBarColor = Color(SimpleTheme.colorScheme.surface.toArgb().darkenColor()).copy(alpha = 0.5f)
DisposableEffect(systemUiController, isSystemInDarkTheme, navigationBarColor) {
systemUiController.setNavigationBarColor(color = navigationBarColor, darkIcons = !isSystemInDarkTheme)
systemUiController.navigationBarDarkContentEnabled = isSurfaceLitWell
onDispose {}
}
}
@Composable
fun <T : Any> onEventValue(event: Lifecycle.Event = Lifecycle.Event.ON_START, value: () -> T): T {
val rememberLatestUpdateState by rememberUpdatedState(newValue = value)
var rememberedValue by remember { mutableStateOf(value()) }
LifecycleEventEffect(event = event) {
rememberedValue = rememberLatestUpdateState()
}
return rememberedValue
}
@Composable
fun <T : Any> onStartEventValue(vararg keys: Any?, onStopOrDispose: (LifecycleOwner.() -> Unit)? = null, value: () -> T): T {
val rememberLatestUpdateState by rememberUpdatedState(newValue = value)
var rememberedValue by remember { mutableStateOf(value()) }
LifecycleStartEffect(keys = keys, effects = {
rememberedValue = rememberLatestUpdateState()
onStopOrDispose {
onStopOrDispose?.invoke(this)
}
})
return rememberedValue
}
@Composable
fun <T : Any> onResumeEventValue(vararg keys: Any?, onPauseOrDispose: (LifecycleOwner.() -> Unit)? = null, value: () -> T): T {
val rememberLatestUpdateState by rememberUpdatedState(newValue = value)
var rememberedValue by remember { mutableStateOf(value()) }
LifecycleResumeEffect(keys = keys, effects = {
rememberedValue = rememberLatestUpdateState()
onPauseOrDispose {
onPauseOrDispose?.invoke(this)
}
})
return rememberedValue
}
@Composable
operator fun PaddingValues.plus(otherPaddingValues: PaddingValues): PaddingValues {
val layoutDirection = LocalLayoutDirection.current
return PaddingValues(
start = calculateLeftPadding(layoutDirection).plus(
otherPaddingValues.calculateLeftPadding(
layoutDirection
)
),
top = calculateTopPadding().plus(otherPaddingValues.calculateTopPadding()),
end = calculateRightPadding(layoutDirection).plus(
otherPaddingValues.calculateRightPadding(
layoutDirection
)
),
bottom = calculateBottomPadding().plus(otherPaddingValues.calculateBottomPadding())
)
}
@Composable
fun PaddingValues.plus(vararg otherPaddingValues: PaddingValues): PaddingValues {
val thisArray = arrayOf(this)
return PaddingValues(
start = thisArray.plus(otherPaddingValues).sumOfDps(PaddingValues::calculateStartPadding),
top = thisArray.plus(otherPaddingValues).sumOfDps(PaddingValues::calculateTopPadding),
end = thisArray.plus(otherPaddingValues).sumOfDps(PaddingValues::calculateEndPadding),
bottom = thisArray.plus(otherPaddingValues).sumOfDps(PaddingValues::calculateBottomPadding)
)
}
@Composable
private fun Array<out PaddingValues>.sumOfDps(aggregator: (PaddingValues, LayoutDirection) -> Dp): Dp {
val layoutDirection = LocalLayoutDirection.current
return asSequence().map { paddingValues ->
aggregator(paddingValues, layoutDirection)
}.sumOfDps()
}
private fun Array<out PaddingValues>.sumOfDps(aggregator: PaddingValues.() -> Dp): Dp =
asSequence().map { paddingValues ->
paddingValues.aggregator()
}.sumOfDps()
private fun Sequence<Dp>.sumOfDps(): Dp {
var sum = 0.dp
for (element in this) {
sum += element
}
return sum
}
fun ComponentActivity.enableEdgeToEdgeSimple() {
WindowCompat.setDecorFitsSystemWindows(window, false)
}
@Composable
internal fun TransparentSystemBars(darkIcons: Boolean = !isSystemInDarkTheme()) {
val systemUiController = rememberSystemUiController()
DisposableEffect(systemUiController, darkIcons) {
systemUiController.setSystemBarsColor(
color = Color.Transparent,
darkIcons = darkIcons
)
onDispose { }
}
}
@Composable
fun composeDonateIntent(): () -> Unit {
val localContext = LocalContext.current
val localView = LocalView.current
return {
if (localView.isInEditMode) Unit else localContext.getActivity().launchViewIntent(R.string.thank_you_url)
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/compose/extensions/ComposeExtensions.kt | 1343091195 |
package com.simplemobiletools.commons.compose.extensions
import androidx.compose.foundation.gestures.detectDragGesturesAfterLongPress
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.hapticfeedback.HapticFeedback
import androidx.compose.ui.hapticfeedback.HapticFeedbackType
import androidx.compose.ui.input.pointer.pointerInput
internal fun Modifier.listDragHandlerLongKey(
lazyListState: LazyListState,
haptics: HapticFeedback,
selectedIds: MutableState<Set<Long>>,
autoScrollSpeed: MutableState<Float>,
autoScrollThreshold: Float,
dragUpdate: (Boolean) -> Unit,
ids: List<Long>,
isScrollingUp: Boolean
) = pointerInput(Unit) {
var initialKey: Long? = null
var currentKey: Long? = null
val onDragCancelAndEnd = {
initialKey = null
autoScrollSpeed.value = 0f
dragUpdate(false)
}
detectDragGesturesAfterLongPress(
onDragStart = { offset ->
dragUpdate(true)
lazyListState.itemKeyAtPosition(offset)?.let { key ->
if (!selectedIds.value.contains(key)) {
haptics.performHapticFeedback(HapticFeedbackType.LongPress)
initialKey = key
currentKey = key
selectedIds.value += key
}
}
},
onDragCancel = onDragCancelAndEnd,
onDragEnd = onDragCancelAndEnd,
onDrag = { change, _ ->
if (initialKey != null) {
val distFromBottom = lazyListState.layoutInfo.viewportSize.height - change.position.y
val distFromTop = change.position.y
autoScrollSpeed.value = when {
distFromBottom < autoScrollThreshold -> autoScrollThreshold - distFromBottom
distFromTop < autoScrollThreshold -> -(autoScrollThreshold - distFromTop)
else -> 0f
}
lazyListState.itemKeyAtPosition(change.position)?.let { key ->
if (currentKey != key) {
val toSelect = if (selectedIds.value.contains(key) && ids.isNotEmpty()) {
val successor = ids.indexOf(key) + if (isScrollingUp) +1 else -1
selectedIds.value
.minus(ids[successor])
} else {
selectedIds.value + setOf(currentKey!!, key)
}
selectedIds.value = toSelect
currentKey = key
}
}
}
}
)
}
/**
* Returns whether the lazy list is currently scrolling up.
*/
@Composable
internal fun LazyListState.isScrollingUp(): Boolean {
var previousIndex by remember(this) { mutableStateOf(firstVisibleItemIndex) }
var previousScrollOffset by remember(this) { mutableStateOf(firstVisibleItemScrollOffset) }
return remember(this) {
derivedStateOf {
if (previousIndex != firstVisibleItemIndex) {
previousIndex > firstVisibleItemIndex
} else {
previousScrollOffset >= firstVisibleItemScrollOffset
}.also {
previousIndex = firstVisibleItemIndex
previousScrollOffset = firstVisibleItemScrollOffset
}
}
}.value
}
internal fun LazyListState.itemKeyAtPosition(hitPoint: Offset): Long? =
layoutInfo.visibleItemsInfo
.firstOrNull { lazyListItemInfo ->
hitPoint.y.toInt() in lazyListItemInfo.offset..lazyListItemInfo.offset + lazyListItemInfo.size
}
?.key as? Long
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/compose/extensions/DragHandler.kt | 228455855 |
package com.simplemobiletools.commons.compose.extensions
import android.app.Activity
import android.content.Context
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.extensions.baseConfig
import com.simplemobiletools.commons.extensions.redirectToRateUs
import com.simplemobiletools.commons.extensions.toast
import com.simplemobiletools.commons.helpers.BaseConfig
val Context.config: BaseConfig get() = BaseConfig.newInstance(applicationContext)
fun Activity.rateStarsRedirectAndThankYou(stars: Int) {
if (stars == 5) {
redirectToRateUs()
}
toast(R.string.thank_you)
baseConfig.wasAppRated = true
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/compose/extensions/ContextComposeExtensions.kt | 3591548524 |
package com.simplemobiletools.commons.compose.extensions
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import com.simplemobiletools.commons.compose.theme.LocalTheme
import com.simplemobiletools.commons.compose.theme.model.Theme
import com.simplemobiletools.commons.extensions.baseConfig
import com.simplemobiletools.commons.extensions.getProperPrimaryColor
@Composable
fun linkColor(): Color {
val theme: Theme = LocalTheme.current
val accentColor = LocalContext.current.baseConfig.accentColor
val primaryColor = LocalContext.current.getProperPrimaryColor()
return onStartEventValue(keys = arrayOf(accentColor, primaryColor)) {
Color(
when (theme) {
is Theme.BlackAndWhite, is Theme.White -> accentColor
else -> primaryColor
}
)
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/compose/extensions/ColorExtensions.kt | 2542839397 |
package com.simplemobiletools.commons.compose.extensions
import android.app.Activity
import android.content.ComponentName
import android.content.Context
import android.content.pm.PackageManager
import android.view.WindowManager
import androidx.activity.ComponentActivity
import androidx.core.content.ContextCompat
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.WindowInsetsControllerCompat
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.isOreoMr1Plus
import com.simplemobiletools.commons.models.Release
fun ComponentActivity.appLaunchedCompose(
appId: String,
showUpgradeDialog: () -> Unit,
showDonateDialog: () -> Unit,
showRateUsDialog: () -> Unit
) {
baseConfig.internalStoragePath = getInternalStoragePath()
updateSDCardPath()
baseConfig.appId = appId
if (baseConfig.appRunCount == 0) {
baseConfig.wasOrangeIconChecked = true
checkAppIconColor()
} else if (!baseConfig.wasOrangeIconChecked) {
baseConfig.wasOrangeIconChecked = true
val primaryColor = ContextCompat.getColor(this, R.color.color_primary)
if (baseConfig.appIconColor != primaryColor) {
getAppIconColors().forEachIndexed { index, color ->
toggleAppIconColor(appId, index, color, false)
}
val defaultClassName = "${baseConfig.appId.removeSuffix(".debug")}.activities.SplashActivity"
packageManager.setComponentEnabledSetting(
ComponentName(baseConfig.appId, defaultClassName),
PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
PackageManager.DONT_KILL_APP
)
val orangeClassName = "${baseConfig.appId.removeSuffix(".debug")}.activities.SplashActivity.Orange"
packageManager.setComponentEnabledSetting(
ComponentName(baseConfig.appId, orangeClassName),
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP
)
baseConfig.appIconColor = primaryColor
baseConfig.lastIconColor = primaryColor
}
}
baseConfig.appRunCount++
if (baseConfig.appRunCount % 30 == 0 && !isAProApp()) {
if (!resources.getBoolean(R.bool.hide_google_relations)) {
if (getCanAppBeUpgraded()) {
showUpgradeDialog()
} else if (!isOrWasThankYouInstalled()) {
showDonateDialog()
}
}
}
if (baseConfig.appRunCount % 40 == 0 && !baseConfig.wasAppRated) {
if (!resources.getBoolean(R.bool.hide_google_relations)) {
showRateUsDialog()
}
}
}
fun ComponentActivity.checkWhatsNewCompose(releases: List<Release>, currVersion: Int, showWhatsNewDialog: (List<Release>) -> Unit) {
if (baseConfig.lastVersion == 0) {
baseConfig.lastVersion = currVersion
return
}
val newReleases = arrayListOf<Release>()
releases.filterTo(newReleases) { it.id > baseConfig.lastVersion }
if (newReleases.isNotEmpty()) {
showWhatsNewDialog(newReleases)
}
baseConfig.lastVersion = currVersion
}
fun ComponentActivity.upgradeToPro() {
launchViewIntent("https://simplemobiletools.com/upgrade_to_pro")
}
const val DEVELOPER_PLAY_STORE_URL = "https://play.google.com/store/apps/dev?id=9070296388022589266"
const val FAKE_VERSION_APP_LABEL =
"You are using a fake version of the app. For your own safety download the original one from www.simplemobiletools.com. Thanks"
fun Context.fakeVersionCheck(
showConfirmationDialog: () -> Unit
) {
if (!packageName.startsWith("com.simplemobiletools.", true)) {
if ((0..50).random() == 10 || baseConfig.appRunCount % 100 == 0) {
showConfirmationDialog()
}
}
}
fun ComponentActivity.appOnSdCardCheckCompose(
showConfirmationDialog: () -> Unit
) {
if (!baseConfig.wasAppOnSDShown && isAppInstalledOnSDCard()) {
baseConfig.wasAppOnSDShown = true
showConfirmationDialog()
}
}
fun Activity.setShowWhenLockedCompat(showWhenLocked: Boolean) {
if (isOreoMr1Plus()) {
setShowWhenLocked(showWhenLocked)
} else {
val flagsToUpdate =
WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD or
WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
if (showWhenLocked) {
window.addFlags(flagsToUpdate)
} else {
window.clearFlags(flagsToUpdate)
}
}
}
fun Activity.setTurnScreenOnCompat(turnScreenOn: Boolean) {
if (isOreoMr1Plus()) {
setTurnScreenOn(turnScreenOn)
} else {
val flagToUpdate = WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
if (turnScreenOn) {
window.addFlags(flagToUpdate)
} else {
window.clearFlags(flagToUpdate)
}
}
}
fun Activity.setFullscreenCompat(fullScreen: Boolean) {
if (isOreoMr1Plus()) {
WindowCompat.getInsetsController(window, window.decorView.rootView).hide(WindowInsetsCompat.Type.statusBars())
} else {
val flagToUpdate = WindowManager.LayoutParams.FLAG_FULLSCREEN
if (fullScreen) {
window.addFlags(flagToUpdate)
} else {
window.clearFlags(flagToUpdate)
}
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/compose/extensions/AcitivtyExtensions.kt | 3513603561 |
package com.simplemobiletools.commons.compose.extensions
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.platform.LocalContext
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.compose.alert_dialog.rememberAlertDialogState
import com.simplemobiletools.commons.dialogs.ConfirmationAlertDialog
import com.simplemobiletools.commons.extensions.launchViewIntent
@Composable
fun FakeVersionCheck() {
val context = LocalContext.current
val confirmationDialogAlertDialogState = rememberAlertDialogState().apply {
DialogMember {
ConfirmationAlertDialog(
alertDialogState = this,
message = FAKE_VERSION_APP_LABEL,
positive = R.string.ok,
negative = null
) {
context.getActivity().launchViewIntent(DEVELOPER_PLAY_STORE_URL)
}
}
}
LaunchedEffect(Unit) {
context.fakeVersionCheck(confirmationDialogAlertDialogState::show)
}
}
@Composable
fun CheckAppOnSdCard() {
val context = LocalContext.current.getComponentActivity()
val confirmationDialogAlertDialogState = rememberAlertDialogState().apply {
DialogMember {
ConfirmationAlertDialog(
alertDialogState = this,
messageId = R.string.app_on_sd_card,
positive = R.string.ok,
negative = null
) {}
}
}
LaunchedEffect(Unit) {
context.appOnSdCardCheckCompose(confirmationDialogAlertDialogState::show)
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/compose/extensions/ComposeActivityExtensions.kt | 3146480474 |
package com.simplemobiletools.commons.compose.extensions
import androidx.compose.ui.Modifier
inline fun Modifier.ifTrue(predicate: Boolean, builder: () -> Modifier) =
then(if (predicate) builder() else Modifier)
inline fun Modifier.ifFalse(predicate: Boolean, builder: () -> Modifier) =
then(if (!predicate) builder() else Modifier)
inline infix fun (() -> Unit).andThen(crossinline function: () -> Unit): () -> Unit = {
this()
function()
}
inline fun (() -> Unit).andThen(
crossinline function: () -> Unit,
crossinline function2: () -> Unit
): () -> Unit = {
this()
function()
function2()
}
inline fun (() -> Unit).andThen(
crossinline function: () -> Unit,
crossinline function2: () -> Unit,
crossinline function3: () -> Unit,
): () -> Unit = {
this()
function()
function2()
function3()
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/compose/extensions/ModifierExtensions.kt | 2326830127 |
package com.simplemobiletools.commons.compose.extensions
import androidx.compose.ui.tooling.preview.PreviewParameterProvider
class BooleanPreviewParameterProvider : PreviewParameterProvider<Boolean> {
override val values: Sequence<Boolean>
get() = sequenceOf(false, true)
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/compose/extensions/BooleanPreviewParameterProvider.kt | 968979023 |
package com.simplemobiletools.commons.compose.screens
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.material3.ListItem
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.compose.components.LinkifyTextComponent
import com.simplemobiletools.commons.compose.extensions.MyDevices
import com.simplemobiletools.commons.compose.lists.SimpleLazyListScaffold
import com.simplemobiletools.commons.compose.settings.SettingsHorizontalDivider
import com.simplemobiletools.commons.compose.theme.AppThemeSurface
import com.simplemobiletools.commons.compose.theme.SimpleTheme
import com.simplemobiletools.commons.extensions.fromHtml
import com.simplemobiletools.commons.models.FAQItem
import kotlinx.collections.immutable.ImmutableList
import kotlinx.collections.immutable.toImmutableList
@Composable
internal fun FAQScreen(
goBack: () -> Unit,
faqItems: ImmutableList<FAQItem>,
) {
SimpleLazyListScaffold(
title = stringResource(id = R.string.frequently_asked_questions),
goBack = goBack,
contentPadding = PaddingValues(bottom = SimpleTheme.dimens.padding.medium)
) {
itemsIndexed(faqItems) { index, faqItem ->
Column(modifier = Modifier.fillMaxWidth()) {
ListItem(
headlineContent = {
val text = if (faqItem.title is Int) stringResource(faqItem.title) else faqItem.title as String
Text(
text = text,
modifier = Modifier
.fillMaxWidth()
.padding(bottom = 6.dp),
color = SimpleTheme.colorScheme.primary,
lineHeight = 16.sp,
)
},
supportingContent = {
if (faqItem.text is Int) {
val text = stringResource(id = faqItem.text).fromHtml()
LinkifyTextComponent(
text = { text },
modifier = Modifier.fillMaxWidth(),
fontSize = 14.sp
)
} else {
Text(
text = faqItem.text as String,
modifier = Modifier.fillMaxWidth(),
fontSize = 14.sp
)
}
},
)
Spacer(modifier = Modifier.padding(bottom = SimpleTheme.dimens.padding.medium))
if (index != faqItems.lastIndex) {
SettingsHorizontalDivider(
modifier = Modifier
.fillMaxWidth()
.padding(bottom = SimpleTheme.dimens.padding.small)
)
}
}
}
}
}
@MyDevices
@Composable
private fun FAQScreenPreview() {
AppThemeSurface {
FAQScreen(
goBack = {},
faqItems = listOf(
FAQItem(R.string.faq_1_title_commons, R.string.faq_1_text_commons),
FAQItem(R.string.faq_1_title_commons, R.string.faq_1_text_commons),
FAQItem(R.string.faq_4_title_commons, R.string.faq_4_text_commons),
FAQItem(R.string.faq_2_title_commons, R.string.faq_2_text_commons),
FAQItem(R.string.faq_6_title_commons, R.string.faq_6_text_commons)
).toImmutableList()
)
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/compose/screens/FAQScreen.kt | 2225068509 |
package com.simplemobiletools.commons.compose.screens
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.material3.ListItem
import androidx.compose.material3.ListItemDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.compose.extensions.MyDevices
import com.simplemobiletools.commons.compose.lists.SimpleLazyListScaffold
import com.simplemobiletools.commons.compose.settings.SettingsHorizontalDivider
import com.simplemobiletools.commons.compose.theme.AppThemeSurface
import com.simplemobiletools.commons.compose.theme.SimpleTheme
import com.simplemobiletools.commons.helpers.*
import com.simplemobiletools.commons.models.License
import kotlinx.collections.immutable.ImmutableList
import kotlinx.collections.immutable.toImmutableList
@Composable
internal fun LicenseScreen(
goBack: () -> Unit,
thirdPartyLicenses: ImmutableList<License>,
onLicenseClick: (urlId: Int) -> Unit,
) {
SimpleLazyListScaffold(
title = stringResource(id = R.string.third_party_licences),
goBack = goBack
) {
itemsIndexed(thirdPartyLicenses) { index, license ->
Column {
LicenseItem(license, onLicenseClick)
if (index != thirdPartyLicenses.lastIndex) {
SettingsHorizontalDivider(modifier = Modifier.padding(bottom = SimpleTheme.dimens.padding.small))
}
}
}
}
}
@Composable
private fun LicenseItem(
license: License,
onLicenseClick: (urlId: Int) -> Unit
) {
ListItem(headlineContent = {
Text(
text = stringResource(id = license.titleId),
modifier = Modifier
.clickable {
onLicenseClick(license.urlId)
}
)
}, supportingContent = {
Text(
text = stringResource(id = license.textId),
modifier = Modifier.padding(top = SimpleTheme.dimens.padding.extraSmall),
)
}, colors = ListItemDefaults.colors(headlineColor = SimpleTheme.colorScheme.primary, supportingColor = SimpleTheme.colorScheme.onSurface))
}
@Composable
@MyDevices
private fun LicenseScreenPreview() {
AppThemeSurface {
LicenseScreen(
goBack = {},
thirdPartyLicenses = listOf(
License(LICENSE_KOTLIN, R.string.kotlin_title, R.string.kotlin_text, R.string.kotlin_url),
License(LICENSE_SUBSAMPLING, R.string.subsampling_title, R.string.subsampling_text, R.string.subsampling_url),
License(LICENSE_GLIDE, R.string.glide_title, R.string.glide_text, R.string.glide_url),
License(LICENSE_CROPPER, R.string.cropper_title, R.string.cropper_text, R.string.cropper_url),
License(LICENSE_RTL, R.string.rtl_viewpager_title, R.string.rtl_viewpager_text, R.string.rtl_viewpager_url),
License(LICENSE_JODA, R.string.joda_title, R.string.joda_text, R.string.joda_url),
License(LICENSE_STETHO, R.string.stetho_title, R.string.stetho_text, R.string.stetho_url),
License(LICENSE_OTTO, R.string.otto_title, R.string.otto_text, R.string.otto_url),
License(LICENSE_PHOTOVIEW, R.string.photoview_title, R.string.photoview_text, R.string.photoview_url),
License(LICENSE_PICASSO, R.string.picasso_title, R.string.picasso_text, R.string.picasso_url),
License(LICENSE_PATTERN, R.string.pattern_title, R.string.pattern_text, R.string.pattern_url),
License(LICENSE_REPRINT, R.string.reprint_title, R.string.reprint_text, R.string.reprint_url),
License(LICENSE_GIF_DRAWABLE, R.string.gif_drawable_title, R.string.gif_drawable_text, R.string.gif_drawable_url),
License(LICENSE_AUTOFITTEXTVIEW, R.string.autofittextview_title, R.string.autofittextview_text, R.string.autofittextview_url),
License(LICENSE_ROBOLECTRIC, R.string.robolectric_title, R.string.robolectric_text, R.string.robolectric_url),
License(LICENSE_ESPRESSO, R.string.espresso_title, R.string.espresso_text, R.string.espresso_url),
License(LICENSE_GSON, R.string.gson_title, R.string.gson_text, R.string.gson_url),
License(LICENSE_LEAK_CANARY, R.string.leak_canary_title, R.string.leakcanary_text, R.string.leakcanary_url),
License(LICENSE_NUMBER_PICKER, R.string.number_picker_title, R.string.number_picker_text, R.string.number_picker_url),
License(LICENSE_EXOPLAYER, R.string.exoplayer_title, R.string.exoplayer_text, R.string.exoplayer_url),
License(LICENSE_PANORAMA_VIEW, R.string.panorama_view_title, R.string.panorama_view_text, R.string.panorama_view_url),
License(LICENSE_SANSELAN, R.string.sanselan_title, R.string.sanselan_text, R.string.sanselan_url),
License(LICENSE_FILTERS, R.string.filters_title, R.string.filters_text, R.string.filters_url),
License(LICENSE_GESTURE_VIEWS, R.string.gesture_views_title, R.string.gesture_views_text, R.string.gesture_views_url),
License(
LICENSE_INDICATOR_FAST_SCROLL,
R.string.indicator_fast_scroll_title,
R.string.indicator_fast_scroll_text,
R.string.indicator_fast_scroll_url
),
License(LICENSE_EVENT_BUS, R.string.event_bus_title, R.string.event_bus_text, R.string.event_bus_url),
License(LICENSE_AUDIO_RECORD_VIEW, R.string.audio_record_view_title, R.string.audio_record_view_text, R.string.audio_record_view_url),
License(LICENSE_SMS_MMS, R.string.sms_mms_title, R.string.sms_mms_text, R.string.sms_mms_url),
License(LICENSE_APNG, R.string.apng_title, R.string.apng_text, R.string.apng_url),
License(LICENSE_PDF_VIEW_PAGER, R.string.pdf_view_pager_title, R.string.pdf_view_pager_text, R.string.pdf_view_pager_url),
License(LICENSE_M3U_PARSER, R.string.m3u_parser_title, R.string.m3u_parser_text, R.string.m3u_parser_url),
License(LICENSE_ANDROID_LAME, R.string.android_lame_title, R.string.android_lame_text, R.string.android_lame_url),
License(LICENSE_PDF_VIEWER, R.string.pdf_viewer_title, R.string.pdf_viewer_text, R.string.pdf_viewer_url),
License(LICENSE_ZIP4J, R.string.zip4j_title, R.string.zip4j_text, R.string.zip4j_url)
).toImmutableList()
) {
}
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/compose/screens/LicenseScreen.kt | 3269800314 |
package com.simplemobiletools.commons.compose.screens
import androidx.activity.compose.BackHandler
import androidx.compose.animation.Crossfade
import androidx.compose.animation.core.FastOutLinearInEasing
import androidx.compose.animation.core.tween
import androidx.compose.foundation.clickable
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.gestures.scrollBy
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListScope
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.ContentCopy
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.hapticfeedback.HapticFeedbackType
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalHapticFeedback
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.onLongClick
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.PreviewParameter
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.compose.components.SimpleDropDownMenuItem
import com.simplemobiletools.commons.compose.extensions.*
import com.simplemobiletools.commons.compose.lists.*
import com.simplemobiletools.commons.compose.menus.ActionItem
import com.simplemobiletools.commons.compose.menus.ActionMenu
import com.simplemobiletools.commons.compose.menus.OverflowMode
import com.simplemobiletools.commons.compose.settings.SettingsCheckBoxComponent
import com.simplemobiletools.commons.compose.settings.SettingsHorizontalDivider
import com.simplemobiletools.commons.compose.system_ui_controller.rememberSystemUiController
import com.simplemobiletools.commons.compose.theme.*
import com.simplemobiletools.commons.compose.theme.model.Theme
import com.simplemobiletools.commons.extensions.darkenColor
import com.simplemobiletools.commons.extensions.getContrastColor
import com.simplemobiletools.commons.models.BlockedNumber
import kotlinx.collections.immutable.ImmutableList
import kotlinx.collections.immutable.toImmutableList
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
private const val CLICK_RESET_TIME = 250L
private const val RESET_IMMEDIATELY = 1L
private const val RESET_IDLE = -1L
private const val BETWEEN_CLICKS_TIME = 200 //time between a click which is slightly lower than the reset time
private const val ON_LONG_CLICK_LABEL = "select"
@Composable
internal fun ManageBlockedNumbersScreen(
goBack: () -> Unit,
onAdd: () -> Unit,
onImportBlockedNumbers: () -> Unit,
onExportBlockedNumbers: () -> Unit,
setAsDefault: () -> Unit,
isDialer: Boolean,
hasGivenPermissionToBlock: Boolean,
isBlockUnknownSelected: Boolean,
onBlockUnknownSelectedChange: (Boolean) -> Unit,
isHiddenSelected: Boolean,
onHiddenSelectedChange: (Boolean) -> Unit,
blockedNumbers: ImmutableList<BlockedNumber>?,
onDelete: (Set<Long>) -> Unit,
onEdit: (BlockedNumber) -> Unit,
onCopy: (BlockedNumber) -> Unit,
) {
val dimens = SimpleTheme.dimens
val startingPadding = remember { Modifier.padding(horizontal = dimens.padding.small) }
val selectedIds: MutableState<Set<Long>> = rememberSaveable { mutableStateOf(emptySet()) }
val hapticFeedback = LocalHapticFeedback.current
val isInActionMode by remember { derivedStateOf { selectedIds.value.isNotEmpty() } }
val clearSelection = remember {
{ selectedIds.value = emptySet() }
}
BackHandler(isInActionMode) {
clearSelection()
}
SimpleScaffold(
darkStatusBarIcons = !isInActionMode,
customTopBar = { scrolledColor: Color,
navigationInteractionSource: MutableInteractionSource,
scrollBehavior: TopAppBarScrollBehavior,
statusBarColor: Int,
colorTransitionFraction: Float,
contrastColor: Color ->
Column {
Crossfade(targetState = isInActionMode, label = "toolbar-anim", animationSpec = tween(easing = FastOutLinearInEasing)) { actionMode ->
if (actionMode && blockedNumbers != null) {
ActionModeToolbar(
selectedIdsCount = selectedIds.value.count(),
blockedNumbersCount = blockedNumbers.count(),
onBackClick = clearSelection,
onCopy = {
onCopy(blockedNumbers.first { blockedNumber -> blockedNumber.id == selectedIds.value.first() })
clearSelection()
},
onDelete = {
onDelete(selectedIds.value)
clearSelection()
},
onSelectAll = {
selectedIds.value = blockedNumbers.map { it.id }.toSet()
}
)
} else {
NonActionModeToolbar(
scrolledColor = scrolledColor,
navigationInteractionSource = navigationInteractionSource,
goBack = goBack,
scrollBehavior = scrollBehavior,
statusBarColor = statusBarColor,
colorTransitionFraction = colorTransitionFraction,
contrastColor = contrastColor,
onAdd = onAdd,
onImportBlockedNumbers = onImportBlockedNumbers,
onExportBlockedNumbers = onExportBlockedNumbers
)
}
}
SettingsCheckBoxComponent(
label = if (isDialer) stringResource(id = R.string.block_not_stored_calls) else stringResource(id = R.string.block_not_stored_messages),
initialValue = isBlockUnknownSelected,
onChange = onBlockUnknownSelectedChange,
modifier = startingPadding.then(Modifier.topAppBarPaddings()),
)
SettingsCheckBoxComponent(
label = if (isDialer) stringResource(id = R.string.block_hidden_calls) else stringResource(id = R.string.block_hidden_messages),
initialValue = isHiddenSelected,
onChange = onHiddenSelectedChange,
modifier = startingPadding.then(Modifier.topAppBarPaddings()),
)
SettingsHorizontalDivider(modifier = Modifier.topAppBarPaddings())
}
},
) { paddingValues ->
val state = rememberLazyListState()
val autoScrollSpeed = remember { mutableFloatStateOf(0f) }
LaunchedEffect(autoScrollSpeed.floatValue) {
if (autoScrollSpeed.floatValue != 0f) {
while (isActive) {
state.scrollBy(autoScrollSpeed.floatValue)
delay(10)
}
}
}
var hasDraggingStarted by remember { mutableStateOf(false) }
var lastClickedValue by remember { mutableStateOf<Pair<Long, BlockedNumber?>>(Pair(RESET_IDLE, null)) }
var triggerReset by remember { mutableLongStateOf(RESET_IDLE) }
LaunchedEffect(triggerReset) {
if (triggerReset != RESET_IDLE) {
delay(triggerReset)
lastClickedValue = Pair(RESET_IDLE, null)
triggerReset = RESET_IDLE
}
}
LazyColumn(
state = state,
modifier = Modifier.ifFalse(blockedNumbers.isNullOrEmpty()) {
Modifier.listDragHandlerLongKey(
isScrollingUp = state.isScrollingUp(),
lazyListState = state,
haptics = hapticFeedback,
selectedIds = selectedIds,
autoScrollSpeed = autoScrollSpeed,
autoScrollThreshold = with(LocalDensity.current) { 40.dp.toPx() },
dragUpdate = { isDraggingStarted ->
hasDraggingStarted = isDraggingStarted
triggerReset = RESET_IMMEDIATELY
},
ids = blockedNumbers?.map { blockedNumber -> blockedNumber.id }.orEmpty()
)
},
verticalArrangement = Arrangement.spacedBy(SimpleTheme.dimens.padding.extraSmall),
contentPadding = PaddingValues(bottom = paddingValues.calculateBottomPadding())
) {
when {
!hasGivenPermissionToBlock -> {
noPermissionToBlock(setAsDefault = setAsDefault)
}
blockedNumbers == null -> {}
blockedNumbers.isEmpty() -> {
emptyBlockedNumbers(addABlockedNumber = onAdd)
}
hasGivenPermissionToBlock && blockedNumbers.isNotEmpty() -> {
itemsIndexed(blockedNumbers, key = { _, blockedNumber -> blockedNumber.id }) { index, blockedNumber ->
val isSelected = selectedIds.value.contains(blockedNumber.id)
BlockedNumber(
modifier = Modifier
.animateItemPlacement()
.semantics {
if (!isInActionMode) {
onLongClick(ON_LONG_CLICK_LABEL) {
selectedIds.value += blockedNumber.id
true
}
}
}
.ifTrue(!isInActionMode) {
Modifier.combinedClickable(onLongClick = {
val selectable = longPressSelectableValue(lastClickedValue, blockedNumber, triggerReset) { bNumber1, bNumber2 ->
updateSelectedIndices(blockedNumbers, bNumber1, bNumber2, selectedIds)
}
lastClickedValue = selectable.first
triggerReset = selectable.second
}, onClick = {
onEdit(blockedNumber)
})
}
.ifTrue(isInActionMode) {
Modifier.combinedClickable(
interactionSource = rememberMutableInteractionSource(),
indication = null,
enabled = !hasDraggingStarted,
onLongClick = {
val indexOfLastValueInSelection = blockedNumbers.indexOfFirst { selectedIds.value.last() == it.id }
when {
indexOfLastValueInSelection == index -> {}
indexOfLastValueInSelection < index -> {
hapticFeedback.performHapticFeedback(HapticFeedbackType.LongPress)
selectedIds.value += blockedNumbers
.subList(indexOfLastValueInSelection, index)
.map { number -> number.id }
}
else -> {
hapticFeedback.performHapticFeedback(HapticFeedbackType.LongPress)
selectedIds.value += blockedNumbers
.subList(index, indexOfLastValueInSelection)
.map { number -> number.id }
}
}
},
onClick = {
if (isSelected) {
selectedIds.value -= blockedNumber.id
} else {
selectedIds.value += blockedNumber.id
}
}
)
},
blockedNumber = blockedNumber,
onDelete = onDelete,
onCopy = onCopy,
isSelected = isSelected
)
}
}
}
}
}
}
private fun updateSelectedIndices(
blockedNumbers: ImmutableList<BlockedNumber>,
bNumber1: BlockedNumber,
bNumber2: BlockedNumber,
selectedIds: MutableState<Set<Long>>
) {
val indices = listOf(blockedNumbers.indexOf(bNumber1), blockedNumbers.indexOf(bNumber2))
selectedIds.value += blockedNumbers
.subList(indices.minOrNull()!!, indices.maxOrNull()!! + 1)
.map { number -> number.id }
}
private fun longPressSelectableValue(
lastClickedValue: Pair<Long, BlockedNumber?>,
blockedNumber: BlockedNumber,
triggerReset: Long,
select: (BlockedNumber, BlockedNumber) -> Unit
): Pair<Pair<Long, BlockedNumber?>, Long> {
var lastClickedValueTemp = lastClickedValue
var triggerResetTemp = triggerReset
if (lastClickedValueTemp.first == RESET_IDLE) {
lastClickedValueTemp = Pair(System.currentTimeMillis(), blockedNumber)
triggerResetTemp = CLICK_RESET_TIME
} else {
if (lastClickedValueTemp.first + BETWEEN_CLICKS_TIME > System.currentTimeMillis()) {
val firstValue = lastClickedValueTemp
select(blockedNumber, firstValue.second!!)
lastClickedValueTemp = Pair(RESET_IDLE, null)
}
}
return lastClickedValueTemp to triggerResetTemp
}
@Composable
private fun BlockedNumber(
modifier: Modifier = Modifier,
blockedNumber: BlockedNumber,
onDelete: (Set<Long>) -> Unit,
onCopy: (BlockedNumber) -> Unit,
isSelected: Boolean
) {
val hasContactName = blockedNumber.contactName != null
val contactNameContent = remember {
movableContentOf {
Text(
text = blockedNumber.contactName.toString(),
modifier = modifier.padding(horizontal = SimpleTheme.dimens.padding.medium, vertical = SimpleTheme.dimens.padding.extraSmall)
)
}
}
val blockedNumberContent = remember {
movableContentOf {
BlockedNumberHeadlineContent(blockedNumber = blockedNumber, hasContactName = hasContactName)
}
}
ListItem(
modifier = modifier,
headlineContent = {
if (hasContactName) {
contactNameContent()
} else {
blockedNumberContent()
}
},
supportingContent = {
if (hasContactName) {
blockedNumberContent()
}
},
trailingContent = {
BlockedNumberTrailingContent(onDelete = {
onDelete(setOf(blockedNumber.id))
}, onCopy = {
onCopy(blockedNumber)
})
},
colors = blockedNumberListItemColors(
isSelected = isSelected
)
)
}
@Composable
private fun blockedNumberListItemColors(
isSelected: Boolean
) = ListItemDefaults.colors(
containerColor = if (isSelected) {
if (LocalTheme.current is Theme.SystemDefaultMaterialYou) {
Color(SimpleTheme.colorScheme.primaryContainer.toArgb().darkenColor()).copy(alpha = 0.8f)
} else {
SimpleTheme.colorScheme.primary.copy(alpha = 0.3f)
}
} else {
SimpleTheme.colorScheme.surface
},
trailingIconColor = iconsColor
)
@Composable
private fun BlockedNumberHeadlineContent(modifier: Modifier = Modifier, blockedNumber: BlockedNumber, hasContactName: Boolean) {
Text(
text = blockedNumber.number,
modifier = modifier.padding(horizontal = SimpleTheme.dimens.padding.medium),
color = if (hasContactName) LocalContentColor.current.copy(alpha = 0.7f) else LocalContentColor.current
)
}
@Composable
private fun BlockedNumberTrailingContent(modifier: Modifier = Modifier, onDelete: () -> Unit, onCopy: () -> Unit) {
var isMenuVisible by remember { mutableStateOf(false) }
val dismissMenu = remember {
{
isMenuVisible = false
}
}
DropdownMenu(
//https://github.com/JetBrains/compose-multiplatform/issues/1878 same in M3, remove the top and bottom margin blocker
expanded = isMenuVisible,
onDismissRequest = dismissMenu,
modifier = modifier
) {
SimpleDropDownMenuItem(onClick = {
onCopy()
dismissMenu()
}, text = {
Text(
text = stringResource(id = R.string.copy_number_to_clipboard),
modifier = Modifier.fillMaxWidth(),
fontSize = 16.sp,
fontWeight = FontWeight.Normal
)
})
SimpleDropDownMenuItem(onClick = {
onDelete()
dismissMenu()
}, text = {
Text(
text = stringResource(id = R.string.delete),
modifier = Modifier.fillMaxWidth(),
fontSize = 16.sp,
fontWeight = FontWeight.Normal
)
})
}
IconButton(onClick = {
isMenuVisible = true
}) {
Icon(Icons.Default.MoreVert, contentDescription = stringResource(id = R.string.more_options), tint = iconsColor)
}
}
@Composable
private fun ActionModeToolbar(
modifier: Modifier = Modifier,
selectedIdsCount: Int,
blockedNumbersCount: Int,
onBackClick: () -> Unit,
onCopy: () -> Unit,
onDelete: () -> Unit,
onSelectAll: () -> Unit,
) {
val systemUiController = rememberSystemUiController()
val navigationIconInteractionSource = rememberMutableInteractionSource()
val bgColor = actionModeBgColor()
val textColor by remember {
derivedStateOf { Color(bgColor.toArgb().getContrastColor()) }
}
DisposableEffect(systemUiController, bgColor) {
systemUiController.setStatusBarColor(color = Color.Transparent, darkIcons = bgColor.isLitWell())
onDispose {}
}
TopAppBar(
title = {
Box(
modifier = Modifier
.fillMaxHeight()
.clickable {
if (selectedIdsCount == blockedNumbersCount) {
onBackClick()
} else {
onSelectAll()
}
}
.padding(horizontal = 18.dp), contentAlignment = Alignment.Center
) {
if (selectedIdsCount != 0) {
Text(text = "$selectedIdsCount / $blockedNumbersCount", color = textColor, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
}
},
navigationIcon = {
SimpleNavigationIcon(navigationIconInteractionSource = navigationIconInteractionSource, goBack = onBackClick, iconColor = textColor)
},
actions = {
BlockedNumberActionMenu(selectedIdsCount = selectedIdsCount, onDelete = onDelete, onCopy = onCopy, iconColor = textColor)
},
colors = TopAppBarDefaults.topAppBarColors(
containerColor = bgColor
),
modifier = modifier.topAppBarPaddings(),
windowInsets = topAppBarInsets()
)
}
@Composable
@ReadOnlyComposable
private fun actionModeBgColor(): Color =
if (LocalTheme.current is Theme.SystemDefaultMaterialYou) {
SimpleTheme.colorScheme.primaryContainer
} else {
actionModeColor
}
@Composable
private fun BlockedNumberActionMenu(
selectedIdsCount: Int,
onDelete: () -> Unit,
onCopy: () -> Unit,
iconColor: Color? = null
) {
val actionMenus = remember(selectedIdsCount) {
val delete =
ActionItem(
nameRes = R.string.delete,
icon = Icons.Default.Delete,
doAction = onDelete,
overflowMode = OverflowMode.NEVER_OVERFLOW,
iconColor = iconColor
)
val list = if (selectedIdsCount == 1) {
listOf(
ActionItem(
nameRes = R.string.copy,
icon = Icons.Default.ContentCopy,
doAction = onCopy,
overflowMode = OverflowMode.NEVER_OVERFLOW,
iconColor = iconColor
),
delete
)
} else {
listOf(delete)
}
list.toImmutableList()
}
ActionMenu(items = actionMenus, numIcons = if (selectedIdsCount == 1) 2 else 1, isMenuVisible = true, onMenuToggle = { }, iconsColor = iconColor)
}
@Composable
private fun NonActionModeToolbar(
scrolledColor: Color,
navigationInteractionSource: MutableInteractionSource,
goBack: () -> Unit,
scrollBehavior: TopAppBarScrollBehavior,
statusBarColor: Int,
colorTransitionFraction: Float,
contrastColor: Color,
onAdd: () -> Unit,
onImportBlockedNumbers: () -> Unit,
onExportBlockedNumbers: () -> Unit
) {
SimpleScaffoldTopBar(
title = { scrolledTextColor ->
Text(
text = stringResource(id = R.string.manage_blocked_numbers),
modifier = Modifier.padding(start = SimpleTheme.dimens.padding.extraLarge),
maxLines = 1,
overflow = TextOverflow.Ellipsis,
color = scrolledTextColor
)
},
scrolledColor = scrolledColor,
navigationIconInteractionSource = navigationInteractionSource,
goBack = goBack,
scrollBehavior = scrollBehavior,
statusBarColor = statusBarColor,
colorTransitionFraction = colorTransitionFraction,
contrastColor = contrastColor,
actions = {
val actionMenus = remember {
listOf(
ActionItem(R.string.add_a_blocked_number, icon = Icons.Filled.Add, doAction = onAdd),
ActionItem(R.string.import_blocked_numbers, doAction = onImportBlockedNumbers, overflowMode = OverflowMode.ALWAYS_OVERFLOW),
ActionItem(R.string.export_blocked_numbers, doAction = onExportBlockedNumbers, overflowMode = OverflowMode.ALWAYS_OVERFLOW),
).toImmutableList()
}
var isMenuVisible by remember { mutableStateOf(false) }
ActionMenu(items = actionMenus, numIcons = 2, isMenuVisible = isMenuVisible, onMenuToggle = { isMenuVisible = it }, iconsColor = scrolledColor)
}
)
}
private fun LazyListScope.emptyBlockedNumbers(
addABlockedNumber: () -> Unit
) {
item {
Text(
text = stringResource(id = R.string.not_blocking_anyone),
style = TextStyle(fontStyle = FontStyle.Italic, textAlign = TextAlign.Center, color = SimpleTheme.colorScheme.onSurface),
modifier = Modifier
.fillMaxWidth()
.padding(top = SimpleTheme.dimens.padding.extraLarge, bottom = SimpleTheme.dimens.padding.small)
.padding(horizontal = SimpleTheme.dimens.padding.extraLarge)
)
}
item {
Box(
modifier = Modifier
.fillMaxWidth(), contentAlignment = Alignment.Center
) {
Box(
modifier = Modifier
.clip(Shapes.large)
.clickable(onClick = addABlockedNumber)
) {
Text(
text = stringResource(id = R.string.add_a_blocked_number),
style = TextStyle(
textAlign = TextAlign.Center,
textDecoration = TextDecoration.Underline,
color = SimpleTheme.colorScheme.primary,
fontSize = 18.sp
),
modifier = Modifier.padding(SimpleTheme.dimens.padding.medium)
)
}
}
}
}
private fun LazyListScope.noPermissionToBlock(
setAsDefault: () -> Unit
) {
item {
Text(
text = stringResource(id = R.string.must_make_default_dialer),
style = TextStyle(fontStyle = FontStyle.Italic, textAlign = TextAlign.Center),
modifier = Modifier
.fillMaxWidth()
.padding(top = SimpleTheme.dimens.padding.extraLarge)
.padding(horizontal = SimpleTheme.dimens.padding.extraLarge)
)
}
item {
Box(
modifier = Modifier
.fillMaxWidth(), contentAlignment = Alignment.Center
) {
Box(
modifier = Modifier
.clip(Shapes.large)
.clickable(onClick = setAsDefault)
) {
Text(
text = stringResource(id = R.string.set_as_default),
style = TextStyle(
textAlign = TextAlign.Center,
textDecoration = TextDecoration.Underline,
color = SimpleTheme.colorScheme.primary,
fontSize = 18.sp
),
modifier = Modifier.padding(SimpleTheme.dimens.padding.extraLarge)
)
}
}
}
}
@MyDevices
@Composable
private fun ManageBlockedNumbersScreenPreview(@PreviewParameter(BooleanPreviewParameterProvider::class) isDialer: Boolean) {
AppThemeSurface {
ManageBlockedNumbersScreen(
goBack = {},
onAdd = {},
onImportBlockedNumbers = {},
onExportBlockedNumbers = {},
setAsDefault = {},
isDialer = isDialer,
hasGivenPermissionToBlock = !isDialer,
isBlockUnknownSelected = false,
onBlockUnknownSelectedChange = {},
isHiddenSelected = false,
onHiddenSelectedChange = {},
blockedNumbers = listOf(
BlockedNumber(id = 1, number = "000000000", normalizedNumber = "000000000", numberToCompare = "000000000", contactName = "Test"),
BlockedNumber(id = 2, number = "111111111", normalizedNumber = "111111111", numberToCompare = "111111111"),
BlockedNumber(id = 3, number = "5555555555", normalizedNumber = "5555555555", numberToCompare = "5555555555"),
BlockedNumber(id = 4, number = "1234567890", normalizedNumber = "1234567890", numberToCompare = "1234567890"),
BlockedNumber(id = 5, number = "9876543210", normalizedNumber = "9876543210", numberToCompare = "9876543210", contactName = "Test"),
BlockedNumber(id = 6, number = "9998887777", normalizedNumber = "9998887777", numberToCompare = "9998887777"),
BlockedNumber(id = 7, number = "2223334444", normalizedNumber = "2223334444", numberToCompare = "2223334444"),
BlockedNumber(id = 8, number = "5552221111", normalizedNumber = "5552221111", numberToCompare = "5552221111")
).toImmutableList(),
onDelete = {},
onEdit = {}
) {}
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/compose/screens/ManageBlockedNumbersScreen.kt | 1291402372 |
package com.simplemobiletools.commons.compose.screens
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.ListItem
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.compose.components.LinkifyTextComponent
import com.simplemobiletools.commons.compose.extensions.MyDevices
import com.simplemobiletools.commons.compose.lists.SimpleLazyListScaffold
import com.simplemobiletools.commons.compose.settings.SettingsGroupTitle
import com.simplemobiletools.commons.compose.settings.SettingsHorizontalDivider
import com.simplemobiletools.commons.compose.settings.SettingsListItem
import com.simplemobiletools.commons.compose.settings.SettingsTitleTextComponent
import com.simplemobiletools.commons.compose.theme.AppThemeSurface
import com.simplemobiletools.commons.compose.theme.SimpleTheme
import com.simplemobiletools.commons.extensions.fromHtml
import com.simplemobiletools.commons.models.LanguageContributor
import kotlinx.collections.immutable.ImmutableList
import kotlinx.collections.immutable.toImmutableList
private val startingPadding = Modifier.padding(start = 58.dp)
@Composable
internal fun ContributorsScreen(
goBack: () -> Unit,
showContributorsLabel: Boolean,
contributors: ImmutableList<LanguageContributor>
) {
SimpleLazyListScaffold(
title = { scrolledColor ->
Text(
text = stringResource(id = R.string.contributors),
modifier = Modifier
.padding(start = 28.dp)
.fillMaxWidth(),
color = scrolledColor,
overflow = TextOverflow.Ellipsis,
maxLines = 1
)
},
goBack = goBack
) {
item {
SettingsGroupTitle {
SettingsTitleTextComponent(text = stringResource(id = R.string.development), modifier = startingPadding)
}
}
item {
SettingsListItem(
text = stringResource(id = R.string.contributors_developers),
icon = R.drawable.ic_code_vector,
tint = SimpleTheme.colorScheme.onSurface,
fontSize = 14.sp
)
}
item {
Spacer(modifier = Modifier.padding(vertical = SimpleTheme.dimens.padding.medium))
}
item {
SettingsHorizontalDivider()
}
item {
SettingsGroupTitle {
SettingsTitleTextComponent(text = stringResource(id = R.string.translation), modifier = startingPadding)
}
}
items(contributors, key = { it.contributorsId.plus(it.iconId).plus(it.labelId) }) {
ContributorItem(
languageContributor = it
)
}
if (showContributorsLabel) {
item {
SettingsListItem(
icon = R.drawable.ic_heart_vector,
text = {
val source = stringResource(id = R.string.contributors_label)
LinkifyTextComponent {
source.fromHtml()
}
},
tint = SimpleTheme.colorScheme.onSurface
)
}
item {
Spacer(modifier = Modifier.padding(bottom = SimpleTheme.dimens.padding.medium))
}
}
}
}
@Composable
private fun ContributorItem(
modifier: Modifier = Modifier,
languageContributor: LanguageContributor
) {
ListItem(
headlineContent = {
Text(
text = stringResource(id = languageContributor.labelId),
modifier = Modifier
.fillMaxWidth()
.then(modifier)
)
},
leadingContent = {
val imageSize = Modifier
.size(SimpleTheme.dimens.icon.medium)
.padding(SimpleTheme.dimens.padding.medium)
Image(
modifier = imageSize,
painter = painterResource(id = languageContributor.iconId),
contentDescription = stringResource(id = languageContributor.contributorsId),
)
},
modifier = Modifier
.fillMaxWidth(),
supportingContent = {
Text(
text = stringResource(id = languageContributor.contributorsId),
modifier = Modifier
.fillMaxWidth(),
color = SimpleTheme.colorScheme.onSurface
)
}
)
}
@Composable
@MyDevices
private fun ContributorsScreenPreview() {
AppThemeSurface {
ContributorsScreen(
goBack = {},
contributors = listOf(
LanguageContributor(R.drawable.ic_flag_arabic_vector, R.string.translation_arabic, R.string.translators_arabic),
LanguageContributor(R.drawable.ic_flag_azerbaijani_vector, R.string.translation_azerbaijani, R.string.translators_azerbaijani),
LanguageContributor(R.drawable.ic_flag_bengali_vector, R.string.translation_bengali, R.string.translators_bengali),
LanguageContributor(R.drawable.ic_flag_catalan_vector, R.string.translation_catalan, R.string.translators_catalan),
).toImmutableList(),
showContributorsLabel = true,
)
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/compose/screens/ContributorsScreen.kt | 116947218 |
package com.simplemobiletools.commons.compose.screens
import androidx.compose.foundation.layout.padding
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.compose.extensions.MyDevices
import com.simplemobiletools.commons.compose.lists.SimpleColumnScaffold
import com.simplemobiletools.commons.compose.settings.SettingsGroup
import com.simplemobiletools.commons.compose.settings.SettingsHorizontalDivider
import com.simplemobiletools.commons.compose.settings.SettingsListItem
import com.simplemobiletools.commons.compose.settings.SettingsTitleTextComponent
import com.simplemobiletools.commons.compose.theme.AppThemeSurface
import com.simplemobiletools.commons.compose.theme.SimpleTheme
private val startingTitlePadding = Modifier.padding(start = 60.dp)
@Composable
internal fun AboutScreen(
goBack: () -> Unit,
helpUsSection: @Composable () -> Unit,
aboutSection: @Composable () -> Unit,
socialSection: @Composable () -> Unit,
otherSection: @Composable () -> Unit,
) {
SimpleColumnScaffold(title = stringResource(id = R.string.about), goBack = goBack) {
aboutSection()
helpUsSection()
socialSection()
otherSection()
SettingsListItem(text = stringResource(id = R.string.about_footer))
}
}
@Composable
internal fun HelpUsSection(
onRateUsClick: () -> Unit,
onInviteClick: () -> Unit,
onContributorsClick: () -> Unit,
showRateUs: Boolean,
showInvite: Boolean,
showDonate: Boolean,
onDonateClick: () -> Unit,
) {
SettingsGroup(title = {
SettingsTitleTextComponent(text = stringResource(id = R.string.help_us), modifier = startingTitlePadding)
}) {
if (showRateUs) {
TwoLinerTextItem(text = stringResource(id = R.string.rate_us), icon = R.drawable.ic_star_vector, click = onRateUsClick)
}
if (showInvite) {
TwoLinerTextItem(text = stringResource(id = R.string.invite_friends), icon = R.drawable.ic_add_person_vector, click = onInviteClick)
}
TwoLinerTextItem(
click = onContributorsClick,
text = stringResource(id = R.string.contributors),
icon = R.drawable.ic_face_vector
)
if (showDonate) {
TwoLinerTextItem(
click = onDonateClick,
text = stringResource(id = R.string.donate),
icon = R.drawable.ic_dollar_vector
)
}
SettingsHorizontalDivider()
}
}
@Composable
internal fun OtherSection(
showMoreApps: Boolean,
onMoreAppsClick: () -> Unit,
onWebsiteClick: () -> Unit,
showWebsite: Boolean,
showPrivacyPolicy: Boolean,
onPrivacyPolicyClick: () -> Unit,
onLicenseClick: () -> Unit,
version: String,
onVersionClick: () -> Unit,
) {
SettingsGroup(title = {
SettingsTitleTextComponent(text = stringResource(id = R.string.other), modifier = startingTitlePadding)
}) {
if (showMoreApps) {
TwoLinerTextItem(
click = onMoreAppsClick,
text = stringResource(id = R.string.more_apps_from_us),
icon = R.drawable.ic_heart_vector
)
}
if (showWebsite) {
TwoLinerTextItem(
click = onWebsiteClick,
text = stringResource(id = R.string.website),
icon = R.drawable.ic_link_vector
)
}
if (showPrivacyPolicy) {
TwoLinerTextItem(
click = onPrivacyPolicyClick,
text = stringResource(id = R.string.privacy_policy),
icon = R.drawable.ic_unhide_vector
)
}
TwoLinerTextItem(
click = onLicenseClick,
text = stringResource(id = R.string.third_party_licences),
icon = R.drawable.ic_article_vector
)
TwoLinerTextItem(
click = onVersionClick,
text = version,
icon = R.drawable.ic_info_vector
)
SettingsHorizontalDivider()
}
}
@Composable
internal fun AboutSection(
setupFAQ: Boolean,
onFAQClick: () -> Unit,
onEmailClick: () -> Unit
) {
SettingsGroup(title = {
SettingsTitleTextComponent(text = stringResource(id = R.string.support), modifier = startingTitlePadding)
}) {
if (setupFAQ) {
TwoLinerTextItem(
click = onFAQClick,
text = stringResource(id = R.string.frequently_asked_questions),
icon = R.drawable.ic_question_mark_vector
)
}
TwoLinerTextItem(
click = onEmailClick,
text = stringResource(id = R.string.my_email),
icon = R.drawable.ic_mail_vector
)
SettingsHorizontalDivider()
}
}
@Composable
internal fun SocialSection(
onFacebookClick: () -> Unit,
onGithubClick: () -> Unit,
onRedditClick: () -> Unit,
onTelegramClick: () -> Unit
) {
SettingsGroup(title = {
SettingsTitleTextComponent(text = stringResource(id = R.string.social), modifier = startingTitlePadding)
}) {
SocialText(
click = onFacebookClick,
text = stringResource(id = R.string.facebook),
icon = R.drawable.ic_facebook_vector,
)
SocialText(
click = onGithubClick,
text = stringResource(id = R.string.github),
icon = R.drawable.ic_github_vector,
tint = SimpleTheme.colorScheme.onSurface
)
SocialText(
click = onRedditClick,
text = stringResource(id = R.string.reddit),
icon = R.drawable.ic_reddit_vector,
)
SocialText(
click = onTelegramClick,
text = stringResource(id = R.string.telegram),
icon = R.drawable.ic_telegram_vector,
)
SettingsHorizontalDivider()
}
}
@Composable
internal fun SocialText(
text: String,
icon: Int,
tint: Color? = null,
click: () -> Unit
) {
SettingsListItem(
click = click,
text = text,
icon = icon,
isImage = true,
tint = tint,
maxLines = 2,
overflow = TextOverflow.Ellipsis
)
}
@Composable
internal fun TwoLinerTextItem(text: String, icon: Int, click: () -> Unit) {
SettingsListItem(
tint = SimpleTheme.colorScheme.onSurface,
click = click,
text = text,
icon = icon,
maxLines = 2,
overflow = TextOverflow.Ellipsis
)
}
@MyDevices
@Composable
private fun AboutScreenPreview() {
AppThemeSurface {
AboutScreen(
goBack = {},
helpUsSection = {
HelpUsSection(
onRateUsClick = {},
onInviteClick = {},
onContributorsClick = {},
showRateUs = true,
showInvite = true,
showDonate = true,
onDonateClick = {}
)
},
aboutSection = {
AboutSection(setupFAQ = true, onFAQClick = {}, onEmailClick = {})
},
socialSection = {
SocialSection(
onFacebookClick = {},
onGithubClick = {},
onRedditClick = {},
onTelegramClick = {}
)
}
) {
OtherSection(
showMoreApps = true,
onMoreAppsClick = {},
onWebsiteClick = {},
showWebsite = true,
showPrivacyPolicy = true,
onPrivacyPolicyClick = {},
onLicenseClick = {},
version = "5.0.4",
onVersionClick = {}
)
}
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/compose/screens/AboutScreen.kt | 3884744787 |
package com.simplemobiletools.commons.compose.alert_dialog
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material3.Surface
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.ReadOnlyComposable
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.platform.SoftwareKeyboardController
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.unit.dp
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.compose.theme.LocalTheme
import com.simplemobiletools.commons.compose.theme.Shapes
import com.simplemobiletools.commons.compose.theme.SimpleTheme
import com.simplemobiletools.commons.compose.theme.light_grey_stroke
import com.simplemobiletools.commons.compose.theme.model.Theme
import com.simplemobiletools.commons.extensions.baseConfig
import com.simplemobiletools.commons.helpers.isSPlus
import kotlinx.coroutines.android.awaitFrame
val dialogContainerColor
@ReadOnlyComposable
@Composable get() = when (LocalTheme.current) {
is Theme.BlackAndWhite -> Color.Black
is Theme.SystemDefaultMaterialYou -> if (isSPlus()) colorResource(R.color.you_dialog_background_color) else SimpleTheme.colorScheme.surface
else -> {
val context = LocalContext.current
Color(context.baseConfig.backgroundColor)
}
}
val Modifier.dialogBackgroundShapeAndBorder: Modifier
@ReadOnlyComposable
@Composable get() = then(
Modifier
.fillMaxWidth()
.background(dialogContainerColor, dialogShape)
.dialogBorder
)
val dialogShape = Shapes.extraLarge
val dialogElevation = 0.dp
val dialogTextColor @Composable @ReadOnlyComposable get() = SimpleTheme.colorScheme.onSurface
val Modifier.dialogBorder: Modifier
@ReadOnlyComposable
@Composable get() =
when (LocalTheme.current) {
is Theme.BlackAndWhite -> then(Modifier.border(1.dp, light_grey_stroke, dialogShape))
else -> Modifier
}
@Composable
fun DialogSurface(
modifier: Modifier = Modifier,
content: @Composable () -> Unit
) {
Surface(
modifier = modifier
.dialogBorder,
shape = dialogShape,
color = dialogContainerColor,
tonalElevation = dialogElevation,
) {
content()
}
}
@Composable
fun ShowKeyboardWhenDialogIsOpenedAndRequestFocus(
keyboardController: SoftwareKeyboardController? = LocalSoftwareKeyboardController.current,
focusRequester: FocusRequester?
) {
LaunchedEffect(Unit) {
//await two frames to render the scrim and the dialog
awaitFrame()
awaitFrame()
keyboardController?.show()
focusRequester?.requestFocus()
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/compose/alert_dialog/AlertDialogsExtensions.kt | 2020310865 |
package com.simplemobiletools.commons.compose.alert_dialog
import androidx.compose.runtime.*
import androidx.compose.runtime.saveable.Saver
import androidx.compose.runtime.saveable.SaverScope
import androidx.compose.runtime.saveable.rememberSaveable
import com.simplemobiletools.commons.compose.alert_dialog.AlertDialogState.Companion.SAVER
@Composable
fun rememberAlertDialogState(
isShownInitially: Boolean = false
) = remember { AlertDialogState(isShownInitially) }
/**
* Use this function to control the state whenever you want its visibility to be retained
* even after configuration and process death
* @param isShownInitially Boolean
* @return AlertDialogState
*/
@Composable
fun rememberAlertDialogStateSaveable(
isShownInitially: Boolean = false
) = rememberSaveable(saver = SAVER) { AlertDialogState(isShownInitially) }
@Stable
class AlertDialogState(isShownInitially: Boolean = false) {
companion object {
val SAVER = object : Saver<AlertDialogState, Boolean> {
override fun restore(value: Boolean): AlertDialogState = AlertDialogState(value)
override fun SaverScope.save(value: AlertDialogState): Boolean = value.isShown
}
}
var isShown by mutableStateOf(isShownInitially)
private set
fun show() {
if (isShown) {
isShown = false
}
isShown = true
}
fun hide() {
isShown = false
}
fun toggleVisibility() {
isShown = !isShown
}
fun changeVisibility(predicate: Boolean) {
isShown = predicate
}
@Composable
fun DialogMember(
content: @Composable () -> Unit
) {
if (isShown) {
content()
}
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/compose/alert_dialog/AlertDialogState.kt | 3748717223 |
package com.simplemobiletools.commons.compose.components
import android.text.Spanned
import android.text.method.LinkMovementMethod
import android.widget.TextView
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.sp
import androidx.compose.ui.viewinterop.AndroidView
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.compose.extensions.MyDevices
import com.simplemobiletools.commons.compose.theme.AppThemeSurface
import com.simplemobiletools.commons.compose.theme.SimpleTheme
import com.simplemobiletools.commons.extensions.fromHtml
import com.simplemobiletools.commons.extensions.removeUnderlines
@Composable
fun LinkifyTextComponent(
modifier: Modifier = Modifier,
fontSize: TextUnit = 14.sp,
removeUnderlines: Boolean = true,
textAlignment: Int = TextView.TEXT_ALIGNMENT_TEXT_START,
text: () -> Spanned
) {
val context = LocalContext.current
val customLinkifyTextView = remember {
TextView(context)
}
val textColor = SimpleTheme.colorScheme.onSurface
val linkTextColor = SimpleTheme.colorScheme.primary
AndroidView(modifier = modifier, factory = { customLinkifyTextView }) { textView ->
textView.setTextColor(textColor.toArgb())
textView.setLinkTextColor(linkTextColor.toArgb())
textView.text = text()
textView.textAlignment = textAlignment
textView.textSize = fontSize.value
textView.movementMethod = LinkMovementMethod.getInstance()
if (removeUnderlines) {
customLinkifyTextView.removeUnderlines()
}
}
}
@Composable
@MyDevices
private fun LinkifyTextComponentPreview() = AppThemeSurface {
val source = stringResource(id = R.string.contributors_label)
LinkifyTextComponent {
source.fromHtml()
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/compose/components/LinkifyTextComponent.kt | 915943679 |
package com.simplemobiletools.commons.compose.components
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import com.simplemobiletools.commons.compose.extensions.MyDevices
import com.simplemobiletools.commons.compose.theme.AppThemeSurface
@Composable
fun RadioGroupDialogComponent(
modifier: Modifier = Modifier,
items: List<String>,
selected: String?,
verticalPadding: Dp = 10.dp,
horizontalPadding: Dp = 20.dp,
setSelected: (selected: String) -> Unit,
) {
Column(
modifier = modifier
.fillMaxWidth()
) {
items.forEach { item ->
RadioButtonDialogComponent(
setSelected = setSelected,
item = item,
selected = selected,
modifier = Modifier.padding(vertical = verticalPadding, horizontal = horizontalPadding)
)
}
}
}
@Composable
@MyDevices
private fun RadioGroupDialogComponentPreview() {
AppThemeSurface {
RadioGroupDialogComponent(items = listOf(
"Test 1",
"Test 2",
"Test 3",
"Test 4",
"Test 5",
"Test 6",
), selected = null, setSelected = {})
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/compose/components/RadioGroupDialogComponent.kt | 1999111601 |
package com.simplemobiletools.commons.compose.components
import androidx.annotation.StringRes
import androidx.compose.foundation.Indication
import androidx.compose.foundation.LocalIndication
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxScope
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import com.simplemobiletools.commons.compose.extensions.MyDevices
import com.simplemobiletools.commons.compose.extensions.rememberMutableInteractionSource
import com.simplemobiletools.commons.compose.theme.AppThemeSurface
import com.simplemobiletools.commons.compose.theme.SimpleTheme
private val dropDownPaddings = Modifier.padding(horizontal = 14.dp, vertical = 16.dp)
@Composable
fun SimpleDropDownMenuItem(
modifier: Modifier = Modifier,
interactionSource: MutableInteractionSource = rememberMutableInteractionSource(),
indication: Indication? = LocalIndication.current,
@StringRes text: Int,
onClick: () -> Unit
) = SimpleDropDownMenuItem(modifier = modifier, text = stringResource(id = text), onClick = onClick, interactionSource = interactionSource, indication = indication)
@Composable
fun SimpleDropDownMenuItem(
modifier: Modifier = Modifier,
text: String,
interactionSource: MutableInteractionSource = rememberMutableInteractionSource(),
indication: Indication? = LocalIndication.current,
onClick: () -> Unit
) =
SimpleDropDownMenuItem(
modifier = modifier,
interactionSource = interactionSource,
indication = indication,
onClick = onClick,
text = {
Text(
text = text,
modifier = Modifier
.fillMaxWidth(),
color = SimpleTheme.colorScheme.onSurface
)
}
)
@Composable
fun SimpleDropDownMenuItem(
modifier: Modifier = Modifier,
interactionSource: MutableInteractionSource = rememberMutableInteractionSource(),
indication: Indication? = LocalIndication.current,
text: @Composable BoxScope.() -> Unit,
onClick: () -> Unit
) =
Box(modifier = modifier
.fillMaxWidth()
.clickable(interactionSource = interactionSource, indication = indication, onClick = onClick)
.then(dropDownPaddings)) {
text()
}
@MyDevices
@Composable
private fun SimpleDropDownMenuItemPreview() {
AppThemeSurface {
SimpleDropDownMenuItem(text = com.simplemobiletools.commons.R.string.copy, onClick = {})
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/compose/components/SimpleDropDownMenuItem.kt | 209407024 |
package com.simplemobiletools.commons.compose.components
import androidx.compose.foundation.LocalIndication
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.material3.RadioButton
import androidx.compose.material3.RadioButtonDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.simplemobiletools.commons.compose.alert_dialog.dialogTextColor
import com.simplemobiletools.commons.compose.extensions.MyDevices
import com.simplemobiletools.commons.compose.extensions.rememberMutableInteractionSource
import com.simplemobiletools.commons.compose.theme.AppThemeSurface
import com.simplemobiletools.commons.compose.theme.SimpleTheme
@Composable
fun RadioButtonDialogComponent(
modifier: Modifier = Modifier,
setSelected: (selected: String) -> Unit,
item: String,
selected: String?
) {
val interactionSource = rememberMutableInteractionSource()
val indication = LocalIndication.current
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.fillMaxWidth()
.clickable(
onClick = { setSelected(item) },
interactionSource = interactionSource,
indication = indication
)
.then(modifier)
) {
RadioButton(
selected = selected == item,
onClick = null,
enabled = true,
colors = RadioButtonDefaults.colors(
selectedColor = SimpleTheme.colorScheme.primary
),
)
Text(
text = item,
modifier = Modifier.padding(start = SimpleTheme.dimens.padding.medium),
color = dialogTextColor
)
}
}
@Composable
@MyDevices
private fun RadioButtonDialogComponentPreview() {
AppThemeSurface {
Box(
modifier = Modifier
.fillMaxWidth()
.height(400.dp),
contentAlignment = Alignment.Center
) {
RadioButtonDialogComponent(
setSelected = {}, item = "item", selected = "item",
modifier = Modifier.padding(horizontal = 16.dp, vertical = 18.dp)
)
}
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/compose/components/RadioButtonDialogComponent.kt | 1136230972 |
package com.simplemobiletools.commons.compose.theme
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.Surface
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalView
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.compose.LifecycleEventEffect
import com.simplemobiletools.commons.compose.extensions.FakeVersionCheck
import com.simplemobiletools.commons.compose.extensions.TransparentSystemBars
import com.simplemobiletools.commons.compose.theme.model.Theme
import com.simplemobiletools.commons.compose.theme.model.Theme.Companion.systemDefaultMaterialYou
@Composable
fun AppTheme(
content: @Composable () -> Unit,
) {
val view = LocalView.current
val context = LocalContext.current
val materialYouTheme = systemDefaultMaterialYou()
var currentTheme: Theme by remember {
mutableStateOf(
if (view.isInEditMode) materialYouTheme else getTheme(
context = context,
materialYouTheme = materialYouTheme
)
)
}
LifecycleEventEffect(event = Lifecycle.Event.ON_START) {
if (!view.isInEditMode) {
currentTheme = getTheme(context = context, materialYouTheme = materialYouTheme)
}
}
TransparentSystemBars()
Theme(theme = currentTheme) {
content()
if (!view.isInEditMode) {
OnContentDisplayed()
}
}
}
@Composable
fun AppThemeSurface(
modifier: Modifier = Modifier,
content: @Composable () -> Unit,
) {
AppTheme {
Surface(modifier = modifier.fillMaxSize()) {
content()
}
}
}
@Composable
private fun OnContentDisplayed() {
FakeVersionCheck()
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/compose/theme/AppTheme.kt | 3621730874 |
package com.simplemobiletools.commons.compose.theme
import android.content.Context
import android.content.res.Configuration
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.ReadOnlyComposable
import androidx.compose.ui.graphics.luminance
import androidx.compose.ui.platform.LocalContext
import com.simplemobiletools.commons.compose.theme.model.Theme.Companion.systemDefaultMaterialYou
@Composable
fun getCurrentTheme() = getTheme(LocalContext.current, systemDefaultMaterialYou())
@Composable
@ReadOnlyComposable
fun isInDarkThemeOrSurfaceIsNotLitWell() = isSystemInDarkTheme() || isSurfaceNotLitWell()
@Composable
@ReadOnlyComposable
fun isInDarkThemeAndSurfaceIsNotLitWell() = isSystemInDarkTheme() && isSurfaceNotLitWell()
internal const val LUMINANCE_THRESHOLD = 0.5f
@Composable
@ReadOnlyComposable
fun isSurfaceNotLitWell(threshold: Float = LUMINANCE_THRESHOLD) = SimpleTheme.colorScheme.surface.luminance() < threshold
@Composable
@ReadOnlyComposable
fun isSurfaceLitWell(threshold: Float = LUMINANCE_THRESHOLD) = SimpleTheme.colorScheme.surface.luminance() > threshold
internal fun Context.isDarkMode(): Boolean {
val darkModeFlag = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
return darkModeFlag == Configuration.UI_MODE_NIGHT_YES
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/compose/theme/ThemeExtensions.kt | 1301945477 |
package com.simplemobiletools.commons.compose.theme
import androidx.compose.ui.graphics.Color
val color_primary = Color(0xFFF57C00)
val color_primary_dark = Color(0xFFD76D00)
val color_accent = color_primary
val pressed_item_foreground = Color(0x08000000)
val activated_item_foreground = Color(0x44888888)
val divider_grey = Color(0x55808080)
val gradient_grey_start = Color(0xCC000000)
val dark_grey = Color(0xFF333333)
val bottom_tabs_light_background = Color(0xFFF1F1F1)
val disabled_text_color_highlight = Color(0x00FFFFFF)
val hint_white = Color(0x99FFFFFF)
val hint_black = Color(0x66000000)
val light_grey_stroke = Color(0x40FFFFFF)
val thumb_deactivated = Color(0xFFECECEC)
val track_deactivated = Color(0xFFB2B2B2)
val radiobutton_disabled = Color(0xFF757575)
val md_amber = Color(0xFFFFC107)
val md_blue = Color(0xFF2196F3)
val md_blue_grey = Color(0xFF607D8B)
val md_brown = Color(0xFF795548)
val md_cyan = Color(0xFF00BCD4)
val md_deep_orange = Color(0xFFFF5722)
val md_deep_purple = Color(0xFF673AB7)
val md_green = Color(0xFF4CAF50)
val md_grey = Color(0xFF9E9E9E)
val md_indigo = Color(0xFF3F51B5)
val md_light_blue = Color(0xFF03A9F4)
val md_light_green = Color(0xFF8BC34A)
val md_lime = Color(0xFFCDDC39)
val md_orange = Color(0xFFFF9800)
val md_pink = Color(0xFFE91E63)
val md_purple = Color(0xFF9C27B0)
val md_red = Color(0xFFF44336)
val md_teal = Color(0xFF009688)
val md_yellow = Color(0xFFFFEB3B)
val md_amber_100 = Color(0xFFFFECB3)
val md_amber_200 = Color(0xFFFFE082)
val md_amber_300 = Color(0xFFFFD54F)
val md_amber_400 = Color(0xFFFFCA28)
val md_amber_500 = Color(0xFFFFC107)
val md_amber_600 = Color(0xFFFFB300)
val md_amber_700 = Color(0xFFFFA000)
val md_amber_800 = Color(0xFFFF8F00)
val md_amber_900 = Color(0xFFFF6F00)
val md_amber_100_dark = Color(0xFFFFE28A)
val md_amber_200_dark = Color(0xFFFFD659)
val md_amber_300_dark = Color(0xFFFFCC26)
val md_amber_400_dark = Color(0xFFFFC100)
val md_amber_500_dark = Color(0xFFDEA700)
val md_amber_600_dark = Color(0xFFD79700)
val md_amber_700_dark = Color(0xFFD78700)
val md_amber_800_dark = Color(0xFFD77800)
val md_amber_900_dark = Color(0xFFD75D00)
val md_blue_100 = Color(0xFFBBDEFB)
val md_blue_200 = Color(0xFF90CAF9)
val md_blue_300 = Color(0xFF64B5F6)
val md_blue_400 = Color(0xFF42A5F5)
val md_blue_500 = Color(0xFF2196F3)
val md_blue_600 = Color(0xFF1E88E5)
val md_blue_700 = Color(0xFF1976D2)
val md_blue_800 = Color(0xFF1565C0)
val md_blue_900 = Color(0xFF0D47A1)
val md_blue_100_dark = Color(0xFF94CCF9)
val md_blue_200_dark = Color(0xFF69B8F7)
val md_blue_300_dark = Color(0xFF3DA2F4)
val md_blue_400_dark = Color(0xFF1A92F3)
val md_blue_500_dark = Color(0xFF0B82E0)
val md_blue_600_dark = Color(0xFF1673C4)
val md_blue_700_dark = Color(0xFF1462AE)
val md_blue_800_dark = Color(0xFF11529B)
val md_blue_900_dark = Color(0xFF09367B)
val md_blue_grey_100 = Color(0xFFCFD8DC)
val md_blue_grey_200 = Color(0xFFB0BBC5)
val md_blue_grey_300 = Color(0xFF90A4AE)
val md_blue_grey_400 = Color(0xFF78909C)
val md_blue_grey_500 = Color(0xFF607D8B)
val md_blue_grey_600 = Color(0xFF546E7A)
val md_blue_grey_700 = Color(0xFF455A64)
val md_blue_grey_800 = Color(0xFF37474F)
val md_blue_grey_900 = Color(0xFF263238)
val md_blue_grey_100_dark = Color(0xFFB8C5CB)
val md_blue_grey_200_dark = Color(0xFF99A7B4)
val md_blue_grey_300_dark = Color(0xFF78919D)
val md_blue_grey_400_dark = Color(0xFF647C88)
val md_blue_grey_500_dark = Color(0xFF4F6873)
val md_blue_grey_600_dark = Color(0xFF445962)
val md_blue_grey_700_dark = Color(0xFF34454C)
val md_blue_grey_800_dark = Color(0xFF263237)
val md_blue_grey_900_dark = Color(0xFF151C1F)
val md_brown_100 = Color(0xFFD7CCC8)
val md_brown_200 = Color(0xFFBCAAA4)
val md_brown_300 = Color(0xFFA1887F)
val md_brown_400 = Color(0xFF8D6E63)
val md_brown_500 = Color(0xFF795548)
val md_brown_600 = Color(0xFF6D4C41)
val md_brown_700 = Color(0xFF5D4037)
val md_brown_800 = Color(0xFF4E342E)
val md_brown_900 = Color(0xFF3E2723)
val md_brown_100_dark = Color(0xFFC6B7B1)
val md_brown_200_dark = Color(0xFFAB958D)
val md_brown_300_dark = Color(0xFF8F7369)
val md_brown_400_dark = Color(0xFF755B52)
val md_brown_500_dark = Color(0xFF5F4339)
val md_brown_600_dark = Color(0xFF533A31)
val md_brown_700_dark = Color(0xFF432E28)
val md_brown_800_dark = Color(0xFF34231F)
val md_brown_900_dark = Color(0xFF241714)
val md_cyan_100 = Color(0xFFB2EBF2)
val md_cyan_200 = Color(0xFF80DEEA)
val md_cyan_300 = Color(0xFF4DD0E1)
val md_cyan_400 = Color(0xFF26C6DA)
val md_cyan_500 = Color(0xFF00BCD4)
val md_cyan_600 = Color(0xFF00ACC1)
val md_cyan_700 = Color(0xFF0097A7)
val md_cyan_800 = Color(0xFF00838F)
val md_cyan_900 = Color(0xFF006064)
val md_cyan_100_dark = Color(0xFF90E3ED)
val md_cyan_200_dark = Color(0xFF5DD5E5)
val md_cyan_300_dark = Color(0xFF2AC7DB)
val md_cyan_400_dark = Color(0xFF1FA7B8)
val md_cyan_500_dark = Color(0xFF0098AB)
val md_cyan_600_dark = Color(0xFF008898)
val md_cyan_700_dark = Color(0xFF00727E)
val md_cyan_800_dark = Color(0xFF005E66)
val md_cyan_900_dark = Color(0xFF00393B)
val md_deep_orange_100 = Color(0xFFFFCCBC)
val md_deep_orange_200 = Color(0xFFFFAB91)
val md_deep_orange_300 = Color(0xFFFF8A65)
val md_deep_orange_400 = Color(0xFFFF7043)
val md_deep_orange_500 = Color(0xFFFF5722)
val md_deep_orange_600 = Color(0xFFF4511E)
val md_deep_orange_700 = Color(0xFFE64A19)
val md_deep_orange_800 = Color(0xFFD84315)
val md_deep_orange_900 = Color(0xFFBF360C)
val md_deep_orange_100_dark = Color(0xFFFFAD93)
val md_deep_orange_200_dark = Color(0xFFFF8C68)
val md_deep_orange_300_dark = Color(0xFFFF6B3C)
val md_deep_orange_400_dark = Color(0xFFFF511A)
val md_deep_orange_500_dark = Color(0xFFF93C00)
val md_deep_orange_600_dark = Color(0xFFDF3D0A)
val md_deep_orange_700_dark = Color(0xFFC13E14)
val md_deep_orange_800_dark = Color(0xFFB33710)
val md_deep_orange_900_dark = Color(0xFF992B09)
val md_deep_purple_100 = Color(0xFFD1C4E9)
val md_deep_purple_200 = Color(0xFFB39DDB)
val md_deep_purple_300 = Color(0xFF9575CD)
val md_deep_purple_400 = Color(0xFF7E57C2)
val md_deep_purple_500 = Color(0xFF673AB7)
val md_deep_purple_600 = Color(0xFF5E35B1)
val md_deep_purple_700 = Color(0xFF512DA8)
val md_deep_purple_800 = Color(0xFF4527A0)
val md_deep_purple_900 = Color(0xFF311B92)
val md_deep_purple_100_dark = Color(0xFFBAA6DE)
val md_deep_purple_200_dark = Color(0xFF9C7FD0)
val md_deep_purple_300_dark = Color(0xFF7E56C2)
val md_deep_purple_400_dark = Color(0xFF693FB0)
val md_deep_purple_500_dark = Color(0xFF563098)
val md_deep_purple_600_dark = Color(0xFF4E2B92)
val md_deep_purple_700_dark = Color(0xFF412488)
val md_deep_purple_800_dark = Color(0xFF371F7F)
val md_deep_purple_900_dark = Color(0xFF251470)
val md_green_100 = Color(0xFFC8E6C9)
val md_green_200 = Color(0xFFA5D6A7)
val md_green_300 = Color(0xFF81C784)
val md_green_400 = Color(0xFF66BB6A)
val md_green_500 = Color(0xFF4CAF50)
val md_green_600 = Color(0xFF43A047)
val md_green_700 = Color(0xFF388E3C)
val md_green_800 = Color(0xFF2E7D32)
val md_green_900 = Color(0xFF1B5E20)
val md_green_100_dark = Color(0xFFACDAAE)
val md_green_200_dark = Color(0xFF89CA8D)
val md_green_300_dark = Color(0xFF65BB69)
val md_green_400_dark = Color(0xFF4CAC51)
val md_green_500_dark = Color(0xFF409343)
val md_green_600_dark = Color(0xFF37833A)
val md_green_700_dark = Color(0xFF2C7130)
val md_green_800_dark = Color(0xFF235F26)
val md_green_900_dark = Color(0xFF113E15)
val md_grey_white = Color(0xFFFFFFFF)
val md_grey_200 = Color(0xFFEEEEEE)
val md_grey_300 = Color(0xFFE0E0E0)
val md_grey_400 = Color(0xFFBDBDBD)
val md_grey_500 = Color(0xFF9E9E9E)
val md_grey_600 = Color(0xFF757575)
val md_grey_700 = Color(0xFF616161)
val md_grey_800 = Color(0xFF424242)
val md_grey_black = Color(0xFF000000)
val md_grey_white_dark = Color(0xFFDFDFDF)
val md_grey_200_dark = Color(0xFFDADADA)
val md_grey_300_dark = Color(0xFFCCCCCC)
val md_grey_400_dark = Color(0xFFA9A9A9)
val md_grey_500_dark = Color(0xFF8A8A8A)
val md_grey_600_dark = Color(0xFF606060)
val md_grey_700_dark = Color(0xFF4C4C4C)
val md_grey_800_dark = Color(0xFF2D2D2D)
val md_grey_black_dark = Color(0xFF000000)
val md_indigo_100 = Color(0xFFC5CAE9)
val md_indigo_200 = Color(0xFF9FA8DA)
val md_indigo_300 = Color(0xFF7986CB)
val md_indigo_400 = Color(0xFF5C6BC0)
val md_indigo_500 = Color(0xFF3F51B5)
val md_indigo_600 = Color(0xFF3949AB)
val md_indigo_700 = Color(0xFF303F9F)
val md_indigo_800 = Color(0xFF283593)
val md_indigo_900 = Color(0xFF1A237E)
val md_indigo_100_dark = Color(0xFFA8AFDE)
val md_indigo_200_dark = Color(0xFF828ECF)
val md_indigo_300_dark = Color(0xFF5B6CC0)
val md_indigo_400_dark = Color(0xFF4354B0)
val md_indigo_500_dark = Color(0xFF344497)
val md_indigo_600_dark = Color(0xFF2E3C8C)
val md_indigo_700_dark = Color(0xFF263380)
val md_indigo_800_dark = Color(0xFF1F2973)
val md_indigo_900_dark = Color(0xFF12195C)
val md_light_blue_100 = Color(0xFFB3E5FC)
val md_light_blue_200 = Color(0xFF81D4fA)
val md_light_blue_300 = Color(0xFF4fC3F7)
val md_light_blue_400 = Color(0xFF29B6FC)
val md_light_blue_500 = Color(0xFF03A9F4)
val md_light_blue_600 = Color(0xFF039BE5)
val md_light_blue_700 = Color(0xFF0288D1)
val md_light_blue_800 = Color(0xFF0277BD)
val md_light_blue_900 = Color(0xFF01579B)
val md_light_blue_100_dark = Color(0xFF8BD8FB)
val md_light_blue_200_dark = Color(0xFF59C7F9)
val md_light_blue_300_dark = Color(0xFF27B6F6)
val md_light_blue_400_dark = Color(0xFF02A7F9)
val md_light_blue_500_dark = Color(0xFF028DCC)
val md_light_blue_600_dark = Color(0xFF0280BD)
val md_light_blue_700_dark = Color(0xFF016EA9)
val md_light_blue_800_dark = Color(0xFF015E95)
val md_light_blue_900_dark = Color(0xFF004072)
val md_light_green_100 = Color(0xFFDCEDC8)
val md_light_green_200 = Color(0xFFC5E1A5)
val md_light_green_300 = Color(0xFFAED581)
val md_light_green_400 = Color(0xFF9CCC65)
val md_light_green_500 = Color(0xFF8BC34A)
val md_light_green_600 = Color(0xFF7CB342)
val md_light_green_700 = Color(0xFF689F38)
val md_light_green_800 = Color(0xFF558B2F)
val md_light_green_900 = Color(0xFF33691E)
val md_light_green_100_dark = Color(0xFFC9E3A9)
val md_light_green_200_dark = Color(0xFFB2D787)
val md_light_green_300_dark = Color(0xFF9BCB62)
val md_light_green_400_dark = Color(0xFF89C246)
val md_light_green_500_dark = Color(0xFF76AC38)
val md_light_green_600_dark = Color(0xFF679537)
val md_light_green_700_dark = Color(0xFF54812D)
val md_light_green_800_dark = Color(0xFF426C24)
val md_light_green_900_dark = Color(0xFF234915)
val md_lime_100 = Color(0xFFF0F4C3)
val md_lime_200 = Color(0xFFE6EE9C)
val md_lime_300 = Color(0xFFDCE775)
val md_lime_400 = Color(0xFFD4E157)
val md_lime_500 = Color(0xFFCDDC39)
val md_lime_600 = Color(0xFFC0CA33)
val md_lime_700 = Color(0xFFA4B42B)
val md_lime_800 = Color(0xFF9E9D24)
val md_lime_900 = Color(0xFF827717)
val md_lime_100_dark = Color(0xFFE8EEA0)
val md_lime_200_dark = Color(0xFFDEE879)
val md_lime_300_dark = Color(0xFFD3E152)
val md_lime_400_dark = Color(0xFFCBDB34)
val md_lime_500_dark = Color(0xFFBAC923)
val md_lime_600_dark = Color(0xFFA2AA2A)
val md_lime_700_dark = Color(0xFF869323)
val md_lime_800_dark = Color(0xFF7D7D1C)
val md_lime_900_dark = Color(0xFF5F5710)
val md_orange_100 = Color(0xFFFFE0B2)
val md_orange_200 = Color(0xFFFFCC80)
val md_orange_300 = Color(0xFFFFB74D)
val md_orange_400 = Color(0xFFFFA726)
val md_orange_500 = Color(0xFFFF9800)
val md_orange_600 = Color(0xFFFB8C00)
val md_orange_700 = Color(0xFFF57C00)
val md_orange_800 = Color(0xFFEF6C00)
val md_orange_900 = Color(0xFFE65100)
val md_orange_100_dark = Color(0xFFFFD089)
val md_orange_200_dark = Color(0xFFFFBC57)
val md_orange_300_dark = Color(0xFFFFA724)
val md_orange_400_dark = Color(0xFFFD9600)
val md_orange_500_dark = Color(0xFFD78000)
val md_orange_600_dark = Color(0xFFD37600)
val md_orange_700_dark = Color(0xFFCD6800)
val md_orange_800_dark = Color(0xFFC65A00)
val md_orange_900_dark = Color(0xFFBD4200)
val md_pink_100 = Color(0xFFF8BBD0)
val md_pink_200 = Color(0xFFF48FB1)
val md_pink_300 = Color(0xFFF06292)
val md_pink_400 = Color(0xFFEC407A)
val md_pink_500 = Color(0xFFE91E63)
val md_pink_600 = Color(0xFFD81B60)
val md_pink_700 = Color(0xFFC2185B)
val md_pink_800 = Color(0xFFAD1457)
val md_pink_900 = Color(0xFF880E4F)
val md_pink_100_dark = Color(0xFFF596B7)
val md_pink_200_dark = Color(0xFFF16998)
val md_pink_300_dark = Color(0xFFED3C78)
val md_pink_400_dark = Color(0xFFE91A60)
val md_pink_500_dark = Color(0xFFCB1352)
val md_pink_600_dark = Color(0xFFB4154F)
val md_pink_700_dark = Color(0xFF9E134A)
val md_pink_800_dark = Color(0xFF880F44)
val md_pink_900_dark = Color(0xFF630A3A)
val md_purple_100 = Color(0xFFE1BEE7)
val md_purple_200 = Color(0xFFCE93D8)
val md_purple_300 = Color(0xFFBA68C8)
val md_purple_400 = Color(0xFFAB47BC)
val md_purple_500 = Color(0xFF9C27B0)
val md_purple_600 = Color(0xFF8E24AA)
val md_purple_700 = Color(0xFF7B1FA2)
val md_purple_800 = Color(0xFF6A1B9A)
val md_purple_900 = Color(0xFF4A148C)
val md_purple_100_dark = Color(0xFFD3A0DC)
val md_purple_200_dark = Color(0xFFC175CD)
val md_purple_300_dark = Color(0xFFAC4ABD)
val md_purple_400_dark = Color(0xFF913AA0)
val md_purple_500_dark = Color(0xFF7F1F8F)
val md_purple_600_dark = Color(0xFF711C88)
val md_purple_700_dark = Color(0xFF611880)
val md_purple_800_dark = Color(0xFF521477)
val md_purple_900_dark = Color(0xFF370E68)
val md_red_100 = Color(0xFFFFCDD2)
val md_red_200 = Color(0xFFEF9A9A)
val md_red_300 = Color(0xFFE57373)
val md_red_400 = Color(0xFFEF5350)
val md_red_500 = Color(0xFFF44336)
val md_red_600 = Color(0xFFE53935)
val md_red_700 = Color(0xFFD32F2F)
val md_red_800 = Color(0xFFC62828)
val md_red_900 = Color(0xFFB71C1C)
val md_red_100_dark = Color(0xFFFFA4AE)
val md_red_200_dark = Color(0xFFEA7777)
val md_red_300_dark = Color(0xFFDF5050)
val md_red_400_dark = Color(0xFFEC2E2A)
val md_red_500_dark = Color(0xFFF21F0F)
val md_red_600_dark = Color(0xFFD61F1A)
val md_red_700_dark = Color(0xFFB32525)
val md_red_800_dark = Color(0xFFA42020)
val md_red_900_dark = Color(0xFF941616)
val md_teal_100 = Color(0xFFB2DFDB)
val md_teal_200 = Color(0xFF80CBC4)
val md_teal_300 = Color(0xFF4DB6AC)
val md_teal_400 = Color(0xFF26A69A)
val md_teal_500 = Color(0xFF009688)
val md_teal_600 = Color(0xFF00897B)
val md_teal_700 = Color(0xFF00796B)
val md_teal_800 = Color(0xFF00695C)
val md_teal_900 = Color(0xFF004D40)
val md_teal_100_dark = Color(0xFF95D3CE)
val md_teal_200_dark = Color(0xFF63BFB7)
val md_teal_300_dark = Color(0xFF3F9B92)
val md_teal_400_dark = Color(0xFF1E857C)
val md_teal_500_dark = Color(0xFF006D63)
val md_teal_600_dark = Color(0xFF006056)
val md_teal_700_dark = Color(0xFF005047)
val md_teal_800_dark = Color(0xFF004038)
val md_teal_900_dark = Color(0xFF00241E)
val md_yellow_100 = Color(0xFFFFF9C4)
val md_yellow_200 = Color(0xFFFFF590)
val md_yellow_300 = Color(0xFFFFF176)
val md_yellow_400 = Color(0xFFFFEE58)
val md_yellow_500 = Color(0xFFFFEB3B)
val md_yellow_600 = Color(0xFFFDD835)
val md_yellow_700 = Color(0xFFFBC02D)
val md_yellow_800 = Color(0xFFF9A825)
val md_yellow_900 = Color(0xFFF57F17)
val md_yellow_100_dark = Color(0xFFFFF59B)
val md_yellow_200_dark = Color(0xFFFFF267)
val md_yellow_300_dark = Color(0xFFFFED4D)
val md_yellow_400_dark = Color(0xFFFFEA2F)
val md_yellow_500_dark = Color(0xFFFFE712)
val md_yellow_600_dark = Color(0xFFFDD10B)
val md_yellow_700_dark = Color(0xFFFBB504)
val md_yellow_800_dark = Color(0xFFEF9606)
val md_yellow_900_dark = Color(0xFFDA6B09)
val theme_light_text_color = md_grey_800_dark
val theme_light_background_color = md_grey_white
val theme_dark_text_color = md_grey_200
val theme_dark_background_color = md_grey_800_dark
val theme_solarized_background_color = md_indigo_900_dark
val theme_solarized_text_color = md_amber_700
val theme_solarized_primary_color = md_indigo_900
val theme_dark_red_primary_color = md_red_700
val default_text_color = theme_dark_text_color
val default_background_color = theme_dark_background_color
val default_primary_color = color_primary
val default_app_icon_color = color_primary
val default_accent_color = color_primary
val default_widget_bg_color = Color(0xAA000000)
val default_widget_text_color = color_primary
val ripple_light = Color(0x1f000000)
val ripple_dark = Color(0x33ffffff)
val actionModeColor = Color(0xFF2D231D)
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/compose/theme/Colors.kt | 3926278858 |
package com.simplemobiletools.commons.compose.theme
import androidx.compose.material.ripple.RippleAlpha
import androidx.compose.material.ripple.RippleTheme
import androidx.compose.material3.LocalContentColor
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Immutable
import androidx.compose.ui.graphics.Color
@Immutable
internal object DynamicThemeRipple : RippleTheme {
@Composable
override fun defaultColor(): Color = if (isSurfaceLitWell()) ripple_light else LocalContentColor.current
@Composable
override fun rippleAlpha(): RippleAlpha = DefaultRippleAlpha
private val DefaultRippleAlpha = RippleAlpha(
pressedAlpha = StateTokens.PressedStateLayerOpacity,
focusedAlpha = StateTokens.FocusStateLayerOpacity,
draggedAlpha = StateTokens.DraggedStateLayerOpacity,
hoveredAlpha = StateTokens.HoverStateLayerOpacity
)
@Immutable
internal object StateTokens {
const val DraggedStateLayerOpacity = 0.16f
const val FocusStateLayerOpacity = 0.12f
const val HoverStateLayerOpacity = 0.08f
const val PressedStateLayerOpacity = 0.12f
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/compose/theme/DynamicThemeRipple.kt | 2719565997 |
package com.simplemobiletools.commons.compose.theme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.lightColorScheme
internal val darkColorScheme = darkColorScheme(
primary = color_primary,
secondary = color_primary_dark,
tertiary = color_accent,
)
internal val lightColorScheme = lightColorScheme(
primary = color_primary,
secondary = color_primary_dark,
tertiary = color_accent,
)
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/compose/theme/ColorSchemes.kt | 821710423 |
package com.simplemobiletools.commons.compose.theme
import android.content.Context
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb
import com.simplemobiletools.commons.compose.extensions.config
import com.simplemobiletools.commons.compose.theme.model.Theme
import com.simplemobiletools.commons.extensions.getProperTextColor
import com.simplemobiletools.commons.extensions.isBlackAndWhiteTheme
import com.simplemobiletools.commons.extensions.isWhiteTheme
fun getTheme(context: Context, materialYouTheme: Theme.SystemDefaultMaterialYou): Theme {
val baseConfig = context.config
val primaryColorInt = baseConfig.primaryColor
val isSystemInDarkTheme = context.isDarkMode()
val accentColor = baseConfig.accentColor
val backgroundColorTheme = if (baseConfig.isUsingSystemTheme || baseConfig.isUsingAutoTheme) {
if (isSystemInDarkTheme) theme_dark_background_color else Color.White
} else {
Color(baseConfig.backgroundColor)
}
val backgroundColor = backgroundColorTheme.toArgb()
val appIconColor = baseConfig.appIconColor
val textColor = context.getProperTextColor()
val theme = when {
baseConfig.isUsingSystemTheme -> materialYouTheme
context.isBlackAndWhiteTheme() -> Theme.BlackAndWhite(
accentColor = accentColor,
primaryColorInt = primaryColorInt,
backgroundColorInt = backgroundColor,
appIconColorInt = appIconColor,
textColorInt = textColor
)
context.isWhiteTheme() -> Theme.White(
accentColor = accentColor,
primaryColorInt = primaryColorInt,
backgroundColorInt = backgroundColor,
appIconColorInt = appIconColor,
textColorInt = textColor
)
else -> {
val customPrimaryColor = when (primaryColorInt) {
-12846 -> md_red_100
-1074534 -> md_red_200
-1739917 -> md_red_300
-1092784 -> md_red_400
-769226 -> md_red_500
-1754827 -> md_red_600
-2937041 -> md_red_700
-3790808 -> md_red_800
-4776932 -> md_red_900
-476208 -> md_pink_100
-749647 -> md_pink_200
-1023342 -> md_pink_300
-1294214 -> md_pink_400
-1499549 -> md_pink_500
-2614432 -> md_pink_600
-4056997 -> md_pink_700
-5434281 -> md_pink_800
-7860657 -> md_pink_900
-1982745 -> md_purple_100
-3238952 -> md_purple_200
-4560696 -> md_purple_300
-5552196 -> md_purple_400
-6543440 -> md_purple_500
-7461718 -> md_purple_600
-8708190 -> md_purple_700
-9823334 -> md_purple_800
-11922292 -> md_purple_900
-3029783 -> md_deep_purple_100
-5005861 -> md_deep_purple_200
-6982195 -> md_deep_purple_300
-8497214 -> md_deep_purple_400
-10011977 -> md_deep_purple_500
-10603087 -> md_deep_purple_600
-11457112 -> md_deep_purple_700
-12245088 -> md_deep_purple_800
-13558894 -> md_deep_purple_900
-3814679 -> md_indigo_100
-6313766 -> md_indigo_200
-8812853 -> md_indigo_300
-10720320 -> md_indigo_400
-12627531 -> md_indigo_500
-13022805 -> md_indigo_600
-13615201 -> md_indigo_700
-14142061 -> md_indigo_800
-15064194 -> md_indigo_900
-4464901 -> md_blue_100
-7288071 -> md_blue_200
-10177034 -> md_blue_300
-12409355 -> md_blue_400
-14575885 -> md_blue_500
-14776091 -> md_blue_600
-15108398 -> md_blue_700
-15374912 -> md_blue_800
-15906911 -> md_blue_900
-4987396 -> md_light_blue_100
-8268550 -> md_light_blue_200
-11549705 -> md_light_blue_300
-14043396 -> md_light_blue_400
-16537100 -> md_light_blue_500
-16540699 -> md_light_blue_600
-16611119 -> md_light_blue_700
-16615491 -> md_light_blue_800
-16689253 -> md_light_blue_900
-5051406 -> md_cyan_100
-8331542 -> md_cyan_200
-11677471 -> md_cyan_300
-14235942 -> md_cyan_400
-16728876 -> md_cyan_500
-16732991 -> md_cyan_600
-16738393 -> md_cyan_700
-16743537 -> md_cyan_800
-16752540 -> md_cyan_900
-5054501 -> md_teal_100
-8336444 -> md_teal_200
-11684180 -> md_teal_300
-14244198 -> md_teal_400
-16738680 -> md_teal_500
-16742021 -> md_teal_600
-16746133 -> md_teal_700
-16750244 -> md_teal_800
-16757440 -> md_teal_900
-3610935 -> md_green_100
-5908825 -> md_green_200
-8271996 -> md_green_300
-10044566 -> md_green_400
-11751600 -> md_green_500
-12345273 -> md_green_600
-13070788 -> md_green_700
-13730510 -> md_green_800
-14983648 -> md_green_900
-2298424 -> md_light_green_100
-3808859 -> md_light_green_200
-5319295 -> md_light_green_300
-6501275 -> md_light_green_400
-7617718 -> md_light_green_500
-8604862 -> md_light_green_600
-9920712 -> md_light_green_700
-11171025 -> md_light_green_800
-13407970 -> md_light_green_900
-985917 -> md_lime_100
-1642852 -> md_lime_200
-2300043 -> md_lime_300
-2825897 -> md_lime_400
-3285959 -> md_lime_500
-4142541 -> md_lime_600
-5983189 -> md_lime_700
-6382300 -> md_lime_800
-8227049 -> md_lime_900
-1596 -> md_yellow_100
-2672 -> md_yellow_200
-3722 -> md_yellow_300
-4520 -> md_yellow_400
-5317 -> md_yellow_500
-141259 -> md_yellow_600
-278483 -> md_yellow_700
-415707 -> md_yellow_800
-688361 -> md_yellow_900
-4941 -> md_amber_100
-8062 -> md_amber_200
-10929 -> md_amber_300
-13784 -> md_amber_400
-16121 -> md_amber_500
-19712 -> md_amber_600
-24576 -> md_amber_700
-28928 -> md_amber_800
-37120 -> md_amber_900
-8014 -> md_orange_100
-13184 -> md_orange_200
-18611 -> md_orange_300
-22746 -> md_orange_400
-26624 -> md_orange_500
-291840 -> md_orange_600
-689152 -> md_orange_700
-1086464 -> md_orange_800
-1683200 -> md_orange_900
-13124 -> md_deep_orange_100
-21615 -> md_deep_orange_200
-30107 -> md_deep_orange_300
-36797 -> md_deep_orange_400
-43230 -> md_deep_orange_500
-765666 -> md_deep_orange_600
-1684967 -> md_deep_orange_700
-2604267 -> md_deep_orange_800
-4246004 -> md_deep_orange_900
-2634552 -> md_brown_100
-4412764 -> md_brown_200
-6190977 -> md_brown_300
-7508381 -> md_brown_400
-8825528 -> md_brown_500
-9614271 -> md_brown_600
-10665929 -> md_brown_700
-11652050 -> md_brown_800
-12703965 -> md_brown_900
-3155748 -> md_blue_grey_100
-5194811 -> md_blue_grey_200
-7297874 -> md_blue_grey_300
-8875876 -> md_blue_grey_400
-10453621 -> md_blue_grey_500
-11243910 -> md_blue_grey_600
-12232092 -> md_blue_grey_700
-13154481 -> md_blue_grey_800
-14273992 -> md_blue_grey_900
-1 -> md_grey_black_dark
-1118482 -> md_grey_200
-2039584 -> md_grey_300
-4342339 -> md_grey_400
-6381922 -> md_grey_500
-9079435 -> md_grey_600
-10395295 -> md_grey_700
-12434878 -> md_grey_800
-16777216 -> md_grey_black_dark
else -> md_orange_700
}
Theme.Custom(
primaryColorInt = customPrimaryColor.toArgb(),
backgroundColorInt = backgroundColor,
appIconColorInt = appIconColor,
textColorInt = textColor
)
}
}
return theme
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/compose/theme/DynamicTheme.kt | 143814936 |
package com.simplemobiletools.commons.compose.theme
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Shapes
import androidx.compose.ui.unit.dp
val Shapes = Shapes(
extraSmall = RoundedCornerShape(16.dp), //used by dropdown menu in M3
small = RoundedCornerShape(8.dp),
medium = RoundedCornerShape(12.dp),
large = RoundedCornerShape(16.dp),
extraLarge = RoundedCornerShape(24.dp),
)
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/compose/theme/Shapes.kt | 4179410772 |
package com.simplemobiletools.commons.compose.theme
import androidx.compose.runtime.ProvidableCompositionLocal
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.ui.unit.dp
import com.simplemobiletools.commons.compose.theme.model.Dimensions
internal val CommonDimensions = Dimensions(
padding = Dimensions.Paddings(
extraSmall = 2.dp,
small = 4.dp,
medium = 8.dp,
large = 12.dp,
extraLarge = 16.dp,
),
icon = Dimensions.IconSizes(
small = 32.dp,
medium = 48.dp,
large = 56.dp,
extraLarge = 64.dp,
)
)
val LocalDimensions: ProvidableCompositionLocal<Dimensions> =
staticCompositionLocalOf { CommonDimensions }
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/compose/theme/Dimensions.kt | 904535777 |
package com.simplemobiletools.commons.compose.theme
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material.ripple.LocalRippleTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.runtime.*
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalView
import com.simplemobiletools.commons.compose.extensions.config
import com.simplemobiletools.commons.compose.theme.model.Theme
import com.simplemobiletools.commons.compose.theme.model.Theme.Companion.systemDefaultMaterialYou
import com.simplemobiletools.commons.helpers.isSPlus
@Composable
internal fun Theme(
theme: Theme = systemDefaultMaterialYou(),
content: @Composable () -> Unit,
) {
val view = LocalView.current
val context = LocalContext.current
val configuration = LocalConfiguration.current
val baseConfig = remember { context.config }
val isSystemInDarkTheme = isSystemInDarkTheme()
val colorScheme = if (!view.isInEditMode) {
when {
theme is Theme.SystemDefaultMaterialYou && isSPlus() -> {
if (isSystemInDarkTheme) {
dynamicDarkColorScheme(context)
} else {
dynamicLightColorScheme(context)
}
}
theme is Theme.Custom || theme is Theme.Dark -> darkColorScheme(
primary = theme.primaryColor,
surface = theme.backgroundColor,
onSurface = theme.textColor
)
theme is Theme.White -> darkColorScheme(
primary = Color(theme.accentColor),
surface = theme.backgroundColor,
tertiary = theme.primaryColor,
onSurface = theme.textColor,
)
theme is Theme.BlackAndWhite -> darkColorScheme(
primary = Color(theme.accentColor),
surface = theme.backgroundColor,
tertiary = theme.primaryColor,
onSurface = theme.textColor
)
else -> darkColorScheme
}
} else {
previewColorScheme()
}
SideEffect {
updateRecentsAppIcon(baseConfig, context)
}
val dimensions = CommonDimensions
MaterialTheme(
colorScheme = colorScheme,
shapes = Shapes,
content = {
CompositionLocalProvider(
LocalRippleTheme provides DynamicThemeRipple,
LocalTheme provides theme,
LocalDimensions provides dimensions
) {
content()
}
},
)
}
val LocalTheme: ProvidableCompositionLocal<Theme> =
staticCompositionLocalOf { Theme.Custom(1, 1, 1, 1) }
@Composable
private fun previewColorScheme() = if (isSystemInDarkTheme()) {
darkColorScheme
} else {
lightColorScheme
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/compose/theme/Theme.kt | 3507287932 |
package com.simplemobiletools.commons.compose.theme.model
import androidx.compose.runtime.Immutable
import androidx.compose.ui.graphics.Color
@Immutable
interface CommonTheme {
val primaryColorInt: Int
val backgroundColorInt: Int
val appIconColorInt: Int
val textColorInt: Int
val primaryColor get() = Color(primaryColorInt)
val backgroundColor get() = Color(backgroundColorInt)
val appIconColor get() = Color(appIconColorInt)
val textColor get() = Color(textColorInt)
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/compose/theme/model/CommonTheme.kt | 3143424208 |
package com.simplemobiletools.commons.compose.theme.model
import androidx.compose.runtime.Immutable
import androidx.compose.ui.unit.Dp
@Immutable
data class Dimensions(
val padding: Paddings,
val icon: IconSizes
) {
@Immutable
data class Paddings(
val extraSmall: Dp,
val small: Dp,
val medium: Dp,
val large: Dp,
val extraLarge: Dp,
)
@Immutable
data class IconSizes(
val small: Dp,
val medium: Dp,
val large: Dp,
val extraLarge: Dp,
)
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/compose/theme/model/Dimensions.kt | 1591428359 |
package com.simplemobiletools.commons.compose.theme.model
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Stable
import androidx.compose.runtime.remember
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.colorResource
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.compose.extensions.config
import com.simplemobiletools.commons.compose.theme.isInDarkThemeAndSurfaceIsNotLitWell
import com.simplemobiletools.commons.helpers.isSPlus
@Stable
sealed class Theme : CommonTheme {
@Stable
data class SystemDefaultMaterialYou(
override val primaryColorInt: Int,
override val backgroundColorInt: Int,
override val appIconColorInt: Int,
override val textColorInt: Int
) : Theme()
@Stable
data class White(
val accentColor: Int,
override val primaryColorInt: Int,
override val backgroundColorInt: Int,
override val appIconColorInt: Int,
override val textColorInt: Int
) : Theme()
@Stable
data class Dark(
override val primaryColorInt: Int,
override val backgroundColorInt: Int,
override val appIconColorInt: Int,
override val textColorInt: Int
) : Theme()
@Stable
data class BlackAndWhite(
val accentColor: Int,
override val primaryColorInt: Int,
override val backgroundColorInt: Int,
override val appIconColorInt: Int,
override val textColorInt: Int
) : Theme()
@Stable
data class Custom(
override val primaryColorInt: Int,
override val backgroundColorInt: Int,
override val appIconColorInt: Int,
override val textColorInt: Int
) : Theme()
companion object {
@Composable
fun systemDefaultMaterialYou(): SystemDefaultMaterialYou {
val context = LocalContext.current
val config = remember { context.config }
return SystemDefaultMaterialYou(
appIconColorInt = config.appIconColor,
primaryColorInt = config.primaryColor,
backgroundColorInt = config.backgroundColor,
textColorInt = if (isSPlus()) colorResource(R.color.you_neutral_text_color).toArgb() else (if (isInDarkThemeAndSurfaceIsNotLitWell()) Color.White else Color.Black).toArgb()
)
}
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/compose/theme/model/Theme.kt | 57904204 |
package com.simplemobiletools.commons.compose.theme
import androidx.compose.material3.ColorScheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Shapes
import androidx.compose.material3.Typography
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.ReadOnlyComposable
import com.simplemobiletools.commons.compose.theme.model.Dimensions
@Immutable
object SimpleTheme {
val dimens: Dimensions
@Composable
@ReadOnlyComposable
get() = LocalDimensions.current
val typography: Typography
@Composable
@ReadOnlyComposable
get() = MaterialTheme.typography
val colorScheme: ColorScheme
@Composable
@ReadOnlyComposable
get() = MaterialTheme.colorScheme
val shapes: Shapes
@Composable
@ReadOnlyComposable
get() = MaterialTheme.shapes
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/compose/theme/SimpleTheme.kt | 4069147735 |
package com.simplemobiletools.commons.compose.theme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.ReadOnlyComposable
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.luminance
@get:ReadOnlyComposable
val disabledTextColor @Composable get() = if (isInDarkThemeOrSurfaceIsNotLitWell()) Color.DarkGray else Color.LightGray
@get:ReadOnlyComposable
val textSubTitleColor
@Composable get() = if (isInDarkThemeOrSurfaceIsNotLitWell()) {
Color.White.copy(0.5f)
} else {
Color.Black.copy(
0.5f,
)
}
@get:ReadOnlyComposable
val iconsColor
@Composable get() = if (isSurfaceNotLitWell()) {
Color.White
} else {
Color.Black
}
@Composable
@ReadOnlyComposable
fun preferenceValueColor(isEnabled: Boolean) =
if (isEnabled) SimpleTheme.colorScheme.onSurface.copy(alpha = 0.6f) else disabledTextColor
@Composable
@ReadOnlyComposable
fun preferenceLabelColor(isEnabled: Boolean) = if (isEnabled) SimpleTheme.colorScheme.onSurface else disabledTextColor
fun Color.isLitWell(threshold: Float = LUMINANCE_THRESHOLD) = luminance() > threshold
fun Color.isNotLitWell(threshold: Float = LUMINANCE_THRESHOLD) = luminance() < threshold
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/compose/theme/ColorsExtensions.kt | 3310461239 |
package com.simplemobiletools.commons.compose.theme
import android.app.Activity
import android.app.ActivityManager
import android.content.Context
import android.graphics.BitmapFactory
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.compose.extensions.getActivity
import com.simplemobiletools.commons.helpers.APP_ICON_IDS
import com.simplemobiletools.commons.helpers.APP_LAUNCHER_NAME
import com.simplemobiletools.commons.helpers.BaseConfig
fun Activity.getAppIconIds(): ArrayList<Int> = ArrayList(intent.getIntegerArrayListExtra(APP_ICON_IDS).orEmpty())
fun Activity.getAppLauncherName(): String = intent.getStringExtra(APP_LAUNCHER_NAME).orEmpty()
internal fun updateRecentsAppIcon(baseConfig: BaseConfig, context: Context) {
if (baseConfig.isUsingModifiedAppIcon) {
val appIconIDs = context.getAppIconIds()
val currentAppIconColorIndex = baseConfig.getCurrentAppIconColorIndex(context)
if (appIconIDs.size - 1 < currentAppIconColorIndex) {
return
}
val recentsIcon = BitmapFactory.decodeResource(context.resources, appIconIDs[currentAppIconColorIndex])
val title = context.getAppLauncherName()
val color = baseConfig.primaryColor
val description = ActivityManager.TaskDescription(title, recentsIcon, color)
context.getActivity().setTaskDescription(description)
}
}
private fun BaseConfig.getCurrentAppIconColorIndex(context: Context): Int {
val appIconColor = appIconColor
context.getAppIconColors().forEachIndexed { index, color ->
if (color == appIconColor) {
return index
}
}
return 0
}
private fun Context.getAppIconColors() = resources.getIntArray(R.array.md_app_icon_colors).toCollection(ArrayList())
private fun Context.getAppIconIds(): List<Int> = getActivity().getAppIconIds()
private fun Context.getAppLauncherName(): String = getActivity().getAppLauncherName()
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/compose/theme/AppModifiers.kt | 330066809 |
package com.simplemobiletools.commons.compose.menus
import androidx.annotation.StringRes
import androidx.compose.foundation.background
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material.ripple.rememberRipple
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.hapticfeedback.HapticFeedbackType
import androidx.compose.ui.platform.LocalHapticFeedback
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.compose.alert_dialog.dialogBorder
import com.simplemobiletools.commons.compose.alert_dialog.dialogContainerColor
import com.simplemobiletools.commons.compose.components.SimpleDropDownMenuItem
import com.simplemobiletools.commons.compose.extensions.MyDevices
import com.simplemobiletools.commons.compose.extensions.rememberMutableInteractionSource
import com.simplemobiletools.commons.compose.theme.AppThemeSurface
import com.simplemobiletools.commons.compose.theme.Shapes
import com.simplemobiletools.commons.compose.theme.SimpleTheme
import kotlinx.collections.immutable.ImmutableList
import kotlinx.collections.immutable.toImmutableList
/**
* Essentially a wrapper around a lambda function to give it a name and icon
* akin to Android menu XML entries.
* As an item on the action bar, the action will be displayed with an IconButton
* with the given icon, if not null. Otherwise, the string from the name resource is used.
* In overflow menu, item will always be displayed as text.
* Original idea: https://gist.github.com/MachFour/369ebb56a66e2f583ebfb988dda2decf
*/
@Immutable
data class ActionItem(
@StringRes
val nameRes: Int,
val icon: ImageVector? = null,
val overflowMode: OverflowMode = OverflowMode.IF_NECESSARY,
val doAction: () -> Unit,
val iconColor: Color? = null
) {
// allow 'calling' the action like a function
operator fun invoke() = doAction()
}
/**
* Whether action items are allowed to overflow into a dropdown menu - or NOT SHOWN to hide
*/
@Immutable
enum class OverflowMode {
NEVER_OVERFLOW, IF_NECESSARY, ALWAYS_OVERFLOW, NOT_SHOWN
}
/**
* Best if combined with [RowScope] or used within a [Row] or [LazyRow]
*/
@Composable
fun ActionMenu(
items: ImmutableList<ActionItem>,
numIcons: Int = 2, // includes overflow menu icon; may be overridden by NEVER_OVERFLOW
isMenuVisible: Boolean,
iconsColor: Color? = null,
onMenuToggle: (isVisible: Boolean) -> Unit
) {
if (items.isEmpty()) {
return
}
// decide how many action items to show as icons
val (appbarActions, overflowActions) = remember(items, numIcons) {
separateIntoIconAndOverflow(items, numIcons)
}
for (item in appbarActions) {
key(item.hashCode()) {
val name = stringResource(item.nameRes)
if (item.icon != null) {
val iconButtonColor = when {
iconsColor != null -> iconsColor
item.iconColor != null -> item.iconColor
else -> LocalContentColor.current
}
TooltipBox(
positionProvider = TooltipDefaults.rememberPlainTooltipPositionProvider(spacingBetweenTooltipAndAnchor = 18.dp),
tooltip = {
PlainTooltip(shape = Shapes.extraLarge) {
Text(
text = name,
fontSize = 14.sp,
modifier = Modifier.padding(SimpleTheme.dimens.padding.medium),
)
}
},
state = rememberTooltipState(),
) {
ActionIconButton(
onClick = item.doAction,
contentColor = iconButtonColor,
) {
Icon(
imageVector = item.icon,
contentDescription = name
)
}
}
} else {
SimpleDropDownMenuItem(onClick = item.doAction, text = name)
}
}
}
if (overflowActions.isNotEmpty()) {
TooltipBox(
tooltip = {
PlainTooltip(shape = Shapes.extraLarge) {
Text(
text = stringResource(id = R.string.more_options),
fontSize = 14.sp,
modifier = Modifier.padding(SimpleTheme.dimens.padding.medium),
)
}
},
state = rememberTooltipState(),
positionProvider = TooltipDefaults.rememberPlainTooltipPositionProvider(spacingBetweenTooltipAndAnchor = 18.dp),
) {
ActionIconButton(
onClick = { onMenuToggle(true) },
contentColor = iconsColor ?: LocalContentColor.current,
) {
Icon(imageVector = Icons.Default.MoreVert, contentDescription = stringResource(id = R.string.more_options))
}
}
DropdownMenu(
modifier = Modifier
.background(dialogContainerColor)
.dialogBorder,
expanded = isMenuVisible,
onDismissRequest = { onMenuToggle(false) },
) {
for (item in overflowActions) {
key(item.hashCode()) {
SimpleDropDownMenuItem(text = item.nameRes, onClick = {
onMenuToggle(false)
item.doAction()
})
}
}
}
}
}
@Composable
internal fun ActionIconButton(
onClick: () -> Unit,
modifier: Modifier = Modifier,
interactionSource: MutableInteractionSource = rememberMutableInteractionSource(),
contentColor: Color,
content: @Composable () -> Unit,
) {
val hapticFeedback = LocalHapticFeedback.current
Box(
modifier = modifier
.minimumInteractiveComponentSize()
.size(40.dp)
.clip(RoundedCornerShape(50))
.combinedClickable(
onClick = onClick,
role = Role.Button,
interactionSource = interactionSource,
indication = rememberRipple(
bounded = false,
radius = 40.dp / 2
),
onLongClick = {
hapticFeedback.performHapticFeedback(HapticFeedbackType.LongPress)
}
),
contentAlignment = Alignment.Center
) {
CompositionLocalProvider(LocalContentColor provides contentColor, content = content)
}
}
private fun separateIntoIconAndOverflow(
items: List<ActionItem>,
numIcons: Int
): Pair<List<ActionItem>, List<ActionItem>> {
var (iconCount, overflowCount, preferIconCount) = Triple(0, 0, 0)
for (item in items) {
when (item.overflowMode) {
OverflowMode.NEVER_OVERFLOW -> iconCount++
OverflowMode.IF_NECESSARY -> preferIconCount++
OverflowMode.ALWAYS_OVERFLOW -> overflowCount++
OverflowMode.NOT_SHOWN -> {}
}
}
val needsOverflow = ((iconCount + preferIconCount) > numIcons) || (overflowCount > 0)
val actionIconSpace = numIcons - (if (needsOverflow) 1 else 0)
val iconActions = mutableListOf<ActionItem>()
val overflowActions = mutableListOf<ActionItem>()
var iconsAvailableBeforeOverflow = actionIconSpace - iconCount
for (item in items) {
when (item.overflowMode) {
OverflowMode.NEVER_OVERFLOW -> {
iconActions.add(item)
}
OverflowMode.ALWAYS_OVERFLOW -> {
overflowActions.add(item)
}
OverflowMode.IF_NECESSARY -> {
if (iconsAvailableBeforeOverflow > 0) {
iconActions.add(item)
iconsAvailableBeforeOverflow--
} else {
overflowActions.add(item)
}
}
OverflowMode.NOT_SHOWN -> {
// skip
}
}
}
return Pair(iconActions, overflowActions)
}
@MyDevices
@Composable
private fun ActionMenuPreview() {
AppThemeSurface {
val actionMenus = remember {
listOf(
ActionItem(R.string.add_a_blocked_number, icon = Icons.Filled.Add, doAction = { }),
ActionItem(R.string.import_blocked_numbers, doAction = {}, overflowMode = OverflowMode.ALWAYS_OVERFLOW),
ActionItem(R.string.export_blocked_numbers, doAction = { }, overflowMode = OverflowMode.ALWAYS_OVERFLOW),
).toImmutableList()
}
ActionMenu(items = actionMenus, numIcons = 2, isMenuVisible = true, onMenuToggle = { }, iconsColor = Color.Black)
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/compose/menus/ActionMenu.kt | 398521843 |
package com.simplemobiletools.commons.compose.bottom_sheet
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CornerSize
import androidx.compose.material3.Surface
import androidx.compose.runtime.Composable
import androidx.compose.runtime.ReadOnlyComposable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import com.simplemobiletools.commons.compose.alert_dialog.dialogContainerColor
import com.simplemobiletools.commons.compose.alert_dialog.dialogElevation
import com.simplemobiletools.commons.compose.theme.LocalTheme
import com.simplemobiletools.commons.compose.theme.Shapes
import com.simplemobiletools.commons.compose.theme.light_grey_stroke
import com.simplemobiletools.commons.compose.theme.model.Theme
val bottomSheetDialogShape = Shapes.extraLarge.copy(
bottomEnd = CornerSize(0f),
bottomStart = CornerSize(0f)
)
val Modifier.bottomSheetDialogBorder: Modifier
@ReadOnlyComposable
@Composable get() =
when (LocalTheme.current) {
is Theme.BlackAndWhite -> then(Modifier.border(2.dp, light_grey_stroke, bottomSheetDialogShape))
else -> Modifier
}
@Composable
fun BottomSheetSpacerEdgeToEdge() {
Spacer(modifier = Modifier.padding(bottom = 42.dp))
}
@Composable
fun BottomSheetColumnDialogSurface(
modifier: Modifier = Modifier,
content: @Composable ColumnScope.() -> Unit
) {
Surface(
modifier = modifier
.fillMaxSize()
.bottomSheetDialogBorder,
shape = bottomSheetDialogShape,
color = dialogContainerColor,
tonalElevation = dialogElevation,
) {
Column(modifier = Modifier.background(dialogContainerColor)) {
content()
}
}
}
@Composable
fun BottomSheetBoxDialogSurface(
modifier: Modifier = Modifier,
content: @Composable BoxScope.() -> Unit
) {
Surface(
modifier = modifier
.fillMaxSize()
.bottomSheetDialogBorder,
shape = bottomSheetDialogShape,
color = dialogContainerColor,
tonalElevation = dialogElevation,
) {
Box(modifier = Modifier.background(dialogContainerColor)) {
content()
}
}
}
@Composable
fun BottomSheetDialogSurface(
modifier: Modifier = Modifier,
content: @Composable (backgroundColor: Color) -> Unit
) {
Surface(
modifier = modifier
.fillMaxSize()
.bottomSheetDialogBorder,
shape = bottomSheetDialogShape,
color = dialogContainerColor,
tonalElevation = dialogElevation,
) {
content(dialogContainerColor)
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/compose/bottom_sheet/BottomSheetDialogsExtensions.kt | 2337434188 |
package com.simplemobiletools.commons.compose.bottom_sheet
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.material3.BottomSheetDefaults
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.SheetValue
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.*
import androidx.compose.runtime.saveable.mapSaver
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Modifier
import com.simplemobiletools.commons.compose.alert_dialog.dialogContainerColor
import com.simplemobiletools.commons.compose.alert_dialog.dialogElevation
@Composable
fun rememberBottomSheetDialogState(
openBottomSheet: Boolean = false,
skipPartiallyExpanded: Boolean = false,
edgeToEdgeEnabled: Boolean = false,
confirmValueChange: (SheetValue) -> Boolean = { true },
) = remember {
BottomSheetDialogState(
openBottomSheet = openBottomSheet,
skipPartiallyExpanded = skipPartiallyExpanded,
edgeToEdgeEnabled = edgeToEdgeEnabled,
confirmValueChange = confirmValueChange
)
}
@Composable
fun rememberBottomSheetDialogStateSaveable(
openBottomSheet: Boolean = false,
skipPartiallyExpanded: Boolean = false,
edgeToEdgeEnabled: Boolean = false,
confirmValueChange: (SheetValue) -> Boolean = { true },
) = rememberSaveable(stateSaver = mapSaver(save = {
mapOf(
"skipPartiallyExpanded" to skipPartiallyExpanded,
"edgeToEdgeEnabled" to edgeToEdgeEnabled,
"openBottomSheet" to openBottomSheet,
)
}, restore = {
BottomSheetDialogState(
openBottomSheet = it["openBottomSheet"] as Boolean,
skipPartiallyExpanded = it["openBottomSheet"] as Boolean,
edgeToEdgeEnabled = it["openBottomSheet"] as Boolean,
)
})) {
mutableStateOf(
BottomSheetDialogState(
skipPartiallyExpanded = skipPartiallyExpanded,
edgeToEdgeEnabled = edgeToEdgeEnabled,
confirmValueChange = confirmValueChange
)
)
}
@Stable
class BottomSheetDialogState(
openBottomSheet: Boolean = false,
private val skipPartiallyExpanded: Boolean = false,
private val edgeToEdgeEnabled: Boolean = false,
private val confirmValueChange: (SheetValue) -> Boolean = { true },
) {
@Composable
private fun rememberWindowInsets(
defaultInsets: WindowInsets = BottomSheetDefaults.windowInsets
) = remember { if (edgeToEdgeEnabled) WindowInsets(0) else defaultInsets }
@Composable
private fun rememberSheetState() = rememberModalBottomSheetState(
skipPartiallyExpanded = skipPartiallyExpanded,
confirmValueChange = confirmValueChange
)
var isOpen by mutableStateOf(openBottomSheet)
private set
fun close() {
isOpen = false
}
fun open() {
isOpen = true
}
@Composable
fun BottomSheetContent(
modifier: Modifier = Modifier,
content: @Composable () -> Unit
) {
val bottomSheetState = rememberSheetState()
val windowInsets = rememberWindowInsets()
LaunchedEffect(isOpen) {
if (isOpen && !bottomSheetState.isVisible) {
bottomSheetState.show()
} else {
bottomSheetState.hide()
}
}
if (isOpen) {
ModalBottomSheet(
modifier = modifier,
onDismissRequest = ::close,
sheetState = bottomSheetState,
windowInsets = windowInsets,
dragHandle = {}, //leave empty as we provide our own dialog surfaces
shape = bottomSheetDialogShape,
containerColor = dialogContainerColor,
tonalElevation = dialogElevation,
) {
content()
}
}
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/compose/bottom_sheet/BottomSheetDialogState.kt | 2950437120 |
package com.simplemobiletools.commons.models
import android.telephony.PhoneNumberUtils
import com.simplemobiletools.commons.extensions.normalizePhoneNumber
import com.simplemobiletools.commons.extensions.normalizeString
import com.simplemobiletools.commons.helpers.SORT_BY_FULL_NAME
import com.simplemobiletools.commons.helpers.SORT_DESCENDING
data class SimpleContact(
val rawId: Int,
val contactId: Int,
var name: String,
var photoUri: String,
var phoneNumbers: ArrayList<PhoneNumber>,
var birthdays: ArrayList<String>,
var anniversaries: ArrayList<String>
) : Comparable<SimpleContact> {
companion object {
var sorting = -1
}
override fun compareTo(other: SimpleContact): Int {
if (sorting == -1) {
return compareByFullName(other)
}
var result = when {
sorting and SORT_BY_FULL_NAME != 0 -> compareByFullName(other)
else -> rawId.compareTo(other.rawId)
}
if (sorting and SORT_DESCENDING != 0) {
result *= -1
}
return result
}
private fun compareByFullName(other: SimpleContact): Int {
val firstString = name.normalizeString()
val secondString = other.name.normalizeString()
return if (firstString.firstOrNull()?.isLetter() == true && secondString.firstOrNull()?.isLetter() == false) {
-1
} else if (firstString.firstOrNull()?.isLetter() == false && secondString.firstOrNull()?.isLetter() == true) {
1
} else {
if (firstString.isEmpty() && secondString.isNotEmpty()) {
1
} else if (firstString.isNotEmpty() && secondString.isEmpty()) {
-1
} else {
firstString.compareTo(secondString, true)
}
}
}
fun doesContainPhoneNumber(text: String): Boolean {
return if (text.isNotEmpty()) {
val normalizedText = text.normalizePhoneNumber()
if (normalizedText.isEmpty()) {
phoneNumbers.map { it.normalizedNumber }.any { phoneNumber ->
phoneNumber.contains(text)
}
} else {
phoneNumbers.map { it.normalizedNumber }.any { phoneNumber ->
PhoneNumberUtils.compare(phoneNumber.normalizePhoneNumber(), normalizedText) ||
phoneNumber.contains(text) ||
phoneNumber.normalizePhoneNumber().contains(normalizedText) ||
phoneNumber.contains(normalizedText)
}
}
} else {
false
}
}
fun doesHavePhoneNumber(text: String): Boolean {
return if (text.isNotEmpty()) {
val normalizedText = text.normalizePhoneNumber()
if (normalizedText.isEmpty()) {
phoneNumbers.map { it.normalizedNumber }.any { phoneNumber ->
phoneNumber == text
}
} else {
phoneNumbers.map { it.normalizedNumber }.any { phoneNumber ->
PhoneNumberUtils.compare(phoneNumber.normalizePhoneNumber(), normalizedText) ||
phoneNumber == text ||
phoneNumber.normalizePhoneNumber() == normalizedText ||
phoneNumber == normalizedText
}
}
} else {
false
}
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/models/SimpleContact.kt | 3479959066 |
package com.simplemobiletools.commons.models
import androidx.compose.runtime.Immutable
@Immutable
data class License(val id: Long, val titleId: Int, val textId: Int, val urlId: Int)
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/models/License.kt | 2660861769 |
package com.simplemobiletools.commons.models
import androidx.compose.runtime.Immutable
@Immutable
data class BlockedNumber(val id: Long, val number: String, val normalizedNumber: String, val numberToCompare: String, val contactName: String? = null)
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/models/BlockedNumber.kt | 1501288094 |
package com.simplemobiletools.commons.models
data class RecyclerSelectionPayload(val selected: Boolean)
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/models/RecyclerViewPayloads.kt | 496973267 |
package com.simplemobiletools.commons.models.contacts
import kotlinx.serialization.Serializable
@Serializable
data class Email(var value: String, var type: Int, var label: String)
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/models/contacts/Email.kt | 1095868121 |
package com.simplemobiletools.commons.models.contacts
data class SocialAction(var actionId: Int, var type: Int, var label: String, var mimetype: String, val dataId: Long, val packageName: String)
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/models/contacts/SocialAction.kt | 3706076724 |
package com.simplemobiletools.commons.models.contacts
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.Index
import androidx.room.PrimaryKey
import com.simplemobiletools.commons.helpers.FIRST_GROUP_ID
import java.io.Serializable
@kotlinx.serialization.Serializable
@Entity(tableName = "groups", indices = [(Index(value = ["id"], unique = true))])
data class Group(
@PrimaryKey(autoGenerate = true) var id: Long?,
@ColumnInfo(name = "title") var title: String,
@ColumnInfo(name = "contacts_count") var contactsCount: Int = 0
) : Serializable {
fun addContact() = contactsCount++
fun getBubbleText() = title
fun isPrivateSecretGroup() = id ?: 0 >= FIRST_GROUP_ID
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/models/contacts/Group.kt | 2660475391 |
package com.simplemobiletools.commons.models.contacts
import kotlinx.serialization.Serializable
@Serializable
data class IM(
var value: String,
var type: Int,
var label: String
)
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/models/contacts/IM.kt | 1424737036 |
package com.simplemobiletools.commons.models.contacts
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.Index
import androidx.room.PrimaryKey
import com.simplemobiletools.commons.models.PhoneNumber
@Entity(tableName = "contacts", indices = [(Index(value = ["id"], unique = true))])
data class LocalContact(
@PrimaryKey(autoGenerate = true) var id: Int?,
@ColumnInfo(name = "prefix") var prefix: String,
@ColumnInfo(name = "first_name") var firstName: String,
@ColumnInfo(name = "middle_name") var middleName: String,
@ColumnInfo(name = "surname") var surname: String,
@ColumnInfo(name = "suffix") var suffix: String,
@ColumnInfo(name = "nickname") var nickname: String,
@ColumnInfo(name = "photo", typeAffinity = ColumnInfo.BLOB) var photo: ByteArray?,
@ColumnInfo(name = "photo_uri") var photoUri: String,
@ColumnInfo(name = "phone_numbers") var phoneNumbers: ArrayList<PhoneNumber>,
@ColumnInfo(name = "emails") var emails: ArrayList<Email>,
@ColumnInfo(name = "events") var events: ArrayList<Event>,
@ColumnInfo(name = "starred") var starred: Int,
@ColumnInfo(name = "addresses") var addresses: ArrayList<Address>,
@ColumnInfo(name = "notes") var notes: String,
@ColumnInfo(name = "groups") var groups: ArrayList<Long>,
@ColumnInfo(name = "company") var company: String,
@ColumnInfo(name = "job_position") var jobPosition: String,
@ColumnInfo(name = "websites") var websites: ArrayList<String>,
@ColumnInfo(name = "ims") var IMs: ArrayList<IM>,
@ColumnInfo(name = "ringtone") var ringtone: String?
) {
override fun equals(other: Any?) = id == (other as? LocalContact?)?.id
override fun hashCode() = id ?: 0
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/models/contacts/LocalContact.kt | 1926224475 |
package com.simplemobiletools.commons.models.contacts
import android.graphics.Bitmap
import android.provider.ContactsContract
import android.telephony.PhoneNumberUtils
import com.simplemobiletools.commons.extensions.normalizePhoneNumber
import com.simplemobiletools.commons.extensions.normalizeString
import com.simplemobiletools.commons.helpers.*
import com.simplemobiletools.commons.models.PhoneNumber
import kotlinx.serialization.Contextual
import kotlinx.serialization.Serializable
@Serializable
data class Contact(
var id: Int,
var prefix: String= "",
var firstName: String= "",
var middleName: String= "",
var surname: String= "",
var suffix: String= "",
var nickname: String= "",
var photoUri: String= "",
var phoneNumbers: ArrayList<PhoneNumber> = arrayListOf(),
var emails: ArrayList<Email> = arrayListOf(),
var addresses: ArrayList<Address> = arrayListOf(),
var events: ArrayList<Event> = arrayListOf(),
var source: String= "",
var starred: Int = 0,
var contactId: Int,
var thumbnailUri: String= "",
@Contextual
var photo: Bitmap? = null,
var notes: String= "",
var groups: ArrayList<Group> = arrayListOf(),
var organization: Organization = Organization("",""),
var websites: ArrayList<String> = arrayListOf(),
var IMs: ArrayList<IM> = arrayListOf(),
var mimetype: String = "",
var ringtone: String? = ""
) : Comparable<Contact> {
val rawId = id
val name = getNameToDisplay()
var birthdays = events.filter { it.type == ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY }.map { it.value }.toMutableList() as ArrayList<String>
var anniversaries = events.filter { it.type == ContactsContract.CommonDataKinds.Event.TYPE_ANNIVERSARY }.map { it.value }.toMutableList() as ArrayList<String>
companion object {
var sorting = 0
var startWithSurname = false
}
override fun compareTo(other: Contact): Int {
var result = when {
sorting and SORT_BY_FIRST_NAME != 0 -> {
val firstString = firstName.normalizeString()
val secondString = other.firstName.normalizeString()
compareUsingStrings(firstString, secondString, other)
}
sorting and SORT_BY_MIDDLE_NAME != 0 -> {
val firstString = middleName.normalizeString()
val secondString = other.middleName.normalizeString()
compareUsingStrings(firstString, secondString, other)
}
sorting and SORT_BY_SURNAME != 0 -> {
val firstString = surname.normalizeString()
val secondString = other.surname.normalizeString()
compareUsingStrings(firstString, secondString, other)
}
sorting and SORT_BY_FULL_NAME != 0 -> {
val firstString = getNameToDisplay().normalizeString()
val secondString = other.getNameToDisplay().normalizeString()
compareUsingStrings(firstString, secondString, other)
}
else -> compareUsingIds(other)
}
if (sorting and SORT_DESCENDING != 0) {
result *= -1
}
return result
}
private fun compareUsingStrings(firstString: String, secondString: String, other: Contact): Int {
var firstValue = firstString
var secondValue = secondString
if (firstValue.isEmpty() && firstName.isEmpty() && middleName.isEmpty() && surname.isEmpty()) {
val fullCompany = getFullCompany()
if (fullCompany.isNotEmpty()) {
firstValue = fullCompany.normalizeString()
} else if (emails.isNotEmpty()) {
firstValue = emails.first().value
}
}
if (secondValue.isEmpty() && other.firstName.isEmpty() && other.middleName.isEmpty() && other.surname.isEmpty()) {
val otherFullCompany = other.getFullCompany()
if (otherFullCompany.isNotEmpty()) {
secondValue = otherFullCompany.normalizeString()
} else if (other.emails.isNotEmpty()) {
secondValue = other.emails.first().value
}
}
return if (firstValue.firstOrNull()?.isLetter() == true && secondValue.firstOrNull()?.isLetter() == false) {
-1
} else if (firstValue.firstOrNull()?.isLetter() == false && secondValue.firstOrNull()?.isLetter() == true) {
1
} else {
if (firstValue.isEmpty() && secondValue.isNotEmpty()) {
1
} else if (firstValue.isNotEmpty() && secondValue.isEmpty()) {
-1
} else {
if (firstValue.equals(secondValue, ignoreCase = true)) {
getNameToDisplay().compareTo(other.getNameToDisplay(), true)
} else {
firstValue.compareTo(secondValue, true)
}
}
}
}
private fun compareUsingIds(other: Contact): Int {
val firstId = id
val secondId = other.id
return firstId.compareTo(secondId)
}
fun getBubbleText() = when {
sorting and SORT_BY_FIRST_NAME != 0 -> firstName
sorting and SORT_BY_MIDDLE_NAME != 0 -> middleName
else -> surname
}
fun getNameToDisplay(): String {
val firstMiddle = "$firstName $middleName".trim()
val firstPart = if (startWithSurname) {
if (surname.isNotEmpty() && firstMiddle.isNotEmpty()) {
"$surname,"
} else {
surname
}
} else {
firstMiddle
}
val lastPart = if (startWithSurname) firstMiddle else surname
val suffixComma = if (suffix.isEmpty()) "" else ", $suffix"
val fullName = "$prefix $firstPart $lastPart$suffixComma".trim()
val organization = getFullCompany()
val email = emails.firstOrNull()?.value?.trim()
val phoneNumber = phoneNumbers.firstOrNull()?.normalizedNumber
return when {
fullName.isNotBlank() -> fullName
organization.isNotBlank() -> organization
!email.isNullOrBlank() -> email
!phoneNumber.isNullOrBlank() -> phoneNumber
else -> return ""
}
}
// photos stored locally always have different hashcodes. Avoid constantly refreshing the contact lists as the app thinks something changed.
fun getHashWithoutPrivatePhoto(): Int {
val photoToUse = if (isPrivate()) null else photo
return copy(photo = photoToUse).hashCode()
}
fun getStringToCompare(): String {
val photoToUse = if (isPrivate()) null else photo
return copy(
id = 0,
prefix = "",
firstName = getNameToDisplay().toLowerCase(),
middleName = "",
surname = "",
suffix = "",
nickname = "",
photoUri = "",
phoneNumbers = ArrayList(),
emails = ArrayList(),
events = ArrayList(),
source = "",
addresses = ArrayList(),
starred = 0,
contactId = 0,
thumbnailUri = "",
photo = photoToUse,
notes = "",
groups = ArrayList(),
websites = ArrayList(),
organization = Organization("", ""),
IMs = ArrayList(),
ringtone = ""
).toString()
}
fun getHashToCompare() = getStringToCompare().hashCode()
fun getFullCompany(): String {
var fullOrganization = if (organization.company.isEmpty()) "" else "${organization.company}, "
fullOrganization += organization.jobPosition
return fullOrganization.trim().trimEnd(',')
}
fun isABusinessContact() =
prefix.isEmpty() && firstName.isEmpty() && middleName.isEmpty() && surname.isEmpty() && suffix.isEmpty() && organization.isNotEmpty()
fun doesContainPhoneNumber(text: String, convertLetters: Boolean = false): Boolean {
return if (text.isNotEmpty()) {
val normalizedText = if (convertLetters) text.normalizePhoneNumber() else text
phoneNumbers.any {
PhoneNumberUtils.compare(it.normalizedNumber, normalizedText) ||
it.value.contains(text) ||
it.normalizedNumber.contains(normalizedText) ||
it.value.normalizePhoneNumber().contains(normalizedText)
}
} else {
false
}
}
fun doesHavePhoneNumber(text: String): Boolean {
return if (text.isNotEmpty()) {
val normalizedText = text.normalizePhoneNumber()
if (normalizedText.isEmpty()) {
phoneNumbers.map { it.normalizedNumber }.any { phoneNumber ->
phoneNumber == text
}
} else {
phoneNumbers.map { it.normalizedNumber }.any { phoneNumber ->
PhoneNumberUtils.compare(phoneNumber.normalizePhoneNumber(), normalizedText) ||
phoneNumber == text ||
phoneNumber.normalizePhoneNumber() == normalizedText ||
phoneNumber == normalizedText
}
}
} else {
false
}
}
fun isPrivate() = source == SMT_PRIVATE
fun getSignatureKey() = if (photoUri.isNotEmpty()) photoUri else hashCode()
fun getPrimaryNumber(): String? {
val primaryNumber = phoneNumbers.firstOrNull { it.isPrimary }
return primaryNumber?.normalizedNumber ?: phoneNumbers.firstOrNull()?.normalizedNumber
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/models/contacts/Contact.kt | 3047053170 |
package com.simplemobiletools.commons.models.contacts
import kotlinx.serialization.Serializable
@Serializable
data class Address(var value: String, var type: Int, var label: String)
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/models/contacts/Address.kt | 3041531046 |
package com.simplemobiletools.commons.models.contacts
import kotlinx.serialization.Serializable
@Serializable
data class Event(var value: String, var type: Int)
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/models/contacts/Event.kt | 3973221739 |
package com.simplemobiletools.commons.models.contacts
import com.simplemobiletools.commons.helpers.SMT_PRIVATE
data class ContactSource(var name: String, var type: String, var publicName: String, var count: Int = 0) {
fun getFullIdentifier(): String {
return if (type == SMT_PRIVATE) {
type
} else {
"$name:$type"
}
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/models/contacts/ContactSource.kt | 473862672 |
package com.simplemobiletools.commons.models.contacts
import kotlinx.serialization.Serializable
@Serializable
data class Organization(var company: String, var jobPosition: String) {
fun isEmpty() = company.isEmpty() && jobPosition.isEmpty()
fun isNotEmpty() = !isEmpty()
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/models/contacts/Organization.kt | 72133067 |
package com.simplemobiletools.commons.models.contacts
import androidx.annotation.Keep
// need for hacky parsing of no longer minified PhoneNumber model in Converters.kt
@Keep
data class PhoneNumberConverter(var a: String, var b: Int, var c: String, var d: String, var e: Boolean = false)
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/models/contacts/PhoneNumberConverter.kt | 1129964785 |
package com.simplemobiletools.commons.models
import android.os.Parcelable
import androidx.compose.runtime.Immutable
import kotlinx.parcelize.Parcelize
@Parcelize
@Immutable
data class SimpleListItem(val id: Int, val textRes: Int, val imageRes: Int? = null, val selected: Boolean = false) : Parcelable {
companion object {
fun areItemsTheSame(old: SimpleListItem, new: SimpleListItem): Boolean {
return old.id == new.id
}
fun areContentsTheSame(old: SimpleListItem, new: SimpleListItem): Boolean {
return old.imageRes == new.imageRes && old.textRes == new.textRes && old.selected == new.selected
}
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/models/SimpleListItem.kt | 1757584637 |
package com.simplemobiletools.commons.models
data class MyTheme(val label: String, val textColorId: Int, val backgroundColorId: Int, val primaryColorId: Int, val appIconColorId: Int)
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/models/MyTheme.kt | 3717262889 |
package com.simplemobiletools.commons.models
import kotlinx.serialization.Serializable
@Serializable
data class PhoneNumber(
var value: String,
var type: Int,
var label: String,
var normalizedNumber: String,
var isPrimary: Boolean = false
)
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/models/PhoneNumber.kt | 1099608615 |
package com.simplemobiletools.commons.models
import androidx.compose.runtime.Immutable
@Immutable
data class Release(val id: Int, val textId: Int)
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/models/Release.kt | 3124372028 |
package com.simplemobiletools.commons.models
enum class Android30RenameFormat {
SAF,
CONTENT_RESOLVER,
NONE
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/models/Android30RenameFormat.kt | 3710251935 |
package com.simplemobiletools.commons.models
data class SharedTheme(
val textColor: Int, val backgroundColor: Int, val primaryColor: Int, val appIconColor: Int, val lastUpdatedTS: Int = 0, val accentColor: Int
)
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/models/SharedTheme.kt | 3569708171 |
package com.simplemobiletools.commons.models
data class AlarmSound(val id: Int, var title: String, var uri: String)
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/models/AlarmSound.kt | 3630447922 |
package com.simplemobiletools.commons.models
import androidx.compose.runtime.Immutable
@Immutable
data class RadioItem(val id: Int, val title: String, val value: Any = id)
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/models/RadioItem.kt | 1593185985 |
package com.simplemobiletools.commons.models
import androidx.annotation.DrawableRes
import androidx.annotation.StringRes
import androidx.compose.runtime.Immutable
@Immutable
data class LanguageContributor(@DrawableRes val iconId: Int, @StringRes val labelId: Int, @StringRes val contributorsId: Int)
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/models/LanguageContributor.kt | 460642583 |
package com.simplemobiletools.commons.models
import android.content.Context
import android.net.Uri
import android.provider.MediaStore
import androidx.compose.runtime.Immutable
import com.bumptech.glide.signature.ObjectKey
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.*
import java.io.File
open class FileDirItem(
val path: String,
val name: String = "",
var isDirectory: Boolean = false,
var children: Int = 0,
var size: Long = 0L,
var modified: Long = 0L,
var mediaStoreId: Long = 0L
) :
Comparable<FileDirItem> {
companion object {
var sorting = 0
}
override fun toString() =
"FileDirItem(path=$path, name=$name, isDirectory=$isDirectory, children=$children, size=$size, modified=$modified, mediaStoreId=$mediaStoreId)"
override fun compareTo(other: FileDirItem): Int {
return if (isDirectory && !other.isDirectory) {
-1
} else if (!isDirectory && other.isDirectory) {
1
} else {
var result: Int
when {
sorting and SORT_BY_NAME != 0 -> {
result = if (sorting and SORT_USE_NUMERIC_VALUE != 0) {
AlphanumericComparator().compare(name.normalizeString().lowercase(), other.name.normalizeString().lowercase())
} else {
name.normalizeString().lowercase().compareTo(other.name.normalizeString().lowercase())
}
}
sorting and SORT_BY_SIZE != 0 -> result = when {
size == other.size -> 0
size > other.size -> 1
else -> -1
}
sorting and SORT_BY_DATE_MODIFIED != 0 -> {
result = when {
modified == other.modified -> 0
modified > other.modified -> 1
else -> -1
}
}
else -> {
result = getExtension().lowercase().compareTo(other.getExtension().lowercase())
}
}
if (sorting and SORT_DESCENDING != 0) {
result *= -1
}
result
}
}
fun getExtension() = if (isDirectory) name else path.substringAfterLast('.', "")
fun getBubbleText(context: Context, dateFormat: String? = null, timeFormat: String? = null) = when {
sorting and SORT_BY_SIZE != 0 -> size.formatSize()
sorting and SORT_BY_DATE_MODIFIED != 0 -> modified.formatDate(context, dateFormat, timeFormat)
sorting and SORT_BY_EXTENSION != 0 -> getExtension().lowercase()
else -> name
}
fun getProperSize(context: Context, countHidden: Boolean): Long {
return when {
context.isRestrictedSAFOnlyRoot(path) -> context.getAndroidSAFFileSize(path)
context.isPathOnOTG(path) -> context.getDocumentFile(path)?.getItemSize(countHidden) ?: 0
isNougatPlus() && path.startsWith("content://") -> {
try {
context.contentResolver.openInputStream(Uri.parse(path))?.available()?.toLong() ?: 0L
} catch (e: Exception) {
context.getSizeFromContentUri(Uri.parse(path))
}
}
else -> File(path).getProperSize(countHidden)
}
}
fun getProperFileCount(context: Context, countHidden: Boolean): Int {
return when {
context.isRestrictedSAFOnlyRoot(path) -> context.getAndroidSAFFileCount(path, countHidden)
context.isPathOnOTG(path) -> context.getDocumentFile(path)?.getFileCount(countHidden) ?: 0
else -> File(path).getFileCount(countHidden)
}
}
fun getDirectChildrenCount(context: Context, countHiddenItems: Boolean): Int {
return when {
context.isRestrictedSAFOnlyRoot(path) -> context.getAndroidSAFDirectChildrenCount(path, countHiddenItems)
context.isPathOnOTG(path) -> context.getDocumentFile(path)?.listFiles()?.filter { if (countHiddenItems) true else !it.name!!.startsWith(".") }?.size
?: 0
else -> File(path).getDirectChildrenCount(context, countHiddenItems)
}
}
fun getLastModified(context: Context): Long {
return when {
context.isRestrictedSAFOnlyRoot(path) -> context.getAndroidSAFLastModified(path)
context.isPathOnOTG(path) -> context.getFastDocumentFile(path)?.lastModified() ?: 0L
isNougatPlus() && path.startsWith("content://") -> context.getMediaStoreLastModified(path)
else -> File(path).lastModified()
}
}
fun getParentPath() = path.getParentPath()
fun getDuration(context: Context) = context.getDuration(path)?.getFormattedDuration()
fun getFileDurationSeconds(context: Context) = context.getDuration(path)
fun getArtist(context: Context) = context.getArtist(path)
fun getAlbum(context: Context) = context.getAlbum(path)
fun getTitle(context: Context) = context.getTitle(path)
fun getResolution(context: Context) = context.getResolution(path)
fun getVideoResolution(context: Context) = context.getVideoResolution(path)
fun getImageResolution(context: Context) = context.getImageResolution(path)
fun getPublicUri(context: Context) = context.getDocumentFile(path)?.uri ?: ""
fun getSignature(): String {
val lastModified = if (modified > 1) {
modified
} else {
File(path).lastModified()
}
return "$path-$lastModified-$size"
}
fun getKey() = ObjectKey(getSignature())
fun assembleContentUri(): Uri {
val uri = when {
path.isImageFast() -> MediaStore.Images.Media.EXTERNAL_CONTENT_URI
path.isVideoFast() -> MediaStore.Video.Media.EXTERNAL_CONTENT_URI
else -> MediaStore.Files.getContentUri("external")
}
return Uri.withAppendedPath(uri, mediaStoreId.toString())
}
}
fun FileDirItem.asReadOnly() = FileDirItemReadOnly(
path = path,
name = name,
isDirectory = isDirectory,
children = children,
size = size,
modified = modified,
mediaStoreId = mediaStoreId
)
fun FileDirItemReadOnly.asFileDirItem() = FileDirItem(
path = path,
name = name,
isDirectory = isDirectory,
children = children,
size = size,
modified = modified,
mediaStoreId = mediaStoreId
)
@Immutable
class FileDirItemReadOnly(
path: String,
name: String = "",
isDirectory: Boolean = false,
children: Int = 0,
size: Long = 0L,
modified: Long = 0L,
mediaStoreId: Long = 0L
) : FileDirItem(path, name, isDirectory, children, size, modified, mediaStoreId)
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/models/FileDirItem.kt | 2377535186 |
package com.simplemobiletools.commons.models
import androidx.compose.runtime.Immutable
import java.io.Serializable
@Immutable
data class FAQItem(val title: Any, val text: Any) : Serializable {
companion object {
private const val serialVersionUID = -6553345863512345L
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/models/FAQItem.kt | 3586274804 |
package com.simplemobiletools.commons.receivers
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import com.simplemobiletools.commons.extensions.baseConfig
import com.simplemobiletools.commons.extensions.checkAppIconColor
import com.simplemobiletools.commons.extensions.getSharedTheme
import com.simplemobiletools.commons.helpers.MyContentProvider
class SharedThemeReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
context.baseConfig.apply {
val oldColor = appIconColor
if (intent.action == MyContentProvider.SHARED_THEME_ACTIVATED) {
if (!wasSharedThemeForced) {
wasSharedThemeForced = true
isUsingSharedTheme = true
wasSharedThemeEverActivated = true
context.getSharedTheme {
if (it != null) {
textColor = it.textColor
backgroundColor = it.backgroundColor
primaryColor = it.primaryColor
accentColor = it.accentColor
appIconColor = it.appIconColor
checkAppIconColorChanged(oldColor, appIconColor, context)
}
}
}
} else if (intent.action == MyContentProvider.SHARED_THEME_UPDATED) {
if (isUsingSharedTheme) {
context.getSharedTheme {
if (it != null) {
textColor = it.textColor
backgroundColor = it.backgroundColor
primaryColor = it.primaryColor
accentColor = it.accentColor
appIconColor = it.appIconColor
checkAppIconColorChanged(oldColor, appIconColor, context)
}
}
}
}
}
}
private fun checkAppIconColorChanged(oldColor: Int, newColor: Int, context: Context) {
if (oldColor != newColor) {
context.checkAppIconColor()
}
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/receivers/SharedThemeReceiver.kt | 1087092333 |
package com.simplemobiletools.commons.extensions
import androidx.viewpager.widget.ViewPager
fun ViewPager.onPageChangeListener(pageChangedAction: (newPosition: Int) -> Unit) =
addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
override fun onPageScrollStateChanged(state: Int) {}
override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {}
override fun onPageSelected(position: Int) {
pageChangedAction(position)
}
})
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/extensions/ViewPager.kt | 3305656841 |
package com.simplemobiletools.commons.extensions
import android.annotation.SuppressLint
import android.content.ComponentName
import android.content.Context
import android.content.pm.PackageManager
import android.content.res.Configuration
import android.graphics.Color
import android.view.ViewGroup
import androidx.loader.content.CursorLoader
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.helpers.*
import com.simplemobiletools.commons.models.SharedTheme
import com.simplemobiletools.commons.views.*
// handle system default theme (Material You) specially as the color is taken from the system, not hardcoded by us
fun Context.getProperTextColor() = if (baseConfig.isUsingSystemTheme) {
resources.getColor(R.color.you_neutral_text_color, theme)
} else {
baseConfig.textColor
}
fun Context.getProperBackgroundColor() = if (baseConfig.isUsingSystemTheme) {
resources.getColor(R.color.you_background_color, theme)
} else {
baseConfig.backgroundColor
}
fun Context.getProperPrimaryColor() = when {
baseConfig.isUsingSystemTheme -> resources.getColor(R.color.you_primary_color, theme)
isWhiteTheme() || isBlackAndWhiteTheme() -> baseConfig.accentColor
else -> baseConfig.primaryColor
}
fun Context.getProperStatusBarColor() = when {
baseConfig.isUsingSystemTheme -> resources.getColor(R.color.you_status_bar_color, theme)
else -> getProperBackgroundColor()
}
// get the color of the statusbar with material activity, if the layout is scrolled down a bit
fun Context.getColoredMaterialStatusBarColor(): Int {
return if (baseConfig.isUsingSystemTheme) {
resources.getColor(R.color.you_status_bar_color, theme)
} else {
getProperPrimaryColor()
}
}
fun Context.updateTextColors(viewGroup: ViewGroup) {
val textColor = when {
baseConfig.isUsingSystemTheme -> getProperTextColor()
else -> baseConfig.textColor
}
val backgroundColor = baseConfig.backgroundColor
val accentColor = when {
isWhiteTheme() || isBlackAndWhiteTheme() -> baseConfig.accentColor
else -> getProperPrimaryColor()
}
val cnt = viewGroup.childCount
(0 until cnt).map { viewGroup.getChildAt(it) }.forEach {
when (it) {
is MyTextView -> it.setColors(textColor, accentColor, backgroundColor)
is MyAppCompatSpinner -> it.setColors(textColor, accentColor, backgroundColor)
is MyCompatRadioButton -> it.setColors(textColor, accentColor, backgroundColor)
is MyAppCompatCheckbox -> it.setColors(textColor, accentColor, backgroundColor)
is MyEditText -> it.setColors(textColor, accentColor, backgroundColor)
is MyAutoCompleteTextView -> it.setColors(textColor, accentColor, backgroundColor)
is MyFloatingActionButton -> it.setColors(textColor, accentColor, backgroundColor)
is MySeekBar -> it.setColors(textColor, accentColor, backgroundColor)
is MyButton -> it.setColors(textColor, accentColor, backgroundColor)
is MyTextInputLayout -> it.setColors(textColor, accentColor, backgroundColor)
is ViewGroup -> updateTextColors(it)
}
}
}
fun Context.isBlackAndWhiteTheme() = baseConfig.textColor == Color.WHITE && baseConfig.primaryColor == Color.BLACK && baseConfig.backgroundColor == Color.BLACK
fun Context.isWhiteTheme() = baseConfig.textColor == DARK_GREY && baseConfig.primaryColor == Color.WHITE && baseConfig.backgroundColor == Color.WHITE
fun Context.isUsingSystemDarkTheme() = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_YES != 0
fun Context.getTimePickerDialogTheme() = when {
baseConfig.isUsingSystemTheme -> if (isUsingSystemDarkTheme()) {
R.style.MyTimePickerMaterialTheme_Dark
} else {
R.style.MyDateTimePickerMaterialTheme
}
baseConfig.backgroundColor.getContrastColor() == Color.WHITE -> R.style.MyDialogTheme_Dark
else -> R.style.MyDialogTheme
}
fun Context.getDatePickerDialogTheme() = when {
baseConfig.isUsingSystemTheme -> R.style.MyDateTimePickerMaterialTheme
baseConfig.backgroundColor.getContrastColor() == Color.WHITE -> R.style.MyDialogTheme_Dark
else -> R.style.MyDialogTheme
}
fun Context.getPopupMenuTheme(): Int {
return if (isSPlus() && baseConfig.isUsingSystemTheme) {
R.style.AppTheme_YouPopupMenuStyle
} else if (isWhiteTheme()) {
R.style.AppTheme_PopupMenuLightStyle
} else {
R.style.AppTheme_PopupMenuDarkStyle
}
}
fun Context.getSharedTheme(callback: (sharedTheme: SharedTheme?) -> Unit) {
if (!isThankYouInstalled()) {
callback(null)
} else {
val cursorLoader = getMyContentProviderCursorLoader()
ensureBackgroundThread {
callback(getSharedThemeSync(cursorLoader))
}
}
}
fun Context.getSharedThemeSync(cursorLoader: CursorLoader): SharedTheme? {
val cursor = cursorLoader.loadInBackground()
cursor?.use {
if (cursor.moveToFirst()) {
try {
val textColor = cursor.getIntValue(MyContentProvider.COL_TEXT_COLOR)
val backgroundColor = cursor.getIntValue(MyContentProvider.COL_BACKGROUND_COLOR)
val primaryColor = cursor.getIntValue(MyContentProvider.COL_PRIMARY_COLOR)
val accentColor = cursor.getIntValue(MyContentProvider.COL_ACCENT_COLOR)
val appIconColor = cursor.getIntValue(MyContentProvider.COL_APP_ICON_COLOR)
val lastUpdatedTS = cursor.getIntValue(MyContentProvider.COL_LAST_UPDATED_TS)
return SharedTheme(textColor, backgroundColor, primaryColor, appIconColor, lastUpdatedTS, accentColor)
} catch (e: Exception) {
}
}
}
return null
}
fun Context.checkAppIconColor() {
val appId = baseConfig.appId
if (appId.isNotEmpty() && baseConfig.lastIconColor != baseConfig.appIconColor) {
getAppIconColors().forEachIndexed { index, color ->
toggleAppIconColor(appId, index, color, false)
}
getAppIconColors().forEachIndexed { index, color ->
if (baseConfig.appIconColor == color) {
toggleAppIconColor(appId, index, color, true)
}
}
}
}
fun Context.toggleAppIconColor(appId: String, colorIndex: Int, color: Int, enable: Boolean) {
val className = "${appId.removeSuffix(".debug")}.activities.SplashActivity${appIconColorStrings[colorIndex]}"
val state = if (enable) PackageManager.COMPONENT_ENABLED_STATE_ENABLED else PackageManager.COMPONENT_ENABLED_STATE_DISABLED
try {
packageManager.setComponentEnabledSetting(ComponentName(appId, className), state, PackageManager.DONT_KILL_APP)
if (enable) {
baseConfig.lastIconColor = color
}
} catch (e: Exception) {
}
}
fun Context.getAppIconColors() = resources.getIntArray(R.array.md_app_icon_colors).toCollection(ArrayList())
@SuppressLint("NewApi")
fun Context.getBottomNavigationBackgroundColor(): Int {
val baseColor = baseConfig.backgroundColor
val bottomColor = when {
baseConfig.isUsingSystemTheme -> resources.getColor(R.color.you_status_bar_color, theme)
baseColor == Color.WHITE -> resources.getColor(R.color.bottom_tabs_light_background)
else -> baseConfig.backgroundColor.lightenColor(4)
}
return bottomColor
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/extensions/Context-styling.kt | 2333811704 |
package com.simplemobiletools.commons.extensions
import android.annotation.TargetApi
import android.content.Context
import android.content.Intent
import android.database.Cursor
import android.net.Uri
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.provider.ContactsContract
import android.telephony.PhoneNumberUtils
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.activities.BaseSimpleActivity
import com.simplemobiletools.commons.databases.ContactsDatabase
import com.simplemobiletools.commons.dialogs.CallConfirmationDialog
import com.simplemobiletools.commons.dialogs.RadioGroupDialog
import com.simplemobiletools.commons.helpers.*
import com.simplemobiletools.commons.interfaces.ContactsDao
import com.simplemobiletools.commons.interfaces.GroupsDao
import com.simplemobiletools.commons.models.RadioItem
import com.simplemobiletools.commons.models.contacts.Contact
import com.simplemobiletools.commons.models.contacts.ContactSource
import com.simplemobiletools.commons.models.contacts.Organization
import com.simplemobiletools.commons.models.contacts.SocialAction
import java.io.File
val Context.contactsDB: ContactsDao get() = ContactsDatabase.getInstance(applicationContext).ContactsDao()
val Context.groupsDB: GroupsDao get() = ContactsDatabase.getInstance(applicationContext).GroupsDao()
fun Context.getEmptyContact(): Contact {
val originalContactSource = if (hasContactPermissions()) baseConfig.lastUsedContactSource else SMT_PRIVATE
val organization = Organization("", "")
return Contact(
0, "", "", "", "", "", "", "", ArrayList(), ArrayList(), ArrayList(), ArrayList(), originalContactSource, 0, 0, "",
null, "", ArrayList(), organization, ArrayList(), ArrayList(), DEFAULT_MIMETYPE, null
)
}
fun Context.sendAddressIntent(address: String) {
val location = Uri.encode(address)
val uri = Uri.parse("geo:0,0?q=$location")
Intent(Intent.ACTION_VIEW, uri).apply {
launchActivityIntent(this)
}
}
fun Context.openWebsiteIntent(url: String) {
val website = if (url.startsWith("http")) {
url
} else {
"https://$url"
}
Intent(Intent.ACTION_VIEW).apply {
data = Uri.parse(website)
launchActivityIntent(this)
}
}
fun Context.getLookupUriRawId(dataUri: Uri): Int {
val lookupKey = getLookupKeyFromUri(dataUri)
if (lookupKey != null) {
val uri = lookupContactUri(lookupKey, this)
if (uri != null) {
return getContactUriRawId(uri)
}
}
return -1
}
fun Context.getContactUriRawId(uri: Uri): Int {
val projection = arrayOf(ContactsContract.Contacts.NAME_RAW_CONTACT_ID)
var cursor: Cursor? = null
try {
cursor = contentResolver.query(uri, projection, null, null, null)
if (cursor!!.moveToFirst()) {
return cursor.getIntValue(ContactsContract.Contacts.NAME_RAW_CONTACT_ID)
}
} catch (ignored: Exception) {
} finally {
cursor?.close()
}
return -1
}
// from https://android.googlesource.com/platform/packages/apps/Dialer/+/68038172793ee0e2ab3e2e56ddfbeb82879d1f58/java/com/android/contacts/common/util/UriUtils.java
fun getLookupKeyFromUri(lookupUri: Uri): String? {
return if (!isEncodedContactUri(lookupUri)) {
val segments = lookupUri.pathSegments
if (segments.size < 3) null else Uri.encode(segments[2])
} else {
null
}
}
fun isEncodedContactUri(uri: Uri?): Boolean {
if (uri == null) {
return false
}
val lastPathSegment = uri.lastPathSegment ?: return false
return lastPathSegment == "encoded"
}
fun lookupContactUri(lookup: String, context: Context): Uri? {
val lookupUri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, lookup)
return try {
ContactsContract.Contacts.lookupContact(context.contentResolver, lookupUri)
} catch (e: Exception) {
null
}
}
fun Context.getCachePhoto(): File {
val imagesFolder = File(cacheDir, "my_cache")
if (!imagesFolder.exists()) {
imagesFolder.mkdirs()
}
val file = File(imagesFolder, "Photo_${System.currentTimeMillis()}.jpg")
file.createNewFile()
return file
}
fun Context.getPhotoThumbnailSize(): Int {
val uri = ContactsContract.DisplayPhoto.CONTENT_MAX_DIMENSIONS_URI
val projection = arrayOf(ContactsContract.DisplayPhoto.THUMBNAIL_MAX_DIM)
var cursor: Cursor? = null
try {
cursor = contentResolver.query(uri, projection, null, null, null)
if (cursor?.moveToFirst() == true) {
return cursor.getIntValue(ContactsContract.DisplayPhoto.THUMBNAIL_MAX_DIM)
}
} catch (ignored: Exception) {
} finally {
cursor?.close()
}
return 0
}
fun Context.hasContactPermissions() = hasPermission(PERMISSION_READ_CONTACTS) && hasPermission(PERMISSION_WRITE_CONTACTS)
fun Context.getPublicContactSource(source: String, callback: (String) -> Unit) {
when (source) {
SMT_PRIVATE -> callback(getString(R.string.phone_storage_hidden))
else -> {
ContactsHelper(this).getContactSources {
var newSource = source
for (contactSource in it) {
if (contactSource.name == source && contactSource.type == TELEGRAM_PACKAGE) {
newSource = getString(R.string.telegram)
break
} else if (contactSource.name == source && contactSource.type == VIBER_PACKAGE) {
newSource = getString(R.string.viber)
break
}
}
Handler(Looper.getMainLooper()).post {
callback(newSource)
}
}
}
}
}
fun Context.getPublicContactSourceSync(source: String, contactSources: ArrayList<ContactSource>): String {
return when (source) {
SMT_PRIVATE -> getString(R.string.phone_storage_hidden)
else -> {
var newSource = source
for (contactSource in contactSources) {
if (contactSource.name == source && contactSource.type == TELEGRAM_PACKAGE) {
newSource = getString(R.string.telegram)
break
} else if (contactSource.name == source && contactSource.type == VIBER_PACKAGE) {
newSource = getString(R.string.viber)
break
}
}
return newSource
}
}
}
fun Context.sendSMSToContacts(contacts: ArrayList<Contact>) {
val numbers = StringBuilder()
contacts.forEach {
val number = it.phoneNumbers.firstOrNull { it.type == ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE }
?: it.phoneNumbers.firstOrNull()
if (number != null) {
numbers.append("${Uri.encode(number.value)};")
}
}
val uriString = "smsto:${numbers.toString().trimEnd(';')}"
Intent(Intent.ACTION_SENDTO, Uri.parse(uriString)).apply {
launchActivityIntent(this)
}
}
fun Context.sendEmailToContacts(contacts: ArrayList<Contact>) {
val emails = ArrayList<String>()
contacts.forEach {
it.emails.forEach {
if (it.value.isNotEmpty()) {
emails.add(it.value)
}
}
}
Intent(Intent.ACTION_SEND_MULTIPLE).apply {
type = "message/rfc822"
putExtra(Intent.EXTRA_EMAIL, emails.toTypedArray())
launchActivityIntent(this)
}
}
fun Context.getTempFile(filename: String = DEFAULT_FILE_NAME): File? {
val folder = File(cacheDir, "contacts")
if (!folder.exists()) {
if (!folder.mkdir()) {
toast(R.string.unknown_error_occurred)
return null
}
}
return File(folder, filename)
}
fun Context.addContactsToGroup(contacts: ArrayList<Contact>, groupId: Long) {
val publicContacts = contacts.filter { !it.isPrivate() }.toMutableList() as ArrayList<Contact>
val privateContacts = contacts.filter { it.isPrivate() }.toMutableList() as ArrayList<Contact>
if (publicContacts.isNotEmpty()) {
ContactsHelper(this).addContactsToGroup(publicContacts, groupId)
}
if (privateContacts.isNotEmpty()) {
LocalContactsHelper(this).addContactsToGroup(privateContacts, groupId)
}
}
fun Context.removeContactsFromGroup(contacts: ArrayList<Contact>, groupId: Long) {
val publicContacts = contacts.filter { !it.isPrivate() }.toMutableList() as ArrayList<Contact>
val privateContacts = contacts.filter { it.isPrivate() }.toMutableList() as ArrayList<Contact>
if (publicContacts.isNotEmpty() && hasContactPermissions()) {
ContactsHelper(this).removeContactsFromGroup(publicContacts, groupId)
}
if (privateContacts.isNotEmpty()) {
LocalContactsHelper(this).removeContactsFromGroup(privateContacts, groupId)
}
}
fun Context.getContactPublicUri(contact: Contact): Uri {
val lookupKey = if (contact.isPrivate()) {
"local_${contact.id}"
} else {
SimpleContactsHelper(this).getContactLookupKey(contact.id.toString())
}
return Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, lookupKey)
}
fun Context.getVisibleContactSources(): ArrayList<String> {
val sources = getAllContactSources()
val ignoredContactSources = baseConfig.ignoredContactSources
return ArrayList(sources).filter { !ignoredContactSources.contains(it.getFullIdentifier()) }
.map { it.name }.toMutableList() as ArrayList<String>
}
fun Context.getAllContactSources(): ArrayList<ContactSource> {
val sources = ContactsHelper(this).getDeviceContactSources()
sources.add(getPrivateContactSource())
return sources.toMutableList() as ArrayList<ContactSource>
}
fun Context.getPrivateContactSource() = ContactSource(SMT_PRIVATE, SMT_PRIVATE, getString(R.string.phone_storage_hidden))
fun Context.getSocialActions(id: Int): ArrayList<SocialAction> {
val uri = ContactsContract.Data.CONTENT_URI
val projection = arrayOf(
ContactsContract.Data._ID,
ContactsContract.Data.DATA3,
ContactsContract.Data.MIMETYPE,
ContactsContract.Data.ACCOUNT_TYPE_AND_DATA_SET
)
val socialActions = ArrayList<SocialAction>()
var curActionId = 0
val selection = "${ContactsContract.Data.RAW_CONTACT_ID} = ?"
val selectionArgs = arrayOf(id.toString())
queryCursor(uri, projection, selection, selectionArgs, null, true) { cursor ->
val mimetype = cursor.getStringValue(ContactsContract.Data.MIMETYPE)
val type = when (mimetype) {
// WhatsApp
"vnd.android.cursor.item/vnd.com.whatsapp.profile" -> SOCIAL_MESSAGE
"vnd.android.cursor.item/vnd.com.whatsapp.voip.call" -> SOCIAL_VOICE_CALL
"vnd.android.cursor.item/vnd.com.whatsapp.video.call" -> SOCIAL_VIDEO_CALL
// Viber
"vnd.android.cursor.item/vnd.com.viber.voip.viber_number_call" -> SOCIAL_VOICE_CALL
"vnd.android.cursor.item/vnd.com.viber.voip.viber_out_call_viber" -> SOCIAL_VOICE_CALL
"vnd.android.cursor.item/vnd.com.viber.voip.viber_out_call_none_viber" -> SOCIAL_VOICE_CALL
"vnd.android.cursor.item/vnd.com.viber.voip.viber_number_message" -> SOCIAL_MESSAGE
// Signal
"vnd.android.cursor.item/vnd.org.thoughtcrime.securesms.contact" -> SOCIAL_MESSAGE
"vnd.android.cursor.item/vnd.org.thoughtcrime.securesms.call" -> SOCIAL_VOICE_CALL
// Telegram
"vnd.android.cursor.item/vnd.org.telegram.messenger.android.call" -> SOCIAL_VOICE_CALL
"vnd.android.cursor.item/vnd.org.telegram.messenger.android.call.video" -> SOCIAL_VIDEO_CALL
"vnd.android.cursor.item/vnd.org.telegram.messenger.android.profile" -> SOCIAL_MESSAGE
// Threema
"vnd.android.cursor.item/vnd.ch.threema.app.profile" -> SOCIAL_MESSAGE
"vnd.android.cursor.item/vnd.ch.threema.app.call" -> SOCIAL_VOICE_CALL
else -> return@queryCursor
}
val label = cursor.getStringValue(ContactsContract.Data.DATA3)
val realID = cursor.getLongValue(ContactsContract.Data._ID)
val packageName = cursor.getStringValue(ContactsContract.Data.ACCOUNT_TYPE_AND_DATA_SET)
val socialAction = SocialAction(curActionId++, type, label, mimetype, realID, packageName)
socialActions.add(socialAction)
}
return socialActions
}
fun BaseSimpleActivity.initiateCall(contact: Contact, onStartCallIntent: (phoneNumber: String) -> Unit) {
val numbers = contact.phoneNumbers
if (numbers.size == 1) {
onStartCallIntent(numbers.first().value)
} else if (numbers.size > 1) {
val primaryNumber = contact.phoneNumbers.find { it.isPrimary }
if (primaryNumber != null) {
onStartCallIntent(primaryNumber.value)
} else {
val items = ArrayList<RadioItem>()
numbers.forEachIndexed { index, phoneNumber ->
items.add(RadioItem(index, "${phoneNumber.value} (${getPhoneNumberTypeText(phoneNumber.type, phoneNumber.label)})", phoneNumber.value))
}
RadioGroupDialog(this, items) {
onStartCallIntent(it as String)
}
}
}
}
fun BaseSimpleActivity.tryInitiateCall(contact: Contact, onStartCallIntent: (phoneNumber: String) -> Unit) {
if (baseConfig.showCallConfirmation) {
CallConfirmationDialog(this, contact.getNameToDisplay()) {
initiateCall(contact, onStartCallIntent)
}
} else {
initiateCall(contact, onStartCallIntent)
}
}
fun Context.isContactBlocked(contact: Contact, callback: (Boolean) -> Unit) {
val phoneNumbers = contact.phoneNumbers.map { PhoneNumberUtils.stripSeparators(it.value) }
getBlockedNumbersWithContact { blockedNumbersWithContact ->
val blockedNumbers = blockedNumbersWithContact.map { it.number }
val allNumbersBlocked = phoneNumbers.all { it in blockedNumbers }
callback(allNumbersBlocked)
}
}
@TargetApi(Build.VERSION_CODES.N)
fun Context.blockContact(contact: Contact): Boolean {
var contactBlocked = true
ensureBackgroundThread {
contact.phoneNumbers.forEach {
val numberBlocked = addBlockedNumber(PhoneNumberUtils.stripSeparators(it.value))
contactBlocked = contactBlocked && numberBlocked
}
}
return contactBlocked
}
@TargetApi(Build.VERSION_CODES.N)
fun Context.unblockContact(contact: Contact): Boolean {
var contactUnblocked = true
ensureBackgroundThread {
contact.phoneNumbers.forEach {
val numberUnblocked = deleteBlockedNumber(PhoneNumberUtils.stripSeparators(it.value))
contactUnblocked = contactUnblocked && numberUnblocked
}
}
return contactUnblocked
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/extensions/Context-contacts.kt | 3735766862 |
package com.simplemobiletools.commons.extensions
import android.content.ContentValues
import android.provider.MediaStore
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.activities.BaseSimpleActivity
import com.simplemobiletools.commons.models.FileDirItem
import java.io.File
import java.io.InputStream
import java.io.OutputStream
fun BaseSimpleActivity.copySingleFileSdk30(source: FileDirItem, destination: FileDirItem): Boolean {
val directory = destination.getParentPath()
if (!createDirectorySync(directory)) {
val error = String.format(getString(R.string.could_not_create_folder), directory)
showErrorToast(error)
return false
}
var inputStream: InputStream? = null
var out: OutputStream? = null
try {
out = getFileOutputStreamSync(destination.path, source.path.getMimeType())
inputStream = getFileInputStreamSync(source.path)!!
var copiedSize = 0L
val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
var bytes = inputStream.read(buffer)
while (bytes >= 0) {
out!!.write(buffer, 0, bytes)
copiedSize += bytes
bytes = inputStream.read(buffer)
}
out?.flush()
return if (source.size == copiedSize && getDoesFilePathExist(destination.path)) {
if (baseConfig.keepLastModified) {
copyOldLastModified(source.path, destination.path)
val lastModified = File(source.path).lastModified()
if (lastModified != 0L) {
File(destination.path).setLastModified(lastModified)
}
}
true
} else {
false
}
} finally {
inputStream?.close()
out?.close()
}
}
fun BaseSimpleActivity.copyOldLastModified(sourcePath: String, destinationPath: String) {
val projection = arrayOf(MediaStore.Images.Media.DATE_TAKEN, MediaStore.Images.Media.DATE_MODIFIED)
val uri = MediaStore.Files.getContentUri("external")
val selection = "${MediaStore.MediaColumns.DATA} = ?"
var selectionArgs = arrayOf(sourcePath)
val cursor = applicationContext.contentResolver.query(uri, projection, selection, selectionArgs, null)
cursor?.use {
if (cursor.moveToFirst()) {
val dateTaken = cursor.getLongValue(MediaStore.Images.Media.DATE_TAKEN)
val dateModified = cursor.getIntValue(MediaStore.Images.Media.DATE_MODIFIED)
val values = ContentValues().apply {
put(MediaStore.Images.Media.DATE_TAKEN, dateTaken)
put(MediaStore.Images.Media.DATE_MODIFIED, dateModified)
}
selectionArgs = arrayOf(destinationPath)
applicationContext.contentResolver.update(uri, values, selection, selectionArgs)
}
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/extensions/Activity-sdk30.kt | 1616867598 |
package com.simplemobiletools.commons.extensions
import android.content.res.Resources
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.PorterDuff
import android.graphics.PorterDuffColorFilter
import android.graphics.drawable.Drawable
fun Resources.getColoredBitmap(resourceId: Int, newColor: Int): Bitmap {
val drawable = getDrawable(resourceId)
val bitmap = Bitmap.createBitmap(drawable.intrinsicWidth, drawable.intrinsicHeight, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
drawable.setBounds(0, 0, canvas.width, canvas.height)
drawable.colorFilter = PorterDuffColorFilter(newColor, PorterDuff.Mode.SRC_IN)
drawable.draw(canvas)
return bitmap
}
fun Resources.getColoredDrawable(drawableId: Int, colorId: Int, alpha: Int = 255) = getColoredDrawableWithColor(drawableId, getColor(colorId), alpha)
fun Resources.getColoredDrawableWithColor(drawableId: Int, color: Int, alpha: Int = 255): Drawable {
val drawable = getDrawable(drawableId)
drawable.mutate().applyColorFilter(color)
drawable.mutate().alpha = alpha
return drawable
}
fun Resources.hasNavBar(): Boolean {
val id = getIdentifier("config_showNavigationBar", "bool", "android")
return id > 0 && getBoolean(id)
}
fun Resources.getNavBarHeight(): Int {
val id = getIdentifier("navigation_bar_height", "dimen", "android")
return if (id > 0 && hasNavBar()) {
getDimensionPixelSize(id)
} else
0
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/extensions/Resources.kt | 1426882333 |
package com.simplemobiletools.commons.extensions
import android.app.Application
import com.simplemobiletools.commons.helpers.isNougatPlus
import java.util.*
fun Application.checkUseEnglish() {
if (baseConfig.useEnglish && !isNougatPlus()) {
val conf = resources.configuration
conf.locale = Locale.ENGLISH
resources.updateConfiguration(conf, resources.displayMetrics)
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/extensions/App.kt | 3552360586 |
package com.simplemobiletools.commons.extensions
import android.graphics.Point
fun Point.formatAsResolution() = "$x x $y ${getMPx()}"
fun Point.getMPx(): String {
val px = x * y / 1000000f
val rounded = Math.round(px * 10) / 10f
return "(${rounded}MP)"
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/extensions/Point.kt | 3382841635 |
package com.simplemobiletools.commons.extensions
import java.io.BufferedWriter
fun BufferedWriter.writeLn(line: String) {
write(line)
newLine()
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/extensions/BufferedWriter.kt | 468660471 |
package com.simplemobiletools.commons.extensions
import android.view.WindowManager
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.widget.AppCompatEditText
// in dialogs, lets use findViewById, because while some dialogs use MyEditText, material theme dialogs use TextInputEditText so the system takes care of it
fun AlertDialog.showKeyboard(editText: AppCompatEditText) {
window!!.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE)
editText.apply {
requestFocus()
onGlobalLayout {
setSelection(text.toString().length)
}
}
}
fun AlertDialog.hideKeyboard() {
window!!.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN)
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/extensions/AlertDialog.kt | 22609286 |
package com.simplemobiletools.commons.extensions
import android.Manifest
import android.annotation.TargetApi
import android.app.Activity
import android.app.NotificationManager
import android.app.role.RoleManager
import android.content.*
import android.content.pm.PackageManager
import android.content.pm.ShortcutManager
import android.content.res.Configuration
import android.database.Cursor
import android.graphics.BitmapFactory
import android.graphics.Point
import android.media.MediaMetadataRetriever
import android.media.RingtoneManager
import android.net.Uri
import android.os.*
import android.provider.BaseColumns
import android.provider.BlockedNumberContract.BlockedNumbers
import android.provider.ContactsContract.CommonDataKinds.BaseTypes
import android.provider.ContactsContract.CommonDataKinds.Phone
import android.provider.DocumentsContract
import android.provider.MediaStore.*
import android.provider.OpenableColumns
import android.provider.Settings
import android.telecom.TelecomManager
import android.telephony.PhoneNumberUtils
import android.view.View
import android.view.WindowManager
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.biometric.BiometricManager
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import androidx.core.content.res.ResourcesCompat
import androidx.core.os.bundleOf
import androidx.exifinterface.media.ExifInterface
import androidx.loader.content.CursorLoader
import com.github.ajalt.reprint.core.Reprint
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.helpers.*
import com.simplemobiletools.commons.models.AlarmSound
import com.simplemobiletools.commons.models.BlockedNumber
import java.io.File
import java.text.SimpleDateFormat
import java.util.*
fun Context.getSharedPrefs() = getSharedPreferences(PREFS_KEY, Context.MODE_PRIVATE)
val Context.isRTLLayout: Boolean get() = resources.configuration.layoutDirection == View.LAYOUT_DIRECTION_RTL
val Context.areSystemAnimationsEnabled: Boolean get() = Settings.Global.getFloat(contentResolver, Settings.Global.ANIMATOR_DURATION_SCALE, 0f) > 0f
fun Context.toast(id: Int, length: Int = Toast.LENGTH_SHORT) {
toast(getString(id), length)
}
fun Context.toast(msg: String, length: Int = Toast.LENGTH_SHORT) {
try {
if (isOnMainThread()) {
doToast(this, msg, length)
} else {
Handler(Looper.getMainLooper()).post {
doToast(this, msg, length)
}
}
} catch (e: Exception) {
}
}
private fun doToast(context: Context, message: String, length: Int) {
if (context is Activity) {
if (!context.isFinishing && !context.isDestroyed) {
Toast.makeText(context, message, length).show()
}
} else {
Toast.makeText(context, message, length).show()
}
}
fun Context.showErrorToast(msg: String, length: Int = Toast.LENGTH_LONG) {
toast(String.format(getString(R.string.error), msg), length)
}
fun Context.showErrorToast(exception: Exception, length: Int = Toast.LENGTH_LONG) {
showErrorToast(exception.toString(), length)
}
val Context.baseConfig: BaseConfig get() = BaseConfig.newInstance(this)
val Context.sdCardPath: String get() = baseConfig.sdCardPath
val Context.internalStoragePath: String get() = baseConfig.internalStoragePath
val Context.otgPath: String get() = baseConfig.OTGPath
fun Context.isFingerPrintSensorAvailable() = Reprint.isHardwarePresent()
fun Context.isBiometricIdAvailable(): Boolean = when (BiometricManager.from(this).canAuthenticate(BiometricManager.Authenticators.BIOMETRIC_WEAK)) {
BiometricManager.BIOMETRIC_SUCCESS, BiometricManager.BIOMETRIC_STATUS_UNKNOWN -> true
else -> false
}
fun Context.getLatestMediaId(uri: Uri = Files.getContentUri("external")): Long {
val projection = arrayOf(
BaseColumns._ID
)
try {
val cursor = queryCursorDesc(uri, projection, BaseColumns._ID, 1)
cursor?.use {
if (cursor.moveToFirst()) {
return cursor.getLongValue(BaseColumns._ID)
}
}
} catch (ignored: Exception) {
}
return 0
}
private fun Context.queryCursorDesc(
uri: Uri,
projection: Array<String>,
sortColumn: String,
limit: Int,
): Cursor? {
return if (isRPlus()) {
val queryArgs = bundleOf(
ContentResolver.QUERY_ARG_LIMIT to limit,
ContentResolver.QUERY_ARG_SORT_DIRECTION to ContentResolver.QUERY_SORT_DIRECTION_DESCENDING,
ContentResolver.QUERY_ARG_SORT_COLUMNS to arrayOf(sortColumn),
)
contentResolver.query(uri, projection, queryArgs, null)
} else {
val sortOrder = "$sortColumn DESC LIMIT $limit"
contentResolver.query(uri, projection, null, null, sortOrder)
}
}
fun Context.getLatestMediaByDateId(uri: Uri = Files.getContentUri("external")): Long {
val projection = arrayOf(
BaseColumns._ID
)
try {
val cursor = queryCursorDesc(uri, projection, Images.ImageColumns.DATE_TAKEN, 1)
cursor?.use {
if (cursor.moveToFirst()) {
return cursor.getLongValue(BaseColumns._ID)
}
}
} catch (ignored: Exception) {
}
return 0
}
// some helper functions were taken from https://github.com/iPaulPro/aFileChooser/blob/master/aFileChooser/src/com/ipaulpro/afilechooser/utils/FileUtils.java
fun Context.getRealPathFromURI(uri: Uri): String? {
if (uri.scheme == "file") {
return uri.path
}
if (isDownloadsDocument(uri)) {
val id = DocumentsContract.getDocumentId(uri)
if (id.areDigitsOnly()) {
val newUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), id.toLong())
val path = getDataColumn(newUri)
if (path != null) {
return path
}
}
} else if (isExternalStorageDocument(uri)) {
val documentId = DocumentsContract.getDocumentId(uri)
val parts = documentId.split(":")
if (parts[0].equals("primary", true)) {
return "${Environment.getExternalStorageDirectory().absolutePath}/${parts[1]}"
}
} else if (isMediaDocument(uri)) {
val documentId = DocumentsContract.getDocumentId(uri)
val split = documentId.split(":").dropLastWhile { it.isEmpty() }.toTypedArray()
val type = split[0]
val contentUri = when (type) {
"video" -> Video.Media.EXTERNAL_CONTENT_URI
"audio" -> Audio.Media.EXTERNAL_CONTENT_URI
else -> Images.Media.EXTERNAL_CONTENT_URI
}
val selection = "_id=?"
val selectionArgs = arrayOf(split[1])
val path = getDataColumn(contentUri, selection, selectionArgs)
if (path != null) {
return path
}
}
return getDataColumn(uri)
}
fun Context.getDataColumn(uri: Uri, selection: String? = null, selectionArgs: Array<String>? = null): String? {
try {
val projection = arrayOf(Files.FileColumns.DATA)
val cursor = contentResolver.query(uri, projection, selection, selectionArgs, null)
cursor?.use {
if (cursor.moveToFirst()) {
val data = cursor.getStringValue(Files.FileColumns.DATA)
if (data != "null") {
return data
}
}
}
} catch (e: Exception) {
}
return null
}
private fun isMediaDocument(uri: Uri) = uri.authority == "com.android.providers.media.documents"
private fun isDownloadsDocument(uri: Uri) = uri.authority == "com.android.providers.downloads.documents"
private fun isExternalStorageDocument(uri: Uri) = uri.authority == "com.android.externalstorage.documents"
fun Context.hasPermission(permId: Int) = ContextCompat.checkSelfPermission(this, getPermissionString(permId)) == PackageManager.PERMISSION_GRANTED
fun Context.hasAllPermissions(permIds: Collection<Int>) = permIds.all(this::hasPermission)
fun Context.getPermissionString(id: Int) = when (id) {
PERMISSION_READ_STORAGE -> Manifest.permission.READ_EXTERNAL_STORAGE
PERMISSION_WRITE_STORAGE -> Manifest.permission.WRITE_EXTERNAL_STORAGE
PERMISSION_CAMERA -> Manifest.permission.CAMERA
PERMISSION_RECORD_AUDIO -> Manifest.permission.RECORD_AUDIO
PERMISSION_READ_CONTACTS -> Manifest.permission.READ_CONTACTS
PERMISSION_WRITE_CONTACTS -> Manifest.permission.WRITE_CONTACTS
PERMISSION_READ_CALENDAR -> Manifest.permission.READ_CALENDAR
PERMISSION_WRITE_CALENDAR -> Manifest.permission.WRITE_CALENDAR
PERMISSION_CALL_PHONE -> Manifest.permission.CALL_PHONE
PERMISSION_READ_CALL_LOG -> Manifest.permission.READ_CALL_LOG
PERMISSION_WRITE_CALL_LOG -> Manifest.permission.WRITE_CALL_LOG
PERMISSION_GET_ACCOUNTS -> Manifest.permission.GET_ACCOUNTS
PERMISSION_READ_SMS -> Manifest.permission.READ_SMS
PERMISSION_SEND_SMS -> Manifest.permission.SEND_SMS
PERMISSION_READ_PHONE_STATE -> Manifest.permission.READ_PHONE_STATE
PERMISSION_MEDIA_LOCATION -> if (isQPlus()) Manifest.permission.ACCESS_MEDIA_LOCATION else ""
PERMISSION_POST_NOTIFICATIONS -> Manifest.permission.POST_NOTIFICATIONS
PERMISSION_READ_MEDIA_IMAGES -> Manifest.permission.READ_MEDIA_IMAGES
PERMISSION_READ_MEDIA_VIDEO -> Manifest.permission.READ_MEDIA_VIDEO
PERMISSION_READ_MEDIA_AUDIO -> Manifest.permission.READ_MEDIA_AUDIO
PERMISSION_ACCESS_COARSE_LOCATION -> Manifest.permission.ACCESS_COARSE_LOCATION
PERMISSION_ACCESS_FINE_LOCATION -> Manifest.permission.ACCESS_FINE_LOCATION
PERMISSION_READ_MEDIA_VISUAL_USER_SELECTED -> Manifest.permission.READ_MEDIA_VISUAL_USER_SELECTED
PERMISSION_READ_SYNC_SETTINGS -> Manifest.permission.READ_SYNC_SETTINGS
else -> ""
}
fun Context.launchActivityIntent(intent: Intent) {
try {
startActivity(intent)
} catch (e: ActivityNotFoundException) {
toast(R.string.no_app_found)
} catch (e: Exception) {
showErrorToast(e)
}
}
fun Context.getFilePublicUri(file: File, applicationId: String): Uri {
// for images/videos/gifs try getting a media content uri first, like content://media/external/images/media/438
// if media content uri is null, get our custom uri like content://com.simplemobiletools.gallery.provider/external_files/emulated/0/DCIM/IMG_20171104_233915.jpg
var uri = if (file.isMediaFile()) {
getMediaContentUri(file.absolutePath)
} else {
getMediaContent(file.absolutePath, Files.getContentUri("external"))
}
if (uri == null) {
uri = FileProvider.getUriForFile(this, "$applicationId.provider", file)
}
return uri!!
}
fun Context.getMediaContentUri(path: String): Uri? {
val uri = when {
path.isImageFast() -> Images.Media.EXTERNAL_CONTENT_URI
path.isVideoFast() -> Video.Media.EXTERNAL_CONTENT_URI
else -> Files.getContentUri("external")
}
return getMediaContent(path, uri)
}
fun Context.getMediaContent(path: String, uri: Uri): Uri? {
val projection = arrayOf(Images.Media._ID)
val selection = Images.Media.DATA + "= ?"
val selectionArgs = arrayOf(path)
try {
val cursor = contentResolver.query(uri, projection, selection, selectionArgs, null)
cursor?.use {
if (cursor.moveToFirst()) {
val id = cursor.getIntValue(Images.Media._ID).toString()
return Uri.withAppendedPath(uri, id)
}
}
} catch (e: Exception) {
}
return null
}
fun Context.queryCursor(
uri: Uri,
projection: Array<String>,
selection: String? = null,
selectionArgs: Array<String>? = null,
sortOrder: String? = null,
showErrors: Boolean = false,
callback: (cursor: Cursor) -> Unit
) {
try {
val cursor = contentResolver.query(uri, projection, selection, selectionArgs, sortOrder)
cursor?.use {
if (cursor.moveToFirst()) {
do {
callback(cursor)
} while (cursor.moveToNext())
}
}
} catch (e: Exception) {
if (showErrors) {
showErrorToast(e)
}
}
}
@RequiresApi(Build.VERSION_CODES.O)
fun Context.queryCursor(
uri: Uri,
projection: Array<String>,
queryArgs: Bundle,
showErrors: Boolean = false,
callback: (cursor: Cursor) -> Unit
) {
try {
val cursor = contentResolver.query(uri, projection, queryArgs, null)
cursor?.use {
if (cursor.moveToFirst()) {
do {
callback(cursor)
} while (cursor.moveToNext())
}
}
} catch (e: Exception) {
if (showErrors) {
showErrorToast(e)
}
}
}
fun Context.getFilenameFromUri(uri: Uri): String {
return if (uri.scheme == "file") {
File(uri.toString()).name
} else {
getFilenameFromContentUri(uri) ?: uri.lastPathSegment ?: ""
}
}
fun Context.getMimeTypeFromUri(uri: Uri): String {
var mimetype = uri.path?.getMimeType() ?: ""
if (mimetype.isEmpty()) {
try {
mimetype = contentResolver.getType(uri) ?: ""
} catch (e: IllegalStateException) {
}
}
return mimetype
}
fun Context.ensurePublicUri(path: String, applicationId: String): Uri? {
return when {
hasProperStoredAndroidTreeUri(path) && isRestrictedSAFOnlyRoot(path) -> {
getAndroidSAFUri(path)
}
hasProperStoredDocumentUriSdk30(path) && isAccessibleWithSAFSdk30(path) -> {
createDocumentUriUsingFirstParentTreeUri(path)
}
isPathOnOTG(path) -> {
getDocumentFile(path)?.uri
}
else -> {
val uri = Uri.parse(path)
if (uri.scheme == "content") {
uri
} else {
val newPath = if (uri.toString().startsWith("/")) uri.toString() else uri.path
val file = File(newPath)
getFilePublicUri(file, applicationId)
}
}
}
}
fun Context.ensurePublicUri(uri: Uri, applicationId: String): Uri {
return if (uri.scheme == "content") {
uri
} else {
val file = File(uri.path)
getFilePublicUri(file, applicationId)
}
}
fun Context.getFilenameFromContentUri(uri: Uri): String? {
val projection = arrayOf(
OpenableColumns.DISPLAY_NAME
)
try {
val cursor = contentResolver.query(uri, projection, null, null, null)
cursor?.use {
if (cursor.moveToFirst()) {
return cursor.getStringValue(OpenableColumns.DISPLAY_NAME)
}
}
} catch (e: Exception) {
}
return null
}
fun Context.getSizeFromContentUri(uri: Uri): Long {
val projection = arrayOf(OpenableColumns.SIZE)
try {
val cursor = contentResolver.query(uri, projection, null, null, null)
cursor?.use {
if (cursor.moveToFirst()) {
return cursor.getLongValue(OpenableColumns.SIZE)
}
}
} catch (e: Exception) {
}
return 0L
}
fun Context.getMyContentProviderCursorLoader() = CursorLoader(this, MyContentProvider.MY_CONTENT_URI, null, null, null, null)
fun Context.getMyContactsCursor(favoritesOnly: Boolean, withPhoneNumbersOnly: Boolean) = try {
val getFavoritesOnly = if (favoritesOnly) "1" else "0"
val getWithPhoneNumbersOnly = if (withPhoneNumbersOnly) "1" else "0"
val args = arrayOf(getFavoritesOnly, getWithPhoneNumbersOnly)
CursorLoader(this, MyContactsContentProvider.CONTACTS_CONTENT_URI, null, null, args, null).loadInBackground()
} catch (e: Exception) {
null
}
fun Context.getCurrentFormattedDateTime(): String {
val simpleDateFormat = SimpleDateFormat("yyyy_MM_dd_HH_mm_ss", Locale.getDefault())
return simpleDateFormat.format(Date(System.currentTimeMillis()))
}
fun Context.updateSDCardPath() {
ensureBackgroundThread {
val oldPath = baseConfig.sdCardPath
baseConfig.sdCardPath = getSDCardPath()
if (oldPath != baseConfig.sdCardPath) {
baseConfig.sdTreeUri = ""
}
}
}
fun Context.getUriMimeType(path: String, newUri: Uri): String {
var mimeType = path.getMimeType()
if (mimeType.isEmpty()) {
mimeType = getMimeTypeFromUri(newUri)
}
return mimeType
}
fun Context.isThankYouInstalled() = isPackageInstalled("com.simplemobiletools.thankyou")
fun Context.isOrWasThankYouInstalled(): Boolean {
return when {
resources.getBoolean(R.bool.pretend_thank_you_installed) -> true
baseConfig.hadThankYouInstalled -> true
isThankYouInstalled() -> {
baseConfig.hadThankYouInstalled = true
true
}
else -> false
}
}
fun Context.isAProApp() = packageName.startsWith("com.simplemobiletools.") && packageName.removeSuffix(".debug").endsWith(".pro")
fun Context.getCustomizeColorsString(): String {
val textId = if (isOrWasThankYouInstalled()) {
R.string.customize_colors
} else {
R.string.customize_colors_locked
}
return getString(textId)
}
fun Context.addLockedLabelIfNeeded(stringId: Int): String {
return if (isOrWasThankYouInstalled()) {
getString(stringId)
} else {
"${getString(stringId)} (${getString(R.string.feature_locked)})"
}
}
fun Context.isPackageInstalled(pkgName: String): Boolean {
return try {
packageManager.getPackageInfo(pkgName, 0)
true
} catch (e: Exception) {
false
}
}
// format day bits to strings like "Mon, Tue, Wed"
fun Context.getSelectedDaysString(bitMask: Int): String {
val dayBits = arrayListOf(MONDAY_BIT, TUESDAY_BIT, WEDNESDAY_BIT, THURSDAY_BIT, FRIDAY_BIT, SATURDAY_BIT, SUNDAY_BIT)
val weekDays = resources.getStringArray(R.array.week_days_short).toList() as ArrayList<String>
if (baseConfig.isSundayFirst) {
dayBits.moveLastItemToFront()
weekDays.moveLastItemToFront()
}
var days = ""
dayBits.forEachIndexed { index, bit ->
if (bitMask and bit != 0) {
days += "${weekDays[index]}, "
}
}
return days.trim().trimEnd(',')
}
fun Context.formatMinutesToTimeString(totalMinutes: Int) = formatSecondsToTimeString(totalMinutes * 60)
fun Context.formatSecondsToTimeString(totalSeconds: Int): String {
val days = totalSeconds / DAY_SECONDS
val hours = (totalSeconds % DAY_SECONDS) / HOUR_SECONDS
val minutes = (totalSeconds % HOUR_SECONDS) / MINUTE_SECONDS
val seconds = totalSeconds % MINUTE_SECONDS
val timesString = StringBuilder()
if (days > 0) {
val daysString = String.format(resources.getQuantityString(R.plurals.days, days, days))
timesString.append("$daysString, ")
}
if (hours > 0) {
val hoursString = String.format(resources.getQuantityString(R.plurals.hours, hours, hours))
timesString.append("$hoursString, ")
}
if (minutes > 0) {
val minutesString = String.format(resources.getQuantityString(R.plurals.minutes, minutes, minutes))
timesString.append("$minutesString, ")
}
if (seconds > 0) {
val secondsString = String.format(resources.getQuantityString(R.plurals.seconds, seconds, seconds))
timesString.append(secondsString)
}
var result = timesString.toString().trim().trimEnd(',')
if (result.isEmpty()) {
result = String.format(resources.getQuantityString(R.plurals.minutes, 0, 0))
}
return result
}
fun Context.getFormattedMinutes(minutes: Int, showBefore: Boolean = true) = getFormattedSeconds(if (minutes == -1) minutes else minutes * 60, showBefore)
fun Context.getFormattedSeconds(seconds: Int, showBefore: Boolean = true) = when (seconds) {
-1 -> getString(R.string.no_reminder)
0 -> getString(R.string.at_start)
else -> {
when {
seconds < 0 && seconds > -60 * 60 * 24 -> {
val minutes = -seconds / 60
getString(R.string.during_day_at).format(minutes / 60, minutes % 60)
}
seconds % YEAR_SECONDS == 0 -> {
val base = if (showBefore) R.plurals.years_before else R.plurals.by_years
resources.getQuantityString(base, seconds / YEAR_SECONDS, seconds / YEAR_SECONDS)
}
seconds % MONTH_SECONDS == 0 -> {
val base = if (showBefore) R.plurals.months_before else R.plurals.by_months
resources.getQuantityString(base, seconds / MONTH_SECONDS, seconds / MONTH_SECONDS)
}
seconds % WEEK_SECONDS == 0 -> {
val base = if (showBefore) R.plurals.weeks_before else R.plurals.by_weeks
resources.getQuantityString(base, seconds / WEEK_SECONDS, seconds / WEEK_SECONDS)
}
seconds % DAY_SECONDS == 0 -> {
val base = if (showBefore) R.plurals.days_before else R.plurals.by_days
resources.getQuantityString(base, seconds / DAY_SECONDS, seconds / DAY_SECONDS)
}
seconds % HOUR_SECONDS == 0 -> {
val base = if (showBefore) R.plurals.hours_before else R.plurals.by_hours
resources.getQuantityString(base, seconds / HOUR_SECONDS, seconds / HOUR_SECONDS)
}
seconds % MINUTE_SECONDS == 0 -> {
val base = if (showBefore) R.plurals.minutes_before else R.plurals.by_minutes
resources.getQuantityString(base, seconds / MINUTE_SECONDS, seconds / MINUTE_SECONDS)
}
else -> {
val base = if (showBefore) R.plurals.seconds_before else R.plurals.by_seconds
resources.getQuantityString(base, seconds, seconds)
}
}
}
}
fun Context.getDefaultAlarmTitle(type: Int): String {
val alarmString = getString(R.string.alarm)
return try {
RingtoneManager.getRingtone(this, RingtoneManager.getDefaultUri(type))?.getTitle(this) ?: alarmString
} catch (e: Exception) {
alarmString
}
}
fun Context.getDefaultAlarmSound(type: Int) = AlarmSound(0, getDefaultAlarmTitle(type), RingtoneManager.getDefaultUri(type).toString())
fun Context.grantReadUriPermission(uriString: String) {
try {
// ensure custom reminder sounds play well
grantUriPermission("com.android.systemui", Uri.parse(uriString), Intent.FLAG_GRANT_READ_URI_PERMISSION)
} catch (ignored: Exception) {
}
}
fun Context.storeNewYourAlarmSound(resultData: Intent): AlarmSound {
val uri = resultData.data
var filename = getFilenameFromUri(uri!!)
if (filename.isEmpty()) {
filename = getString(R.string.alarm)
}
val token = object : TypeToken<ArrayList<AlarmSound>>() {}.type
val yourAlarmSounds = Gson().fromJson<ArrayList<AlarmSound>>(baseConfig.yourAlarmSounds, token)
?: ArrayList()
val newAlarmSoundId = (yourAlarmSounds.maxByOrNull { it.id }?.id ?: YOUR_ALARM_SOUNDS_MIN_ID) + 1
val newAlarmSound = AlarmSound(newAlarmSoundId, filename, uri.toString())
if (yourAlarmSounds.firstOrNull { it.uri == uri.toString() } == null) {
yourAlarmSounds.add(newAlarmSound)
}
baseConfig.yourAlarmSounds = Gson().toJson(yourAlarmSounds)
val takeFlags = Intent.FLAG_GRANT_READ_URI_PERMISSION
contentResolver.takePersistableUriPermission(uri, takeFlags)
return newAlarmSound
}
@RequiresApi(Build.VERSION_CODES.N)
fun Context.saveImageRotation(path: String, degrees: Int): Boolean {
if (!needsStupidWritePermissions(path)) {
saveExifRotation(ExifInterface(path), degrees)
return true
} else if (isNougatPlus()) {
val documentFile = getSomeDocumentFile(path)
if (documentFile != null) {
val parcelFileDescriptor = contentResolver.openFileDescriptor(documentFile.uri, "rw")
val fileDescriptor = parcelFileDescriptor!!.fileDescriptor
saveExifRotation(ExifInterface(fileDescriptor), degrees)
return true
}
}
return false
}
fun Context.saveExifRotation(exif: ExifInterface, degrees: Int) {
val orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL)
val orientationDegrees = (orientation.degreesFromOrientation() + degrees) % 360
exif.setAttribute(ExifInterface.TAG_ORIENTATION, orientationDegrees.orientationFromDegrees())
exif.saveAttributes()
}
fun Context.getLaunchIntent() = packageManager.getLaunchIntentForPackage(baseConfig.appId)
fun Context.getCanAppBeUpgraded() = proPackages.contains(baseConfig.appId.removeSuffix(".debug").removePrefix("com.simplemobiletools."))
fun Context.getProUrl() = "https://play.google.com/store/apps/details?id=${baseConfig.appId.removeSuffix(".debug")}.pro"
fun Context.getStoreUrl() = "https://play.google.com/store/apps/details?id=${packageName.removeSuffix(".debug")}"
fun Context.getTimeFormat() = if (baseConfig.use24HourFormat) TIME_FORMAT_24 else TIME_FORMAT_12
fun Context.getResolution(path: String): Point? {
return if (path.isImageFast() || path.isImageSlow()) {
getImageResolution(path)
} else if (path.isVideoFast() || path.isVideoSlow()) {
getVideoResolution(path)
} else {
null
}
}
fun Context.getImageResolution(path: String): Point? {
val options = BitmapFactory.Options()
options.inJustDecodeBounds = true
if (isRestrictedSAFOnlyRoot(path)) {
BitmapFactory.decodeStream(contentResolver.openInputStream(getAndroidSAFUri(path)), null, options)
} else {
BitmapFactory.decodeFile(path, options)
}
val width = options.outWidth
val height = options.outHeight
return if (width > 0 && height > 0) {
Point(options.outWidth, options.outHeight)
} else {
null
}
}
fun Context.getVideoResolution(path: String): Point? {
var point = try {
val retriever = MediaMetadataRetriever()
if (isRestrictedSAFOnlyRoot(path)) {
retriever.setDataSource(this, getAndroidSAFUri(path))
} else {
retriever.setDataSource(path)
}
val width = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH)!!.toInt()
val height = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT)!!.toInt()
Point(width, height)
} catch (ignored: Exception) {
null
}
if (point == null && path.startsWith("content://", true)) {
try {
val fd = contentResolver.openFileDescriptor(Uri.parse(path), "r")?.fileDescriptor
val retriever = MediaMetadataRetriever()
retriever.setDataSource(fd)
val width = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH)!!.toInt()
val height = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT)!!.toInt()
point = Point(width, height)
} catch (ignored: Exception) {
}
}
return point
}
fun Context.getDuration(path: String): Int? {
val projection = arrayOf(
MediaColumns.DURATION
)
val uri = getFileUri(path)
val selection = if (path.startsWith("content://")) "${BaseColumns._ID} = ?" else "${MediaColumns.DATA} = ?"
val selectionArgs = if (path.startsWith("content://")) arrayOf(path.substringAfterLast("/")) else arrayOf(path)
try {
val cursor = contentResolver.query(uri, projection, selection, selectionArgs, null)
cursor?.use {
if (cursor.moveToFirst()) {
return Math.round(cursor.getIntValue(MediaColumns.DURATION) / 1000.toDouble()).toInt()
}
}
} catch (ignored: Exception) {
}
return try {
val retriever = MediaMetadataRetriever()
retriever.setDataSource(path)
Math.round(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)!!.toInt() / 1000f)
} catch (ignored: Exception) {
null
}
}
fun Context.getTitle(path: String): String? {
val projection = arrayOf(
MediaColumns.TITLE
)
val uri = getFileUri(path)
val selection = if (path.startsWith("content://")) "${BaseColumns._ID} = ?" else "${MediaColumns.DATA} = ?"
val selectionArgs = if (path.startsWith("content://")) arrayOf(path.substringAfterLast("/")) else arrayOf(path)
try {
val cursor = contentResolver.query(uri, projection, selection, selectionArgs, null)
cursor?.use {
if (cursor.moveToFirst()) {
return cursor.getStringValue(MediaColumns.TITLE)
}
}
} catch (ignored: Exception) {
}
return try {
val retriever = MediaMetadataRetriever()
retriever.setDataSource(path)
retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE)
} catch (ignored: Exception) {
null
}
}
fun Context.getArtist(path: String): String? {
val projection = arrayOf(
Audio.Media.ARTIST
)
val uri = getFileUri(path)
val selection = if (path.startsWith("content://")) "${BaseColumns._ID} = ?" else "${MediaColumns.DATA} = ?"
val selectionArgs = if (path.startsWith("content://")) arrayOf(path.substringAfterLast("/")) else arrayOf(path)
try {
val cursor = contentResolver.query(uri, projection, selection, selectionArgs, null)
cursor?.use {
if (cursor.moveToFirst()) {
return cursor.getStringValue(Audio.Media.ARTIST)
}
}
} catch (ignored: Exception) {
}
return try {
val retriever = MediaMetadataRetriever()
retriever.setDataSource(path)
retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST)
} catch (ignored: Exception) {
null
}
}
fun Context.getAlbum(path: String): String? {
val projection = arrayOf(
Audio.Media.ALBUM
)
val uri = getFileUri(path)
val selection = if (path.startsWith("content://")) "${BaseColumns._ID} = ?" else "${MediaColumns.DATA} = ?"
val selectionArgs = if (path.startsWith("content://")) arrayOf(path.substringAfterLast("/")) else arrayOf(path)
try {
val cursor = contentResolver.query(uri, projection, selection, selectionArgs, null)
cursor?.use {
if (cursor.moveToFirst()) {
return cursor.getStringValue(Audio.Media.ALBUM)
}
}
} catch (ignored: Exception) {
}
return try {
val retriever = MediaMetadataRetriever()
retriever.setDataSource(path)
retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUM)
} catch (ignored: Exception) {
null
}
}
fun Context.getMediaStoreLastModified(path: String): Long {
val projection = arrayOf(
MediaColumns.DATE_MODIFIED
)
val uri = getFileUri(path)
val selection = "${BaseColumns._ID} = ?"
val selectionArgs = arrayOf(path.substringAfterLast("/"))
try {
val cursor = contentResolver.query(uri, projection, selection, selectionArgs, null)
cursor?.use {
if (cursor.moveToFirst()) {
return cursor.getLongValue(MediaColumns.DATE_MODIFIED) * 1000
}
}
} catch (ignored: Exception) {
}
return 0
}
fun Context.getStringsPackageName() = getString(R.string.package_name)
fun Context.getFontSizeText() = getString(
when (baseConfig.fontSize) {
FONT_SIZE_SMALL -> R.string.small
FONT_SIZE_MEDIUM -> R.string.medium
FONT_SIZE_LARGE -> R.string.large
else -> R.string.extra_large
}
)
fun Context.getTextSize() = when (baseConfig.fontSize) {
FONT_SIZE_SMALL -> resources.getDimension(R.dimen.smaller_text_size)
FONT_SIZE_MEDIUM -> resources.getDimension(R.dimen.bigger_text_size)
FONT_SIZE_LARGE -> resources.getDimension(R.dimen.big_text_size)
else -> resources.getDimension(R.dimen.extra_big_text_size)
}
val Context.telecomManager: TelecomManager get() = getSystemService(Context.TELECOM_SERVICE) as TelecomManager
val Context.windowManager: WindowManager get() = getSystemService(Context.WINDOW_SERVICE) as WindowManager
val Context.notificationManager: NotificationManager get() = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val Context.shortcutManager: ShortcutManager get() = getSystemService(ShortcutManager::class.java) as ShortcutManager
val Context.portrait get() = resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT
val Context.navigationBarOnSide: Boolean get() = usableScreenSize.x < realScreenSize.x && usableScreenSize.x > usableScreenSize.y
val Context.navigationBarOnBottom: Boolean get() = usableScreenSize.y < realScreenSize.y
val Context.navigationBarHeight: Int get() = if (navigationBarOnBottom && navigationBarSize.y != usableScreenSize.y) navigationBarSize.y else 0
val Context.navigationBarWidth: Int get() = if (navigationBarOnSide) navigationBarSize.x else 0
val Context.navigationBarSize: Point
get() = when {
navigationBarOnSide -> Point(newNavigationBarHeight, usableScreenSize.y)
navigationBarOnBottom -> Point(usableScreenSize.x, newNavigationBarHeight)
else -> Point()
}
val Context.newNavigationBarHeight: Int
get() {
var navigationBarHeight = 0
val resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android")
if (resourceId > 0) {
navigationBarHeight = resources.getDimensionPixelSize(resourceId)
}
return navigationBarHeight
}
val Context.statusBarHeight: Int
get() {
var statusBarHeight = 0
val resourceId = resources.getIdentifier("status_bar_height", "dimen", "android")
if (resourceId > 0) {
statusBarHeight = resources.getDimensionPixelSize(resourceId)
}
return statusBarHeight
}
val Context.actionBarHeight: Int
get() {
val styledAttributes = theme.obtainStyledAttributes(intArrayOf(android.R.attr.actionBarSize))
val actionBarHeight = styledAttributes.getDimension(0, 0f)
styledAttributes.recycle()
return actionBarHeight.toInt()
}
val Context.usableScreenSize: Point
get() {
val size = Point()
windowManager.defaultDisplay.getSize(size)
return size
}
val Context.realScreenSize: Point
get() {
val size = Point()
windowManager.defaultDisplay.getRealSize(size)
return size
}
fun Context.isUsingGestureNavigation(): Boolean {
return try {
val resourceId = resources.getIdentifier("config_navBarInteractionMode", "integer", "android")
if (resourceId > 0) {
resources.getInteger(resourceId) == 2
} else {
false
}
} catch (e: Exception) {
false
}
}
fun Context.getCornerRadius() = resources.getDimension(R.dimen.rounded_corner_radius_small)
// we need the Default Dialer functionality only in Simple Dialer and in Simple Contacts for now
fun Context.isDefaultDialer(): Boolean {
return if (!packageName.startsWith("com.simplemobiletools.contacts") && !packageName.startsWith("com.simplemobiletools.dialer")) {
true
} else if ((packageName.startsWith("com.simplemobiletools.contacts") || packageName.startsWith("com.simplemobiletools.dialer")) && isQPlus()) {
val roleManager = getSystemService(RoleManager::class.java)
roleManager!!.isRoleAvailable(RoleManager.ROLE_DIALER) && roleManager.isRoleHeld(RoleManager.ROLE_DIALER)
} else {
telecomManager.defaultDialerPackage == packageName
}
}
fun Context.getContactsHasMap(withComparableNumbers: Boolean = false, callback: (HashMap<String, String>) -> Unit) {
ContactsHelper(this).getContacts(showOnlyContactsWithNumbers = true) { contactList ->
val privateContacts: HashMap<String, String> = HashMap()
for (contact in contactList) {
for (phoneNumber in contact.phoneNumbers) {
var number = PhoneNumberUtils.stripSeparators(phoneNumber.value)
if (withComparableNumbers) {
number = number.trimToComparableNumber()
}
privateContacts[number] = contact.name
}
}
callback(privateContacts)
}
}
@TargetApi(Build.VERSION_CODES.N)
fun Context.getBlockedNumbersWithContact(callback: (ArrayList<BlockedNumber>) -> Unit) {
getContactsHasMap(true) { contacts ->
val blockedNumbers = ArrayList<BlockedNumber>()
if (!isNougatPlus() || !isDefaultDialer()) {
callback(blockedNumbers)
}
val uri = BlockedNumbers.CONTENT_URI
val projection = arrayOf(
BlockedNumbers.COLUMN_ID,
BlockedNumbers.COLUMN_ORIGINAL_NUMBER,
BlockedNumbers.COLUMN_E164_NUMBER,
)
queryCursor(uri, projection) { cursor ->
val id = cursor.getLongValue(BlockedNumbers.COLUMN_ID)
val number = cursor.getStringValue(BlockedNumbers.COLUMN_ORIGINAL_NUMBER) ?: ""
val normalizedNumber = cursor.getStringValue(BlockedNumbers.COLUMN_E164_NUMBER) ?: number
val comparableNumber = normalizedNumber.trimToComparableNumber()
val contactName = contacts[comparableNumber]
val blockedNumber = BlockedNumber(id, number, normalizedNumber, comparableNumber, contactName)
blockedNumbers.add(blockedNumber)
}
val blockedNumbersPair = blockedNumbers.partition { it.contactName != null }
val blockedNumbersWithNameSorted = blockedNumbersPair.first.sortedBy { it.contactName }
val blockedNumbersNoNameSorted = blockedNumbersPair.second.sortedBy { it.number }
callback(ArrayList(blockedNumbersWithNameSorted + blockedNumbersNoNameSorted))
}
}
@TargetApi(Build.VERSION_CODES.N)
fun Context.getBlockedNumbers(): ArrayList<BlockedNumber> {
val blockedNumbers = ArrayList<BlockedNumber>()
if (!isNougatPlus() || !isDefaultDialer()) {
return blockedNumbers
}
val uri = BlockedNumbers.CONTENT_URI
val projection = arrayOf(
BlockedNumbers.COLUMN_ID,
BlockedNumbers.COLUMN_ORIGINAL_NUMBER,
BlockedNumbers.COLUMN_E164_NUMBER
)
queryCursor(uri, projection) { cursor ->
val id = cursor.getLongValue(BlockedNumbers.COLUMN_ID)
val number = cursor.getStringValue(BlockedNumbers.COLUMN_ORIGINAL_NUMBER) ?: ""
val normalizedNumber = cursor.getStringValue(BlockedNumbers.COLUMN_E164_NUMBER) ?: number
val comparableNumber = normalizedNumber.trimToComparableNumber()
val blockedNumber = BlockedNumber(id, number, normalizedNumber, comparableNumber)
blockedNumbers.add(blockedNumber)
}
return blockedNumbers
}
@TargetApi(Build.VERSION_CODES.N)
fun Context.addBlockedNumber(number: String): Boolean {
ContentValues().apply {
put(BlockedNumbers.COLUMN_ORIGINAL_NUMBER, number)
if (number.isPhoneNumber()) {
put(BlockedNumbers.COLUMN_E164_NUMBER, PhoneNumberUtils.normalizeNumber(number))
}
try {
contentResolver.insert(BlockedNumbers.CONTENT_URI, this)
} catch (e: Exception) {
showErrorToast(e)
return false
}
}
return true
}
@TargetApi(Build.VERSION_CODES.N)
fun Context.deleteBlockedNumber(number: String): Boolean {
val selection = "${BlockedNumbers.COLUMN_ORIGINAL_NUMBER} = ?"
val selectionArgs = arrayOf(number)
return if (isNumberBlocked(number)) {
val deletedRowCount = contentResolver.delete(BlockedNumbers.CONTENT_URI, selection, selectionArgs)
deletedRowCount > 0
} else {
true
}
}
fun Context.isNumberBlocked(number: String, blockedNumbers: ArrayList<BlockedNumber> = getBlockedNumbers()): Boolean {
if (!isNougatPlus()) {
return false
}
val numberToCompare = number.trimToComparableNumber()
return blockedNumbers.any {
numberToCompare == it.numberToCompare ||
numberToCompare == it.number ||
PhoneNumberUtils.stripSeparators(number) == it.number
} || isNumberBlockedByPattern(number, blockedNumbers)
}
fun Context.isNumberBlockedByPattern(number: String, blockedNumbers: ArrayList<BlockedNumber> = getBlockedNumbers()): Boolean {
for (blockedNumber in blockedNumbers) {
val num = blockedNumber.number
if (num.isBlockedNumberPattern()) {
val pattern = num.replace("+", "\\+").replace("*", ".*")
if (number.matches(pattern.toRegex())) {
return true
}
}
}
return false
}
fun Context.copyToClipboard(text: String) {
val clip = ClipData.newPlainText(getString(R.string.simple_commons), text)
(getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager).setPrimaryClip(clip)
val toastText = String.format(getString(R.string.value_copied_to_clipboard_show), text)
toast(toastText)
}
fun Context.getPhoneNumberTypeText(type: Int, label: String): String {
return if (type == BaseTypes.TYPE_CUSTOM) {
label
} else {
getString(
when (type) {
Phone.TYPE_MOBILE -> R.string.mobile
Phone.TYPE_HOME -> R.string.home
Phone.TYPE_WORK -> R.string.work
Phone.TYPE_MAIN -> R.string.main_number
Phone.TYPE_FAX_WORK -> R.string.work_fax
Phone.TYPE_FAX_HOME -> R.string.home_fax
Phone.TYPE_PAGER -> R.string.pager
else -> R.string.other
}
)
}
}
fun Context.updateBottomTabItemColors(view: View?, isActive: Boolean, drawableId: Int? = null) {
val color = if (isActive) {
getProperPrimaryColor()
} else {
getProperTextColor()
}
if (drawableId != null) {
val drawable = ResourcesCompat.getDrawable(resources, drawableId, theme)
view?.findViewById<ImageView>(R.id.tab_item_icon)?.setImageDrawable(drawable)
}
view?.findViewById<ImageView>(R.id.tab_item_icon)?.applyColorFilter(color)
view?.findViewById<TextView>(R.id.tab_item_label)?.setTextColor(color)
}
fun Context.sendEmailIntent(recipient: String) {
Intent(Intent.ACTION_SENDTO).apply {
data = Uri.fromParts(KEY_MAILTO, recipient, null)
launchActivityIntent(this)
}
}
fun Context.openNotificationSettings() {
if (isOreoPlus()) {
val intent = Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS)
intent.putExtra(Settings.EXTRA_APP_PACKAGE, packageName)
startActivity(intent)
} else {
// For Android versions below Oreo, you can't directly open the app's notification settings.
// You can open the general notification settings instead.
val intent = Intent(Settings.ACTION_SETTINGS)
startActivity(intent)
}
}
fun Context.getTempFile(folderName: String, filename: String): File? {
val folder = File(cacheDir, folderName)
if (!folder.exists()) {
if (!folder.mkdir()) {
toast(R.string.unknown_error_occurred)
return null
}
}
return File(folder, filename)
}
fun Context.openDeviceSettings() {
val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply {
data = Uri.fromParts("package", packageName, null)
}
try {
startActivity(intent)
} catch (e: Exception) {
showErrorToast(e)
}
}
@RequiresApi(Build.VERSION_CODES.S)
fun Context.openRequestExactAlarmSettings(appId: String) {
if (isSPlus()) {
val uri = Uri.fromParts("package", appId, null)
val intent = Intent(Settings.ACTION_REQUEST_SCHEDULE_EXACT_ALARM)
intent.data = uri
startActivity(intent)
}
}
fun Context.canUseFullScreenIntent(): Boolean {
return !isUpsideDownCakePlus() || notificationManager.canUseFullScreenIntent()
}
@RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
fun Context.openFullScreenIntentSettings(appId: String) {
if (isUpsideDownCakePlus()) {
val uri = Uri.fromParts("package", appId, null)
val intent = Intent(Settings.ACTION_MANAGE_APP_USE_FULL_SCREEN_INTENT)
intent.data = uri
startActivity(intent)
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/extensions/Context.kt | 3920653500 |
package com.simplemobiletools.commons.extensions
import android.widget.SeekBar
fun SeekBar.onSeekBarChangeListener(seekBarChangeListener: (progress: Int) -> Unit) = setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
seekBarChangeListener(progress)
}
override fun onStartTrackingTouch(seekBar: SeekBar) {}
override fun onStopTrackingTouch(seekBar: SeekBar) {}
})
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/extensions/SeekBar.kt | 1821892594 |
package com.simplemobiletools.commons.extensions
import android.content.Context
import com.simplemobiletools.commons.helpers.*
import com.simplemobiletools.commons.models.FileDirItem
import java.io.File
import java.util.*
fun File.isMediaFile() = absolutePath.isMediaFile()
fun File.isGif() = absolutePath.endsWith(".gif", true)
fun File.isApng() = absolutePath.endsWith(".apng", true)
fun File.isVideoFast() = videoExtensions.any { absolutePath.endsWith(it, true) }
fun File.isImageFast() = photoExtensions.any { absolutePath.endsWith(it, true) }
fun File.isAudioFast() = audioExtensions.any { absolutePath.endsWith(it, true) }
fun File.isRawFast() = rawExtensions.any { absolutePath.endsWith(it, true) }
fun File.isSvg() = absolutePath.isSvg()
fun File.isPortrait() = absolutePath.isPortrait()
fun File.isImageSlow() = absolutePath.isImageFast() || getMimeType().startsWith("image")
fun File.isVideoSlow() = absolutePath.isVideoFast() || getMimeType().startsWith("video")
fun File.isAudioSlow() = absolutePath.isAudioFast() || getMimeType().startsWith("audio")
fun File.getMimeType() = absolutePath.getMimeType()
fun File.getProperSize(countHiddenItems: Boolean): Long {
return if (isDirectory) {
getDirectorySize(this, countHiddenItems)
} else {
length()
}
}
private fun getDirectorySize(dir: File, countHiddenItems: Boolean): Long {
var size = 0L
if (dir.exists()) {
val files = dir.listFiles()
if (files != null) {
for (i in files.indices) {
if (files[i].isDirectory) {
size += getDirectorySize(files[i], countHiddenItems)
} else if (!files[i].name.startsWith('.') && !dir.name.startsWith('.') || countHiddenItems) {
size += files[i].length()
}
}
}
}
return size
}
fun File.getFileCount(countHiddenItems: Boolean): Int {
return if (isDirectory) {
getDirectoryFileCount(this, countHiddenItems)
} else {
1
}
}
private fun getDirectoryFileCount(dir: File, countHiddenItems: Boolean): Int {
var count = -1
if (dir.exists()) {
val files = dir.listFiles()
if (files != null) {
count++
for (i in files.indices) {
val file = files[i]
if (file.isDirectory) {
count++
count += getDirectoryFileCount(file, countHiddenItems)
} else if (!file.name.startsWith('.') || countHiddenItems) {
count++
}
}
}
}
return count
}
fun File.getDirectChildrenCount(context: Context, countHiddenItems: Boolean): Int {
val fileCount = if (context.isRestrictedSAFOnlyRoot(path)) {
context.getAndroidSAFDirectChildrenCount(
path,
countHiddenItems
)
} else {
listFiles()?.filter {
if (countHiddenItems) {
true
} else {
!it.name.startsWith('.')
}
}?.size ?: 0
}
return fileCount
}
fun File.toFileDirItem(context: Context) = FileDirItem(absolutePath, name, context.getIsPathDirectory(absolutePath), 0, length(), lastModified())
fun File.containsNoMedia(): Boolean {
return if (!isDirectory) {
false
} else {
File(this, NOMEDIA).exists()
}
}
fun File.doesThisOrParentHaveNoMedia(
folderNoMediaStatuses: HashMap<String, Boolean>,
callback: ((path: String, hasNoMedia: Boolean) -> Unit)?
): Boolean {
var curFile = this
while (true) {
val noMediaPath = "${curFile.absolutePath}/$NOMEDIA"
val hasNoMedia = if (folderNoMediaStatuses.keys.contains(noMediaPath)) {
folderNoMediaStatuses[noMediaPath]!!
} else {
val contains = curFile.containsNoMedia()
callback?.invoke(curFile.absolutePath, contains)
contains
}
if (hasNoMedia) {
return true
}
curFile = curFile.parentFile ?: break
if (curFile.absolutePath == "/") {
break
}
}
return false
}
fun File.doesParentHaveNoMedia(): Boolean {
var curFile = parentFile
while (true) {
if (curFile?.containsNoMedia() == true) {
return true
}
curFile = curFile?.parentFile ?: break
if (curFile.absolutePath == "/") {
break
}
}
return false
}
fun File.getDigest(algorithm: String): String? {
return try {
inputStream().getDigest(algorithm)
} catch (e: Exception) {
null
}
}
fun File.md5() = this.getDigest(MD5)
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/extensions/File.kt | 533036373 |
package com.simplemobiletools.commons.extensions
import android.content.Context
import android.view.HapticFeedbackConstants
import android.view.View
import android.view.ViewTreeObserver
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.helpers.SHORT_ANIMATION_DURATION
fun View.beInvisibleIf(beInvisible: Boolean) = if (beInvisible) beInvisible() else beVisible()
fun View.beVisibleIf(beVisible: Boolean) = if (beVisible) beVisible() else beGone()
fun View.beGoneIf(beGone: Boolean) = beVisibleIf(!beGone)
fun View.beInvisible() {
visibility = View.INVISIBLE
}
fun View.beVisible() {
visibility = View.VISIBLE
}
fun View.beGone() {
visibility = View.GONE
}
fun View.onGlobalLayout(callback: () -> Unit) {
viewTreeObserver?.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
if (viewTreeObserver != null) {
viewTreeObserver.removeOnGlobalLayoutListener(this)
callback()
}
}
})
}
fun View.isVisible() = visibility == View.VISIBLE
fun View.isInvisible() = visibility == View.INVISIBLE
fun View.isGone() = visibility == View.GONE
fun View.performHapticFeedback() = performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY, HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING)
fun View.fadeIn() {
animate().alpha(1f).setDuration(SHORT_ANIMATION_DURATION).withStartAction { beVisible() }.start()
}
fun View.fadeOut() {
animate().alpha(0f).setDuration(SHORT_ANIMATION_DURATION).withEndAction { beGone() }.start()
}
fun View.setupViewBackground(context: Context) {
background = if (context.baseConfig.isUsingSystemTheme) {
resources.getDrawable(R.drawable.selector_clickable_you)
} else {
resources.getDrawable(R.drawable.selector_clickable)
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/extensions/View.kt | 2528512062 |
package com.simplemobiletools.commons.extensions
import android.content.Context
import android.content.res.ColorStateList
import android.graphics.Color
import android.media.ExifInterface
import android.os.Handler
import android.os.Looper
import android.text.format.DateFormat
import android.text.format.DateUtils
import android.text.format.Time
import androidx.core.os.postDelayed
import com.simplemobiletools.commons.helpers.DARK_GREY
import java.text.DecimalFormat
import java.util.Calendar
import java.util.Locale
import java.util.Random
fun Int.getContrastColor(): Int {
val y = (299 * Color.red(this) + 587 * Color.green(this) + 114 * Color.blue(this)) / 1000
return if (y >= 149 && this != Color.BLACK) DARK_GREY else Color.WHITE
}
fun Int.toHex() = String.format("#%06X", 0xFFFFFF and this).toUpperCase()
fun Int.adjustAlpha(factor: Float): Int {
val alpha = Math.round(Color.alpha(this) * factor)
val red = Color.red(this)
val green = Color.green(this)
val blue = Color.blue(this)
return Color.argb(alpha, red, green, blue)
}
fun Int.getFormattedDuration(forceShowHours: Boolean = false): String {
val sb = StringBuilder(8)
val hours = this / 3600
val minutes = this % 3600 / 60
val seconds = this % 60
if (this >= 3600) {
sb.append(String.format(Locale.getDefault(), "%02d", hours)).append(":")
} else if (forceShowHours) {
sb.append("0:")
}
sb.append(String.format(Locale.getDefault(), "%02d", minutes))
sb.append(":").append(String.format(Locale.getDefault(), "%02d", seconds))
return sb.toString()
}
fun Int.formatSize(): String {
if (this <= 0) {
return "0 B"
}
val units = arrayOf("B", "kB", "MB", "GB", "TB")
val digitGroups = (Math.log10(toDouble()) / Math.log10(1024.0)).toInt()
return "${DecimalFormat("#,##0.#").format(this / Math.pow(1024.0, digitGroups.toDouble()))} ${units[digitGroups]}"
}
fun Int.formatDate(context: Context, dateFormat: String? = null, timeFormat: String? = null): String {
val useDateFormat = dateFormat ?: context.baseConfig.dateFormat
val useTimeFormat = timeFormat ?: context.getTimeFormat()
val cal = Calendar.getInstance(Locale.ENGLISH)
cal.timeInMillis = this * 1000L
return DateFormat.format("$useDateFormat, $useTimeFormat", cal).toString()
}
// if the given date is today, we show only the time. Else we show the date and optionally the time too
fun Int.formatDateOrTime(context: Context, hideTimeAtOtherDays: Boolean, showYearEvenIfCurrent: Boolean): String {
val cal = Calendar.getInstance(Locale.ENGLISH)
cal.timeInMillis = this * 1000L
return if (DateUtils.isToday(this * 1000L)) {
DateFormat.format(context.getTimeFormat(), cal).toString()
} else {
var format = context.baseConfig.dateFormat
if (!showYearEvenIfCurrent && isThisYear()) {
format = format.replace("y", "").trim().trim('-').trim('.').trim('/')
}
if (!hideTimeAtOtherDays) {
format += ", ${context.getTimeFormat()}"
}
DateFormat.format(format, cal).toString()
}
}
fun Int.isThisYear(): Boolean {
val time = Time()
time.set(this * 1000L)
val thenYear = time.year
time.set(System.currentTimeMillis())
return (thenYear == time.year)
}
fun Int.addBitIf(add: Boolean, bit: Int) =
if (add) {
addBit(bit)
} else {
removeBit(bit)
}
// TODO: how to do "bits & ~bit" in kotlin?
fun Int.removeBit(bit: Int) = addBit(bit) - bit
fun Int.addBit(bit: Int) = this or bit
fun Int.flipBit(bit: Int) = if (this and bit == 0) addBit(bit) else removeBit(bit)
fun ClosedRange<Int>.random() = Random().nextInt(endInclusive - start) + start
// taken from https://stackoverflow.com/a/40964456/1967672
fun Int.darkenColor(factor: Int = 8): Int {
if (this == Color.WHITE || this == Color.BLACK) {
return this
}
val DARK_FACTOR = factor
var hsv = FloatArray(3)
Color.colorToHSV(this, hsv)
val hsl = hsv2hsl(hsv)
hsl[2] -= DARK_FACTOR / 100f
if (hsl[2] < 0)
hsl[2] = 0f
hsv = hsl2hsv(hsl)
return Color.HSVToColor(hsv)
}
fun Int.lightenColor(factor: Int = 8): Int {
if (this == Color.WHITE || this == Color.BLACK) {
return this
}
val LIGHT_FACTOR = factor
var hsv = FloatArray(3)
Color.colorToHSV(this, hsv)
val hsl = hsv2hsl(hsv)
hsl[2] += LIGHT_FACTOR / 100f
if (hsl[2] < 0)
hsl[2] = 0f
hsv = hsl2hsv(hsl)
return Color.HSVToColor(hsv)
}
private fun hsl2hsv(hsl: FloatArray): FloatArray {
val hue = hsl[0]
var sat = hsl[1]
val light = hsl[2]
sat *= if (light < .5) light else 1 - light
return floatArrayOf(hue, 2f * sat / (light + sat), light + sat)
}
private fun hsv2hsl(hsv: FloatArray): FloatArray {
val hue = hsv[0]
val sat = hsv[1]
val value = hsv[2]
val newHue = (2f - sat) * value
var newSat = sat * value / if (newHue < 1f) newHue else 2f - newHue
if (newSat > 1f)
newSat = 1f
return floatArrayOf(hue, newSat, newHue / 2f)
}
fun Int.orientationFromDegrees() = when (this) {
270 -> ExifInterface.ORIENTATION_ROTATE_270
180 -> ExifInterface.ORIENTATION_ROTATE_180
90 -> ExifInterface.ORIENTATION_ROTATE_90
else -> ExifInterface.ORIENTATION_NORMAL
}.toString()
fun Int.degreesFromOrientation() = when (this) {
ExifInterface.ORIENTATION_ROTATE_270 -> 270
ExifInterface.ORIENTATION_ROTATE_180 -> 180
ExifInterface.ORIENTATION_ROTATE_90 -> 90
else -> 0
}
fun Int.ensureTwoDigits(): String {
return if (toString().length == 1) {
"0$this"
} else {
toString()
}
}
fun Int.getColorStateList(): ColorStateList {
val states = arrayOf(
intArrayOf(android.R.attr.state_enabled),
intArrayOf(-android.R.attr.state_enabled),
intArrayOf(-android.R.attr.state_checked),
intArrayOf(android.R.attr.state_pressed)
)
val colors = intArrayOf(this, this, this, this)
return ColorStateList(states, colors)
}
fun Int.countdown(intervalMillis: Long, callback: (count: Int) -> Unit) {
callback(this)
if (this == 0) {
return
}
Handler(Looper.getMainLooper()).postDelayed(intervalMillis) {
(this - 1).countdown(intervalMillis, callback)
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/extensions/Int.kt | 1648520321 |
package com.simplemobiletools.commons.extensions
import android.graphics.Color
import android.view.View
import android.widget.RemoteViews
fun RemoteViews.setBackgroundColor(id: Int, color: Int) {
setInt(id, "setBackgroundColor", color)
}
fun RemoteViews.setTextSize(id: Int, size: Float) {
setFloat(id, "setTextSize", size)
}
fun RemoteViews.setText(id: Int, text: String) {
setTextViewText(id, text)
}
fun RemoteViews.setVisibleIf(id: Int, beVisible: Boolean) {
val visibility = if (beVisible) View.VISIBLE else View.GONE
setViewVisibility(id, visibility)
}
fun RemoteViews.applyColorFilter(id: Int, color: Int) {
setInt(id, "setColorFilter", color)
setInt(id, "setImageAlpha", Color.alpha(color))
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/extensions/RemoteViews.kt | 1602882271 |
package com.simplemobiletools.commons.extensions
import android.database.Cursor
fun Cursor.getStringValue(key: String) = getString(getColumnIndex(key))
fun Cursor.getStringValueOrNull(key: String) = if (isNull(getColumnIndex(key))) null else getString(getColumnIndex(key))
fun Cursor.getIntValue(key: String) = getInt(getColumnIndex(key))
fun Cursor.getIntValueOrNull(key: String) = if (isNull(getColumnIndex(key))) null else getInt(getColumnIndex(key))
fun Cursor.getLongValue(key: String) = getLong(getColumnIndex(key))
fun Cursor.getLongValueOrNull(key: String) = if (isNull(getColumnIndex(key))) null else getLong(getColumnIndex(key))
fun Cursor.getBlobValue(key: String) = getBlob(getColumnIndex(key))
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/extensions/Cursor.kt | 4261146913 |
package com.simplemobiletools.commons.extensions
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Point
import android.os.Build
import android.os.StatFs
import android.provider.MediaStore
import android.telephony.PhoneNumberUtils
import android.text.*
import android.text.style.ForegroundColorSpan
import android.widget.TextView
import com.bumptech.glide.signature.ObjectKey
import com.simplemobiletools.commons.helpers.*
import java.io.File
import java.text.DateFormat
import java.text.Normalizer
import java.text.SimpleDateFormat
import java.util.Locale
import java.util.regex.Pattern
import org.joda.time.DateTime
import org.joda.time.Years
import org.joda.time.format.DateTimeFormat
fun String.getFilenameFromPath() = substring(lastIndexOf("/") + 1)
fun String.getFilenameExtension() = substring(lastIndexOf(".") + 1)
fun String.getBasePath(context: Context): String {
return when {
startsWith(context.internalStoragePath) -> context.internalStoragePath
context.isPathOnSD(this) -> context.sdCardPath
context.isPathOnOTG(this) -> context.otgPath
else -> "/"
}
}
fun String.getFirstParentDirName(context: Context, level: Int): String? {
val basePath = getBasePath(context)
val startIndex = basePath.length + 1
return if (length > startIndex) {
val pathWithoutBasePath = substring(startIndex)
val pathSegments = pathWithoutBasePath.split("/")
if (level < pathSegments.size) {
pathSegments.slice(0..level).joinToString("/")
} else {
null
}
} else {
null
}
}
fun String.getFirstParentPath(context: Context, level: Int): String {
val basePath = getBasePath(context)
val startIndex = basePath.length + 1
return if (length > startIndex) {
val pathWithoutBasePath = substring(basePath.length + 1)
val pathSegments = pathWithoutBasePath.split("/")
val firstParentPath = if (level < pathSegments.size) {
pathSegments.slice(0..level).joinToString("/")
} else {
pathWithoutBasePath
}
"$basePath/$firstParentPath"
} else {
basePath
}
}
fun String.isAValidFilename(): Boolean {
val ILLEGAL_CHARACTERS = charArrayOf('/', '\n', '\r', '\t', '\u0000', '`', '?', '*', '\\', '<', '>', '|', '\"', ':')
ILLEGAL_CHARACTERS.forEach {
if (contains(it))
return false
}
return true
}
fun String.getOTGPublicPath(context: Context) =
"${context.baseConfig.OTGTreeUri}/document/${context.baseConfig.OTGPartition}%3A${substring(context.baseConfig.OTGPath.length).replace("/", "%2F")}"
fun String.isMediaFile() = isImageFast() || isVideoFast() || isGif() || isRawFast() || isSvg() || isPortrait()
fun String.isWebP() = endsWith(".webp", true)
fun String.isGif() = endsWith(".gif", true)
fun String.isPng() = endsWith(".png", true)
fun String.isApng() = endsWith(".apng", true)
fun String.isJpg() = endsWith(".jpg", true) or endsWith(".jpeg", true)
fun String.isSvg() = endsWith(".svg", true)
fun String.isPortrait() = getFilenameFromPath().contains("portrait", true) && File(this).parentFile?.name?.startsWith("img_", true) == true
// fast extension checks, not guaranteed to be accurate
fun String.isVideoFast() = videoExtensions.any { endsWith(it, true) }
fun String.isImageFast() = photoExtensions.any { endsWith(it, true) }
fun String.isAudioFast() = audioExtensions.any { endsWith(it, true) }
fun String.isRawFast() = rawExtensions.any { endsWith(it, true) }
fun String.isImageSlow() = isImageFast() || getMimeType().startsWith("image") || startsWith(MediaStore.Images.Media.EXTERNAL_CONTENT_URI.toString())
fun String.isVideoSlow() = isVideoFast() || getMimeType().startsWith("video") || startsWith(MediaStore.Video.Media.EXTERNAL_CONTENT_URI.toString())
fun String.isAudioSlow() = isAudioFast() || getMimeType().startsWith("audio") || startsWith(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI.toString())
fun String.canModifyEXIF() = extensionsSupportingEXIF.any { endsWith(it, true) }
fun String.getCompressionFormat() = when (getFilenameExtension().toLowerCase()) {
"png" -> Bitmap.CompressFormat.PNG
"webp" -> Bitmap.CompressFormat.WEBP
else -> Bitmap.CompressFormat.JPEG
}
fun String.areDigitsOnly() = matches(Regex("[0-9]+"))
fun String.areLettersOnly() = matches(Regex("[a-zA-Z]+"))
fun String.getGenericMimeType(): String {
if (!contains("/"))
return this
val type = substring(0, indexOf("/"))
return "$type/*"
}
fun String.getParentPath() = removeSuffix("/${getFilenameFromPath()}")
fun String.relativizeWith(path: String) = this.substring(path.length)
fun String.containsNoMedia() = File(this).containsNoMedia()
fun String.doesThisOrParentHaveNoMedia(folderNoMediaStatuses: HashMap<String, Boolean>, callback: ((path: String, hasNoMedia: Boolean) -> Unit)?) =
File(this).doesThisOrParentHaveNoMedia(folderNoMediaStatuses, callback)
fun String.getImageResolution(context: Context): Point? {
val options = BitmapFactory.Options()
options.inJustDecodeBounds = true
if (context.isRestrictedSAFOnlyRoot(this)) {
BitmapFactory.decodeStream(context.contentResolver.openInputStream(context.getAndroidSAFUri(this)), null, options)
} else {
BitmapFactory.decodeFile(this, options)
}
val width = options.outWidth
val height = options.outHeight
return if (width > 0 && height > 0) {
Point(options.outWidth, options.outHeight)
} else {
null
}
}
fun String.getPublicUri(context: Context) = context.getDocumentFile(this)?.uri ?: ""
fun String.substringTo(cnt: Int): String {
return if (isEmpty()) {
""
} else {
substring(0, Math.min(length, cnt))
}
}
fun String.highlightTextPart(textToHighlight: String, color: Int, highlightAll: Boolean = false, ignoreCharsBetweenDigits: Boolean = false): SpannableString {
val spannableString = SpannableString(this)
if (textToHighlight.isEmpty()) {
return spannableString
}
var startIndex = normalizeString().indexOf(textToHighlight, 0, true)
val indexes = ArrayList<Int>()
while (startIndex >= 0) {
if (startIndex != -1) {
indexes.add(startIndex)
}
startIndex = normalizeString().indexOf(textToHighlight, startIndex + textToHighlight.length, true)
if (!highlightAll) {
break
}
}
// handle cases when we search for 643, but in reality the string contains it like 6-43
if (ignoreCharsBetweenDigits && indexes.isEmpty()) {
try {
val regex = TextUtils.join("(\\D*)", textToHighlight.toCharArray().toTypedArray())
val pattern = Pattern.compile(regex)
val result = pattern.matcher(normalizeString())
if (result.find()) {
spannableString.setSpan(ForegroundColorSpan(color), result.start(), result.end(), Spannable.SPAN_EXCLUSIVE_INCLUSIVE)
}
} catch (ignored: Exception) {
}
return spannableString
}
indexes.forEach {
val endIndex = Math.min(it + textToHighlight.length, length)
try {
spannableString.setSpan(ForegroundColorSpan(color), it, endIndex, Spannable.SPAN_EXCLUSIVE_INCLUSIVE)
} catch (ignored: IndexOutOfBoundsException) {
}
}
return spannableString
}
fun String.searchMatches(textToHighlight: String): ArrayList<Int> {
val indexes = arrayListOf<Int>()
var indexOf = indexOf(textToHighlight, 0, true)
var offset = 0
while (offset < length && indexOf != -1) {
indexOf = indexOf(textToHighlight, offset, true)
if (indexOf == -1) {
break
} else {
indexes.add(indexOf)
}
offset = indexOf + 1
}
return indexes
}
fun String.getFileSignature(lastModified: Long? = null) = ObjectKey(getFileKey(lastModified))
fun String.getFileKey(lastModified: Long? = null): String {
val file = File(this)
val modified = if (lastModified != null && lastModified > 0) {
lastModified
} else {
file.lastModified()
}
return "${file.absolutePath}$modified"
}
fun String.getAvailableStorageB(): Long {
return try {
val stat = StatFs(this)
val bytesAvailable = stat.blockSizeLong * stat.availableBlocksLong
bytesAvailable
} catch (e: Exception) {
-1L
}
}
// remove diacritics, for example č -> c
fun String.normalizeString() = Normalizer.normalize(this, Normalizer.Form.NFD).replace(normalizeRegex, "")
// checks if string is a phone number
fun String.isPhoneNumber(): Boolean {
return this.matches("^[0-9+\\-\\)\\( *#]+\$".toRegex())
}
// if we are comparing phone numbers, compare just the last 9 digits
fun String.trimToComparableNumber(): String {
// don't trim if it's not a phone number
if (!this.isPhoneNumber()) {
return this
}
val normalizedNumber = this.normalizeString()
val startIndex = Math.max(0, normalizedNumber.length - 9)
return normalizedNumber.substring(startIndex)
}
// get the contact names first letter at showing the placeholder without image
fun String.getNameLetter() = normalizeString().toCharArray().getOrNull(0)?.toString()?.toUpperCase(Locale.getDefault()) ?: "A"
fun String.normalizePhoneNumber() = PhoneNumberUtils.normalizeNumber(this)
fun String.highlightTextFromNumbers(textToHighlight: String, primaryColor: Int): SpannableString {
val spannableString = SpannableString(this)
val digits = PhoneNumberUtils.convertKeypadLettersToDigits(this)
if (digits.contains(textToHighlight)) {
val startIndex = digits.indexOf(textToHighlight, 0, true)
val endIndex = Math.min(startIndex + textToHighlight.length, length)
try {
spannableString.setSpan(ForegroundColorSpan(primaryColor), startIndex, endIndex, Spannable.SPAN_EXCLUSIVE_INCLUSIVE)
} catch (ignored: IndexOutOfBoundsException) {
}
}
return spannableString
}
fun String.getDateTimeFromDateString(showYearsSince: Boolean, viewToUpdate: TextView? = null): DateTime {
val dateFormats = getDateFormats()
var date = DateTime()
for (format in dateFormats) {
try {
date = DateTime.parse(this, DateTimeFormat.forPattern(format))
val formatter = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.getDefault())
var localPattern = (formatter as SimpleDateFormat).toLocalizedPattern()
val hasYear = format.contains("y")
if (!hasYear) {
localPattern = localPattern.replace("y", "").replace(",", "").trim()
date = date.withYear(DateTime().year)
}
var formattedString = date.toString(localPattern)
if (showYearsSince && hasYear) {
formattedString += " (${Years.yearsBetween(date, DateTime.now()).years})"
}
viewToUpdate?.text = formattedString
break
} catch (ignored: Exception) {
}
}
return date
}
fun String.getMimeType(): String {
val typesMap = HashMap<String, String>().apply {
put("323", "text/h323")
put("3g2", "video/3gpp2")
put("3gp", "video/3gpp")
put("3gp2", "video/3gpp2")
put("3gpp", "video/3gpp")
put("7z", "application/x-7z-compressed")
put("aa", "audio/audible")
put("aac", "audio/aac")
put("aaf", "application/octet-stream")
put("aax", "audio/vnd.audible.aax")
put("ac3", "audio/ac3")
put("aca", "application/octet-stream")
put("accda", "application/msaccess.addin")
put("accdb", "application/msaccess")
put("accdc", "application/msaccess.cab")
put("accde", "application/msaccess")
put("accdr", "application/msaccess.runtime")
put("accdt", "application/msaccess")
put("accdw", "application/msaccess.webapplication")
put("accft", "application/msaccess.ftemplate")
put("acx", "application/internet-property-stream")
put("addin", "text/xml")
put("ade", "application/msaccess")
put("adobebridge", "application/x-bridge-url")
put("adp", "application/msaccess")
put("adt", "audio/vnd.dlna.adts")
put("adts", "audio/aac")
put("afm", "application/octet-stream")
put("ai", "application/postscript")
put("aif", "audio/aiff")
put("aifc", "audio/aiff")
put("aiff", "audio/aiff")
put("air", "application/vnd.adobe.air-application-installer-package+zip")
put("amc", "application/mpeg")
put("anx", "application/annodex")
put("apk", "application/vnd.android.package-archive")
put("application", "application/x-ms-application")
put("art", "image/x-jg")
put("asa", "application/xml")
put("asax", "application/xml")
put("ascx", "application/xml")
put("asd", "application/octet-stream")
put("asf", "video/x-ms-asf")
put("ashx", "application/xml")
put("asi", "application/octet-stream")
put("asm", "text/plain")
put("asmx", "application/xml")
put("aspx", "application/xml")
put("asr", "video/x-ms-asf")
put("asx", "video/x-ms-asf")
put("atom", "application/atom+xml")
put("au", "audio/basic")
put("avi", "video/x-msvideo")
put("axa", "audio/annodex")
put("axs", "application/olescript")
put("axv", "video/annodex")
put("bas", "text/plain")
put("bcpio", "application/x-bcpio")
put("bin", "application/octet-stream")
put("bmp", "image/bmp")
put("c", "text/plain")
put("cab", "application/octet-stream")
put("caf", "audio/x-caf")
put("calx", "application/vnd.ms-office.calx")
put("cat", "application/vnd.ms-pki.seccat")
put("cc", "text/plain")
put("cd", "text/plain")
put("cdda", "audio/aiff")
put("cdf", "application/x-cdf")
put("cer", "application/x-x509-ca-cert")
put("cfg", "text/plain")
put("chm", "application/octet-stream")
put("class", "application/x-java-applet")
put("clp", "application/x-msclip")
put("cmd", "text/plain")
put("cmx", "image/x-cmx")
put("cnf", "text/plain")
put("cod", "image/cis-cod")
put("config", "application/xml")
put("contact", "text/x-ms-contact")
put("coverage", "application/xml")
put("cpio", "application/x-cpio")
put("cpp", "text/plain")
put("crd", "application/x-mscardfile")
put("crl", "application/pkix-crl")
put("crt", "application/x-x509-ca-cert")
put("cs", "text/plain")
put("csdproj", "text/plain")
put("csh", "application/x-csh")
put("csproj", "text/plain")
put("css", "text/css")
put("csv", "text/csv")
put("cur", "application/octet-stream")
put("cxx", "text/plain")
put("dat", "application/octet-stream")
put("datasource", "application/xml")
put("dbproj", "text/plain")
put("dcr", "application/x-director")
put("def", "text/plain")
put("deploy", "application/octet-stream")
put("der", "application/x-x509-ca-cert")
put("dgml", "application/xml")
put("dib", "image/bmp")
put("dif", "video/x-dv")
put("dir", "application/x-director")
put("disco", "text/xml")
put("divx", "video/divx")
put("dll", "application/x-msdownload")
put("dll.config", "text/xml")
put("dlm", "text/dlm")
put("dng", "image/x-adobe-dng")
put("doc", "application/msword")
put("docm", "application/vnd.ms-word.document.macroEnabled.12")
put("docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document")
put("dot", "application/msword")
put("dotm", "application/vnd.ms-word.template.macroEnabled.12")
put("dotx", "application/vnd.openxmlformats-officedocument.wordprocessingml.template")
put("dsp", "application/octet-stream")
put("dsw", "text/plain")
put("dtd", "text/xml")
put("dtsconfig", "text/xml")
put("dv", "video/x-dv")
put("dvi", "application/x-dvi")
put("dwf", "drawing/x-dwf")
put("dwp", "application/octet-stream")
put("dxr", "application/x-director")
put("eml", "message/rfc822")
put("emz", "application/octet-stream")
put("eot", "application/vnd.ms-fontobject")
put("eps", "application/postscript")
put("etl", "application/etl")
put("etx", "text/x-setext")
put("evy", "application/envoy")
put("exe", "application/octet-stream")
put("exe.config", "text/xml")
put("fdf", "application/vnd.fdf")
put("fif", "application/fractals")
put("filters", "application/xml")
put("fla", "application/octet-stream")
put("flac", "audio/flac")
put("flr", "x-world/x-vrml")
put("flv", "video/x-flv")
put("fsscript", "application/fsharp-script")
put("fsx", "application/fsharp-script")
put("generictest", "application/xml")
put("gif", "image/gif")
put("group", "text/x-ms-group")
put("gsm", "audio/x-gsm")
put("gtar", "application/x-gtar")
put("gz", "application/x-gzip")
put("h", "text/plain")
put("hdf", "application/x-hdf")
put("hdml", "text/x-hdml")
put("hhc", "application/x-oleobject")
put("hhk", "application/octet-stream")
put("hhp", "application/octet-stream")
put("hlp", "application/winhlp")
put("hpp", "text/plain")
put("hqx", "application/mac-binhex40")
put("hta", "application/hta")
put("htc", "text/x-component")
put("htm", "text/html")
put("html", "text/html")
put("htt", "text/webviewhtml")
put("hxa", "application/xml")
put("hxc", "application/xml")
put("hxd", "application/octet-stream")
put("hxe", "application/xml")
put("hxf", "application/xml")
put("hxh", "application/octet-stream")
put("hxi", "application/octet-stream")
put("hxk", "application/xml")
put("hxq", "application/octet-stream")
put("hxr", "application/octet-stream")
put("hxs", "application/octet-stream")
put("hxt", "text/html")
put("hxv", "application/xml")
put("hxw", "application/octet-stream")
put("hxx", "text/plain")
put("i", "text/plain")
put("ico", "image/x-icon")
put("ics", "text/calendar")
put("idl", "text/plain")
put("ief", "image/ief")
put("iii", "application/x-iphone")
put("inc", "text/plain")
put("inf", "application/octet-stream")
put("ini", "text/plain")
put("inl", "text/plain")
put("ins", "application/x-internet-signup")
put("ipa", "application/x-itunes-ipa")
put("ipg", "application/x-itunes-ipg")
put("ipproj", "text/plain")
put("ipsw", "application/x-itunes-ipsw")
put("iqy", "text/x-ms-iqy")
put("isp", "application/x-internet-signup")
put("ite", "application/x-itunes-ite")
put("itlp", "application/x-itunes-itlp")
put("itms", "application/x-itunes-itms")
put("itpc", "application/x-itunes-itpc")
put("ivf", "video/x-ivf")
put("jar", "application/java-archive")
put("java", "application/octet-stream")
put("jck", "application/liquidmotion")
put("jcz", "application/liquidmotion")
put("jfif", "image/pjpeg")
put("jnlp", "application/x-java-jnlp-file")
put("jpb", "application/octet-stream")
put("jpe", "image/jpeg")
put("jpeg", "image/jpeg")
put("jpg", "image/jpeg")
put("js", "application/javascript")
put("json", "application/json")
put("jsx", "text/jscript")
put("jsxbin", "text/plain")
put("latex", "application/x-latex")
put("library-ms", "application/windows-library+xml")
put("lit", "application/x-ms-reader")
put("loadtest", "application/xml")
put("lpk", "application/octet-stream")
put("lsf", "video/x-la-asf")
put("lst", "text/plain")
put("lsx", "video/x-la-asf")
put("lzh", "application/octet-stream")
put("m13", "application/x-msmediaview")
put("m14", "application/x-msmediaview")
put("m1v", "video/mpeg")
put("m2t", "video/vnd.dlna.mpeg-tts")
put("m2ts", "video/vnd.dlna.mpeg-tts")
put("m2v", "video/mpeg")
put("m3u", "audio/x-mpegurl")
put("m3u8", "audio/x-mpegurl")
put("m4a", "audio/m4a")
put("m4b", "audio/m4b")
put("m4p", "audio/m4p")
put("m4r", "audio/x-m4r")
put("m4v", "video/x-m4v")
put("mac", "image/x-macpaint")
put("mak", "text/plain")
put("man", "application/x-troff-man")
put("manifest", "application/x-ms-manifest")
put("map", "text/plain")
put("master", "application/xml")
put("mda", "application/msaccess")
put("mdb", "application/x-msaccess")
put("mde", "application/msaccess")
put("mdp", "application/octet-stream")
put("me", "application/x-troff-me")
put("mfp", "application/x-shockwave-flash")
put("mht", "message/rfc822")
put("mhtml", "message/rfc822")
put("mid", "audio/mid")
put("midi", "audio/mid")
put("mix", "application/octet-stream")
put("mk", "text/plain")
put("mkv", "video/x-matroska")
put("mmf", "application/x-smaf")
put("mno", "text/xml")
put("mny", "application/x-msmoney")
put("mod", "video/mpeg")
put("mov", "video/quicktime")
put("movie", "video/x-sgi-movie")
put("mp2", "video/mpeg")
put("mp2v", "video/mpeg")
put("mp3", "audio/mpeg")
put("mp4", "video/mp4")
put("mp4v", "video/mp4")
put("mpa", "video/mpeg")
put("mpe", "video/mpeg")
put("mpeg", "video/mpeg")
put("mpf", "application/vnd.ms-mediapackage")
put("mpg", "video/mpeg")
put("mpp", "application/vnd.ms-project")
put("mpv2", "video/mpeg")
put("mqv", "video/quicktime")
put("ms", "application/x-troff-ms")
put("msi", "application/octet-stream")
put("mso", "application/octet-stream")
put("mts", "video/vnd.dlna.mpeg-tts")
put("mtx", "application/xml")
put("mvb", "application/x-msmediaview")
put("mvc", "application/x-miva-compiled")
put("mxp", "application/x-mmxp")
put("nc", "application/x-netcdf")
put("nsc", "video/x-ms-asf")
put("nws", "message/rfc822")
put("ocx", "application/octet-stream")
put("oda", "application/oda")
put("odb", "application/vnd.oasis.opendocument.database")
put("odc", "application/vnd.oasis.opendocument.chart")
put("odf", "application/vnd.oasis.opendocument.formula")
put("odg", "application/vnd.oasis.opendocument.graphics")
put("odh", "text/plain")
put("odi", "application/vnd.oasis.opendocument.image")
put("odl", "text/plain")
put("odm", "application/vnd.oasis.opendocument.text-master")
put("odp", "application/vnd.oasis.opendocument.presentation")
put("ods", "application/vnd.oasis.opendocument.spreadsheet")
put("odt", "application/vnd.oasis.opendocument.text")
put("oga", "audio/ogg")
put("ogg", "audio/ogg")
put("ogv", "video/ogg")
put("ogx", "application/ogg")
put("one", "application/onenote")
put("onea", "application/onenote")
put("onepkg", "application/onenote")
put("onetmp", "application/onenote")
put("onetoc", "application/onenote")
put("onetoc2", "application/onenote")
put("opus", "audio/ogg")
put("orderedtest", "application/xml")
put("osdx", "application/opensearchdescription+xml")
put("otf", "application/font-sfnt")
put("otg", "application/vnd.oasis.opendocument.graphics-template")
put("oth", "application/vnd.oasis.opendocument.text-web")
put("otp", "application/vnd.oasis.opendocument.presentation-template")
put("ots", "application/vnd.oasis.opendocument.spreadsheet-template")
put("ott", "application/vnd.oasis.opendocument.text-template")
put("oxt", "application/vnd.openofficeorg.extension")
put("p10", "application/pkcs10")
put("p12", "application/x-pkcs12")
put("p7b", "application/x-pkcs7-certificates")
put("p7c", "application/pkcs7-mime")
put("p7m", "application/pkcs7-mime")
put("p7r", "application/x-pkcs7-certreqresp")
put("p7s", "application/pkcs7-signature")
put("pbm", "image/x-portable-bitmap")
put("pcast", "application/x-podcast")
put("pct", "image/pict")
put("pcx", "application/octet-stream")
put("pcz", "application/octet-stream")
put("pdf", "application/pdf")
put("pfb", "application/octet-stream")
put("pfm", "application/octet-stream")
put("pfx", "application/x-pkcs12")
put("pgm", "image/x-portable-graymap")
put("php", "text/plain")
put("pic", "image/pict")
put("pict", "image/pict")
put("pkgdef", "text/plain")
put("pkgundef", "text/plain")
put("pko", "application/vnd.ms-pki.pko")
put("pls", "audio/scpls")
put("pma", "application/x-perfmon")
put("pmc", "application/x-perfmon")
put("pml", "application/x-perfmon")
put("pmr", "application/x-perfmon")
put("pmw", "application/x-perfmon")
put("png", "image/png")
put("pnm", "image/x-portable-anymap")
put("pnt", "image/x-macpaint")
put("pntg", "image/x-macpaint")
put("pnz", "image/png")
put("pot", "application/vnd.ms-powerpoint")
put("potm", "application/vnd.ms-powerpoint.template.macroEnabled.12")
put("potx", "application/vnd.openxmlformats-officedocument.presentationml.template")
put("ppa", "application/vnd.ms-powerpoint")
put("ppam", "application/vnd.ms-powerpoint.addin.macroEnabled.12")
put("ppm", "image/x-portable-pixmap")
put("pps", "application/vnd.ms-powerpoint")
put("ppsm", "application/vnd.ms-powerpoint.slideshow.macroEnabled.12")
put("ppsx", "application/vnd.openxmlformats-officedocument.presentationml.slideshow")
put("ppt", "application/vnd.ms-powerpoint")
put("pptm", "application/vnd.ms-powerpoint.presentation.macroEnabled.12")
put("pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation")
put("prf", "application/pics-rules")
put("prm", "application/octet-stream")
put("prx", "application/octet-stream")
put("ps", "application/postscript")
put("psc1", "application/PowerShell")
put("psd", "application/octet-stream")
put("psess", "application/xml")
put("psm", "application/octet-stream")
put("psp", "application/octet-stream")
put("pub", "application/x-mspublisher")
put("pwz", "application/vnd.ms-powerpoint")
put("py", "text/plain")
put("qht", "text/x-html-insertion")
put("qhtm", "text/x-html-insertion")
put("qt", "video/quicktime")
put("qti", "image/x-quicktime")
put("qtif", "image/x-quicktime")
put("qtl", "application/x-quicktimeplayer")
put("qxd", "application/octet-stream")
put("ra", "audio/x-pn-realaudio")
put("ram", "audio/x-pn-realaudio")
put("rar", "application/x-rar-compressed")
put("ras", "image/x-cmu-raster")
put("rat", "application/rat-file")
put("rb", "text/plain")
put("rc", "text/plain")
put("rc2", "text/plain")
put("rct", "text/plain")
put("rdlc", "application/xml")
put("reg", "text/plain")
put("resx", "application/xml")
put("rf", "image/vnd.rn-realflash")
put("rgb", "image/x-rgb")
put("rgs", "text/plain")
put("rm", "application/vnd.rn-realmedia")
put("rmi", "audio/mid")
put("rmp", "application/vnd.rn-rn_music_package")
put("roff", "application/x-troff")
put("rpm", "audio/x-pn-realaudio-plugin")
put("rqy", "text/x-ms-rqy")
put("rtf", "application/rtf")
put("rtx", "text/richtext")
put("ruleset", "application/xml")
put("s", "text/plain")
put("safariextz", "application/x-safari-safariextz")
put("scd", "application/x-msschedule")
put("scr", "text/plain")
put("sct", "text/scriptlet")
put("sd2", "audio/x-sd2")
put("sdp", "application/sdp")
put("sea", "application/octet-stream")
put("searchConnector-ms", "application/windows-search-connector+xml")
put("setpay", "application/set-payment-initiation")
put("setreg", "application/set-registration-initiation")
put("settings", "application/xml")
put("sgimb", "application/x-sgimb")
put("sgml", "text/sgml")
put("sh", "application/x-sh")
put("shar", "application/x-shar")
put("shtml", "text/html")
put("sit", "application/x-stuffit")
put("sitemap", "application/xml")
put("skin", "application/xml")
put("sldm", "application/vnd.ms-powerpoint.slide.macroEnabled.12")
put("sldx", "application/vnd.openxmlformats-officedocument.presentationml.slide")
put("slk", "application/vnd.ms-excel")
put("sln", "text/plain")
put("slupkg-ms", "application/x-ms-license")
put("smd", "audio/x-smd")
put("smi", "application/octet-stream")
put("smx", "audio/x-smd")
put("smz", "audio/x-smd")
put("snd", "audio/basic")
put("snippet", "application/xml")
put("snp", "application/octet-stream")
put("sol", "text/plain")
put("sor", "text/plain")
put("spc", "application/x-pkcs7-certificates")
put("spl", "application/futuresplash")
put("spx", "audio/ogg")
put("src", "application/x-wais-source")
put("srf", "text/plain")
put("ssisdeploymentmanifest", "text/xml")
put("ssm", "application/streamingmedia")
put("sst", "application/vnd.ms-pki.certstore")
put("stl", "application/vnd.ms-pki.stl")
put("sv4cpio", "application/x-sv4cpio")
put("sv4crc", "application/x-sv4crc")
put("svc", "application/xml")
put("svg", "image/svg+xml")
put("swf", "application/x-shockwave-flash")
put("t", "application/x-troff")
put("tar", "application/x-tar")
put("tcl", "application/x-tcl")
put("testrunconfig", "application/xml")
put("testsettings", "application/xml")
put("tex", "application/x-tex")
put("texi", "application/x-texinfo")
put("texinfo", "application/x-texinfo")
put("tgz", "application/x-compressed")
put("thmx", "application/vnd.ms-officetheme")
put("thn", "application/octet-stream")
put("tif", "image/tiff")
put("tiff", "image/tiff")
put("tlh", "text/plain")
put("tli", "text/plain")
put("toc", "application/octet-stream")
put("tr", "application/x-troff")
put("trm", "application/x-msterminal")
put("trx", "application/xml")
put("ts", "video/vnd.dlna.mpeg-tts")
put("tsv", "text/tab-separated-values")
put("ttf", "application/font-sfnt")
put("tts", "video/vnd.dlna.mpeg-tts")
put("txt", "text/plain")
put("u32", "application/octet-stream")
put("uls", "text/iuls")
put("user", "text/plain")
put("ustar", "application/x-ustar")
put("vb", "text/plain")
put("vbdproj", "text/plain")
put("vbk", "video/mpeg")
put("vbproj", "text/plain")
put("vbs", "text/vbscript")
put("vcf", "text/x-vcard")
put("vcproj", "application/xml")
put("vcs", "text/calendar")
put("vcxproj", "application/xml")
put("vddproj", "text/plain")
put("vdp", "text/plain")
put("vdproj", "text/plain")
put("vdx", "application/vnd.ms-visio.viewer")
put("vml", "text/xml")
put("vscontent", "application/xml")
put("vsct", "text/xml")
put("vsd", "application/vnd.visio")
put("vsi", "application/ms-vsi")
put("vsix", "application/vsix")
put("vsixlangpack", "text/xml")
put("vsixmanifest", "text/xml")
put("vsmdi", "application/xml")
put("vspscc", "text/plain")
put("vss", "application/vnd.visio")
put("vsscc", "text/plain")
put("vssettings", "text/xml")
put("vssscc", "text/plain")
put("vst", "application/vnd.visio")
put("vstemplate", "text/xml")
put("vsto", "application/x-ms-vsto")
put("vsw", "application/vnd.visio")
put("vsx", "application/vnd.visio")
put("vtx", "application/vnd.visio")
put("wav", "audio/wav")
put("wave", "audio/wav")
put("wax", "audio/x-ms-wax")
put("wbk", "application/msword")
put("wbmp", "image/vnd.wap.wbmp")
put("wcm", "application/vnd.ms-works")
put("wdb", "application/vnd.ms-works")
put("wdp", "image/vnd.ms-photo")
put("webarchive", "application/x-safari-webarchive")
put("webm", "video/webm")
put("webp", "image/webp")
put("webtest", "application/xml")
put("wiq", "application/xml")
put("wiz", "application/msword")
put("wks", "application/vnd.ms-works")
put("wlmp", "application/wlmoviemaker")
put("wlpginstall", "application/x-wlpg-detect")
put("wlpginstall3", "application/x-wlpg3-detect")
put("wm", "video/x-ms-wm")
put("wma", "audio/x-ms-wma")
put("wmd", "application/x-ms-wmd")
put("wmf", "application/x-msmetafile")
put("wml", "text/vnd.wap.wml")
put("wmlc", "application/vnd.wap.wmlc")
put("wmls", "text/vnd.wap.wmlscript")
put("wmlsc", "application/vnd.wap.wmlscriptc")
put("wmp", "video/x-ms-wmp")
put("wmv", "video/x-ms-wmv")
put("wmx", "video/x-ms-wmx")
put("wmz", "application/x-ms-wmz")
put("woff", "application/font-woff")
put("wpl", "application/vnd.ms-wpl")
put("wps", "application/vnd.ms-works")
put("wri", "application/x-mswrite")
put("wrl", "x-world/x-vrml")
put("wrz", "x-world/x-vrml")
put("wsc", "text/scriptlet")
put("wsdl", "text/xml")
put("wvx", "video/x-ms-wvx")
put("x", "application/directx")
put("xaf", "x-world/x-vrml")
put("xaml", "application/xaml+xml")
put("xap", "application/x-silverlight-app")
put("xbap", "application/x-ms-xbap")
put("xbm", "image/x-xbitmap")
put("xdr", "text/plain")
put("xht", "application/xhtml+xml")
put("xhtml", "application/xhtml+xml")
put("xla", "application/vnd.ms-excel")
put("xlam", "application/vnd.ms-excel.addin.macroEnabled.12")
put("xlc", "application/vnd.ms-excel")
put("xld", "application/vnd.ms-excel")
put("xlk", "application/vnd.ms-excel")
put("xll", "application/vnd.ms-excel")
put("xlm", "application/vnd.ms-excel")
put("xls", "application/vnd.ms-excel")
put("xlsb", "application/vnd.ms-excel.sheet.binary.macroEnabled.12")
put("xlsm", "application/vnd.ms-excel.sheet.macroEnabled.12")
put("xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
put("xlt", "application/vnd.ms-excel")
put("xltm", "application/vnd.ms-excel.template.macroEnabled.12")
put("xltx", "application/vnd.openxmlformats-officedocument.spreadsheetml.template")
put("xlw", "application/vnd.ms-excel")
put("xml", "text/xml")
put("xmta", "application/xml")
put("xof", "x-world/x-vrml")
put("xoml", "text/plain")
put("xpm", "image/x-xpixmap")
put("xps", "application/vnd.ms-xpsdocument")
put("xrm-ms", "text/xml")
put("xsc", "application/xml")
put("xsd", "text/xml")
put("xsf", "text/xml")
put("xsl", "text/xml")
put("xslt", "text/xml")
put("xsn", "application/octet-stream")
put("xss", "application/xml")
put("xspf", "application/xspf+xml")
put("xtp", "application/octet-stream")
put("xwd", "image/x-xwindowdump")
put("z", "application/x-compress")
put("zip", "application/zip")
}
return typesMap[getFilenameExtension().toLowerCase()] ?: ""
}
fun String.isBlockedNumberPattern() = contains("*")
fun String?.fromHtml(): Spanned =
when {
this == null -> SpannableString("")
Build.VERSION.SDK_INT >= Build.VERSION_CODES.N -> Html.fromHtml(this, Html.FROM_HTML_MODE_LEGACY)
else -> Html.fromHtml(this)
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/extensions/String.kt | 2697913186 |
package com.simplemobiletools.commons.extensions
import android.graphics.Bitmap
import java.io.ByteArrayOutputStream
fun Bitmap.getByteArray(): ByteArray {
var baos: ByteArrayOutputStream? = null
try {
baos = ByteArrayOutputStream()
compress(Bitmap.CompressFormat.JPEG, 80, baos)
return baos.toByteArray()
} finally {
baos?.close()
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/extensions/Bitmap.kt | 487551861 |
package com.simplemobiletools.commons.extensions
import android.content.Context
import android.net.Uri
import android.os.Environment
import android.provider.DocumentsContract
import android.provider.MediaStore
import androidx.documentfile.provider.DocumentFile
import com.simplemobiletools.commons.helpers.EXTERNAL_STORAGE_PROVIDER_AUTHORITY
import com.simplemobiletools.commons.helpers.isRPlus
import com.simplemobiletools.commons.helpers.isSPlus
import com.simplemobiletools.commons.models.FileDirItem
import java.io.File
private const val DOWNLOAD_DIR = "Download"
private const val ANDROID_DIR = "Android"
private val DIRS_INACCESSIBLE_WITH_SAF_SDK_30 = listOf(DOWNLOAD_DIR, ANDROID_DIR)
fun Context.hasProperStoredFirstParentUri(path: String): Boolean {
val firstParentUri = createFirstParentTreeUri(path)
return contentResolver.persistedUriPermissions.any { it.uri.toString() == firstParentUri.toString() }
}
fun Context.isAccessibleWithSAFSdk30(path: String): Boolean {
if (path.startsWith(recycleBinPath) || isExternalStorageManager()) {
return false
}
val level = getFirstParentLevel(path)
val firstParentDir = path.getFirstParentDirName(this, level)
val firstParentPath = path.getFirstParentPath(this, level)
val isValidName = firstParentDir != null
val isDirectory = File(firstParentPath).isDirectory
val isAnAccessibleDirectory = DIRS_INACCESSIBLE_WITH_SAF_SDK_30.all { !firstParentDir.equals(it, true) }
return isRPlus() && isValidName && isDirectory && isAnAccessibleDirectory
}
fun Context.getFirstParentLevel(path: String): Int {
return when {
isRPlus() && (isInAndroidDir(path) || isInSubFolderInDownloadDir(path)) -> 1
else -> 0
}
}
fun Context.isRestrictedWithSAFSdk30(path: String): Boolean {
if (path.startsWith(recycleBinPath) || isExternalStorageManager()) {
return false
}
val level = getFirstParentLevel(path)
val firstParentDir = path.getFirstParentDirName(this, level)
val firstParentPath = path.getFirstParentPath(this, level)
val isInvalidName = firstParentDir == null
val isDirectory = File(firstParentPath).isDirectory
val isARestrictedDirectory = DIRS_INACCESSIBLE_WITH_SAF_SDK_30.any { firstParentDir.equals(it, true) }
return isRPlus() && (isInvalidName || (isDirectory && isARestrictedDirectory))
}
fun Context.isInDownloadDir(path: String): Boolean {
if (path.startsWith(recycleBinPath)) {
return false
}
val firstParentDir = path.getFirstParentDirName(this, 0)
return firstParentDir.equals(DOWNLOAD_DIR, true)
}
fun Context.isInSubFolderInDownloadDir(path: String): Boolean {
if (path.startsWith(recycleBinPath)) {
return false
}
val firstParentDir = path.getFirstParentDirName(this, 1)
return if (firstParentDir == null) {
false
} else {
val startsWithDownloadDir = firstParentDir.startsWith(DOWNLOAD_DIR, true)
val hasAtLeast1PathSegment = firstParentDir.split("/").filter { it.isNotEmpty() }.size > 1
val firstParentPath = path.getFirstParentPath(this, 1)
startsWithDownloadDir && hasAtLeast1PathSegment && File(firstParentPath).isDirectory
}
}
fun Context.isInAndroidDir(path: String): Boolean {
if (path.startsWith(recycleBinPath)) {
return false
}
val firstParentDir = path.getFirstParentDirName(this, 0)
return firstParentDir.equals(ANDROID_DIR, true)
}
fun isExternalStorageManager(): Boolean {
return isRPlus() && Environment.isExternalStorageManager()
}
// is the app a Media Management App on Android 12+?
fun Context.canManageMedia(): Boolean {
return isSPlus() && MediaStore.canManageMedia(this)
}
fun Context.createFirstParentTreeUriUsingRootTree(fullPath: String): Uri {
val storageId = getSAFStorageId(fullPath)
val level = getFirstParentLevel(fullPath)
val rootParentDirName = fullPath.getFirstParentDirName(this, level)
val treeUri = DocumentsContract.buildTreeDocumentUri(EXTERNAL_STORAGE_PROVIDER_AUTHORITY, "$storageId:")
val documentId = "${storageId}:$rootParentDirName"
return DocumentsContract.buildDocumentUriUsingTree(treeUri, documentId)
}
fun Context.createFirstParentTreeUri(fullPath: String): Uri {
val storageId = getSAFStorageId(fullPath)
val level = getFirstParentLevel(fullPath)
val rootParentDirName = fullPath.getFirstParentDirName(this, level)
val firstParentId = "$storageId:$rootParentDirName"
return DocumentsContract.buildTreeDocumentUri(EXTERNAL_STORAGE_PROVIDER_AUTHORITY, firstParentId)
}
fun Context.createDocumentUriUsingFirstParentTreeUri(fullPath: String): Uri {
val storageId = getSAFStorageId(fullPath)
val relativePath = when {
fullPath.startsWith(internalStoragePath) -> fullPath.substring(internalStoragePath.length).trim('/')
else -> fullPath.substringAfter(storageId).trim('/')
}
val treeUri = createFirstParentTreeUri(fullPath)
val documentId = "${storageId}:$relativePath"
return DocumentsContract.buildDocumentUriUsingTree(treeUri, documentId)
}
fun Context.getSAFDocumentId(path: String): String {
val basePath = path.getBasePath(this)
val relativePath = path.substring(basePath.length).trim('/')
val storageId = getSAFStorageId(path)
return "$storageId:$relativePath"
}
fun Context.createSAFDirectorySdk30(path: String): Boolean {
return try {
val treeUri = createFirstParentTreeUri(path)
val parentPath = path.getParentPath()
if (!getDoesFilePathExistSdk30(parentPath)) {
createSAFDirectorySdk30(parentPath)
}
val documentId = getSAFDocumentId(parentPath)
val parentUri = DocumentsContract.buildDocumentUriUsingTree(treeUri, documentId)
DocumentsContract.createDocument(contentResolver, parentUri, DocumentsContract.Document.MIME_TYPE_DIR, path.getFilenameFromPath()) != null
} catch (e: IllegalStateException) {
showErrorToast(e)
false
}
}
fun Context.createSAFFileSdk30(path: String): Boolean {
return try {
val treeUri = createFirstParentTreeUri(path)
val parentPath = path.getParentPath()
if (!getDoesFilePathExistSdk30(parentPath)) {
createSAFDirectorySdk30(parentPath)
}
val documentId = getSAFDocumentId(parentPath)
val parentUri = DocumentsContract.buildDocumentUriUsingTree(treeUri, documentId)
DocumentsContract.createDocument(contentResolver, parentUri, path.getMimeType(), path.getFilenameFromPath()) != null
} catch (e: IllegalStateException) {
showErrorToast(e)
false
}
}
fun Context.getDoesFilePathExistSdk30(path: String): Boolean {
return when {
isAccessibleWithSAFSdk30(path) -> getFastDocumentSdk30(path)?.exists() ?: false
else -> File(path).exists()
}
}
fun Context.getSomeDocumentSdk30(path: String): DocumentFile? = getFastDocumentSdk30(path) ?: getDocumentSdk30(path)
fun Context.getFastDocumentSdk30(path: String): DocumentFile? {
val uri = createDocumentUriUsingFirstParentTreeUri(path)
return DocumentFile.fromSingleUri(this, uri)
}
fun Context.getDocumentSdk30(path: String): DocumentFile? {
val level = getFirstParentLevel(path)
val firstParentPath = path.getFirstParentPath(this, level)
var relativePath = path.substring(firstParentPath.length)
if (relativePath.startsWith(File.separator)) {
relativePath = relativePath.substring(1)
}
return try {
val treeUri = createFirstParentTreeUri(path)
var document = DocumentFile.fromTreeUri(applicationContext, treeUri)
val parts = relativePath.split("/").filter { it.isNotEmpty() }
for (part in parts) {
document = document?.findFile(part)
}
document
} catch (ignored: Exception) {
null
}
}
fun Context.deleteDocumentWithSAFSdk30(fileDirItem: FileDirItem, allowDeleteFolder: Boolean, callback: ((wasSuccess: Boolean) -> Unit)?) {
try {
var fileDeleted = false
if (fileDirItem.isDirectory.not() || allowDeleteFolder) {
val fileUri = createDocumentUriUsingFirstParentTreeUri(fileDirItem.path)
fileDeleted = DocumentsContract.deleteDocument(contentResolver, fileUri)
}
if (fileDeleted) {
deleteFromMediaStore(fileDirItem.path)
callback?.invoke(true)
}
} catch (e: Exception) {
callback?.invoke(false)
showErrorToast(e)
}
}
fun Context.renameDocumentSdk30(oldPath: String, newPath: String): Boolean {
return try {
val treeUri = createFirstParentTreeUri(oldPath)
val documentId = getSAFDocumentId(oldPath)
val parentUri = DocumentsContract.buildDocumentUriUsingTree(treeUri, documentId)
DocumentsContract.renameDocument(contentResolver, parentUri, newPath.getFilenameFromPath()) != null
} catch (e: IllegalStateException) {
showErrorToast(e)
false
}
}
fun Context.hasProperStoredDocumentUriSdk30(path: String): Boolean {
val documentUri = buildDocumentUriSdk30(path)
return contentResolver.persistedUriPermissions.any { it.uri.toString() == documentUri.toString() }
}
fun Context.buildDocumentUriSdk30(fullPath: String): Uri {
val storageId = getSAFStorageId(fullPath)
val relativePath = when {
fullPath.startsWith(internalStoragePath) -> fullPath.substring(internalStoragePath.length).trim('/')
else -> fullPath.substringAfter(storageId).trim('/')
}
val documentId = "${storageId}:$relativePath"
return DocumentsContract.buildDocumentUri(EXTERNAL_STORAGE_PROVIDER_AUTHORITY, documentId)
}
fun Context.getPicturesDirectoryPath(fullPath: String): String {
val basePath = fullPath.getBasePath(this)
return File(basePath, Environment.DIRECTORY_PICTURES).absolutePath
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/extensions/Context-storage-sdk30.kt | 4204712970 |
package com.simplemobiletools.commons.extensions
import android.app.Activity
import android.view.LayoutInflater
import androidx.viewbinding.ViewBinding
inline fun <T : ViewBinding> Activity.viewBinding(crossinline bindingInflater: (LayoutInflater) -> T) =
lazy(LazyThreadSafetyMode.NONE) {
bindingInflater.invoke(layoutInflater)
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/extensions/Binding.kt | 1313117904 |
package com.simplemobiletools.commons.extensions
// extensions used mostly at importing app settings for now
fun Any.toBoolean() = toString() == "true"
fun Any.toInt() = Integer.parseInt(toString())
fun Any.toStringSet() = toString().split(",".toRegex()).toSet()
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/extensions/Any.kt | 4076079568 |
package com.simplemobiletools.commons.extensions
import android.content.Context
import android.text.format.DateFormat
import java.text.DecimalFormat
import java.util.*
fun Long.formatSize(): String {
if (this <= 0) {
return "0 B"
}
val units = arrayOf("B", "kB", "MB", "GB", "TB")
val digitGroups = (Math.log10(toDouble()) / Math.log10(1024.0)).toInt()
return "${DecimalFormat("#,##0.#").format(this / Math.pow(1024.0, digitGroups.toDouble()))} ${units[digitGroups]}"
}
fun Long.formatDate(context: Context, dateFormat: String? = null, timeFormat: String? = null): String {
val useDateFormat = dateFormat ?: context.baseConfig.dateFormat
val useTimeFormat = timeFormat ?: context.getTimeFormat()
val cal = Calendar.getInstance(Locale.ENGLISH)
cal.timeInMillis = this
return DateFormat.format("$useDateFormat, $useTimeFormat", cal).toString()
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/extensions/Long.kt | 254445831 |
package com.simplemobiletools.commons.extensions
import com.simplemobiletools.commons.helpers.MD5
import java.io.InputStream
import java.security.MessageDigest
fun InputStream.getDigest(algorithm: String): String {
return use { fis ->
val md = MessageDigest.getInstance(algorithm)
val buffer = ByteArray(8192)
generateSequence {
when (val bytesRead = fis.read(buffer)) {
-1 -> null
else -> bytesRead
}
}.forEach { bytesRead -> md.update(buffer, 0, bytesRead) }
md.digest().joinToString("") { "%02x".format(it) }
}
}
fun InputStream.md5(): String = this.getDigest(MD5)
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/extensions/InputStream.kt | 805498360 |
package com.simplemobiletools.commons.extensions
import java.util.*
fun List<String>.getMimeType(): String {
val mimeGroups = HashSet<String>(size)
val subtypes = HashSet<String>(size)
forEach {
val parts = it.getMimeType().split("/")
if (parts.size == 2) {
mimeGroups.add(parts.getOrElse(0) { "" })
subtypes.add(parts.getOrElse(1) { "" })
} else {
return "*/*"
}
}
return when {
subtypes.size == 1 -> "${mimeGroups.first()}/${subtypes.first()}"
mimeGroups.size == 1 -> "${mimeGroups.first()}/*"
else -> "*/*"
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/extensions/List.kt | 3455182540 |
package com.simplemobiletools.commons.extensions
import androidx.documentfile.provider.DocumentFile
fun DocumentFile.getItemSize(countHiddenItems: Boolean): Long {
return if (isDirectory) {
getDirectorySize(this, countHiddenItems)
} else {
length()
}
}
private fun getDirectorySize(dir: DocumentFile, countHiddenItems: Boolean): Long {
var size = 0L
if (dir.exists()) {
val files = dir.listFiles()
for (i in files.indices) {
val file = files[i]
if (file.isDirectory) {
size += getDirectorySize(file, countHiddenItems)
} else if (!file.name!!.startsWith(".") || countHiddenItems) {
size += file.length()
}
}
}
return size
}
fun DocumentFile.getFileCount(countHiddenItems: Boolean): Int {
return if (isDirectory) {
getDirectoryFileCount(this, countHiddenItems)
} else {
1
}
}
private fun getDirectoryFileCount(dir: DocumentFile, countHiddenItems: Boolean): Int {
var count = 0
if (dir.exists()) {
val files = dir.listFiles()
for (i in files.indices) {
val file = files[i]
if (file.isDirectory) {
count++
count += getDirectoryFileCount(file, countHiddenItems)
} else if (!file.name!!.startsWith(".") || countHiddenItems) {
count++
}
}
}
return count
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/extensions/DocumentFile.kt | 522705125 |
package com.simplemobiletools.commons.extensions
import com.google.android.material.tabs.TabLayout
fun TabLayout.onTabSelectionChanged(
tabUnselectedAction: ((inactiveTab: TabLayout.Tab) -> Unit)? = null,
tabSelectedAction: ((activeTab: TabLayout.Tab) -> Unit)? = null
) = setOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
override fun onTabSelected(tab: TabLayout.Tab) {
tabSelectedAction?.invoke(tab)
}
override fun onTabUnselected(tab: TabLayout.Tab) {
tabUnselectedAction?.invoke(tab)
}
override fun onTabReselected(tab: TabLayout.Tab) {
tabSelectedAction?.invoke(tab)
}
})
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/extensions/TabLayout.kt | 1380947379 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.