content
stringlengths 0
13M
| path
stringlengths 4
263
| contentHash
stringlengths 1
10
|
---|---|---|
package com.simplemobiletools.commons.extensions
import android.text.Editable
import android.text.Spannable
import android.text.SpannableString
import android.text.TextWatcher
import android.text.style.BackgroundColorSpan
import android.widget.EditText
import android.widget.TextView
import androidx.core.graphics.ColorUtils
val EditText.value: String get() = text.toString().trim()
fun EditText.onTextChangeListener(onTextChangedAction: (newText: String) -> Unit) = addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable?) {
onTextChangedAction(s.toString())
}
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
})
fun EditText.highlightText(highlightText: String, color: Int) {
val content = text.toString()
var indexOf = content.indexOf(highlightText, 0, true)
val wordToSpan = SpannableString(text)
var offset = 0
while (offset < content.length && indexOf != -1) {
indexOf = content.indexOf(highlightText, offset, true)
if (indexOf == -1) {
break
} else {
val spanBgColor = BackgroundColorSpan(ColorUtils.setAlphaComponent(color, 128))
val spanFlag = Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
wordToSpan.setSpan(spanBgColor, indexOf, indexOf + highlightText.length, spanFlag)
setText(wordToSpan, TextView.BufferType.SPANNABLE)
}
offset = indexOf + 1
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/extensions/EditText.kt | 18849800 |
package com.simplemobiletools.commons.extensions
import android.app.Activity
import android.graphics.Color
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.helpers.DARK_GREY
fun Activity.getThemeId(color: Int = baseConfig.primaryColor, showTransparentTop: Boolean = false) = when {
baseConfig.isUsingSystemTheme -> if (isUsingSystemDarkTheme()) R.style.AppTheme_Base_System else R.style.AppTheme_Base_System_Light
isBlackAndWhiteTheme() -> when {
showTransparentTop -> R.style.AppTheme_BlackAndWhite_NoActionBar
baseConfig.primaryColor.getContrastColor() == DARK_GREY -> R.style.AppTheme_BlackAndWhite_DarkTextColor
else -> R.style.AppTheme_BlackAndWhite
}
isWhiteTheme() -> when {
showTransparentTop -> R.style.AppTheme_White_NoActionBar
baseConfig.primaryColor.getContrastColor() == Color.WHITE -> R.style.AppTheme_White_LightTextColor
else -> R.style.AppTheme_White
}
showTransparentTop -> {
when (color) {
-12846 -> R.style.AppTheme_Red_100_core
-1074534 -> R.style.AppTheme_Red_200_core
-1739917 -> R.style.AppTheme_Red_300_core
-1092784 -> R.style.AppTheme_Red_400_core
-769226 -> R.style.AppTheme_Red_500_core
-1754827 -> R.style.AppTheme_Red_600_core
-2937041 -> R.style.AppTheme_Red_700_core
-3790808 -> R.style.AppTheme_Red_800_core
-4776932 -> R.style.AppTheme_Red_900_core
-476208 -> R.style.AppTheme_Pink_100_core
-749647 -> R.style.AppTheme_Pink_200_core
-1023342 -> R.style.AppTheme_Pink_300_core
-1294214 -> R.style.AppTheme_Pink_400_core
-1499549 -> R.style.AppTheme_Pink_500_core
-2614432 -> R.style.AppTheme_Pink_600_core
-4056997 -> R.style.AppTheme_Pink_700_core
-5434281 -> R.style.AppTheme_Pink_800_core
-7860657 -> R.style.AppTheme_Pink_900_core
-1982745 -> R.style.AppTheme_Purple_100_core
-3238952 -> R.style.AppTheme_Purple_200_core
-4560696 -> R.style.AppTheme_Purple_300_core
-5552196 -> R.style.AppTheme_Purple_400_core
-6543440 -> R.style.AppTheme_Purple_500_core
-7461718 -> R.style.AppTheme_Purple_600_core
-8708190 -> R.style.AppTheme_Purple_700_core
-9823334 -> R.style.AppTheme_Purple_800_core
-11922292 -> R.style.AppTheme_Purple_900_core
-3029783 -> R.style.AppTheme_Deep_Purple_100_core
-5005861 -> R.style.AppTheme_Deep_Purple_200_core
-6982195 -> R.style.AppTheme_Deep_Purple_300_core
-8497214 -> R.style.AppTheme_Deep_Purple_400_core
-10011977 -> R.style.AppTheme_Deep_Purple_500_core
-10603087 -> R.style.AppTheme_Deep_Purple_600_core
-11457112 -> R.style.AppTheme_Deep_Purple_700_core
-12245088 -> R.style.AppTheme_Deep_Purple_800_core
-13558894 -> R.style.AppTheme_Deep_Purple_900_core
-3814679 -> R.style.AppTheme_Indigo_100_core
-6313766 -> R.style.AppTheme_Indigo_200_core
-8812853 -> R.style.AppTheme_Indigo_300_core
-10720320 -> R.style.AppTheme_Indigo_400_core
-12627531 -> R.style.AppTheme_Indigo_500_core
-13022805 -> R.style.AppTheme_Indigo_600_core
-13615201 -> R.style.AppTheme_Indigo_700_core
-14142061 -> R.style.AppTheme_Indigo_800_core
-15064194 -> R.style.AppTheme_Indigo_900_core
-4464901 -> R.style.AppTheme_Blue_100_core
-7288071 -> R.style.AppTheme_Blue_200_core
-10177034 -> R.style.AppTheme_Blue_300_core
-12409355 -> R.style.AppTheme_Blue_400_core
-14575885 -> R.style.AppTheme_Blue_500_core
-14776091 -> R.style.AppTheme_Blue_600_core
-15108398 -> R.style.AppTheme_Blue_700_core
-15374912 -> R.style.AppTheme_Blue_800_core
-15906911 -> R.style.AppTheme_Blue_900_core
-4987396 -> R.style.AppTheme_Light_Blue_100_core
-8268550 -> R.style.AppTheme_Light_Blue_200_core
-11549705 -> R.style.AppTheme_Light_Blue_300_core
-14043396 -> R.style.AppTheme_Light_Blue_400_core
-16537100 -> R.style.AppTheme_Light_Blue_500_core
-16540699 -> R.style.AppTheme_Light_Blue_600_core
-16611119 -> R.style.AppTheme_Light_Blue_700_core
-16615491 -> R.style.AppTheme_Light_Blue_800_core
-16689253 -> R.style.AppTheme_Light_Blue_900_core
-5051406 -> R.style.AppTheme_Cyan_100_core
-8331542 -> R.style.AppTheme_Cyan_200_core
-11677471 -> R.style.AppTheme_Cyan_300_core
-14235942 -> R.style.AppTheme_Cyan_400_core
-16728876 -> R.style.AppTheme_Cyan_500_core
-16732991 -> R.style.AppTheme_Cyan_600_core
-16738393 -> R.style.AppTheme_Cyan_700_core
-16743537 -> R.style.AppTheme_Cyan_800_core
-16752540 -> R.style.AppTheme_Cyan_900_core
-5054501 -> R.style.AppTheme_Teal_100_core
-8336444 -> R.style.AppTheme_Teal_200_core
-11684180 -> R.style.AppTheme_Teal_300_core
-14244198 -> R.style.AppTheme_Teal_400_core
-16738680 -> R.style.AppTheme_Teal_500_core
-16742021 -> R.style.AppTheme_Teal_600_core
-16746133 -> R.style.AppTheme_Teal_700_core
-16750244 -> R.style.AppTheme_Teal_800_core
-16757440 -> R.style.AppTheme_Teal_900_core
-3610935 -> R.style.AppTheme_Green_100_core
-5908825 -> R.style.AppTheme_Green_200_core
-8271996 -> R.style.AppTheme_Green_300_core
-10044566 -> R.style.AppTheme_Green_400_core
-11751600 -> R.style.AppTheme_Green_500_core
-12345273 -> R.style.AppTheme_Green_600_core
-13070788 -> R.style.AppTheme_Green_700_core
-13730510 -> R.style.AppTheme_Green_800_core
-14983648 -> R.style.AppTheme_Green_900_core
-2298424 -> R.style.AppTheme_Light_Green_100_core
-3808859 -> R.style.AppTheme_Light_Green_200_core
-5319295 -> R.style.AppTheme_Light_Green_300_core
-6501275 -> R.style.AppTheme_Light_Green_400_core
-7617718 -> R.style.AppTheme_Light_Green_500_core
-8604862 -> R.style.AppTheme_Light_Green_600_core
-9920712 -> R.style.AppTheme_Light_Green_700_core
-11171025 -> R.style.AppTheme_Light_Green_800_core
-13407970 -> R.style.AppTheme_Light_Green_900_core
-985917 -> R.style.AppTheme_Lime_100_core
-1642852 -> R.style.AppTheme_Lime_200_core
-2300043 -> R.style.AppTheme_Lime_300_core
-2825897 -> R.style.AppTheme_Lime_400_core
-3285959 -> R.style.AppTheme_Lime_500_core
-4142541 -> R.style.AppTheme_Lime_600_core
-5983189 -> R.style.AppTheme_Lime_700_core
-6382300 -> R.style.AppTheme_Lime_800_core
-8227049 -> R.style.AppTheme_Lime_900_core
-1596 -> R.style.AppTheme_Yellow_100_core
-2672 -> R.style.AppTheme_Yellow_200_core
-3722 -> R.style.AppTheme_Yellow_300_core
-4520 -> R.style.AppTheme_Yellow_400_core
-5317 -> R.style.AppTheme_Yellow_500_core
-141259 -> R.style.AppTheme_Yellow_600_core
-278483 -> R.style.AppTheme_Yellow_700_core
-415707 -> R.style.AppTheme_Yellow_800_core
-688361 -> R.style.AppTheme_Yellow_900_core
-4941 -> R.style.AppTheme_Amber_100_core
-8062 -> R.style.AppTheme_Amber_200_core
-10929 -> R.style.AppTheme_Amber_300_core
-13784 -> R.style.AppTheme_Amber_400_core
-16121 -> R.style.AppTheme_Amber_500_core
-19712 -> R.style.AppTheme_Amber_600_core
-24576 -> R.style.AppTheme_Amber_700_core
-28928 -> R.style.AppTheme_Amber_800_core
-37120 -> R.style.AppTheme_Amber_900_core
-8014 -> R.style.AppTheme_Orange_100_core
-13184 -> R.style.AppTheme_Orange_200_core
-18611 -> R.style.AppTheme_Orange_300_core
-22746 -> R.style.AppTheme_Orange_400_core
-26624 -> R.style.AppTheme_Orange_500_core
-291840 -> R.style.AppTheme_Orange_600_core
-689152 -> R.style.AppTheme_Orange_700_core
-1086464 -> R.style.AppTheme_Orange_800_core
-1683200 -> R.style.AppTheme_Orange_900_core
-13124 -> R.style.AppTheme_Deep_Orange_100_core
-21615 -> R.style.AppTheme_Deep_Orange_200_core
-30107 -> R.style.AppTheme_Deep_Orange_300_core
-36797 -> R.style.AppTheme_Deep_Orange_400_core
-43230 -> R.style.AppTheme_Deep_Orange_500_core
-765666 -> R.style.AppTheme_Deep_Orange_600_core
-1684967 -> R.style.AppTheme_Deep_Orange_700_core
-2604267 -> R.style.AppTheme_Deep_Orange_800_core
-4246004 -> R.style.AppTheme_Deep_Orange_900_core
-2634552 -> R.style.AppTheme_Brown_100_core
-4412764 -> R.style.AppTheme_Brown_200_core
-6190977 -> R.style.AppTheme_Brown_300_core
-7508381 -> R.style.AppTheme_Brown_400_core
-8825528 -> R.style.AppTheme_Brown_500_core
-9614271 -> R.style.AppTheme_Brown_600_core
-10665929 -> R.style.AppTheme_Brown_700_core
-11652050 -> R.style.AppTheme_Brown_800_core
-12703965 -> R.style.AppTheme_Brown_900_core
-3155748 -> R.style.AppTheme_Blue_Grey_100_core
-5194811 -> R.style.AppTheme_Blue_Grey_200_core
-7297874 -> R.style.AppTheme_Blue_Grey_300_core
-8875876 -> R.style.AppTheme_Blue_Grey_400_core
-10453621 -> R.style.AppTheme_Blue_Grey_500_core
-11243910 -> R.style.AppTheme_Blue_Grey_600_core
-12232092 -> R.style.AppTheme_Blue_Grey_700_core
-13154481 -> R.style.AppTheme_Blue_Grey_800_core
-14273992 -> R.style.AppTheme_Blue_Grey_900_core
-1 -> R.style.AppTheme_Grey_100_core
-1118482 -> R.style.AppTheme_Grey_200_core
-2039584 -> R.style.AppTheme_Grey_300_core
-4342339 -> R.style.AppTheme_Grey_400_core
-6381922 -> R.style.AppTheme_Grey_500_core
-9079435 -> R.style.AppTheme_Grey_600_core
-10395295 -> R.style.AppTheme_Grey_700_core
-12434878 -> R.style.AppTheme_Grey_800_core
-16777216 -> R.style.AppTheme_Grey_900_core
else -> R.style.AppTheme_Orange_700_core
}
}
else -> {
when (color) {
-12846 -> R.style.AppTheme_Red_100
-1074534 -> R.style.AppTheme_Red_200
-1739917 -> R.style.AppTheme_Red_300
-1092784 -> R.style.AppTheme_Red_400
-769226 -> R.style.AppTheme_Red_500
-1754827 -> R.style.AppTheme_Red_600
-2937041 -> R.style.AppTheme_Red_700
-3790808 -> R.style.AppTheme_Red_800
-4776932 -> R.style.AppTheme_Red_900
-476208 -> R.style.AppTheme_Pink_100
-749647 -> R.style.AppTheme_Pink_200
-1023342 -> R.style.AppTheme_Pink_300
-1294214 -> R.style.AppTheme_Pink_400
-1499549 -> R.style.AppTheme_Pink_500
-2614432 -> R.style.AppTheme_Pink_600
-4056997 -> R.style.AppTheme_Pink_700
-5434281 -> R.style.AppTheme_Pink_800
-7860657 -> R.style.AppTheme_Pink_900
-1982745 -> R.style.AppTheme_Purple_100
-3238952 -> R.style.AppTheme_Purple_200
-4560696 -> R.style.AppTheme_Purple_300
-5552196 -> R.style.AppTheme_Purple_400
-6543440 -> R.style.AppTheme_Purple_500
-7461718 -> R.style.AppTheme_Purple_600
-8708190 -> R.style.AppTheme_Purple_700
-9823334 -> R.style.AppTheme_Purple_800
-11922292 -> R.style.AppTheme_Purple_900
-3029783 -> R.style.AppTheme_Deep_Purple_100
-5005861 -> R.style.AppTheme_Deep_Purple_200
-6982195 -> R.style.AppTheme_Deep_Purple_300
-8497214 -> R.style.AppTheme_Deep_Purple_400
-10011977 -> R.style.AppTheme_Deep_Purple_500
-10603087 -> R.style.AppTheme_Deep_Purple_600
-11457112 -> R.style.AppTheme_Deep_Purple_700
-12245088 -> R.style.AppTheme_Deep_Purple_800
-13558894 -> R.style.AppTheme_Deep_Purple_900
-3814679 -> R.style.AppTheme_Indigo_100
-6313766 -> R.style.AppTheme_Indigo_200
-8812853 -> R.style.AppTheme_Indigo_300
-10720320 -> R.style.AppTheme_Indigo_400
-12627531 -> R.style.AppTheme_Indigo_500
-13022805 -> R.style.AppTheme_Indigo_600
-13615201 -> R.style.AppTheme_Indigo_700
-14142061 -> R.style.AppTheme_Indigo_800
-15064194 -> R.style.AppTheme_Indigo_900
-4464901 -> R.style.AppTheme_Blue_100
-7288071 -> R.style.AppTheme_Blue_200
-10177034 -> R.style.AppTheme_Blue_300
-12409355 -> R.style.AppTheme_Blue_400
-14575885 -> R.style.AppTheme_Blue_500
-14776091 -> R.style.AppTheme_Blue_600
-15108398 -> R.style.AppTheme_Blue_700
-15374912 -> R.style.AppTheme_Blue_800
-15906911 -> R.style.AppTheme_Blue_900
-4987396 -> R.style.AppTheme_Light_Blue_100
-8268550 -> R.style.AppTheme_Light_Blue_200
-11549705 -> R.style.AppTheme_Light_Blue_300
-14043396 -> R.style.AppTheme_Light_Blue_400
-16537100 -> R.style.AppTheme_Light_Blue_500
-16540699 -> R.style.AppTheme_Light_Blue_600
-16611119 -> R.style.AppTheme_Light_Blue_700
-16615491 -> R.style.AppTheme_Light_Blue_800
-16689253 -> R.style.AppTheme_Light_Blue_900
-5051406 -> R.style.AppTheme_Cyan_100
-8331542 -> R.style.AppTheme_Cyan_200
-11677471 -> R.style.AppTheme_Cyan_300
-14235942 -> R.style.AppTheme_Cyan_400
-16728876 -> R.style.AppTheme_Cyan_500
-16732991 -> R.style.AppTheme_Cyan_600
-16738393 -> R.style.AppTheme_Cyan_700
-16743537 -> R.style.AppTheme_Cyan_800
-16752540 -> R.style.AppTheme_Cyan_900
-5054501 -> R.style.AppTheme_Teal_100
-8336444 -> R.style.AppTheme_Teal_200
-11684180 -> R.style.AppTheme_Teal_300
-14244198 -> R.style.AppTheme_Teal_400
-16738680 -> R.style.AppTheme_Teal_500
-16742021 -> R.style.AppTheme_Teal_600
-16746133 -> R.style.AppTheme_Teal_700
-16750244 -> R.style.AppTheme_Teal_800
-16757440 -> R.style.AppTheme_Teal_900
-3610935 -> R.style.AppTheme_Green_100
-5908825 -> R.style.AppTheme_Green_200
-8271996 -> R.style.AppTheme_Green_300
-10044566 -> R.style.AppTheme_Green_400
-11751600 -> R.style.AppTheme_Green_500
-12345273 -> R.style.AppTheme_Green_600
-13070788 -> R.style.AppTheme_Green_700
-13730510 -> R.style.AppTheme_Green_800
-14983648 -> R.style.AppTheme_Green_900
-2298424 -> R.style.AppTheme_Light_Green_100
-3808859 -> R.style.AppTheme_Light_Green_200
-5319295 -> R.style.AppTheme_Light_Green_300
-6501275 -> R.style.AppTheme_Light_Green_400
-7617718 -> R.style.AppTheme_Light_Green_500
-8604862 -> R.style.AppTheme_Light_Green_600
-9920712 -> R.style.AppTheme_Light_Green_700
-11171025 -> R.style.AppTheme_Light_Green_800
-13407970 -> R.style.AppTheme_Light_Green_900
-985917 -> R.style.AppTheme_Lime_100
-1642852 -> R.style.AppTheme_Lime_200
-2300043 -> R.style.AppTheme_Lime_300
-2825897 -> R.style.AppTheme_Lime_400
-3285959 -> R.style.AppTheme_Lime_500
-4142541 -> R.style.AppTheme_Lime_600
-5983189 -> R.style.AppTheme_Lime_700
-6382300 -> R.style.AppTheme_Lime_800
-8227049 -> R.style.AppTheme_Lime_900
-1596 -> R.style.AppTheme_Yellow_100
-2672 -> R.style.AppTheme_Yellow_200
-3722 -> R.style.AppTheme_Yellow_300
-4520 -> R.style.AppTheme_Yellow_400
-5317 -> R.style.AppTheme_Yellow_500
-141259 -> R.style.AppTheme_Yellow_600
-278483 -> R.style.AppTheme_Yellow_700
-415707 -> R.style.AppTheme_Yellow_800
-688361 -> R.style.AppTheme_Yellow_900
-4941 -> R.style.AppTheme_Amber_100
-8062 -> R.style.AppTheme_Amber_200
-10929 -> R.style.AppTheme_Amber_300
-13784 -> R.style.AppTheme_Amber_400
-16121 -> R.style.AppTheme_Amber_500
-19712 -> R.style.AppTheme_Amber_600
-24576 -> R.style.AppTheme_Amber_700
-28928 -> R.style.AppTheme_Amber_800
-37120 -> R.style.AppTheme_Amber_900
-8014 -> R.style.AppTheme_Orange_100
-13184 -> R.style.AppTheme_Orange_200
-18611 -> R.style.AppTheme_Orange_300
-22746 -> R.style.AppTheme_Orange_400
-26624 -> R.style.AppTheme_Orange_500
-291840 -> R.style.AppTheme_Orange_600
-689152 -> R.style.AppTheme_Orange_700
-1086464 -> R.style.AppTheme_Orange_800
-1683200 -> R.style.AppTheme_Orange_900
-13124 -> R.style.AppTheme_Deep_Orange_100
-21615 -> R.style.AppTheme_Deep_Orange_200
-30107 -> R.style.AppTheme_Deep_Orange_300
-36797 -> R.style.AppTheme_Deep_Orange_400
-43230 -> R.style.AppTheme_Deep_Orange_500
-765666 -> R.style.AppTheme_Deep_Orange_600
-1684967 -> R.style.AppTheme_Deep_Orange_700
-2604267 -> R.style.AppTheme_Deep_Orange_800
-4246004 -> R.style.AppTheme_Deep_Orange_900
-2634552 -> R.style.AppTheme_Brown_100
-4412764 -> R.style.AppTheme_Brown_200
-6190977 -> R.style.AppTheme_Brown_300
-7508381 -> R.style.AppTheme_Brown_400
-8825528 -> R.style.AppTheme_Brown_500
-9614271 -> R.style.AppTheme_Brown_600
-10665929 -> R.style.AppTheme_Brown_700
-11652050 -> R.style.AppTheme_Brown_800
-12703965 -> R.style.AppTheme_Brown_900
-3155748 -> R.style.AppTheme_Blue_Grey_100
-5194811 -> R.style.AppTheme_Blue_Grey_200
-7297874 -> R.style.AppTheme_Blue_Grey_300
-8875876 -> R.style.AppTheme_Blue_Grey_400
-10453621 -> R.style.AppTheme_Blue_Grey_500
-11243910 -> R.style.AppTheme_Blue_Grey_600
-12232092 -> R.style.AppTheme_Blue_Grey_700
-13154481 -> R.style.AppTheme_Blue_Grey_800
-14273992 -> R.style.AppTheme_Blue_Grey_900
-1 -> R.style.AppTheme_Grey_100
-1118482 -> R.style.AppTheme_Grey_200
-2039584 -> R.style.AppTheme_Grey_300
-4342339 -> R.style.AppTheme_Grey_400
-6381922 -> R.style.AppTheme_Grey_500
-9079435 -> R.style.AppTheme_Grey_600
-10395295 -> R.style.AppTheme_Grey_700
-12434878 -> R.style.AppTheme_Grey_800
-16777216 -> R.style.AppTheme_Grey_900
else -> R.style.AppTheme_Orange_700
}
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/extensions/Activity-themes.kt | 3252968979 |
package com.simplemobiletools.commons.extensions
import android.text.Editable
import android.text.style.BackgroundColorSpan
fun Editable.clearBackgroundSpans() {
val spans = getSpans(0, length, Any::class.java)
for (span in spans) {
if (span is BackgroundColorSpan) {
removeSpan(span)
}
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/extensions/Editable.kt | 1925476729 |
package com.simplemobiletools.commons.extensions
import android.content.SharedPreferences
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.callbackFlow
context (SharedPreferences)
fun <T> sharedPreferencesCallback(
sendOnCollect: Boolean = false,
value: () -> T?,
): Flow<T?> = callbackFlow {
val sharedPreferencesListener =
SharedPreferences.OnSharedPreferenceChangeListener { _, _ ->
trySend(value())
}
if (sendOnCollect) {
trySend(value())
}
registerOnSharedPreferenceChangeListener(sharedPreferencesListener)
awaitClose { unregisterOnSharedPreferenceChangeListener(sharedPreferencesListener) }
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/extensions/SharedPreferencesProducerExtensions.kt | 166101770 |
package com.simplemobiletools.commons.extensions
import android.graphics.PorterDuff
import android.graphics.drawable.GradientDrawable
import android.widget.ImageView
import androidx.annotation.DrawableRes
fun ImageView.setFillWithStroke(fillColor: Int, backgroundColor: Int, drawRectangle: Boolean = false) {
GradientDrawable().apply {
shape = if (drawRectangle) GradientDrawable.RECTANGLE else GradientDrawable.OVAL
setColor(fillColor)
background = this
if (backgroundColor == fillColor || fillColor == -2 && backgroundColor == -1) {
val strokeColor = backgroundColor.getContrastColor().adjustAlpha(0.5f)
setStroke(2, strokeColor)
}
}
}
fun ImageView.applyColorFilter(color: Int) = setColorFilter(color, PorterDuff.Mode.SRC_IN)
fun ImageView.setImageResourceOrBeGone(@DrawableRes imageRes: Int?) {
if (imageRes != null) {
beVisible()
setImageResource(imageRes)
} else {
beGone()
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/extensions/ImageView.kt | 3102956018 |
package com.simplemobiletools.commons.extensions
import android.graphics.Paint
import android.text.SpannableString
import android.text.TextPaint
import android.text.style.URLSpan
import android.widget.TextView
import androidx.annotation.StringRes
val TextView.value: String get() = text.toString().trim()
fun TextView.underlineText() {
paintFlags = paintFlags or Paint.UNDERLINE_TEXT_FLAG
}
fun TextView.removeUnderlines() {
val spannable = SpannableString(text)
for (u in spannable.getSpans(0, spannable.length, URLSpan::class.java)) {
spannable.setSpan(object : URLSpan(u.url) {
override fun updateDrawState(textPaint: TextPaint) {
super.updateDrawState(textPaint)
textPaint.isUnderlineText = false
}
}, spannable.getSpanStart(u), spannable.getSpanEnd(u), 0)
}
text = spannable
}
fun TextView.setTextOrBeGone(@StringRes textRes: Int?) {
if (textRes != null) {
beVisible()
this.text = context.getString(textRes)
} else {
beGone()
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/extensions/TextView.kt | 3259821595 |
package com.simplemobiletools.commons.extensions
import android.content.ContentUris
import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.hardware.usb.UsbConstants
import android.hardware.usb.UsbManager
import android.media.MediaScannerConnection
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.os.Handler
import android.os.Looper
import android.provider.DocumentsContract
import android.provider.DocumentsContract.Document
import android.provider.MediaStore.*
import android.text.TextUtils
import androidx.annotation.RequiresApi
import androidx.core.content.FileProvider
import androidx.core.net.toUri
import androidx.documentfile.provider.DocumentFile
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.helpers.*
import com.simplemobiletools.commons.models.FileDirItem
import java.io.*
import java.net.URLDecoder
import java.util.*
import java.util.regex.Pattern
private const val ANDROID_DATA_DIR = "/Android/data/"
private const val ANDROID_OBB_DIR = "/Android/obb/"
val DIRS_ACCESSIBLE_ONLY_WITH_SAF = listOf(ANDROID_DATA_DIR, ANDROID_OBB_DIR)
val Context.recycleBinPath: String get() = filesDir.absolutePath
// http://stackoverflow.com/a/40582634/1967672
fun Context.getSDCardPath(): String {
val directories = getStorageDirectories().filter {
!it.equals(getInternalStoragePath()) && !it.equals(
"/storage/emulated/0",
true
) && (baseConfig.OTGPartition.isEmpty() || !it.endsWith(baseConfig.OTGPartition))
}
val fullSDpattern = Pattern.compile(SD_OTG_PATTERN)
var sdCardPath = directories.firstOrNull { fullSDpattern.matcher(it).matches() }
?: directories.firstOrNull { !physicalPaths.contains(it.toLowerCase()) } ?: ""
// on some devices no method retrieved any SD card path, so test if its not sdcard1 by any chance. It happened on an Android 5.1
if (sdCardPath.trimEnd('/').isEmpty()) {
val file = File("/storage/sdcard1")
if (file.exists()) {
return file.absolutePath
}
sdCardPath = directories.firstOrNull() ?: ""
}
if (sdCardPath.isEmpty()) {
val SDpattern = Pattern.compile(SD_OTG_SHORT)
try {
File("/storage").listFiles()?.forEach {
if (SDpattern.matcher(it.name).matches()) {
sdCardPath = "/storage/${it.name}"
}
}
} catch (e: Exception) {
}
}
val finalPath = sdCardPath.trimEnd('/')
baseConfig.sdCardPath = finalPath
return finalPath
}
fun Context.hasExternalSDCard() = sdCardPath.isNotEmpty()
fun Context.hasOTGConnected(): Boolean {
return try {
(getSystemService(Context.USB_SERVICE) as UsbManager).deviceList.any {
it.value.getInterface(0).interfaceClass == UsbConstants.USB_CLASS_MASS_STORAGE
}
} catch (e: Exception) {
false
}
}
fun Context.getStorageDirectories(): Array<String> {
val paths = HashSet<String>()
val rawExternalStorage = System.getenv("EXTERNAL_STORAGE")
val rawSecondaryStoragesStr = System.getenv("SECONDARY_STORAGE")
val rawEmulatedStorageTarget = System.getenv("EMULATED_STORAGE_TARGET")
if (TextUtils.isEmpty(rawEmulatedStorageTarget)) {
getExternalFilesDirs(null).filterNotNull().map { it.absolutePath }
.mapTo(paths) { it.substring(0, it.indexOf("Android/data")) }
} else {
val path = Environment.getExternalStorageDirectory().absolutePath
val folders = Pattern.compile("/").split(path)
val lastFolder = folders[folders.size - 1]
var isDigit = false
try {
Integer.valueOf(lastFolder)
isDigit = true
} catch (ignored: NumberFormatException) {
}
val rawUserId = if (isDigit) lastFolder else ""
if (TextUtils.isEmpty(rawUserId)) {
paths.add(rawEmulatedStorageTarget!!)
} else {
paths.add(rawEmulatedStorageTarget + File.separator + rawUserId)
}
}
if (!TextUtils.isEmpty(rawSecondaryStoragesStr)) {
val rawSecondaryStorages = rawSecondaryStoragesStr!!.split(File.pathSeparator.toRegex()).dropLastWhile(String::isEmpty).toTypedArray()
Collections.addAll(paths, *rawSecondaryStorages)
}
return paths.map { it.trimEnd('/') }.toTypedArray()
}
fun Context.getHumanReadablePath(path: String): String {
return getString(
when (path) {
"/" -> R.string.root
internalStoragePath -> R.string.internal
otgPath -> R.string.usb
else -> R.string.sd_card
}
)
}
fun Context.humanizePath(path: String): String {
val trimmedPath = path.trimEnd('/')
val basePath = path.getBasePath(this)
return when (basePath) {
"/" -> "${getHumanReadablePath(basePath)}$trimmedPath"
else -> trimmedPath.replaceFirst(basePath, getHumanReadablePath(basePath))
}
}
fun Context.getInternalStoragePath() =
if (File("/storage/emulated/0").exists()) "/storage/emulated/0" else Environment.getExternalStorageDirectory().absolutePath.trimEnd('/')
fun Context.isPathOnSD(path: String) = sdCardPath.isNotEmpty() && path.startsWith(sdCardPath)
fun Context.isPathOnOTG(path: String) = otgPath.isNotEmpty() && path.startsWith(otgPath)
fun Context.isPathOnInternalStorage(path: String) = internalStoragePath.isNotEmpty() && path.startsWith(internalStoragePath)
fun Context.getSAFOnlyDirs(): List<String> {
return DIRS_ACCESSIBLE_ONLY_WITH_SAF.map { "$internalStoragePath$it" } +
DIRS_ACCESSIBLE_ONLY_WITH_SAF.map { "$sdCardPath$it" }
}
fun Context.isSAFOnlyRoot(path: String): Boolean {
return getSAFOnlyDirs().any { "${path.trimEnd('/')}/".startsWith(it) }
}
fun Context.isRestrictedSAFOnlyRoot(path: String): Boolean {
return isRPlus() && isSAFOnlyRoot(path)
}
// no need to use DocumentFile if an SD card is set as the default storage
fun Context.needsStupidWritePermissions(path: String) = (!isRPlus() && isPathOnSD(path) && !isSDCardSetAsDefaultStorage()) || isPathOnOTG(path)
fun Context.isSDCardSetAsDefaultStorage() = sdCardPath.isNotEmpty() && Environment.getExternalStorageDirectory().absolutePath.equals(sdCardPath, true)
fun Context.hasProperStoredTreeUri(isOTG: Boolean): Boolean {
val uri = if (isOTG) baseConfig.OTGTreeUri else baseConfig.sdTreeUri
val hasProperUri = contentResolver.persistedUriPermissions.any { it.uri.toString() == uri }
if (!hasProperUri) {
if (isOTG) {
baseConfig.OTGTreeUri = ""
} else {
baseConfig.sdTreeUri = ""
}
}
return hasProperUri
}
fun Context.hasProperStoredAndroidTreeUri(path: String): Boolean {
val uri = getAndroidTreeUri(path)
val hasProperUri = contentResolver.persistedUriPermissions.any { it.uri.toString() == uri }
if (!hasProperUri) {
storeAndroidTreeUri(path, "")
}
return hasProperUri
}
fun Context.getAndroidTreeUri(path: String): String {
return when {
isPathOnOTG(path) -> if (isAndroidDataDir(path)) baseConfig.otgAndroidDataTreeUri else baseConfig.otgAndroidObbTreeUri
isPathOnSD(path) -> if (isAndroidDataDir(path)) baseConfig.sdAndroidDataTreeUri else baseConfig.sdAndroidObbTreeUri
else -> if (isAndroidDataDir(path)) baseConfig.primaryAndroidDataTreeUri else baseConfig.primaryAndroidObbTreeUri
}
}
fun isAndroidDataDir(path: String): Boolean {
val resolvedPath = "${path.trimEnd('/')}/"
return resolvedPath.contains(ANDROID_DATA_DIR)
}
fun Context.storeAndroidTreeUri(path: String, treeUri: String) {
return when {
isPathOnOTG(path) -> if (isAndroidDataDir(path)) baseConfig.otgAndroidDataTreeUri = treeUri else baseConfig.otgAndroidObbTreeUri = treeUri
isPathOnSD(path) -> if (isAndroidDataDir(path)) baseConfig.sdAndroidDataTreeUri = treeUri else baseConfig.sdAndroidObbTreeUri = treeUri
else -> if (isAndroidDataDir(path)) baseConfig.primaryAndroidDataTreeUri = treeUri else baseConfig.primaryAndroidObbTreeUri = treeUri
}
}
fun Context.getSAFStorageId(fullPath: String): String {
return if (fullPath.startsWith('/')) {
when {
fullPath.startsWith(internalStoragePath) -> "primary"
else -> fullPath.substringAfter("/storage/", "").substringBefore('/')
}
} else {
fullPath.substringBefore(':', "").substringAfterLast('/')
}
}
fun Context.createDocumentUriFromRootTree(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 = DocumentsContract.buildTreeDocumentUri(EXTERNAL_STORAGE_PROVIDER_AUTHORITY, "$storageId:")
val documentId = "${storageId}:$relativePath"
return DocumentsContract.buildDocumentUriUsingTree(treeUri, documentId)
}
fun Context.createAndroidDataOrObbPath(fullPath: String): String {
return if (isAndroidDataDir(fullPath)) {
fullPath.getBasePath(this).trimEnd('/').plus(ANDROID_DATA_DIR)
} else {
fullPath.getBasePath(this).trimEnd('/').plus(ANDROID_OBB_DIR)
}
}
fun Context.createAndroidDataOrObbUri(fullPath: String): Uri {
val path = createAndroidDataOrObbPath(fullPath)
return createDocumentUriFromRootTree(path)
}
fun Context.getStorageRootIdForAndroidDir(path: String) =
getAndroidTreeUri(path).removeSuffix(if (isAndroidDataDir(path)) "%3AAndroid%2Fdata" else "%3AAndroid%2Fobb").substringAfterLast('/').trimEnd('/')
fun Context.isAStorageRootFolder(path: String): Boolean {
val trimmed = path.trimEnd('/')
return trimmed.isEmpty() || trimmed.equals(internalStoragePath, true) || trimmed.equals(sdCardPath, true) || trimmed.equals(otgPath, true)
}
fun Context.getMyFileUri(file: File): Uri {
return if (isNougatPlus()) {
FileProvider.getUriForFile(this, "$packageName.provider", file)
} else {
Uri.fromFile(file)
}
}
fun Context.tryFastDocumentDelete(path: String, allowDeleteFolder: Boolean): Boolean {
val document = getFastDocumentFile(path)
return if (document?.isFile == true || allowDeleteFolder) {
try {
DocumentsContract.deleteDocument(contentResolver, document?.uri!!)
} catch (e: Exception) {
false
}
} else {
false
}
}
fun Context.getFastDocumentFile(path: String): DocumentFile? {
if (isPathOnOTG(path)) {
return getOTGFastDocumentFile(path)
}
if (baseConfig.sdCardPath.isEmpty()) {
return null
}
val relativePath = Uri.encode(path.substring(baseConfig.sdCardPath.length).trim('/'))
val externalPathPart = baseConfig.sdCardPath.split("/").lastOrNull(String::isNotEmpty)?.trim('/') ?: return null
val fullUri = "${baseConfig.sdTreeUri}/document/$externalPathPart%3A$relativePath"
return DocumentFile.fromSingleUri(this, Uri.parse(fullUri))
}
fun Context.getOTGFastDocumentFile(path: String, otgPathToUse: String? = null): DocumentFile? {
if (baseConfig.OTGTreeUri.isEmpty()) {
return null
}
val otgPath = otgPathToUse ?: baseConfig.OTGPath
if (baseConfig.OTGPartition.isEmpty()) {
baseConfig.OTGPartition = baseConfig.OTGTreeUri.removeSuffix("%3A").substringAfterLast('/').trimEnd('/')
updateOTGPathFromPartition()
}
val relativePath = Uri.encode(path.substring(otgPath.length).trim('/'))
val fullUri = "${baseConfig.OTGTreeUri}/document/${baseConfig.OTGPartition}%3A$relativePath"
return DocumentFile.fromSingleUri(this, Uri.parse(fullUri))
}
fun Context.getDocumentFile(path: String): DocumentFile? {
val isOTG = isPathOnOTG(path)
var relativePath = path.substring(if (isOTG) otgPath.length else sdCardPath.length)
if (relativePath.startsWith(File.separator)) {
relativePath = relativePath.substring(1)
}
return try {
val treeUri = Uri.parse(if (isOTG) baseConfig.OTGTreeUri else baseConfig.sdTreeUri)
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.getSomeDocumentFile(path: String) = getFastDocumentFile(path) ?: getDocumentFile(path)
fun Context.scanFileRecursively(file: File, callback: (() -> Unit)? = null) {
scanFilesRecursively(arrayListOf(file), callback)
}
fun Context.scanPathRecursively(path: String, callback: (() -> Unit)? = null) {
scanPathsRecursively(arrayListOf(path), callback)
}
fun Context.scanFilesRecursively(files: List<File>, callback: (() -> Unit)? = null) {
val allPaths = ArrayList<String>()
for (file in files) {
allPaths.addAll(getPaths(file))
}
rescanPaths(allPaths, callback)
}
fun Context.scanPathsRecursively(paths: List<String>, callback: (() -> Unit)? = null) {
val allPaths = ArrayList<String>()
for (path in paths) {
allPaths.addAll(getPaths(File(path)))
}
rescanPaths(allPaths, callback)
}
fun Context.rescanPath(path: String, callback: (() -> Unit)? = null) {
rescanPaths(arrayListOf(path), callback)
}
// avoid calling this multiple times in row, it can delete whole folder contents
fun Context.rescanPaths(paths: List<String>, callback: (() -> Unit)? = null) {
if (paths.isEmpty()) {
callback?.invoke()
return
}
for (path in paths) {
Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE).apply {
data = Uri.fromFile(File(path))
sendBroadcast(this)
}
}
var cnt = paths.size
MediaScannerConnection.scanFile(applicationContext, paths.toTypedArray(), null) { s, uri ->
if (--cnt == 0) {
callback?.invoke()
}
}
}
fun getPaths(file: File): ArrayList<String> {
val paths = arrayListOf<String>(file.absolutePath)
if (file.isDirectory) {
val files = file.listFiles() ?: return paths
for (curFile in files) {
paths.addAll(getPaths(curFile))
}
}
return paths
}
fun Context.getFileUri(path: String) = when {
path.isImageSlow() -> Images.Media.EXTERNAL_CONTENT_URI
path.isVideoSlow() -> Video.Media.EXTERNAL_CONTENT_URI
path.isAudioSlow() -> Audio.Media.EXTERNAL_CONTENT_URI
else -> Files.getContentUri("external")
}
// these functions update the mediastore instantly, MediaScannerConnection.scanFileRecursively takes some time to really get applied
fun Context.deleteFromMediaStore(path: String, callback: ((needsRescan: Boolean) -> Unit)? = null) {
if (getIsPathDirectory(path)) {
callback?.invoke(false)
return
}
ensureBackgroundThread {
try {
val where = "${MediaColumns.DATA} = ?"
val args = arrayOf(path)
val needsRescan = contentResolver.delete(getFileUri(path), where, args) != 1
callback?.invoke(needsRescan)
} catch (ignored: Exception) {
callback?.invoke(true)
}
}
}
fun Context.rescanAndDeletePath(path: String, callback: () -> Unit) {
val SCAN_FILE_MAX_DURATION = 1000L
val scanFileHandler = Handler(Looper.getMainLooper())
scanFileHandler.postDelayed({
callback()
}, SCAN_FILE_MAX_DURATION)
MediaScannerConnection.scanFile(applicationContext, arrayOf(path), null) { path, uri ->
scanFileHandler.removeCallbacksAndMessages(null)
try {
applicationContext.contentResolver.delete(uri, null, null)
} catch (e: Exception) {
}
callback()
}
}
fun Context.updateInMediaStore(oldPath: String, newPath: String) {
ensureBackgroundThread {
val values = ContentValues().apply {
put(MediaColumns.DATA, newPath)
put(MediaColumns.DISPLAY_NAME, newPath.getFilenameFromPath())
put(MediaColumns.TITLE, newPath.getFilenameFromPath())
}
val uri = getFileUri(oldPath)
val selection = "${MediaColumns.DATA} = ?"
val selectionArgs = arrayOf(oldPath)
try {
contentResolver.update(uri, values, selection, selectionArgs)
} catch (ignored: Exception) {
}
}
}
fun Context.updateLastModified(path: String, lastModified: Long) {
val values = ContentValues().apply {
put(MediaColumns.DATE_MODIFIED, lastModified / 1000)
}
File(path).setLastModified(lastModified)
val uri = getFileUri(path)
val selection = "${MediaColumns.DATA} = ?"
val selectionArgs = arrayOf(path)
try {
contentResolver.update(uri, values, selection, selectionArgs)
} catch (ignored: Exception) {
}
}
fun Context.getOTGItems(path: String, shouldShowHidden: Boolean, getProperFileSize: Boolean, callback: (ArrayList<FileDirItem>) -> Unit) {
val items = ArrayList<FileDirItem>()
val OTGTreeUri = baseConfig.OTGTreeUri
var rootUri = try {
DocumentFile.fromTreeUri(applicationContext, Uri.parse(OTGTreeUri))
} catch (e: Exception) {
showErrorToast(e)
baseConfig.OTGPath = ""
baseConfig.OTGTreeUri = ""
baseConfig.OTGPartition = ""
null
}
if (rootUri == null) {
callback(items)
return
}
val parts = path.split("/").dropLastWhile { it.isEmpty() }
for (part in parts) {
if (path == otgPath) {
break
}
if (part == "otg:" || part == "") {
continue
}
val file = rootUri!!.findFile(part)
if (file != null) {
rootUri = file
}
}
val files = rootUri!!.listFiles().filter { it.exists() }
val basePath = "${baseConfig.OTGTreeUri}/document/${baseConfig.OTGPartition}%3A"
for (file in files) {
val name = file.name ?: continue
if (!shouldShowHidden && name.startsWith(".")) {
continue
}
val isDirectory = file.isDirectory
val filePath = file.uri.toString().substring(basePath.length)
val decodedPath = otgPath + "/" + URLDecoder.decode(filePath, "UTF-8")
val fileSize = when {
getProperFileSize -> file.getItemSize(shouldShowHidden)
isDirectory -> 0L
else -> file.length()
}
val childrenCount = if (isDirectory) {
file.listFiles().size
} else {
0
}
val lastModified = file.lastModified()
val fileDirItem = FileDirItem(decodedPath, name, isDirectory, childrenCount, fileSize, lastModified)
items.add(fileDirItem)
}
callback(items)
}
@RequiresApi(Build.VERSION_CODES.O)
fun Context.getAndroidSAFFileItems(path: String, shouldShowHidden: Boolean, getProperFileSize: Boolean = true, callback: (ArrayList<FileDirItem>) -> Unit) {
val items = ArrayList<FileDirItem>()
val rootDocId = getStorageRootIdForAndroidDir(path)
val treeUri = getAndroidTreeUri(path).toUri()
val documentId = createAndroidSAFDocumentId(path)
val childrenUri = try {
DocumentsContract.buildChildDocumentsUriUsingTree(treeUri, documentId)
} catch (e: Exception) {
showErrorToast(e)
storeAndroidTreeUri(path, "")
null
}
if (childrenUri == null) {
callback(items)
return
}
val projection = arrayOf(Document.COLUMN_DOCUMENT_ID, Document.COLUMN_DISPLAY_NAME, Document.COLUMN_MIME_TYPE, Document.COLUMN_LAST_MODIFIED)
try {
val rawCursor = contentResolver.query(childrenUri, projection, null, null)!!
val cursor = ExternalStorageProviderHack.transformQueryResult(rootDocId, childrenUri, rawCursor)
cursor.use {
if (cursor.moveToFirst()) {
do {
val docId = cursor.getStringValue(Document.COLUMN_DOCUMENT_ID)
val name = cursor.getStringValue(Document.COLUMN_DISPLAY_NAME)
val mimeType = cursor.getStringValue(Document.COLUMN_MIME_TYPE)
val lastModified = cursor.getLongValue(Document.COLUMN_LAST_MODIFIED)
val isDirectory = mimeType == Document.MIME_TYPE_DIR
val filePath = docId.substring("${getStorageRootIdForAndroidDir(path)}:".length)
if (!shouldShowHidden && name.startsWith(".")) {
continue
}
val decodedPath = path.getBasePath(this) + "/" + URLDecoder.decode(filePath, "UTF-8")
val fileSize = when {
getProperFileSize -> getFileSize(treeUri, docId)
isDirectory -> 0L
else -> getFileSize(treeUri, docId)
}
val childrenCount = if (isDirectory) {
getDirectChildrenCount(rootDocId, treeUri, docId, shouldShowHidden)
} else {
0
}
val fileDirItem = FileDirItem(decodedPath, name, isDirectory, childrenCount, fileSize, lastModified)
items.add(fileDirItem)
} while (cursor.moveToNext())
}
}
} catch (e: Exception) {
showErrorToast(e)
}
callback(items)
}
fun Context.getDirectChildrenCount(rootDocId: String, treeUri: Uri, documentId: String, shouldShowHidden: Boolean): Int {
return try {
val projection = arrayOf(Document.COLUMN_DOCUMENT_ID)
val childrenUri = DocumentsContract.buildChildDocumentsUriUsingTree(treeUri, documentId)
val rawCursor = contentResolver.query(childrenUri, projection, null, null, null)!!
val cursor = ExternalStorageProviderHack.transformQueryResult(rootDocId, childrenUri, rawCursor)
if (shouldShowHidden) {
cursor.count
} else {
var count = 0
cursor.use {
while (cursor.moveToNext()) {
val docId = cursor.getStringValue(Document.COLUMN_DOCUMENT_ID)
if (!docId.getFilenameFromPath().startsWith('.') || shouldShowHidden) {
count++
}
}
}
count
}
} catch (e: Exception) {
0
}
}
fun Context.getProperChildrenCount(rootDocId: String, treeUri: Uri, documentId: String, shouldShowHidden: Boolean): Int {
val projection = arrayOf(Document.COLUMN_DOCUMENT_ID, Document.COLUMN_MIME_TYPE)
val childrenUri = DocumentsContract.buildChildDocumentsUriUsingTree(treeUri, documentId)
val rawCursor = contentResolver.query(childrenUri, projection, null, null, null)!!
val cursor = ExternalStorageProviderHack.transformQueryResult(rootDocId, childrenUri, rawCursor)
return if (cursor.count > 0) {
var count = 0
cursor.use {
while (cursor.moveToNext()) {
val docId = cursor.getStringValue(Document.COLUMN_DOCUMENT_ID)
val mimeType = cursor.getStringValue(Document.COLUMN_MIME_TYPE)
if (mimeType == Document.MIME_TYPE_DIR) {
count++
count += getProperChildrenCount(rootDocId, treeUri, docId, shouldShowHidden)
} else if (!docId.getFilenameFromPath().startsWith('.') || shouldShowHidden) {
count++
}
}
}
count
} else {
1
}
}
fun Context.getFileSize(treeUri: Uri, documentId: String): Long {
val projection = arrayOf(Document.COLUMN_SIZE)
val documentUri = DocumentsContract.buildDocumentUriUsingTree(treeUri, documentId)
return contentResolver.query(documentUri, projection, null, null, null)?.use { cursor ->
if (cursor.moveToFirst()) {
cursor.getLongValue(Document.COLUMN_SIZE)
} else {
0L
}
} ?: 0L
}
fun Context.createAndroidSAFDocumentId(path: String): String {
val basePath = path.getBasePath(this)
val relativePath = path.substring(basePath.length).trim('/')
val storageId = getStorageRootIdForAndroidDir(path)
return "$storageId:$relativePath"
}
fun Context.getAndroidSAFUri(path: String): Uri {
val treeUri = getAndroidTreeUri(path).toUri()
val documentId = createAndroidSAFDocumentId(path)
return DocumentsContract.buildDocumentUriUsingTree(treeUri, documentId)
}
fun Context.getAndroidSAFDocument(path: String): DocumentFile? {
val basePath = path.getBasePath(this)
val androidPath = File(basePath, "Android").path
var relativePath = path.substring(androidPath.length)
if (relativePath.startsWith(File.separator)) {
relativePath = relativePath.substring(1)
}
return try {
val treeUri = getAndroidTreeUri(path).toUri()
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.getSomeAndroidSAFDocument(path: String): DocumentFile? = getFastAndroidSAFDocument(path) ?: getAndroidSAFDocument(path)
fun Context.getFastAndroidSAFDocument(path: String): DocumentFile? {
val treeUri = getAndroidTreeUri(path)
if (treeUri.isEmpty()) {
return null
}
val uri = getAndroidSAFUri(path)
return DocumentFile.fromSingleUri(this, uri)
}
fun Context.getAndroidSAFChildrenUri(path: String): Uri {
val treeUri = getAndroidTreeUri(path).toUri()
val documentId = createAndroidSAFDocumentId(path)
return DocumentsContract.buildChildDocumentsUriUsingTree(treeUri, documentId)
}
fun Context.createAndroidSAFDirectory(path: String): Boolean {
return try {
val treeUri = getAndroidTreeUri(path).toUri()
val parentPath = path.getParentPath()
if (!getDoesFilePathExist(parentPath)) {
createAndroidSAFDirectory(parentPath)
}
val documentId = createAndroidSAFDocumentId(parentPath)
val parentUri = DocumentsContract.buildDocumentUriUsingTree(treeUri, documentId)
DocumentsContract.createDocument(contentResolver, parentUri, Document.MIME_TYPE_DIR, path.getFilenameFromPath()) != null
} catch (e: IllegalStateException) {
showErrorToast(e)
false
}
}
fun Context.createAndroidSAFFile(path: String): Boolean {
return try {
val treeUri = getAndroidTreeUri(path).toUri()
val parentPath = path.getParentPath()
if (!getDoesFilePathExist(parentPath)) {
createAndroidSAFDirectory(parentPath)
}
val documentId = createAndroidSAFDocumentId(path.getParentPath())
val parentUri = DocumentsContract.buildDocumentUriUsingTree(treeUri, documentId)
DocumentsContract.createDocument(contentResolver, parentUri, path.getMimeType(), path.getFilenameFromPath()) != null
} catch (e: IllegalStateException) {
showErrorToast(e)
false
}
}
fun Context.renameAndroidSAFDocument(oldPath: String, newPath: String): Boolean {
return try {
val treeUri = getAndroidTreeUri(oldPath).toUri()
val documentId = createAndroidSAFDocumentId(oldPath)
val parentUri = DocumentsContract.buildDocumentUriUsingTree(treeUri, documentId)
DocumentsContract.renameDocument(contentResolver, parentUri, newPath.getFilenameFromPath()) != null
} catch (e: IllegalStateException) {
showErrorToast(e)
false
}
}
fun Context.getAndroidSAFFileSize(path: String): Long {
val treeUri = getAndroidTreeUri(path).toUri()
val documentId = createAndroidSAFDocumentId(path)
return getFileSize(treeUri, documentId)
}
fun Context.getAndroidSAFFileCount(path: String, countHidden: Boolean): Int {
val treeUri = getAndroidTreeUri(path).toUri()
if (treeUri == Uri.EMPTY) {
return 0
}
val documentId = createAndroidSAFDocumentId(path)
val rootDocId = getStorageRootIdForAndroidDir(path)
return getProperChildrenCount(rootDocId, treeUri, documentId, countHidden)
}
fun Context.getAndroidSAFDirectChildrenCount(path: String, countHidden: Boolean): Int {
val treeUri = getAndroidTreeUri(path).toUri()
if (treeUri == Uri.EMPTY) {
return 0
}
val documentId = createAndroidSAFDocumentId(path)
val rootDocId = getStorageRootIdForAndroidDir(path)
return getDirectChildrenCount(rootDocId, treeUri, documentId, countHidden)
}
fun Context.getAndroidSAFLastModified(path: String): Long {
val treeUri = getAndroidTreeUri(path).toUri()
if (treeUri == Uri.EMPTY) {
return 0L
}
val documentId = createAndroidSAFDocumentId(path)
val projection = arrayOf(Document.COLUMN_LAST_MODIFIED)
val documentUri = DocumentsContract.buildDocumentUriUsingTree(treeUri, documentId)
return contentResolver.query(documentUri, projection, null, null, null)?.use { cursor ->
if (cursor.moveToFirst()) {
cursor.getLongValue(Document.COLUMN_LAST_MODIFIED)
} else {
0L
}
} ?: 0L
}
fun Context.deleteAndroidSAFDirectory(path: String, allowDeleteFolder: Boolean = false, callback: ((wasSuccess: Boolean) -> Unit)? = null) {
val treeUri = getAndroidTreeUri(path).toUri()
val documentId = createAndroidSAFDocumentId(path)
try {
val uri = DocumentsContract.buildDocumentUriUsingTree(treeUri, documentId)
val document = DocumentFile.fromSingleUri(this, uri)
val fileDeleted = (document!!.isFile || allowDeleteFolder) && DocumentsContract.deleteDocument(applicationContext.contentResolver, document.uri)
callback?.invoke(fileDeleted)
} catch (e: Exception) {
showErrorToast(e)
callback?.invoke(false)
storeAndroidTreeUri(path, "")
}
}
fun Context.trySAFFileDelete(fileDirItem: FileDirItem, allowDeleteFolder: Boolean = false, callback: ((wasSuccess: Boolean) -> Unit)? = null) {
var fileDeleted = tryFastDocumentDelete(fileDirItem.path, allowDeleteFolder)
if (!fileDeleted) {
val document = getDocumentFile(fileDirItem.path)
if (document != null && (fileDirItem.isDirectory == document.isDirectory)) {
try {
fileDeleted = (document.isFile || allowDeleteFolder) && DocumentsContract.deleteDocument(applicationContext.contentResolver, document.uri)
} catch (ignored: Exception) {
baseConfig.sdTreeUri = ""
baseConfig.sdCardPath = ""
}
}
}
if (fileDeleted) {
deleteFromMediaStore(fileDirItem.path)
callback?.invoke(true)
}
}
fun Context.getFileInputStreamSync(path: String): InputStream? {
return when {
isRestrictedSAFOnlyRoot(path) -> {
val uri = getAndroidSAFUri(path)
applicationContext.contentResolver.openInputStream(uri)
}
isAccessibleWithSAFSdk30(path) -> {
try {
FileInputStream(File(path))
} catch (e: Exception) {
val uri = createDocumentUriUsingFirstParentTreeUri(path)
applicationContext.contentResolver.openInputStream(uri)
}
}
isPathOnOTG(path) -> {
val fileDocument = getSomeDocumentFile(path)
applicationContext.contentResolver.openInputStream(fileDocument?.uri!!)
}
else -> FileInputStream(File(path))
}
}
fun Context.updateOTGPathFromPartition() {
val otgPath = "/storage/${baseConfig.OTGPartition}"
baseConfig.OTGPath = if (getOTGFastDocumentFile(otgPath, otgPath)?.exists() == true) {
"/storage/${baseConfig.OTGPartition}"
} else {
"/mnt/media_rw/${baseConfig.OTGPartition}"
}
}
fun Context.getDoesFilePathExist(path: String, otgPathToUse: String? = null): Boolean {
val otgPath = otgPathToUse ?: baseConfig.OTGPath
return when {
isRestrictedSAFOnlyRoot(path) -> getFastAndroidSAFDocument(path)?.exists() ?: false
otgPath.isNotEmpty() && path.startsWith(otgPath) -> getOTGFastDocumentFile(path)?.exists() ?: false
else -> File(path).exists()
}
}
fun Context.getIsPathDirectory(path: String): Boolean {
return when {
isRestrictedSAFOnlyRoot(path) -> getFastAndroidSAFDocument(path)?.isDirectory ?: false
isPathOnOTG(path) -> getOTGFastDocumentFile(path)?.isDirectory ?: false
else -> File(path).isDirectory
}
}
fun Context.getFolderLastModifieds(folder: String): HashMap<String, Long> {
val lastModifieds = HashMap<String, Long>()
val projection = arrayOf(
Images.Media.DISPLAY_NAME,
Images.Media.DATE_MODIFIED
)
val uri = Files.getContentUri("external")
val selection = "${Images.Media.DATA} LIKE ? AND ${Images.Media.DATA} NOT LIKE ? AND ${Images.Media.MIME_TYPE} IS NOT NULL" // avoid selecting folders
val selectionArgs = arrayOf("$folder/%", "$folder/%/%")
try {
val cursor = contentResolver.query(uri, projection, selection, selectionArgs, null)
cursor?.use {
if (cursor.moveToFirst()) {
do {
try {
val lastModified = cursor.getLongValue(Images.Media.DATE_MODIFIED) * 1000
if (lastModified != 0L) {
val name = cursor.getStringValue(Images.Media.DISPLAY_NAME)
lastModifieds["$folder/$name"] = lastModified
}
} catch (e: Exception) {
}
} while (cursor.moveToNext())
}
}
} catch (e: Exception) {
}
return lastModifieds
}
// avoid these being set as SD card paths
private val physicalPaths = arrayListOf(
"/storage/sdcard1", // Motorola Xoom
"/storage/extsdcard", // Samsung SGS3
"/storage/sdcard0/external_sdcard", // User request
"/mnt/extsdcard", "/mnt/sdcard/external_sd", // Samsung galaxy family
"/mnt/external_sd", "/mnt/media_rw/sdcard1", // 4.4.2 on CyanogenMod S3
"/removable/microsd", // Asus transformer prime
"/mnt/emmc", "/storage/external_SD", // LG
"/storage/ext_sd", // HTC One Max
"/storage/removable/sdcard1", // Sony Xperia Z1
"/data/sdext", "/data/sdext2", "/data/sdext3", "/data/sdext4", "/sdcard1", // Sony Xperia Z
"/sdcard2", // HTC One M8s
"/storage/usbdisk0",
"/storage/usbdisk1",
"/storage/usbdisk2"
)
// Convert paths like /storage/emulated/0/Pictures/Screenshots/first.jpg to content://media/external/images/media/131799
// so that we can refer to the file in the MediaStore.
// If we found no mediastore uri for a given file, do not return its path either to avoid some mismatching
fun Context.getUrisPathsFromFileDirItems(fileDirItems: List<FileDirItem>): Pair<ArrayList<String>, ArrayList<Uri>> {
val fileUris = ArrayList<Uri>()
val successfulFilePaths = ArrayList<String>()
val allIds = getMediaStoreIds(this)
val filePaths = fileDirItems.map { it.path }
filePaths.forEach { path ->
for ((filePath, mediaStoreId) in allIds) {
if (filePath.lowercase() == path.lowercase()) {
val baseUri = getFileUri(filePath)
val uri = ContentUris.withAppendedId(baseUri, mediaStoreId)
fileUris.add(uri)
successfulFilePaths.add(path)
}
}
}
return Pair(successfulFilePaths, fileUris)
}
fun getMediaStoreIds(context: Context): HashMap<String, Long> {
val ids = HashMap<String, Long>()
val projection = arrayOf(
Images.Media.DATA,
Images.Media._ID
)
val uri = Files.getContentUri("external")
try {
context.queryCursor(uri, projection) { cursor ->
try {
val id = cursor.getLongValue(Images.Media._ID)
if (id != 0L) {
val path = cursor.getStringValue(Images.Media.DATA)
ids[path] = id
}
} catch (e: Exception) {
}
}
} catch (e: Exception) {
}
return ids
}
fun Context.getFileUrisFromFileDirItems(fileDirItems: List<FileDirItem>): List<Uri> {
val fileUris = getUrisPathsFromFileDirItems(fileDirItems).second
if (fileUris.isEmpty()) {
fileDirItems.map { fileDirItem ->
fileUris.add(fileDirItem.assembleContentUri())
}
}
return fileUris
}
fun Context.getDefaultCopyDestinationPath(showHidden: Boolean, currentPath: String): String {
val lastCopyPath = baseConfig.lastCopyPath
return if (getDoesFilePathExist(lastCopyPath)) {
val isLastCopyPathVisible = !lastCopyPath.split(File.separator).any { it.startsWith(".") && it.length > 1 }
if (showHidden || isLastCopyPathVisible) {
lastCopyPath
} else {
currentPath
}
} else {
currentPath
}
}
fun Context.createDirectorySync(directory: String): Boolean {
if (getDoesFilePathExist(directory)) {
return true
}
if (needsStupidWritePermissions(directory)) {
val documentFile = getDocumentFile(directory.getParentPath()) ?: return false
val newDir = documentFile.createDirectory(directory.getFilenameFromPath()) ?: getDocumentFile(directory)
return newDir != null
}
if (isRestrictedSAFOnlyRoot(directory)) {
return createAndroidSAFDirectory(directory)
}
if (isAccessibleWithSAFSdk30(directory)) {
return createSAFDirectorySdk30(directory)
}
return File(directory).mkdirs()
}
fun Context.getFileOutputStreamSync(path: String, mimeType: String, parentDocumentFile: DocumentFile? = null): OutputStream? {
val targetFile = File(path)
return when {
isRestrictedSAFOnlyRoot(path) -> {
val uri = getAndroidSAFUri(path)
if (!getDoesFilePathExist(path)) {
createAndroidSAFFile(path)
}
applicationContext.contentResolver.openOutputStream(uri, "wt")
}
needsStupidWritePermissions(path) -> {
var documentFile = parentDocumentFile
if (documentFile == null) {
if (getDoesFilePathExist(targetFile.parentFile.absolutePath)) {
documentFile = getDocumentFile(targetFile.parent)
} else {
documentFile = getDocumentFile(targetFile.parentFile.parent)
documentFile = documentFile!!.createDirectory(targetFile.parentFile.name) ?: getDocumentFile(targetFile.parentFile.absolutePath)
}
}
if (documentFile == null) {
val casualOutputStream = createCasualFileOutputStream(targetFile)
return if (casualOutputStream == null) {
showFileCreateError(targetFile.parent)
null
} else {
casualOutputStream
}
}
try {
val uri = if (getDoesFilePathExist(path)) {
createDocumentUriFromRootTree(path)
} else {
documentFile.createFile(mimeType, path.getFilenameFromPath())!!.uri
}
applicationContext.contentResolver.openOutputStream(uri, "wt")
} catch (e: Exception) {
showErrorToast(e)
null
}
}
isAccessibleWithSAFSdk30(path) -> {
try {
val uri = createDocumentUriUsingFirstParentTreeUri(path)
if (!getDoesFilePathExist(path)) {
createSAFFileSdk30(path)
}
applicationContext.contentResolver.openOutputStream(uri, "wt")
} catch (e: Exception) {
null
} ?: createCasualFileOutputStream(targetFile)
}
else -> return createCasualFileOutputStream(targetFile)
}
}
fun Context.showFileCreateError(path: String) {
val error = String.format(getString(R.string.could_not_create_file), path)
baseConfig.sdTreeUri = ""
showErrorToast(error)
}
private fun Context.createCasualFileOutputStream(targetFile: File): OutputStream? {
if (targetFile.parentFile?.exists() == false) {
targetFile.parentFile?.mkdirs()
}
return try {
FileOutputStream(targetFile)
} catch (e: Exception) {
showErrorToast(e)
null
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/extensions/Context-storage.kt | 4228828839 |
package com.simplemobiletools.commons.extensions
import android.annotation.TargetApi
import android.content.Context
import android.os.Build
import androidx.exifinterface.media.ExifInterface
import java.text.SimpleDateFormat
import java.util.*
fun ExifInterface.copyTo(destination: ExifInterface, copyOrientation: Boolean = true) {
val attributes = arrayListOf(
ExifInterface.TAG_APERTURE_VALUE,
ExifInterface.TAG_DATETIME,
ExifInterface.TAG_DATETIME_DIGITIZED,
ExifInterface.TAG_DATETIME_ORIGINAL,
ExifInterface.TAG_EXPOSURE_TIME,
ExifInterface.TAG_FLASH,
ExifInterface.TAG_FOCAL_LENGTH,
ExifInterface.TAG_GPS_ALTITUDE,
ExifInterface.TAG_GPS_ALTITUDE_REF,
ExifInterface.TAG_GPS_DATESTAMP,
ExifInterface.TAG_GPS_LATITUDE,
ExifInterface.TAG_GPS_LATITUDE_REF,
ExifInterface.TAG_GPS_LONGITUDE,
ExifInterface.TAG_GPS_LONGITUDE_REF,
ExifInterface.TAG_GPS_PROCESSING_METHOD,
ExifInterface.TAG_GPS_TIMESTAMP,
ExifInterface.TAG_IMAGE_LENGTH,
ExifInterface.TAG_IMAGE_WIDTH,
ExifInterface.TAG_ISO_SPEED_RATINGS,
ExifInterface.TAG_MAKE,
ExifInterface.TAG_MODEL,
ExifInterface.TAG_WHITE_BALANCE
)
if (copyOrientation) {
attributes.add(ExifInterface.TAG_ORIENTATION)
}
attributes.forEach {
val value = getAttribute(it)
if (value != null) {
destination.setAttribute(it, value)
}
}
try {
destination.saveAttributes()
} catch (ignored: Exception) {
}
}
fun ExifInterface.removeValues() {
val attributes = arrayListOf(
// ExifInterface.TAG_ORIENTATION, // do not remove the orientation, it could lead to unexpected behaviour at displaying the file
ExifInterface.TAG_APERTURE_VALUE,
ExifInterface.TAG_DATETIME,
ExifInterface.TAG_DATETIME_DIGITIZED,
ExifInterface.TAG_DATETIME_ORIGINAL,
ExifInterface.TAG_EXPOSURE_TIME,
ExifInterface.TAG_FLASH,
ExifInterface.TAG_F_NUMBER,
ExifInterface.TAG_FOCAL_LENGTH,
ExifInterface.TAG_GPS_ALTITUDE,
ExifInterface.TAG_GPS_ALTITUDE_REF,
ExifInterface.TAG_GPS_DATESTAMP,
ExifInterface.TAG_GPS_LATITUDE,
ExifInterface.TAG_GPS_LATITUDE_REF,
ExifInterface.TAG_GPS_LONGITUDE,
ExifInterface.TAG_GPS_LONGITUDE_REF,
ExifInterface.TAG_GPS_PROCESSING_METHOD,
ExifInterface.TAG_GPS_TIMESTAMP,
ExifInterface.TAG_IMAGE_LENGTH,
ExifInterface.TAG_IMAGE_WIDTH,
ExifInterface.TAG_ISO_SPEED_RATINGS,
ExifInterface.TAG_MAKE,
ExifInterface.TAG_MODEL,
ExifInterface.TAG_WHITE_BALANCE
)
attributes.forEach {
setAttribute(it, null)
}
saveAttributes()
}
fun ExifInterface.getExifProperties(): String {
var exifString = ""
getAttribute(ExifInterface.TAG_F_NUMBER).let {
if (it?.isNotEmpty() == true) {
val number = it.trimEnd('0').trimEnd('.')
exifString += "F/$number "
}
}
getAttribute(ExifInterface.TAG_FOCAL_LENGTH).let {
if (it?.isNotEmpty() == true) {
val values = it.split('/')
val focalLength = "${values[0].toDouble() / values[1].toDouble()}mm"
exifString += "$focalLength "
}
}
getAttribute(ExifInterface.TAG_EXPOSURE_TIME).let {
if (it?.isNotEmpty() == true) {
val exposureValue = it.toFloat()
exifString += if (exposureValue > 1f) {
"${exposureValue}s "
} else {
"1/${Math.round(1 / exposureValue)}s "
}
}
}
getAttribute(ExifInterface.TAG_ISO_SPEED_RATINGS).let {
if (it?.isNotEmpty() == true) {
exifString += "ISO-$it"
}
}
return exifString.trim()
}
@TargetApi(Build.VERSION_CODES.N)
fun ExifInterface.getExifDateTaken(context: Context): String {
val dateTime = getAttribute(ExifInterface.TAG_DATETIME_ORIGINAL) ?: getAttribute(ExifInterface.TAG_DATETIME)
dateTime.let {
if (it?.isNotEmpty() == true) {
try {
val simpleDateFormat = SimpleDateFormat("yyyy:MM:dd kk:mm:ss", Locale.ENGLISH)
return simpleDateFormat.parse(it).time.formatDate(context).trim()
} catch (ignored: Exception) {
}
}
}
return ""
}
fun ExifInterface.getExifCameraModel(): String {
getAttribute(ExifInterface.TAG_MAKE).let {
if (it?.isNotEmpty() == true) {
val model = getAttribute(ExifInterface.TAG_MODEL)
return "$it $model".trim()
}
}
return ""
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/extensions/ExifInterface.kt | 3636544368 |
package com.simplemobiletools.commons.extensions
import android.annotation.SuppressLint
import android.app.Activity
import android.app.Dialog
import android.app.TimePickerDialog
import android.content.*
import android.content.Intent.EXTRA_STREAM
import android.content.pm.ApplicationInfo
import android.content.pm.PackageManager
import android.media.RingtoneManager
import android.net.Uri
import android.os.Environment
import android.os.Handler
import android.os.Looper
import android.os.TransactionTooLargeException
import android.provider.ContactsContract
import android.provider.DocumentsContract
import android.provider.MediaStore
import android.telecom.PhoneAccountHandle
import android.telecom.TelecomManager
import android.view.View
import android.view.ViewGroup
import android.view.Window
import android.view.WindowManager
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.biometric.BiometricPrompt
import androidx.biometric.auth.AuthPromptCallback
import androidx.biometric.auth.AuthPromptHost
import androidx.biometric.auth.Class2BiometricAuthPrompt
import androidx.core.view.WindowInsetsCompat
import androidx.fragment.app.FragmentActivity
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.activities.BaseSimpleActivity
import com.simplemobiletools.commons.compose.extensions.DEVELOPER_PLAY_STORE_URL
import com.simplemobiletools.commons.databinding.DialogTitleBinding
import com.simplemobiletools.commons.dialogs.*
import com.simplemobiletools.commons.dialogs.WritePermissionDialog.WritePermissionDialogMode
import com.simplemobiletools.commons.helpers.*
import com.simplemobiletools.commons.models.*
import com.simplemobiletools.commons.views.MyTextView
import java.io.*
import java.util.*
fun Activity.appLaunched(appId: String) {
baseConfig.internalStoragePath = getInternalStoragePath()
updateSDCardPath()
baseConfig.appId = appId
if (baseConfig.appRunCount == 0) {
baseConfig.wasOrangeIconChecked = true
checkAppIconColor()
} else if (!baseConfig.wasOrangeIconChecked) {
baseConfig.wasOrangeIconChecked = true
val primaryColor = resources.getColor(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)) {
showDonateOrUpgradeDialog()
}
}
if (baseConfig.appRunCount % 40 == 0 && !baseConfig.wasAppRated) {
if (!resources.getBoolean(R.bool.hide_google_relations)) {
RateStarsDialog(this)
}
}
}
fun Activity.showDonateOrUpgradeDialog() {
if (getCanAppBeUpgraded()) {
UpgradeToProDialog(this)
} else if (!isOrWasThankYouInstalled()) {
DonateDialog(this)
}
}
fun Activity.isAppInstalledOnSDCard(): Boolean = try {
val applicationInfo = packageManager.getPackageInfo(packageName, 0).applicationInfo
(applicationInfo.flags and ApplicationInfo.FLAG_EXTERNAL_STORAGE) == ApplicationInfo.FLAG_EXTERNAL_STORAGE
} catch (e: Exception) {
false
}
fun BaseSimpleActivity.isShowingSAFDialog(path: String): Boolean {
return if ((!isRPlus() && isPathOnSD(path) && !isSDCardSetAsDefaultStorage() && (baseConfig.sdTreeUri.isEmpty() || !hasProperStoredTreeUri(false)))) {
runOnUiThread {
if (!isDestroyed && !isFinishing) {
WritePermissionDialog(this, WritePermissionDialogMode.SdCard) {
Intent(Intent.ACTION_OPEN_DOCUMENT_TREE).apply {
putExtra(EXTRA_SHOW_ADVANCED, true)
try {
startActivityForResult(this, OPEN_DOCUMENT_TREE_SD)
checkedDocumentPath = path
return@apply
} catch (e: Exception) {
type = "*/*"
}
try {
startActivityForResult(this, OPEN_DOCUMENT_TREE_SD)
checkedDocumentPath = path
} catch (e: ActivityNotFoundException) {
toast(R.string.system_service_disabled, Toast.LENGTH_LONG)
} catch (e: Exception) {
toast(R.string.unknown_error_occurred)
}
}
}
}
}
true
} else {
false
}
}
@SuppressLint("InlinedApi")
fun BaseSimpleActivity.isShowingSAFDialogSdk30(path: String): Boolean {
return if (isAccessibleWithSAFSdk30(path) && !hasProperStoredFirstParentUri(path)) {
runOnUiThread {
if (!isDestroyed && !isFinishing) {
val level = getFirstParentLevel(path)
WritePermissionDialog(this, WritePermissionDialogMode.OpenDocumentTreeSDK30(path.getFirstParentPath(this, level))) {
Intent(Intent.ACTION_OPEN_DOCUMENT_TREE).apply {
putExtra(EXTRA_SHOW_ADVANCED, true)
putExtra(DocumentsContract.EXTRA_INITIAL_URI, createFirstParentTreeUriUsingRootTree(path))
try {
startActivityForResult(this, OPEN_DOCUMENT_TREE_FOR_SDK_30)
checkedDocumentPath = path
return@apply
} catch (e: Exception) {
type = "*/*"
}
try {
startActivityForResult(this, OPEN_DOCUMENT_TREE_FOR_SDK_30)
checkedDocumentPath = path
} catch (e: ActivityNotFoundException) {
toast(R.string.system_service_disabled, Toast.LENGTH_LONG)
} catch (e: Exception) {
toast(R.string.unknown_error_occurred)
}
}
}
}
}
true
} else {
false
}
}
@SuppressLint("InlinedApi")
fun BaseSimpleActivity.isShowingSAFCreateDocumentDialogSdk30(path: String): Boolean {
return if (!hasProperStoredDocumentUriSdk30(path)) {
runOnUiThread {
if (!isDestroyed && !isFinishing) {
WritePermissionDialog(this, WritePermissionDialogMode.CreateDocumentSDK30) {
Intent(Intent.ACTION_CREATE_DOCUMENT).apply {
type = DocumentsContract.Document.MIME_TYPE_DIR
putExtra(EXTRA_SHOW_ADVANCED, true)
addCategory(Intent.CATEGORY_OPENABLE)
putExtra(DocumentsContract.EXTRA_INITIAL_URI, buildDocumentUriSdk30(path.getParentPath()))
putExtra(Intent.EXTRA_TITLE, path.getFilenameFromPath())
try {
startActivityForResult(this, CREATE_DOCUMENT_SDK_30)
checkedDocumentPath = path
return@apply
} catch (e: Exception) {
type = "*/*"
}
try {
startActivityForResult(this, CREATE_DOCUMENT_SDK_30)
checkedDocumentPath = path
} catch (e: ActivityNotFoundException) {
toast(R.string.system_service_disabled, Toast.LENGTH_LONG)
} catch (e: Exception) {
toast(R.string.unknown_error_occurred)
}
}
}
}
}
true
} else {
false
}
}
fun BaseSimpleActivity.isShowingAndroidSAFDialog(path: String): Boolean {
return if (isRestrictedSAFOnlyRoot(path) && (getAndroidTreeUri(path).isEmpty() || !hasProperStoredAndroidTreeUri(path))) {
runOnUiThread {
if (!isDestroyed && !isFinishing) {
ConfirmationAdvancedDialog(this, "", R.string.confirm_storage_access_android_text, R.string.ok, R.string.cancel) { success ->
if (success) {
Intent(Intent.ACTION_OPEN_DOCUMENT_TREE).apply {
putExtra(EXTRA_SHOW_ADVANCED, true)
putExtra(DocumentsContract.EXTRA_INITIAL_URI, createAndroidDataOrObbUri(path))
try {
startActivityForResult(this, OPEN_DOCUMENT_TREE_FOR_ANDROID_DATA_OR_OBB)
checkedDocumentPath = path
return@apply
} catch (e: Exception) {
type = "*/*"
}
try {
startActivityForResult(this, OPEN_DOCUMENT_TREE_FOR_ANDROID_DATA_OR_OBB)
checkedDocumentPath = path
} catch (e: ActivityNotFoundException) {
toast(R.string.system_service_disabled, Toast.LENGTH_LONG)
} catch (e: Exception) {
toast(R.string.unknown_error_occurred)
}
}
}
}
}
}
true
} else {
false
}
}
fun BaseSimpleActivity.isShowingOTGDialog(path: String): Boolean {
return if (!isRPlus() && isPathOnOTG(path) && (baseConfig.OTGTreeUri.isEmpty() || !hasProperStoredTreeUri(true))) {
showOTGPermissionDialog(path)
true
} else {
false
}
}
fun BaseSimpleActivity.showOTGPermissionDialog(path: String) {
runOnUiThread {
if (!isDestroyed && !isFinishing) {
WritePermissionDialog(this, WritePermissionDialogMode.Otg) {
Intent(Intent.ACTION_OPEN_DOCUMENT_TREE).apply {
try {
startActivityForResult(this, OPEN_DOCUMENT_TREE_OTG)
checkedDocumentPath = path
return@apply
} catch (e: Exception) {
type = "*/*"
}
try {
startActivityForResult(this, OPEN_DOCUMENT_TREE_OTG)
checkedDocumentPath = path
} catch (e: ActivityNotFoundException) {
toast(R.string.system_service_disabled, Toast.LENGTH_LONG)
} catch (e: Exception) {
toast(R.string.unknown_error_occurred)
}
}
}
}
}
}
fun Activity.launchPurchaseThankYouIntent() {
hideKeyboard()
try {
launchViewIntent("market://details?id=com.simplemobiletools.thankyou")
} catch (ignored: Exception) {
launchViewIntent(getString(R.string.thank_you_url))
}
}
fun Activity.launchUpgradeToProIntent() {
hideKeyboard()
try {
launchViewIntent("market://details?id=${baseConfig.appId.removeSuffix(".debug")}.pro")
} catch (ignored: Exception) {
launchViewIntent(getStoreUrl())
}
}
fun Activity.launchMoreAppsFromUsIntent() {
launchViewIntent(DEVELOPER_PLAY_STORE_URL)
}
fun Activity.launchViewIntent(id: Int) = launchViewIntent(getString(id))
fun Activity.launchViewIntent(url: String) {
hideKeyboard()
ensureBackgroundThread {
Intent(Intent.ACTION_VIEW, Uri.parse(url)).apply {
try {
startActivity(this)
} catch (e: ActivityNotFoundException) {
toast(R.string.no_browser_found)
} catch (e: Exception) {
showErrorToast(e)
}
}
}
}
fun Activity.redirectToRateUs() {
hideKeyboard()
try {
launchViewIntent("market://details?id=${packageName.removeSuffix(".debug")}")
} catch (ignored: ActivityNotFoundException) {
launchViewIntent(getStoreUrl())
}
}
fun Activity.sharePathIntent(path: String, applicationId: String) {
ensureBackgroundThread {
val newUri = getFinalUriFromPath(path, applicationId) ?: return@ensureBackgroundThread
Intent().apply {
action = Intent.ACTION_SEND
putExtra(EXTRA_STREAM, newUri)
type = getUriMimeType(path, newUri)
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
grantUriPermission("android", newUri, Intent.FLAG_GRANT_READ_URI_PERMISSION)
try {
startActivity(Intent.createChooser(this, getString(R.string.share_via)))
} catch (e: ActivityNotFoundException) {
toast(R.string.no_app_found)
} catch (e: RuntimeException) {
if (e.cause is TransactionTooLargeException) {
toast(R.string.maximum_share_reached)
} else {
showErrorToast(e)
}
} catch (e: Exception) {
showErrorToast(e)
}
}
}
}
fun Activity.sharePathsIntent(paths: List<String>, applicationId: String) {
ensureBackgroundThread {
if (paths.size == 1) {
sharePathIntent(paths.first(), applicationId)
} else {
val uriPaths = ArrayList<String>()
val newUris = paths.map {
val uri = getFinalUriFromPath(it, applicationId) ?: return@ensureBackgroundThread
uriPaths.add(uri.path!!)
uri
} as ArrayList<Uri>
var mimeType = uriPaths.getMimeType()
if (mimeType.isEmpty() || mimeType == "*/*") {
mimeType = paths.getMimeType()
}
Intent().apply {
action = Intent.ACTION_SEND_MULTIPLE
type = mimeType
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
putParcelableArrayListExtra(EXTRA_STREAM, newUris)
try {
startActivity(Intent.createChooser(this, getString(R.string.share_via)))
} catch (e: ActivityNotFoundException) {
toast(R.string.no_app_found)
} catch (e: RuntimeException) {
if (e.cause is TransactionTooLargeException) {
toast(R.string.maximum_share_reached)
} else {
showErrorToast(e)
}
} catch (e: Exception) {
showErrorToast(e)
}
}
}
}
}
fun Activity.setAsIntent(path: String, applicationId: String) {
ensureBackgroundThread {
val newUri = getFinalUriFromPath(path, applicationId) ?: return@ensureBackgroundThread
Intent().apply {
action = Intent.ACTION_ATTACH_DATA
setDataAndType(newUri, getUriMimeType(path, newUri))
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
val chooser = Intent.createChooser(this, getString(R.string.set_as))
try {
startActivityForResult(chooser, REQUEST_SET_AS)
} catch (e: ActivityNotFoundException) {
toast(R.string.no_app_found)
} catch (e: Exception) {
showErrorToast(e)
}
}
}
}
fun Activity.shareTextIntent(text: String) {
ensureBackgroundThread {
Intent().apply {
action = Intent.ACTION_SEND
type = "text/plain"
putExtra(Intent.EXTRA_TEXT, text)
try {
startActivity(Intent.createChooser(this, getString(R.string.share_via)))
} catch (e: ActivityNotFoundException) {
toast(R.string.no_app_found)
} catch (e: RuntimeException) {
if (e.cause is TransactionTooLargeException) {
toast(R.string.maximum_share_reached)
} else {
showErrorToast(e)
}
} catch (e: Exception) {
showErrorToast(e)
}
}
}
}
fun Activity.openEditorIntent(path: String, forceChooser: Boolean, applicationId: String) {
ensureBackgroundThread {
val newUri = getFinalUriFromPath(path, applicationId) ?: return@ensureBackgroundThread
Intent().apply {
action = Intent.ACTION_EDIT
setDataAndType(newUri, getUriMimeType(path, newUri))
if (!isRPlus() || (isRPlus() && (hasProperStoredDocumentUriSdk30(path) || Environment.isExternalStorageManager()))) {
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
}
val parent = path.getParentPath()
val newFilename = "${path.getFilenameFromPath().substringBeforeLast('.')}_1"
val extension = path.getFilenameExtension()
val newFilePath = File(parent, "$newFilename.$extension")
val outputUri = if (isPathOnOTG(path)) newUri else getFinalUriFromPath("$newFilePath", applicationId)
if (!isRPlus()) {
val resInfoList = packageManager.queryIntentActivities(this, PackageManager.MATCH_DEFAULT_ONLY)
for (resolveInfo in resInfoList) {
val packageName = resolveInfo.activityInfo.packageName
grantUriPermission(packageName, outputUri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION or Intent.FLAG_GRANT_READ_URI_PERMISSION)
}
}
if (!isRPlus()) {
putExtra(MediaStore.EXTRA_OUTPUT, outputUri)
}
putExtra(REAL_FILE_PATH, path)
try {
val chooser = Intent.createChooser(this, getString(R.string.edit_with))
startActivityForResult(if (forceChooser) chooser else this, REQUEST_EDIT_IMAGE)
} catch (e: ActivityNotFoundException) {
toast(R.string.no_app_found)
} catch (e: Exception) {
showErrorToast(e)
}
}
}
}
fun Activity.openPathIntent(
path: String,
forceChooser: Boolean,
applicationId: String,
forceMimeType: String = "",
extras: HashMap<String, Boolean> = HashMap()
) {
ensureBackgroundThread {
val newUri = getFinalUriFromPath(path, applicationId) ?: return@ensureBackgroundThread
val mimeType = if (forceMimeType.isNotEmpty()) forceMimeType else getUriMimeType(path, newUri)
Intent().apply {
action = Intent.ACTION_VIEW
setDataAndType(newUri, mimeType)
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
if (applicationId == "com.simplemobiletools.gallery.pro" || applicationId == "com.simplemobiletools.gallery.pro.debug") {
putExtra(IS_FROM_GALLERY, true)
}
for ((key, value) in extras) {
putExtra(key, value)
}
putExtra(REAL_FILE_PATH, path)
try {
val chooser = Intent.createChooser(this, getString(R.string.open_with))
startActivity(if (forceChooser) chooser else this)
} catch (e: ActivityNotFoundException) {
if (!tryGenericMimeType(this, mimeType, newUri)) {
toast(R.string.no_app_found)
}
} catch (e: Exception) {
showErrorToast(e)
}
}
}
}
fun Activity.launchViewContactIntent(uri: Uri) {
Intent().apply {
action = ContactsContract.QuickContact.ACTION_QUICK_CONTACT
data = uri
launchActivityIntent(this)
}
}
fun BaseSimpleActivity.launchCallIntent(recipient: String, handle: PhoneAccountHandle? = null) {
handlePermission(PERMISSION_CALL_PHONE) {
val action = if (it) Intent.ACTION_CALL else Intent.ACTION_DIAL
Intent(action).apply {
data = Uri.fromParts("tel", recipient, null)
if (handle != null) {
putExtra(TelecomManager.EXTRA_PHONE_ACCOUNT_HANDLE, handle)
}
if (isDefaultDialer()) {
val packageName = if (baseConfig.appId.contains(".debug", true)) "com.simplemobiletools.dialer.debug" else "com.simplemobiletools.dialer"
val className = "com.simplemobiletools.dialer.activities.DialerActivity"
setClassName(packageName, className)
}
launchActivityIntent(this)
}
}
}
fun Activity.launchSendSMSIntent(recipient: String) {
Intent(Intent.ACTION_SENDTO).apply {
data = Uri.fromParts("smsto", recipient, null)
launchActivityIntent(this)
}
}
fun Activity.showLocationOnMap(coordinates: String) {
val uriBegin = "geo:${coordinates.replace(" ", "")}"
val encodedQuery = Uri.encode(coordinates)
val uriString = "$uriBegin?q=$encodedQuery&z=16"
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(uriString))
launchActivityIntent(intent)
}
fun Activity.getFinalUriFromPath(path: String, applicationId: String): Uri? {
val uri = try {
ensurePublicUri(path, applicationId)
} catch (e: Exception) {
showErrorToast(e)
return null
}
if (uri == null) {
toast(R.string.unknown_error_occurred)
return null
}
return uri
}
fun Activity.tryGenericMimeType(intent: Intent, mimeType: String, uri: Uri): Boolean {
var genericMimeType = mimeType.getGenericMimeType()
if (genericMimeType.isEmpty()) {
genericMimeType = "*/*"
}
intent.setDataAndType(uri, genericMimeType)
return try {
startActivity(intent)
true
} catch (e: Exception) {
false
}
}
fun BaseSimpleActivity.checkWhatsNew(releases: List<Release>, currVersion: Int) {
if (baseConfig.lastVersion == 0) {
baseConfig.lastVersion = currVersion
return
}
val newReleases = arrayListOf<Release>()
releases.filterTo(newReleases) { it.id > baseConfig.lastVersion }
if (newReleases.isNotEmpty()) {
WhatsNewDialog(this, newReleases)
}
baseConfig.lastVersion = currVersion
}
fun BaseSimpleActivity.deleteFolders(folders: List<FileDirItem>, deleteMediaOnly: Boolean = true, callback: ((wasSuccess: Boolean) -> Unit)? = null) {
ensureBackgroundThread {
deleteFoldersBg(folders, deleteMediaOnly, callback)
}
}
fun BaseSimpleActivity.deleteFoldersBg(folders: List<FileDirItem>, deleteMediaOnly: Boolean = true, callback: ((wasSuccess: Boolean) -> Unit)? = null) {
var wasSuccess = false
var needPermissionForPath = ""
for (folder in folders) {
if (needsStupidWritePermissions(folder.path) && baseConfig.sdTreeUri.isEmpty()) {
needPermissionForPath = folder.path
break
}
}
handleSAFDialog(needPermissionForPath) {
if (!it) {
return@handleSAFDialog
}
folders.forEachIndexed { index, folder ->
deleteFolderBg(folder, deleteMediaOnly) {
if (it)
wasSuccess = true
if (index == folders.size - 1) {
runOnUiThread {
callback?.invoke(wasSuccess)
}
}
}
}
}
}
fun BaseSimpleActivity.deleteFolder(folder: FileDirItem, deleteMediaOnly: Boolean = true, callback: ((wasSuccess: Boolean) -> Unit)? = null) {
ensureBackgroundThread {
deleteFolderBg(folder, deleteMediaOnly, callback)
}
}
fun BaseSimpleActivity.deleteFolderBg(fileDirItem: FileDirItem, deleteMediaOnly: Boolean = true, callback: ((wasSuccess: Boolean) -> Unit)? = null) {
val folder = File(fileDirItem.path)
if (folder.exists()) {
val filesArr = folder.listFiles()
if (filesArr == null) {
runOnUiThread {
callback?.invoke(true)
}
return
}
val files = filesArr.toMutableList().filter { !deleteMediaOnly || it.isMediaFile() }
for (file in files) {
deleteFileBg(file.toFileDirItem(applicationContext), allowDeleteFolder = false, isDeletingMultipleFiles = false) { }
}
if (folder.listFiles()?.isEmpty() == true) {
deleteFileBg(fileDirItem, allowDeleteFolder = true, isDeletingMultipleFiles = false) { }
}
}
runOnUiThread {
callback?.invoke(true)
}
}
fun BaseSimpleActivity.deleteFile(file: FileDirItem, allowDeleteFolder: Boolean = false, callback: ((wasSuccess: Boolean) -> Unit)? = null) {
deleteFiles(arrayListOf(file), allowDeleteFolder, callback)
}
fun BaseSimpleActivity.deleteFiles(files: List<FileDirItem>, allowDeleteFolder: Boolean = false, callback: ((wasSuccess: Boolean) -> Unit)? = null) {
ensureBackgroundThread {
deleteFilesBg(files, allowDeleteFolder, callback)
}
}
fun BaseSimpleActivity.deleteFilesBg(files: List<FileDirItem>, allowDeleteFolder: Boolean = false, callback: ((wasSuccess: Boolean) -> Unit)? = null) {
if (files.isEmpty()) {
runOnUiThread {
callback?.invoke(true)
}
return
}
val firstFile = files.first()
val firstFilePath = firstFile.path
handleSAFDialog(firstFilePath) {
if (!it) {
return@handleSAFDialog
}
checkManageMediaOrHandleSAFDialogSdk30(firstFilePath) {
if (!it) {
return@checkManageMediaOrHandleSAFDialogSdk30
}
val recycleBinPath = firstFile.isRecycleBinPath(this)
if (canManageMedia() && !recycleBinPath && !firstFilePath.doesThisOrParentHaveNoMedia(HashMap(), null)) {
val fileUris = getFileUrisFromFileDirItems(files)
deleteSDK30Uris(fileUris) { success ->
runOnUiThread {
callback?.invoke(success)
}
}
} else {
deleteFilesCasual(files, allowDeleteFolder, callback)
}
}
}
}
private fun BaseSimpleActivity.deleteFilesCasual(
files: List<FileDirItem>,
allowDeleteFolder: Boolean = false,
callback: ((wasSuccess: Boolean) -> Unit)? = null
) {
var wasSuccess = false
val failedFileDirItems = ArrayList<FileDirItem>()
files.forEachIndexed { index, file ->
deleteFileBg(file, allowDeleteFolder, true) {
if (it) {
wasSuccess = true
} else {
failedFileDirItems.add(file)
}
if (index == files.lastIndex) {
if (isRPlus() && failedFileDirItems.isNotEmpty()) {
val fileUris = getFileUrisFromFileDirItems(failedFileDirItems)
deleteSDK30Uris(fileUris) { success ->
runOnUiThread {
callback?.invoke(success)
}
}
} else {
runOnUiThread {
callback?.invoke(wasSuccess)
}
}
}
}
}
}
fun BaseSimpleActivity.deleteFile(
fileDirItem: FileDirItem,
allowDeleteFolder: Boolean = false,
isDeletingMultipleFiles: Boolean,
callback: ((wasSuccess: Boolean) -> Unit)? = null
) {
ensureBackgroundThread {
deleteFileBg(fileDirItem, allowDeleteFolder, isDeletingMultipleFiles, callback)
}
}
fun BaseSimpleActivity.deleteFileBg(
fileDirItem: FileDirItem,
allowDeleteFolder: Boolean = false,
isDeletingMultipleFiles: Boolean,
callback: ((wasSuccess: Boolean) -> Unit)? = null,
) {
val path = fileDirItem.path
if (isRestrictedSAFOnlyRoot(path)) {
deleteAndroidSAFDirectory(path, allowDeleteFolder, callback)
} else {
val file = File(path)
if (!isRPlus() && file.absolutePath.startsWith(internalStoragePath) && !file.canWrite()) {
callback?.invoke(false)
return
}
var fileDeleted = !isPathOnOTG(path) && ((!file.exists() && file.length() == 0L) || file.delete())
if (fileDeleted) {
deleteFromMediaStore(path) { needsRescan ->
if (needsRescan) {
rescanAndDeletePath(path) {
runOnUiThread {
callback?.invoke(true)
}
}
} else {
runOnUiThread {
callback?.invoke(true)
}
}
}
} else {
if (getIsPathDirectory(file.absolutePath) && allowDeleteFolder) {
fileDeleted = deleteRecursively(file, this)
}
if (!fileDeleted) {
if (needsStupidWritePermissions(path)) {
handleSAFDialog(path) {
if (it) {
trySAFFileDelete(fileDirItem, allowDeleteFolder, callback)
}
}
} else if (isAccessibleWithSAFSdk30(path)) {
if (canManageMedia()) {
deleteSdk30(fileDirItem, callback)
} else {
handleSAFDialogSdk30(path) {
if (it) {
deleteDocumentWithSAFSdk30(fileDirItem, allowDeleteFolder, callback)
}
}
}
} else if (isRPlus() && !isDeletingMultipleFiles) {
deleteSdk30(fileDirItem, callback)
} else {
callback?.invoke(false)
}
}
}
}
}
private fun BaseSimpleActivity.deleteSdk30(fileDirItem: FileDirItem, callback: ((wasSuccess: Boolean) -> Unit)?) {
val fileUris = getFileUrisFromFileDirItems(arrayListOf(fileDirItem))
deleteSDK30Uris(fileUris) { success ->
runOnUiThread {
callback?.invoke(success)
}
}
}
private fun deleteRecursively(file: File, context: Context): Boolean {
if (file.isDirectory) {
val files = file.listFiles() ?: return file.delete()
for (child in files) {
deleteRecursively(child, context)
}
}
val deleted = file.delete()
if (deleted) {
context.deleteFromMediaStore(file.absolutePath)
}
return deleted
}
fun Activity.scanFileRecursively(file: File, callback: (() -> Unit)? = null) {
applicationContext.scanFileRecursively(file, callback)
}
fun Activity.scanPathRecursively(path: String, callback: (() -> Unit)? = null) {
applicationContext.scanPathRecursively(path, callback)
}
fun Activity.scanFilesRecursively(files: List<File>, callback: (() -> Unit)? = null) {
applicationContext.scanFilesRecursively(files, callback)
}
fun Activity.scanPathsRecursively(paths: List<String>, callback: (() -> Unit)? = null) {
applicationContext.scanPathsRecursively(paths, callback)
}
fun Activity.rescanPath(path: String, callback: (() -> Unit)? = null) {
applicationContext.rescanPath(path, callback)
}
fun Activity.rescanPaths(paths: List<String>, callback: (() -> Unit)? = null) {
applicationContext.rescanPaths(paths, callback)
}
fun BaseSimpleActivity.renameFile(
oldPath: String,
newPath: String,
isRenamingMultipleFiles: Boolean,
callback: ((success: Boolean, android30RenameFormat: Android30RenameFormat) -> Unit)? = null
) {
if (isRestrictedSAFOnlyRoot(oldPath)) {
handleAndroidSAFDialog(oldPath) {
if (!it) {
runOnUiThread {
callback?.invoke(false, Android30RenameFormat.NONE)
}
return@handleAndroidSAFDialog
}
try {
ensureBackgroundThread {
val success = renameAndroidSAFDocument(oldPath, newPath)
runOnUiThread {
callback?.invoke(success, Android30RenameFormat.NONE)
}
}
} catch (e: Exception) {
showErrorToast(e)
runOnUiThread {
callback?.invoke(false, Android30RenameFormat.NONE)
}
}
}
} else if (isAccessibleWithSAFSdk30(oldPath)) {
if (canManageMedia() && !File(oldPath).isDirectory && isPathOnInternalStorage(oldPath)) {
renameCasually(oldPath, newPath, isRenamingMultipleFiles, callback)
} else {
handleSAFDialogSdk30(oldPath) {
if (!it) {
return@handleSAFDialogSdk30
}
try {
ensureBackgroundThread {
val success = renameDocumentSdk30(oldPath, newPath)
if (success) {
updateInMediaStore(oldPath, newPath)
rescanPath(newPath) {
runOnUiThread {
callback?.invoke(true, Android30RenameFormat.NONE)
}
if (!oldPath.equals(newPath, true)) {
deleteFromMediaStore(oldPath)
}
scanPathRecursively(newPath)
}
} else {
runOnUiThread {
callback?.invoke(false, Android30RenameFormat.NONE)
}
}
}
} catch (e: Exception) {
showErrorToast(e)
runOnUiThread {
callback?.invoke(false, Android30RenameFormat.NONE)
}
}
}
}
} else if (needsStupidWritePermissions(newPath)) {
handleSAFDialog(newPath) {
if (!it) {
return@handleSAFDialog
}
val document = getSomeDocumentFile(oldPath)
if (document == null || (File(oldPath).isDirectory != document.isDirectory)) {
runOnUiThread {
toast(R.string.unknown_error_occurred)
callback?.invoke(false, Android30RenameFormat.NONE)
}
return@handleSAFDialog
}
try {
ensureBackgroundThread {
try {
DocumentsContract.renameDocument(applicationContext.contentResolver, document.uri, newPath.getFilenameFromPath())
} catch (ignored: FileNotFoundException) {
// FileNotFoundException is thrown in some weird cases, but renaming works just fine
} catch (e: Exception) {
showErrorToast(e)
callback?.invoke(false, Android30RenameFormat.NONE)
return@ensureBackgroundThread
}
updateInMediaStore(oldPath, newPath)
rescanPaths(arrayListOf(oldPath, newPath)) {
if (!baseConfig.keepLastModified) {
updateLastModified(newPath, System.currentTimeMillis())
}
deleteFromMediaStore(oldPath)
runOnUiThread {
callback?.invoke(true, Android30RenameFormat.NONE)
}
}
}
} catch (e: Exception) {
showErrorToast(e)
runOnUiThread {
callback?.invoke(false, Android30RenameFormat.NONE)
}
}
}
} else renameCasually(oldPath, newPath, isRenamingMultipleFiles, callback)
}
private fun BaseSimpleActivity.renameCasually(
oldPath: String,
newPath: String,
isRenamingMultipleFiles: Boolean,
callback: ((success: Boolean, android30RenameFormat: Android30RenameFormat) -> Unit)?
) {
val oldFile = File(oldPath)
val newFile = File(newPath)
val tempFile = try {
createTempFile(oldFile) ?: return
} catch (exception: Exception) {
if (isRPlus() && exception is java.nio.file.FileSystemException) {
// if we are renaming multiple files at once, we should give the Android 30+ permission dialog all uris together, not one by one
if (isRenamingMultipleFiles) {
callback?.invoke(false, Android30RenameFormat.CONTENT_RESOLVER)
} else {
val fileUris = getFileUrisFromFileDirItems(arrayListOf(File(oldPath).toFileDirItem(this)))
updateSDK30Uris(fileUris) { success ->
if (success) {
val values = ContentValues().apply {
put(MediaStore.Images.Media.DISPLAY_NAME, newPath.getFilenameFromPath())
}
try {
contentResolver.update(fileUris.first(), values, null, null)
callback?.invoke(true, Android30RenameFormat.NONE)
} catch (e: Exception) {
showErrorToast(e)
callback?.invoke(false, Android30RenameFormat.NONE)
}
} else {
callback?.invoke(false, Android30RenameFormat.NONE)
}
}
}
} else {
if (exception is IOException && File(oldPath).isDirectory && isRestrictedWithSAFSdk30(oldPath)) {
toast(R.string.cannot_rename_folder)
} else {
showErrorToast(exception)
}
callback?.invoke(false, Android30RenameFormat.NONE)
}
return
}
val oldToTempSucceeds = oldFile.renameTo(tempFile)
val tempToNewSucceeds = tempFile.renameTo(newFile)
if (oldToTempSucceeds && tempToNewSucceeds) {
if (newFile.isDirectory) {
updateInMediaStore(oldPath, newPath)
rescanPath(newPath) {
runOnUiThread {
callback?.invoke(true, Android30RenameFormat.NONE)
}
if (!oldPath.equals(newPath, true)) {
deleteFromMediaStore(oldPath)
}
scanPathRecursively(newPath)
}
} else {
if (!baseConfig.keepLastModified) {
newFile.setLastModified(System.currentTimeMillis())
}
updateInMediaStore(oldPath, newPath)
scanPathsRecursively(arrayListOf(newPath)) {
if (!oldPath.equals(newPath, true)) {
deleteFromMediaStore(oldPath)
}
runOnUiThread {
callback?.invoke(true, Android30RenameFormat.NONE)
}
}
}
} else {
tempFile.delete()
newFile.delete()
if (isRPlus()) {
// if we are renaming multiple files at once, we should give the Android 30+ permission dialog all uris together, not one by one
if (isRenamingMultipleFiles) {
callback?.invoke(false, Android30RenameFormat.SAF)
} else {
val fileUris = getFileUrisFromFileDirItems(arrayListOf(File(oldPath).toFileDirItem(this)))
updateSDK30Uris(fileUris) { success ->
if (!success) {
return@updateSDK30Uris
}
try {
val sourceUri = fileUris.first()
val sourceFile = File(oldPath).toFileDirItem(this)
if (oldPath.equals(newPath, true)) {
val tempDestination = try {
createTempFile(File(sourceFile.path)) ?: return@updateSDK30Uris
} catch (exception: Exception) {
showErrorToast(exception)
callback?.invoke(false, Android30RenameFormat.NONE)
return@updateSDK30Uris
}
val copyTempSuccess = copySingleFileSdk30(sourceFile, tempDestination.toFileDirItem(this))
if (copyTempSuccess) {
contentResolver.delete(sourceUri, null)
tempDestination.renameTo(File(newPath))
if (!baseConfig.keepLastModified) {
newFile.setLastModified(System.currentTimeMillis())
}
updateInMediaStore(oldPath, newPath)
scanPathsRecursively(arrayListOf(newPath)) {
runOnUiThread {
callback?.invoke(true, Android30RenameFormat.NONE)
}
}
} else {
callback?.invoke(false, Android30RenameFormat.NONE)
}
} else {
val destinationFile = FileDirItem(
newPath,
newPath.getFilenameFromPath(),
sourceFile.isDirectory,
sourceFile.children,
sourceFile.size,
sourceFile.modified
)
val copySuccessful = copySingleFileSdk30(sourceFile, destinationFile)
if (copySuccessful) {
if (!baseConfig.keepLastModified) {
newFile.setLastModified(System.currentTimeMillis())
}
contentResolver.delete(sourceUri, null)
updateInMediaStore(oldPath, newPath)
scanPathsRecursively(arrayListOf(newPath)) {
runOnUiThread {
callback?.invoke(true, Android30RenameFormat.NONE)
}
}
} else {
toast(R.string.unknown_error_occurred)
callback?.invoke(false, Android30RenameFormat.NONE)
}
}
} catch (e: Exception) {
showErrorToast(e)
callback?.invoke(false, Android30RenameFormat.NONE)
}
}
}
} else {
toast(R.string.unknown_error_occurred)
callback?.invoke(false, Android30RenameFormat.NONE)
}
}
}
fun Activity.createTempFile(file: File): File? {
return if (file.isDirectory) {
createTempDir("temp", "${System.currentTimeMillis()}", file.parentFile)
} else {
if (isRPlus()) {
// this can throw FileSystemException, lets catch and handle it at the place calling this function
kotlin.io.path.createTempFile(file.parentFile.toPath(), "temp", "${System.currentTimeMillis()}").toFile()
} else {
createTempFile("temp", "${System.currentTimeMillis()}", file.parentFile)
}
}
}
fun Activity.hideKeyboard() {
if (isOnMainThread()) {
hideKeyboardSync()
} else {
Handler(Looper.getMainLooper()).post {
hideKeyboardSync()
}
}
}
fun Activity.hideKeyboardSync() {
val inputMethodManager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.hideSoftInputFromWindow((currentFocus ?: View(this)).windowToken, 0)
window!!.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN)
currentFocus?.clearFocus()
}
fun Activity.showKeyboard(et: EditText) {
et.requestFocus()
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.showSoftInput(et, InputMethodManager.SHOW_IMPLICIT)
}
fun Activity.hideKeyboard(view: View) {
val inputMethodManager = getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.hideSoftInputFromWindow(view.windowToken, 0)
}
fun BaseSimpleActivity.getFileOutputStream(fileDirItem: FileDirItem, allowCreatingNewFile: Boolean = false, callback: (outputStream: OutputStream?) -> Unit) {
val targetFile = File(fileDirItem.path)
when {
isRestrictedSAFOnlyRoot(fileDirItem.path) -> {
handleAndroidSAFDialog(fileDirItem.path) {
if (!it) {
return@handleAndroidSAFDialog
}
val uri = getAndroidSAFUri(fileDirItem.path)
if (!getDoesFilePathExist(fileDirItem.path)) {
createAndroidSAFFile(fileDirItem.path)
}
callback.invoke(applicationContext.contentResolver.openOutputStream(uri, "wt"))
}
}
needsStupidWritePermissions(fileDirItem.path) -> {
handleSAFDialog(fileDirItem.path) {
if (!it) {
return@handleSAFDialog
}
var document = getDocumentFile(fileDirItem.path)
if (document == null && allowCreatingNewFile) {
document = getDocumentFile(fileDirItem.getParentPath())
}
if (document == null) {
showFileCreateError(fileDirItem.path)
callback(null)
return@handleSAFDialog
}
if (!getDoesFilePathExist(fileDirItem.path)) {
document = getDocumentFile(fileDirItem.path) ?: document.createFile("", fileDirItem.name)
}
if (document?.exists() == true) {
try {
callback(applicationContext.contentResolver.openOutputStream(document.uri, "wt"))
} catch (e: FileNotFoundException) {
showErrorToast(e)
callback(null)
}
} else {
showFileCreateError(fileDirItem.path)
callback(null)
}
}
}
isAccessibleWithSAFSdk30(fileDirItem.path) -> {
handleSAFDialogSdk30(fileDirItem.path) {
if (!it) {
return@handleSAFDialogSdk30
}
callback.invoke(
try {
val uri = createDocumentUriUsingFirstParentTreeUri(fileDirItem.path)
if (!getDoesFilePathExist(fileDirItem.path)) {
createSAFFileSdk30(fileDirItem.path)
}
applicationContext.contentResolver.openOutputStream(uri, "wt")
} catch (e: Exception) {
null
} ?: createCasualFileOutputStream(this, targetFile)
)
}
}
isRestrictedWithSAFSdk30(fileDirItem.path) -> {
callback.invoke(
try {
val fileUri = getFileUrisFromFileDirItems(arrayListOf(fileDirItem))
applicationContext.contentResolver.openOutputStream(fileUri.first(), "wt")
} catch (e: Exception) {
null
} ?: createCasualFileOutputStream(this, targetFile)
)
}
else -> {
callback.invoke(createCasualFileOutputStream(this, targetFile))
}
}
}
private fun createCasualFileOutputStream(activity: BaseSimpleActivity, targetFile: File): OutputStream? {
if (targetFile.parentFile?.exists() == false) {
targetFile.parentFile?.mkdirs()
}
return try {
FileOutputStream(targetFile)
} catch (e: Exception) {
activity.showErrorToast(e)
null
}
}
fun Activity.performSecurityCheck(
protectionType: Int,
requiredHash: String,
successCallback: ((String, Int) -> Unit)? = null,
failureCallback: (() -> Unit)? = null
) {
if (protectionType == PROTECTION_FINGERPRINT && isRPlus()) {
showBiometricPrompt(successCallback, failureCallback)
} else {
SecurityDialog(
activity = this,
requiredHash = requiredHash,
showTabIndex = protectionType,
callback = { hash, type, success ->
if (success) {
successCallback?.invoke(hash, type)
} else {
failureCallback?.invoke()
}
}
)
}
}
fun Activity.showBiometricPrompt(
successCallback: ((String, Int) -> Unit)? = null,
failureCallback: (() -> Unit)? = null
) {
Class2BiometricAuthPrompt.Builder(getText(R.string.authenticate), getText(R.string.cancel))
.build()
.startAuthentication(
AuthPromptHost(this as FragmentActivity),
object : AuthPromptCallback() {
override fun onAuthenticationSucceeded(activity: FragmentActivity?, result: BiometricPrompt.AuthenticationResult) {
successCallback?.invoke("", PROTECTION_FINGERPRINT)
}
override fun onAuthenticationError(activity: FragmentActivity?, errorCode: Int, errString: CharSequence) {
val isCanceledByUser = errorCode == BiometricPrompt.ERROR_NEGATIVE_BUTTON || errorCode == BiometricPrompt.ERROR_USER_CANCELED
if (!isCanceledByUser) {
toast(errString.toString())
}
failureCallback?.invoke()
}
override fun onAuthenticationFailed(activity: FragmentActivity?) {
toast(R.string.authentication_failed)
failureCallback?.invoke()
}
}
)
}
fun Activity.handleHiddenFolderPasswordProtection(callback: () -> Unit) {
if (baseConfig.isHiddenPasswordProtectionOn) {
SecurityDialog(this, baseConfig.hiddenPasswordHash, baseConfig.hiddenProtectionType) { _, _, success ->
if (success) {
callback()
}
}
} else {
callback()
}
}
fun Activity.handleAppPasswordProtection(callback: (success: Boolean) -> Unit) {
if (baseConfig.isAppPasswordProtectionOn) {
SecurityDialog(this, baseConfig.appPasswordHash, baseConfig.appProtectionType) { _, _, success ->
callback(success)
}
} else {
callback(true)
}
}
fun Activity.handleDeletePasswordProtection(callback: () -> Unit) {
if (baseConfig.isDeletePasswordProtectionOn) {
SecurityDialog(this, baseConfig.deletePasswordHash, baseConfig.deleteProtectionType) { _, _, success ->
if (success) {
callback()
}
}
} else {
callback()
}
}
fun Activity.handleLockedFolderOpening(path: String, callback: (success: Boolean) -> Unit) {
if (baseConfig.isFolderProtected(path)) {
SecurityDialog(this, baseConfig.getFolderProtectionHash(path), baseConfig.getFolderProtectionType(path)) { _, _, success ->
callback(success)
}
} else {
callback(true)
}
}
fun Activity.updateSharedTheme(sharedTheme: SharedTheme) {
try {
val contentValues = MyContentProvider.fillThemeContentValues(sharedTheme)
applicationContext.contentResolver.update(MyContentProvider.MY_CONTENT_URI, contentValues, null, null)
} catch (e: Exception) {
showErrorToast(e)
}
}
fun Activity.setupDialogStuff(
view: View,
dialog: AlertDialog.Builder,
titleId: Int = 0,
titleText: String = "",
cancelOnTouchOutside: Boolean = true,
callback: ((alertDialog: AlertDialog) -> Unit)? = null
) {
if (isDestroyed || isFinishing) {
return
}
val textColor = getProperTextColor()
val backgroundColor = getProperBackgroundColor()
val primaryColor = getProperPrimaryColor()
if (view is ViewGroup) {
updateTextColors(view)
} else if (view is MyTextView) {
view.setColors(textColor, primaryColor, backgroundColor)
}
if (dialog is MaterialAlertDialogBuilder) {
dialog.create().apply {
if (titleId != 0) {
setTitle(titleId)
} else if (titleText.isNotEmpty()) {
setTitle(titleText)
}
setView(view)
setCancelable(cancelOnTouchOutside)
if (!isFinishing) {
show()
}
getButton(Dialog.BUTTON_POSITIVE)?.setTextColor(primaryColor)
getButton(Dialog.BUTTON_NEGATIVE)?.setTextColor(primaryColor)
getButton(Dialog.BUTTON_NEUTRAL)?.setTextColor(primaryColor)
callback?.invoke(this)
}
} else {
var title: DialogTitleBinding? = null
if (titleId != 0 || titleText.isNotEmpty()) {
title = DialogTitleBinding.inflate(layoutInflater, null, false)
title.dialogTitleTextview.apply {
if (titleText.isNotEmpty()) {
text = titleText
} else {
setText(titleId)
}
setTextColor(textColor)
}
}
// if we use the same primary and background color, use the text color for dialog confirmation buttons
val dialogButtonColor = if (primaryColor == baseConfig.backgroundColor) {
textColor
} else {
primaryColor
}
dialog.create().apply {
setView(view)
requestWindowFeature(Window.FEATURE_NO_TITLE)
setCustomTitle(title?.root)
setCanceledOnTouchOutside(cancelOnTouchOutside)
if (!isFinishing) {
show()
}
getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(dialogButtonColor)
getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(dialogButtonColor)
getButton(AlertDialog.BUTTON_NEUTRAL).setTextColor(dialogButtonColor)
val bgDrawable = when {
isBlackAndWhiteTheme() -> resources.getDrawable(R.drawable.black_dialog_background, theme)
baseConfig.isUsingSystemTheme -> resources.getDrawable(R.drawable.dialog_you_background, theme)
else -> resources.getColoredDrawableWithColor(R.drawable.dialog_bg, baseConfig.backgroundColor)
}
window?.setBackgroundDrawable(bgDrawable)
callback?.invoke(this)
}
}
}
fun Activity.getAlertDialogBuilder() = if (baseConfig.isUsingSystemTheme) {
MaterialAlertDialogBuilder(this)
} else {
AlertDialog.Builder(this)
}
fun Activity.showPickSecondsDialogHelper(
curMinutes: Int, isSnoozePicker: Boolean = false, showSecondsAtCustomDialog: Boolean = false, showDuringDayOption: Boolean = false,
cancelCallback: (() -> Unit)? = null, callback: (seconds: Int) -> Unit
) {
val seconds = if (curMinutes == -1) curMinutes else curMinutes * 60
showPickSecondsDialog(seconds, isSnoozePicker, showSecondsAtCustomDialog, showDuringDayOption, cancelCallback, callback)
}
fun Activity.showPickSecondsDialog(
curSeconds: Int, isSnoozePicker: Boolean = false, showSecondsAtCustomDialog: Boolean = false, showDuringDayOption: Boolean = false,
cancelCallback: (() -> Unit)? = null, callback: (seconds: Int) -> Unit
) {
hideKeyboard()
val seconds = TreeSet<Int>()
seconds.apply {
if (!isSnoozePicker) {
add(-1)
add(0)
}
add(1 * MINUTE_SECONDS)
add(5 * MINUTE_SECONDS)
add(10 * MINUTE_SECONDS)
add(30 * MINUTE_SECONDS)
add(60 * MINUTE_SECONDS)
add(curSeconds)
}
val items = ArrayList<RadioItem>(seconds.size + 1)
seconds.mapIndexedTo(items) { index, value ->
RadioItem(index, getFormattedSeconds(value, !isSnoozePicker), value)
}
var selectedIndex = 0
seconds.forEachIndexed { index, value ->
if (value == curSeconds) {
selectedIndex = index
}
}
items.add(RadioItem(-2, getString(R.string.custom)))
if (showDuringDayOption) {
items.add(RadioItem(-3, getString(R.string.during_day_at_hh_mm)))
}
RadioGroupDialog(this, items, selectedIndex, showOKButton = isSnoozePicker, cancelCallback = cancelCallback) {
when (it) {
-2 -> {
CustomIntervalPickerDialog(this, showSeconds = showSecondsAtCustomDialog) {
callback(it)
}
}
-3 -> {
TimePickerDialog(
this, getTimePickerDialogTheme(),
{ view, hourOfDay, minute -> callback(hourOfDay * -3600 + minute * -60) },
curSeconds / 3600, curSeconds % 3600, baseConfig.use24HourFormat
).show()
}
else -> {
callback(it as Int)
}
}
}
}
fun BaseSimpleActivity.getAlarmSounds(type: Int, callback: (ArrayList<AlarmSound>) -> Unit) {
val alarms = ArrayList<AlarmSound>()
val manager = RingtoneManager(this)
manager.setType(type)
try {
val cursor = manager.cursor
var curId = 1
val silentAlarm = AlarmSound(curId++, getString(R.string.no_sound), SILENT)
alarms.add(silentAlarm)
while (cursor.moveToNext()) {
val title = cursor.getString(RingtoneManager.TITLE_COLUMN_INDEX)
var uri = cursor.getString(RingtoneManager.URI_COLUMN_INDEX)
val id = cursor.getString(RingtoneManager.ID_COLUMN_INDEX)
if (!uri.endsWith(id)) {
uri += "/$id"
}
val alarmSound = AlarmSound(curId++, title, uri)
alarms.add(alarmSound)
}
callback(alarms)
} catch (e: Exception) {
if (e is SecurityException) {
handlePermission(PERMISSION_READ_STORAGE) {
if (it) {
getAlarmSounds(type, callback)
} else {
showErrorToast(e)
callback(ArrayList())
}
}
} else {
showErrorToast(e)
callback(ArrayList())
}
}
}
fun Activity.checkAppSideloading(): Boolean {
val isSideloaded = when (baseConfig.appSideloadingStatus) {
SIDELOADING_TRUE -> true
SIDELOADING_FALSE -> false
else -> isAppSideloaded()
}
baseConfig.appSideloadingStatus = if (isSideloaded) SIDELOADING_TRUE else SIDELOADING_FALSE
if (isSideloaded) {
showSideloadingDialog()
}
return isSideloaded
}
fun Activity.isAppSideloaded(): Boolean {
return try {
getDrawable(R.drawable.ic_camera_vector)
false
} catch (e: Exception) {
true
}
}
fun Activity.showSideloadingDialog() {
AppSideloadedDialog(this) {
finish()
}
}
fun Activity.onApplyWindowInsets(callback: (WindowInsetsCompat) -> Unit) {
window.decorView.setOnApplyWindowInsetsListener { view, insets ->
callback(WindowInsetsCompat.toWindowInsetsCompat(insets))
view.onApplyWindowInsets(insets)
insets
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/extensions/Activity.kt | 1112282100 |
package com.simplemobiletools.commons.extensions
import java.util.*
fun <T> ArrayList<T>.moveLastItemToFront() {
val last = removeAt(size - 1)
add(0, last)
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/extensions/ArrayList.kt | 399733624 |
package com.simplemobiletools.commons.extensions
import android.content.Context
import com.simplemobiletools.commons.models.FileDirItem
fun FileDirItem.isRecycleBinPath(context: Context): Boolean {
return path.startsWith(context.recycleBinPath)
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/extensions/FileDirItem.kt | 1570722835 |
package com.simplemobiletools.commons.extensions
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.PorterDuff
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
fun Drawable.applyColorFilter(color: Int) = mutate().setColorFilter(color, PorterDuff.Mode.SRC_IN)
fun Drawable.convertToBitmap(): Bitmap {
val bitmap = if (intrinsicWidth <= 0 || intrinsicHeight <= 0) {
Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888)
} else {
Bitmap.createBitmap(intrinsicWidth, intrinsicHeight, Bitmap.Config.ARGB_8888)
}
if (this is BitmapDrawable) {
if (this.bitmap != null) {
return this.bitmap
}
}
val canvas = Canvas(bitmap!!)
setBounds(0, 0, canvas.width, canvas.height)
draw(canvas)
return bitmap
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/extensions/Drawable.kt | 736366954 |
package com.simplemobiletools.commons.adapters
import android.content.Context
import android.util.SparseArray
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.biometric.auth.AuthPromptHost
import androidx.viewpager.widget.PagerAdapter
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.helpers.PROTECTION_FINGERPRINT
import com.simplemobiletools.commons.helpers.PROTECTION_PATTERN
import com.simplemobiletools.commons.helpers.PROTECTION_PIN
import com.simplemobiletools.commons.helpers.isRPlus
import com.simplemobiletools.commons.interfaces.HashListener
import com.simplemobiletools.commons.interfaces.SecurityTab
import com.simplemobiletools.commons.views.MyScrollView
class PasswordTypesAdapter(
private val context: Context,
private val requiredHash: String,
private val hashListener: HashListener,
private val scrollView: MyScrollView,
private val biometricPromptHost: AuthPromptHost,
private val showBiometricIdTab: Boolean,
private val showBiometricAuthentication: Boolean
) : PagerAdapter() {
private val tabs = SparseArray<SecurityTab>()
override fun instantiateItem(container: ViewGroup, position: Int): Any {
val view = LayoutInflater.from(context).inflate(layoutSelection(position), container, false)
container.addView(view)
tabs.put(position, view as SecurityTab)
(view as SecurityTab).initTab(requiredHash, hashListener, scrollView, biometricPromptHost, showBiometricAuthentication)
return view
}
override fun destroyItem(container: ViewGroup, position: Int, item: Any) {
tabs.remove(position)
container.removeView(item as View)
}
override fun getCount() = if (showBiometricIdTab) 3 else 2
override fun isViewFromObject(view: View, item: Any) = view == item
private fun layoutSelection(position: Int): Int = when (position) {
PROTECTION_PATTERN -> R.layout.tab_pattern
PROTECTION_PIN -> R.layout.tab_pin
PROTECTION_FINGERPRINT -> if (isRPlus()) R.layout.tab_biometric_id else R.layout.tab_fingerprint
else -> throw RuntimeException("Only 3 tabs allowed")
}
fun isTabVisible(position: Int, isVisible: Boolean) {
tabs[position]?.visibilityChanged(isVisible)
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/adapters/PasswordTypesAdapter.kt | 3537525164 |
package com.simplemobiletools.commons.adapters
import android.graphics.Color
import android.view.*
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.ActionBar
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.RecyclerView
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.activities.BaseSimpleActivity
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.interfaces.MyActionModeCallback
import com.simplemobiletools.commons.views.MyRecyclerView
import kotlin.math.max
import kotlin.math.min
abstract class MyRecyclerViewAdapter(val activity: BaseSimpleActivity, val recyclerView: MyRecyclerView, val itemClick: (Any) -> Unit) :
RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder>() {
protected val baseConfig = activity.baseConfig
protected val resources = activity.resources!!
protected val layoutInflater = activity.layoutInflater
protected var textColor = activity.getProperTextColor()
protected var backgroundColor = activity.getProperBackgroundColor()
protected var properPrimaryColor = activity.getProperPrimaryColor()
protected var contrastColor = properPrimaryColor.getContrastColor()
protected var actModeCallback: MyActionModeCallback
protected var selectedKeys = LinkedHashSet<Int>()
protected var positionOffset = 0
protected var actMode: ActionMode? = null
private var actBarTextView: TextView? = null
private var lastLongPressedItem = -1
abstract fun getActionMenuId(): Int
abstract fun prepareActionMode(menu: Menu)
abstract fun actionItemPressed(id: Int)
abstract fun getSelectableItemCount(): Int
abstract fun getIsItemSelectable(position: Int): Boolean
abstract fun getItemSelectionKey(position: Int): Int?
abstract fun getItemKeyPosition(key: Int): Int
abstract fun onActionModeCreated()
abstract fun onActionModeDestroyed()
protected fun isOneItemSelected() = selectedKeys.size == 1
init {
actModeCallback = object : MyActionModeCallback() {
override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean {
actionItemPressed(item.itemId)
return true
}
override fun onCreateActionMode(actionMode: ActionMode, menu: Menu?): Boolean {
if (getActionMenuId() == 0) {
return true
}
selectedKeys.clear()
isSelectable = true
actMode = actionMode
actBarTextView = layoutInflater.inflate(R.layout.actionbar_title, null) as TextView
actBarTextView!!.layoutParams = ActionBar.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT)
actMode!!.customView = actBarTextView
actBarTextView!!.setOnClickListener {
if (getSelectableItemCount() == selectedKeys.size) {
finishActMode()
} else {
selectAll()
}
}
activity.menuInflater.inflate(getActionMenuId(), menu)
val bgColor = if (baseConfig.isUsingSystemTheme) {
resources.getColor(R.color.you_contextual_status_bar_color, activity.theme)
} else {
Color.BLACK
}
actBarTextView!!.setTextColor(bgColor.getContrastColor())
activity.updateMenuItemColors(menu, baseColor = bgColor)
onActionModeCreated()
if (baseConfig.isUsingSystemTheme) {
actBarTextView?.onGlobalLayout {
val backArrow = activity.findViewById<ImageView>(androidx.appcompat.R.id.action_mode_close_button)
backArrow?.applyColorFilter(bgColor.getContrastColor())
}
}
return true
}
override fun onPrepareActionMode(actionMode: ActionMode, menu: Menu): Boolean {
prepareActionMode(menu)
return true
}
override fun onDestroyActionMode(actionMode: ActionMode) {
isSelectable = false
(selectedKeys.clone() as HashSet<Int>).forEach {
val position = getItemKeyPosition(it)
if (position != -1) {
toggleItemSelection(false, position, false)
}
}
updateTitle()
selectedKeys.clear()
actBarTextView?.text = ""
actMode = null
lastLongPressedItem = -1
onActionModeDestroyed()
}
}
}
protected fun toggleItemSelection(select: Boolean, pos: Int, updateTitle: Boolean = true) {
if (select && !getIsItemSelectable(pos)) {
return
}
val itemKey = getItemSelectionKey(pos) ?: return
if ((select && selectedKeys.contains(itemKey)) || (!select && !selectedKeys.contains(itemKey))) {
return
}
if (select) {
selectedKeys.add(itemKey)
} else {
selectedKeys.remove(itemKey)
}
notifyItemChanged(pos + positionOffset)
if (updateTitle) {
updateTitle()
}
if (selectedKeys.isEmpty()) {
finishActMode()
}
}
private fun updateTitle() {
val selectableItemCount = getSelectableItemCount()
val selectedCount = Math.min(selectedKeys.size, selectableItemCount)
val oldTitle = actBarTextView?.text
val newTitle = "$selectedCount / $selectableItemCount"
if (oldTitle != newTitle) {
actBarTextView?.text = newTitle
actMode?.invalidate()
}
}
fun itemLongClicked(position: Int) {
recyclerView.setDragSelectActive(position)
lastLongPressedItem = if (lastLongPressedItem == -1) {
position
} else {
val min = min(lastLongPressedItem, position)
val max = max(lastLongPressedItem, position)
for (i in min..max) {
toggleItemSelection(true, i, false)
}
updateTitle()
position
}
}
protected fun getSelectedItemPositions(sortDescending: Boolean = true): ArrayList<Int> {
val positions = ArrayList<Int>()
val keys = selectedKeys.toList()
keys.forEach {
val position = getItemKeyPosition(it)
if (position != -1) {
positions.add(position)
}
}
if (sortDescending) {
positions.sortDescending()
}
return positions
}
protected fun selectAll() {
val cnt = itemCount - positionOffset
for (i in 0 until cnt) {
toggleItemSelection(true, i, false)
}
lastLongPressedItem = -1
updateTitle()
}
protected fun setupDragListener(enable: Boolean) {
if (enable) {
recyclerView.setupDragListener(object : MyRecyclerView.MyDragListener {
override fun selectItem(position: Int) {
toggleItemSelection(true, position, true)
}
override fun selectRange(initialSelection: Int, lastDraggedIndex: Int, minReached: Int, maxReached: Int) {
selectItemRange(
initialSelection,
Math.max(0, lastDraggedIndex - positionOffset),
Math.max(0, minReached - positionOffset),
maxReached - positionOffset
)
if (minReached != maxReached) {
lastLongPressedItem = -1
}
}
})
} else {
recyclerView.setupDragListener(null)
}
}
protected fun selectItemRange(from: Int, to: Int, min: Int, max: Int) {
if (from == to) {
(min..max).filter { it != from }.forEach { toggleItemSelection(false, it, true) }
return
}
if (to < from) {
for (i in to..from) {
toggleItemSelection(true, i, true)
}
if (min > -1 && min < to) {
(min until to).filter { it != from }.forEach { toggleItemSelection(false, it, true) }
}
if (max > -1) {
for (i in from + 1..max) {
toggleItemSelection(false, i, true)
}
}
} else {
for (i in from..to) {
toggleItemSelection(true, i, true)
}
if (max > -1 && max > to) {
(to + 1..max).filter { it != from }.forEach { toggleItemSelection(false, it, true) }
}
if (min > -1) {
for (i in min until from) {
toggleItemSelection(false, i, true)
}
}
}
}
fun setupZoomListener(zoomListener: MyRecyclerView.MyZoomListener?) {
recyclerView.setupZoomListener(zoomListener)
}
fun addVerticalDividers(add: Boolean) {
if (recyclerView.itemDecorationCount > 0) {
recyclerView.removeItemDecorationAt(0)
}
if (add) {
DividerItemDecoration(activity, DividerItemDecoration.VERTICAL).apply {
setDrawable(resources.getDrawable(R.drawable.divider))
recyclerView.addItemDecoration(this)
}
}
}
fun finishActMode() {
actMode?.finish()
}
fun updateTextColor(textColor: Int) {
this.textColor = textColor
notifyDataSetChanged()
}
fun updatePrimaryColor() {
properPrimaryColor = activity.getProperPrimaryColor()
contrastColor = properPrimaryColor.getContrastColor()
}
fun updateBackgroundColor(backgroundColor: Int) {
this.backgroundColor = backgroundColor
}
protected fun createViewHolder(layoutType: Int, parent: ViewGroup?): ViewHolder {
val view = layoutInflater.inflate(layoutType, parent, false)
return ViewHolder(view)
}
protected fun createViewHolder(view: View): ViewHolder {
return ViewHolder(view)
}
protected fun bindViewHolder(holder: ViewHolder) {
holder.itemView.tag = holder
}
protected fun removeSelectedItems(positions: ArrayList<Int>) {
positions.forEach {
notifyItemRemoved(it)
}
finishActMode()
}
open inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
fun bindView(any: Any, allowSingleClick: Boolean, allowLongClick: Boolean, callback: (itemView: View, adapterPosition: Int) -> Unit): View {
return itemView.apply {
callback(this, adapterPosition)
if (allowSingleClick) {
setOnClickListener { viewClicked(any) }
setOnLongClickListener { if (allowLongClick) viewLongClicked() else viewClicked(any); true }
} else {
setOnClickListener(null)
setOnLongClickListener(null)
}
}
}
fun viewClicked(any: Any) {
if (actModeCallback.isSelectable) {
val currentPosition = adapterPosition - positionOffset
val isSelected = selectedKeys.contains(getItemSelectionKey(currentPosition))
toggleItemSelection(!isSelected, currentPosition, true)
} else {
itemClick.invoke(any)
}
lastLongPressedItem = -1
}
fun viewLongClicked() {
val currentPosition = adapterPosition - positionOffset
if (!actModeCallback.isSelectable) {
activity.startActionMode(actModeCallback)
}
toggleItemSelection(true, currentPosition, true)
itemLongClicked(currentPosition)
}
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/adapters/MyRecyclerViewAdapter.kt | 3235398067 |
package com.simplemobiletools.commons.adapters
import android.content.pm.PackageManager
import android.graphics.drawable.Drawable
import android.util.TypedValue
import android.view.Menu
import android.view.ViewGroup
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions.withCrossFade
import com.bumptech.glide.request.RequestOptions
import com.qtalk.recyclerviewfastscroller.RecyclerViewFastScroller
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.activities.BaseSimpleActivity
import com.simplemobiletools.commons.databinding.ItemFilepickerListBinding
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.getFilePlaceholderDrawables
import com.simplemobiletools.commons.models.FileDirItem
import com.simplemobiletools.commons.views.MyRecyclerView
import java.util.Locale
class FilepickerItemsAdapter(
activity: BaseSimpleActivity, val fileDirItems: List<FileDirItem>, recyclerView: MyRecyclerView,
itemClick: (Any) -> Unit
) : MyRecyclerViewAdapter(activity, recyclerView, itemClick), RecyclerViewFastScroller.OnPopupTextUpdate {
private lateinit var fileDrawable: Drawable
private lateinit var folderDrawable: Drawable
private var fileDrawables = HashMap<String, Drawable>()
private val hasOTGConnected = activity.hasOTGConnected()
private var fontSize = 0f
private val cornerRadius = resources.getDimension(R.dimen.rounded_corner_radius_small).toInt()
private val dateFormat = activity.baseConfig.dateFormat
private val timeFormat = activity.getTimeFormat()
init {
initDrawables()
fontSize = activity.getTextSize()
}
override fun getActionMenuId() = 0
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = createViewHolder(R.layout.item_filepicker_list, parent)
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val fileDirItem = fileDirItems[position]
holder.bindView(fileDirItem, allowSingleClick = true, allowLongClick = false) { itemView, adapterPosition ->
setupView(ItemFilepickerListBinding.bind(itemView), fileDirItem)
}
bindViewHolder(holder)
}
override fun getItemCount() = fileDirItems.size
override fun prepareActionMode(menu: Menu) {}
override fun actionItemPressed(id: Int) {}
override fun getSelectableItemCount() = fileDirItems.size
override fun getIsItemSelectable(position: Int) = false
override fun getItemKeyPosition(key: Int) = fileDirItems.indexOfFirst { it.path.hashCode() == key }
override fun getItemSelectionKey(position: Int) = fileDirItems[position].path.hashCode()
override fun onActionModeCreated() {}
override fun onActionModeDestroyed() {}
override fun onViewRecycled(holder: ViewHolder) {
super.onViewRecycled(holder)
if (!activity.isDestroyed && !activity.isFinishing) {
Glide.with(activity).clear(ItemFilepickerListBinding.bind(holder.itemView).listItemIcon)
}
}
private fun setupView(view: ItemFilepickerListBinding, fileDirItem: FileDirItem) {
view.apply {
listItemName.text = fileDirItem.name
listItemName.setTextColor(textColor)
listItemName.setTextSize(TypedValue.COMPLEX_UNIT_PX, fontSize)
listItemDetails.setTextColor(textColor)
listItemDetails.setTextSize(TypedValue.COMPLEX_UNIT_PX, fontSize)
if (fileDirItem.isDirectory) {
listItemIcon.setImageDrawable(folderDrawable)
listItemDetails.text = getChildrenCnt(fileDirItem)
} else {
listItemDetails.text = fileDirItem.size.formatSize()
val path = fileDirItem.path
val placeholder = fileDrawables.getOrElse(fileDirItem.name.substringAfterLast(".").lowercase(Locale.getDefault())) { fileDrawable }
val options = RequestOptions()
.signature(fileDirItem.getKey())
.diskCacheStrategy(DiskCacheStrategy.RESOURCE)
.centerCrop()
.error(placeholder)
var itemToLoad = if (fileDirItem.name.endsWith(".apk", true)) {
val packageInfo = root.context.packageManager.getPackageArchiveInfo(path, PackageManager.GET_ACTIVITIES)
if (packageInfo != null) {
val appInfo = packageInfo.applicationInfo
appInfo.sourceDir = path
appInfo.publicSourceDir = path
appInfo.loadIcon(root.context.packageManager)
} else {
path
}
} else {
path
}
if (!activity.isDestroyed && !activity.isFinishing) {
if (activity.isRestrictedSAFOnlyRoot(path)) {
itemToLoad = activity.getAndroidSAFUri(path)
} else if (hasOTGConnected && itemToLoad is String && activity.isPathOnOTG(itemToLoad)) {
itemToLoad = itemToLoad.getOTGPublicPath(activity)
}
if (itemToLoad.toString().isGif()) {
Glide.with(activity).asBitmap().load(itemToLoad).apply(options).into(listItemIcon)
} else {
Glide.with(activity)
.load(itemToLoad)
.transition(withCrossFade())
.apply(options)
.transform(CenterCrop(), RoundedCorners(cornerRadius))
.into(listItemIcon)
}
}
}
}
}
private fun getChildrenCnt(item: FileDirItem): String {
val children = item.children
return activity.resources.getQuantityString(R.plurals.items, children, children)
}
private fun initDrawables() {
folderDrawable = resources.getColoredDrawableWithColor(R.drawable.ic_folder_vector, textColor)
folderDrawable.alpha = 180
fileDrawable = resources.getDrawable(R.drawable.ic_file_generic)
fileDrawables = getFilePlaceholderDrawables(activity)
}
override fun onChange(position: Int) = fileDirItems.getOrNull(position)?.getBubbleText(activity, dateFormat, timeFormat) ?: ""
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/adapters/FilepickerItemsAdapter.kt | 1779674330 |
package com.simplemobiletools.commons.adapters
import android.util.TypedValue
import android.view.Menu
import android.view.ViewGroup
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.activities.BaseSimpleActivity
import com.simplemobiletools.commons.databinding.FilepickerFavoriteBinding
import com.simplemobiletools.commons.extensions.getTextSize
import com.simplemobiletools.commons.views.MyRecyclerView
class FilepickerFavoritesAdapter(
activity: BaseSimpleActivity, val paths: List<String>, recyclerView: MyRecyclerView,
itemClick: (Any) -> Unit
) : MyRecyclerViewAdapter(activity, recyclerView, itemClick) {
private var fontSize = 0f
init {
fontSize = activity.getTextSize()
}
override fun getActionMenuId() = 0
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = createViewHolder(R.layout.filepicker_favorite, parent)
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val path = paths[position]
holder.bindView(path, allowSingleClick = true, allowLongClick = false) { itemView, adapterPosition ->
setupView(FilepickerFavoriteBinding.bind(itemView), path)
}
bindViewHolder(holder)
}
override fun getItemCount() = paths.size
override fun prepareActionMode(menu: Menu) {}
override fun actionItemPressed(id: Int) {}
override fun getSelectableItemCount() = paths.size
override fun getIsItemSelectable(position: Int) = false
override fun getItemKeyPosition(key: Int) = paths.indexOfFirst { it.hashCode() == key }
override fun getItemSelectionKey(position: Int) = paths[position].hashCode()
override fun onActionModeCreated() {}
override fun onActionModeDestroyed() {}
private fun setupView(view: FilepickerFavoriteBinding, path: String) {
view.apply {
filepickerFavoriteLabel.text = path
filepickerFavoriteLabel.setTextColor(textColor)
filepickerFavoriteLabel.setTextSize(TypedValue.COMPLEX_UNIT_PX, fontSize)
}
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/adapters/FilepickerFavoritesAdapter.kt | 2092934499 |
package com.simplemobiletools.commons.adapters
import android.app.Activity
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.databinding.ItemSimpleListBinding
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.models.SimpleListItem
open class SimpleListItemAdapter(val activity: Activity, val onItemClicked: (SimpleListItem) -> Unit) :
ListAdapter<SimpleListItem, SimpleListItemAdapter.SimpleItemViewHolder>(SimpleListItemDiffCallback()) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SimpleItemViewHolder {
val view = activity.layoutInflater.inflate(R.layout.item_simple_list, parent, false)
return SimpleItemViewHolder(view)
}
override fun onBindViewHolder(holder: SimpleItemViewHolder, position: Int) {
val route = getItem(position)
holder.bindView(route)
}
open inner class SimpleItemViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val binding = ItemSimpleListBinding.bind(itemView)
fun bindView(item: SimpleListItem) {
setupSimpleListItem(binding, item, onItemClicked)
}
}
private class SimpleListItemDiffCallback : DiffUtil.ItemCallback<SimpleListItem>() {
override fun areItemsTheSame(oldItem: SimpleListItem, newItem: SimpleListItem): Boolean {
return SimpleListItem.areItemsTheSame(oldItem, newItem)
}
override fun areContentsTheSame(oldItem: SimpleListItem, newItem: SimpleListItem): Boolean {
return SimpleListItem.areContentsTheSame(oldItem, newItem)
}
}
}
fun setupSimpleListItem(view: ItemSimpleListBinding, item: SimpleListItem, onItemClicked: (SimpleListItem) -> Unit) {
view.apply {
val color = if (item.selected) {
root.context.getProperPrimaryColor()
} else {
root.context.getProperTextColor()
}
bottomSheetItemTitle.setText(item.textRes)
bottomSheetItemTitle.setTextColor(color)
bottomSheetItemIcon.setImageResourceOrBeGone(item.imageRes)
bottomSheetItemIcon.applyColorFilter(color)
bottomSheetSelectedIcon.beVisibleIf(item.selected)
bottomSheetSelectedIcon.applyColorFilter(color)
root.setOnClickListener {
onItemClicked(item)
}
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/adapters/SimpleListItemAdapter.kt | 1649484597 |
package com.simplemobiletools.commons.adapters
import android.content.Context
import android.graphics.drawable.ColorDrawable
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.TextView
class MyArrayAdapter<T>(context: Context, res: Int, items: Array<T>, val textColor: Int, val backgroundColor: Int, val padding: Int) :
ArrayAdapter<T>(context, res, items) {
override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup): View {
val view = super.getView(position, convertView, parent)
view.findViewById<TextView>(android.R.id.text1).apply {
setTextColor(textColor)
setPadding(padding, padding, padding, padding)
background = ColorDrawable(backgroundColor)
}
return view
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/adapters/MyArrayAdapter.kt | 2774995207 |
package com.simplemobiletools.commons.adapters
import android.util.SparseArray
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.viewpager.widget.PagerAdapter
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.activities.BaseSimpleActivity
import com.simplemobiletools.commons.interfaces.RenameTab
class RenameAdapter(val activity: BaseSimpleActivity, val paths: ArrayList<String>) : PagerAdapter() {
private val tabs = SparseArray<RenameTab>()
override fun instantiateItem(container: ViewGroup, position: Int): Any {
val view = LayoutInflater.from(activity).inflate(layoutSelection(position), container, false)
container.addView(view)
tabs.put(position, view as RenameTab)
(view as RenameTab).initTab(activity, paths)
return view
}
override fun destroyItem(container: ViewGroup, position: Int, item: Any) {
tabs.remove(position)
container.removeView(item as View)
}
override fun getCount() = 2
override fun isViewFromObject(view: View, item: Any) = view == item
private fun layoutSelection(position: Int): Int = when (position) {
0 -> R.layout.tab_rename_simple
1 -> R.layout.tab_rename_pattern
else -> throw RuntimeException("Only 2 tabs allowed")
}
fun dialogConfirmed(useMediaFileExtension: Boolean, position: Int, callback: (success: Boolean) -> Unit) {
tabs[position].dialogConfirmed(useMediaFileExtension, callback)
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/adapters/RenameAdapter.kt | 1937438383 |
package com.simplemobiletools.commons.adapters
import android.graphics.Color
import android.view.*
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.ActionBar
import androidx.core.content.res.ResourcesCompat
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.activities.BaseSimpleActivity
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.interfaces.MyActionModeCallback
import com.simplemobiletools.commons.models.RecyclerSelectionPayload
import com.simplemobiletools.commons.views.MyRecyclerView
import kotlin.math.max
import kotlin.math.min
abstract class MyRecyclerViewListAdapter<T>(
val activity: BaseSimpleActivity,
val recyclerView: MyRecyclerView,
diffUtil: DiffUtil.ItemCallback<T>,
val itemClick: (T) -> Unit,
val onRefresh: () -> Unit = {}
) : ListAdapter<T, MyRecyclerViewListAdapter<T>.ViewHolder>(diffUtil) {
protected val baseConfig = activity.baseConfig
protected val resources = activity.resources!!
protected val layoutInflater = activity.layoutInflater
protected var textColor = activity.getProperTextColor()
protected var backgroundColor = activity.getProperBackgroundColor()
protected var properPrimaryColor = activity.getProperPrimaryColor()
protected var contrastColor = properPrimaryColor.getContrastColor()
protected var actModeCallback: MyActionModeCallback
protected var selectedKeys = LinkedHashSet<Int>()
protected var positionOffset = 0
protected var actMode: ActionMode? = null
private var actBarTextView: TextView? = null
private var lastLongPressedItem = -1
abstract fun getActionMenuId(): Int
abstract fun prepareActionMode(menu: Menu)
abstract fun actionItemPressed(id: Int)
abstract fun getSelectableItemCount(): Int
abstract fun getIsItemSelectable(position: Int): Boolean
abstract fun getItemSelectionKey(position: Int): Int?
abstract fun getItemKeyPosition(key: Int): Int
abstract fun onActionModeCreated()
abstract fun onActionModeDestroyed()
protected fun isOneItemSelected() = selectedKeys.size == 1
init {
actModeCallback = object : MyActionModeCallback() {
override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean {
actionItemPressed(item.itemId)
return true
}
override fun onCreateActionMode(actionMode: ActionMode, menu: Menu?): Boolean {
if (getActionMenuId() == 0) {
return true
}
isSelectable = true
actMode = actionMode
actBarTextView = layoutInflater.inflate(R.layout.actionbar_title, null) as TextView
actBarTextView!!.layoutParams = ActionBar.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT)
actMode!!.customView = actBarTextView
actBarTextView!!.setOnClickListener {
if (getSelectableItemCount() == selectedKeys.size) {
finishActMode()
} else {
selectAll()
}
}
activity.menuInflater.inflate(getActionMenuId(), menu)
val bgColor = if (baseConfig.isUsingSystemTheme) {
ResourcesCompat.getColor(resources, R.color.you_contextual_status_bar_color, activity.theme)
} else {
Color.BLACK
}
actBarTextView!!.setTextColor(bgColor.getContrastColor())
activity.updateMenuItemColors(menu, baseColor = bgColor)
onActionModeCreated()
if (baseConfig.isUsingSystemTheme) {
actBarTextView?.onGlobalLayout {
val backArrow = activity.findViewById<ImageView>(androidx.appcompat.R.id.action_mode_close_button)
backArrow?.applyColorFilter(bgColor.getContrastColor())
}
}
return true
}
override fun onPrepareActionMode(actionMode: ActionMode, menu: Menu): Boolean {
prepareActionMode(menu)
return true
}
override fun onDestroyActionMode(actionMode: ActionMode) {
isSelectable = false
(selectedKeys.clone() as HashSet<Int>).forEach {
val position = getItemKeyPosition(it)
if (position != -1) {
toggleItemSelection(false, position, false)
}
}
updateTitle()
selectedKeys.clear()
actBarTextView?.text = ""
actMode = null
lastLongPressedItem = -1
onActionModeDestroyed()
}
}
}
protected fun toggleItemSelection(select: Boolean, pos: Int, updateTitle: Boolean = true) {
if (select && !getIsItemSelectable(pos)) {
return
}
val itemKey = getItemSelectionKey(pos) ?: return
if ((select && selectedKeys.contains(itemKey)) || (!select && !selectedKeys.contains(itemKey))) {
return
}
if (select) {
selectedKeys.add(itemKey)
} else {
selectedKeys.remove(itemKey)
}
notifyItemChanged(pos + positionOffset, RecyclerSelectionPayload(select))
if (updateTitle) {
updateTitle()
}
if (selectedKeys.isEmpty()) {
finishActMode()
}
}
override fun onBindViewHolder(holder: ViewHolder, position: Int, payloads: MutableList<Any>) {
val any = payloads.firstOrNull()
if (any is RecyclerSelectionPayload) {
holder.itemView.isSelected = any.selected
} else {
onBindViewHolder(holder, position)
}
}
private fun updateTitle() {
val selectableItemCount = getSelectableItemCount()
val selectedCount = min(selectedKeys.size, selectableItemCount)
val oldTitle = actBarTextView?.text
val newTitle = "$selectedCount / $selectableItemCount"
if (oldTitle != newTitle) {
actBarTextView?.text = newTitle
actMode?.invalidate()
}
}
fun itemLongClicked(position: Int) {
recyclerView.setDragSelectActive(position)
lastLongPressedItem = if (lastLongPressedItem == -1) {
position
} else {
val min = min(lastLongPressedItem, position)
val max = max(lastLongPressedItem, position)
for (i in min..max) {
toggleItemSelection(true, i, false)
}
updateTitle()
position
}
}
protected fun getSelectedItemPositions(sortDescending: Boolean = true): ArrayList<Int> {
val positions = ArrayList<Int>()
val keys = selectedKeys.toList()
keys.forEach {
val position = getItemKeyPosition(it)
if (position != -1) {
positions.add(position)
}
}
if (sortDescending) {
positions.sortDescending()
}
return positions
}
protected fun selectAll() {
val cnt = itemCount - positionOffset
for (i in 0 until cnt) {
toggleItemSelection(true, i, false)
}
lastLongPressedItem = -1
updateTitle()
}
protected fun setupDragListener(enable: Boolean) {
if (enable) {
recyclerView.setupDragListener(object : MyRecyclerView.MyDragListener {
override fun selectItem(position: Int) {
toggleItemSelection(true, position, true)
}
override fun selectRange(initialSelection: Int, lastDraggedIndex: Int, minReached: Int, maxReached: Int) {
selectItemRange(
initialSelection,
max(0, lastDraggedIndex - positionOffset),
max(0, minReached - positionOffset),
maxReached - positionOffset
)
if (minReached != maxReached) {
lastLongPressedItem = -1
}
}
})
} else {
recyclerView.setupDragListener(null)
}
}
protected fun selectItemRange(from: Int, to: Int, min: Int, max: Int) {
if (from == to) {
(min..max).filter { it != from }.forEach { toggleItemSelection(false, it, true) }
return
}
if (to < from) {
for (i in to..from) {
toggleItemSelection(true, i, true)
}
if (min > -1 && min < to) {
(min until to).filter { it != from }.forEach { toggleItemSelection(false, it, true) }
}
if (max > -1) {
for (i in from + 1..max) {
toggleItemSelection(false, i, true)
}
}
} else {
for (i in from..to) {
toggleItemSelection(true, i, true)
}
if (max > -1 && max > to) {
(to + 1..max).filter { it != from }.forEach { toggleItemSelection(false, it, true) }
}
if (min > -1) {
for (i in min until from) {
toggleItemSelection(false, i, true)
}
}
}
}
fun setupZoomListener(zoomListener: MyRecyclerView.MyZoomListener?) {
recyclerView.setupZoomListener(zoomListener)
}
fun addVerticalDividers(add: Boolean) {
if (recyclerView.itemDecorationCount > 0) {
recyclerView.removeItemDecorationAt(0)
}
if (add) {
DividerItemDecoration(activity, DividerItemDecoration.VERTICAL).apply {
setDrawable(resources.getDrawable(R.drawable.divider))
recyclerView.addItemDecoration(this)
}
}
}
fun finishActMode() {
actMode?.finish()
}
fun updateTextColor(textColor: Int) {
this.textColor = textColor
onRefresh.invoke()
}
fun updatePrimaryColor() {
properPrimaryColor = activity.getProperPrimaryColor()
contrastColor = properPrimaryColor.getContrastColor()
}
fun updateBackgroundColor(backgroundColor: Int) {
this.backgroundColor = backgroundColor
}
protected fun createViewHolder(layoutType: Int, parent: ViewGroup?): ViewHolder {
val view = layoutInflater.inflate(layoutType, parent, false)
return ViewHolder(view)
}
protected fun createViewHolder(view: View): ViewHolder {
return ViewHolder(view)
}
protected fun bindViewHolder(holder: ViewHolder) {
holder.itemView.tag = holder
}
protected fun removeSelectedItems(positions: ArrayList<Int>) {
positions.forEach {
notifyItemRemoved(it)
}
finishActMode()
}
open inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
fun bindView(item: T, allowSingleClick: Boolean, allowLongClick: Boolean, callback: (itemView: View, adapterPosition: Int) -> Unit): View {
return itemView.apply {
callback(this, adapterPosition)
if (allowSingleClick) {
setOnClickListener { viewClicked(item) }
setOnLongClickListener { if (allowLongClick) viewLongClicked() else viewClicked(item); true }
} else {
setOnClickListener(null)
setOnLongClickListener(null)
}
}
}
fun viewClicked(any: T) {
if (actModeCallback.isSelectable) {
val currentPosition = adapterPosition - positionOffset
val isSelected = selectedKeys.contains(getItemSelectionKey(currentPosition))
toggleItemSelection(!isSelected, currentPosition, true)
} else {
itemClick.invoke(any)
}
lastLongPressedItem = -1
}
fun viewLongClicked() {
val currentPosition = adapterPosition - positionOffset
if (!actModeCallback.isSelectable) {
activity.startActionMode(actModeCallback)
}
toggleItemSelection(true, currentPosition, true)
itemLongClicked(currentPosition)
}
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/adapters/MyRecyclerViewListAdapter.kt | 3812672634 |
package com.simplemobiletools.commons.dialogs
import android.app.Activity
import android.content.Context
import android.content.DialogInterface
import android.view.KeyEvent
import android.view.View
import androidx.appcompat.app.AlertDialog
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.TextRange
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.DialogProperties
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.compose.alert_dialog.AlertDialogState
import com.simplemobiletools.commons.compose.alert_dialog.DialogSurface
import com.simplemobiletools.commons.compose.alert_dialog.ShowKeyboardWhenDialogIsOpenedAndRequestFocus
import com.simplemobiletools.commons.compose.alert_dialog.rememberAlertDialogState
import com.simplemobiletools.commons.compose.components.RadioGroupDialogComponent
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.databinding.DialogCustomIntervalPickerBinding
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.DAY_SECONDS
import com.simplemobiletools.commons.helpers.HOUR_SECONDS
import com.simplemobiletools.commons.helpers.MINUTE_SECONDS
import kotlinx.collections.immutable.toImmutableList
class CustomIntervalPickerDialog(val activity: Activity, val selectedSeconds: Int = 0, val showSeconds: Boolean = false, val callback: (minutes: Int) -> Unit) {
private var dialog: AlertDialog? = null
private var view = DialogCustomIntervalPickerBinding.inflate(activity.layoutInflater, null, false)
init {
activity.getAlertDialogBuilder()
.setPositiveButton(R.string.ok) { _, _ -> confirmReminder() }
.setNegativeButton(R.string.cancel, null)
.apply {
activity.setupDialogStuff(view.root, this) { alertDialog ->
dialog = alertDialog
alertDialog.showKeyboard(view.dialogCustomIntervalValue)
}
}
view.apply {
dialogRadioSeconds.beVisibleIf(showSeconds)
when {
selectedSeconds == 0 -> dialogRadioView.check(R.id.dialog_radio_minutes)
selectedSeconds % DAY_SECONDS == 0 -> {
dialogRadioView.check(R.id.dialog_radio_days)
dialogCustomIntervalValue.setText((selectedSeconds / DAY_SECONDS).toString())
}
selectedSeconds % HOUR_SECONDS == 0 -> {
dialogRadioView.check(R.id.dialog_radio_hours)
dialogCustomIntervalValue.setText((selectedSeconds / HOUR_SECONDS).toString())
}
selectedSeconds % MINUTE_SECONDS == 0 -> {
dialogRadioView.check(R.id.dialog_radio_minutes)
dialogCustomIntervalValue.setText((selectedSeconds / MINUTE_SECONDS).toString())
}
else -> {
dialogRadioView.check(R.id.dialog_radio_seconds)
dialogCustomIntervalValue.setText(selectedSeconds.toString())
}
}
dialogCustomIntervalValue.setOnKeyListener(object : View.OnKeyListener {
override fun onKey(v: View?, keyCode: Int, event: KeyEvent): Boolean {
if (event.action == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER) {
dialog?.getButton(DialogInterface.BUTTON_POSITIVE)?.performClick()
return true
}
return false
}
})
}
}
private fun confirmReminder() {
val value = view.dialogCustomIntervalValue.value
val multiplier = getMultiplier(view.dialogRadioView.checkedRadioButtonId)
val minutes = Integer.valueOf(value.ifEmpty { "0" })
callback(minutes * multiplier)
activity.hideKeyboard()
dialog?.dismiss()
}
private fun getMultiplier(id: Int) = when (id) {
R.id.dialog_radio_days -> DAY_SECONDS
R.id.dialog_radio_hours -> HOUR_SECONDS
R.id.dialog_radio_minutes -> MINUTE_SECONDS
else -> 1
}
}
@Composable
fun CustomIntervalPickerAlertDialog(
alertDialogState: AlertDialogState,
modifier: Modifier = Modifier,
selectedSeconds: Int = 0,
showSeconds: Boolean = false,
callback: (minutes: Int) -> Unit
) {
val focusRequester = remember { FocusRequester() }
var textFieldValue by remember {
mutableStateOf(initialTextFieldValue(selectedSeconds))
}
val context = LocalContext.current
val selections = remember {
buildCustomIntervalEntries(context, showSeconds)
}
val initiallySelected = remember {
initialSelection(selectedSeconds, context)
}
val (selected, setSelected) = remember { mutableStateOf(initiallySelected) }
AlertDialog(
modifier = modifier.fillMaxWidth(0.95f),
onDismissRequest = alertDialogState::hide,
properties = DialogProperties(usePlatformDefaultWidth = false)
) {
DialogSurface {
Box {
Column(
modifier = modifier
.padding(bottom = 64.dp)
.verticalScroll(rememberScrollState())
) {
OutlinedTextField(
modifier = Modifier
.fillMaxWidth()
.padding(
top = SimpleTheme.dimens.padding.extraLarge,
start = SimpleTheme.dimens.padding.extraLarge,
end = SimpleTheme.dimens.padding.extraLarge
)
.focusRequester(focusRequester),
value = textFieldValue,
onValueChange = { newValue ->
if (newValue.text.length <= 5) textFieldValue = newValue
},
label = {
Text(text = stringResource(id = R.string.value))
},
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
maxLines = 1
)
RadioGroupDialogComponent(
items = selections,
selected = selected,
setSelected = setSelected,
modifier = Modifier.padding(
vertical = SimpleTheme.dimens.padding.extraLarge,
)
)
}
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.End,
modifier = Modifier
.fillMaxWidth()
.padding(
top = SimpleTheme.dimens.padding.extraLarge,
bottom = SimpleTheme.dimens.padding.extraLarge,
end = SimpleTheme.dimens.padding.extraLarge
)
.align(Alignment.BottomStart)
) {
TextButton(onClick = alertDialogState::hide) {
Text(text = stringResource(id = R.string.cancel))
}
TextButton(onClick = {
val multiplier = getMultiplier(context, selected)
val minutes = Integer.valueOf(textFieldValue.text.ifEmpty { "0" })
callback(minutes * multiplier)
alertDialogState.hide()
}) {
Text(text = stringResource(id = R.string.ok))
}
}
}
}
}
ShowKeyboardWhenDialogIsOpenedAndRequestFocus(focusRequester = focusRequester)
}
private fun initialSelection(selectedSeconds: Int, context: Context) = requireNotNull(
when {
selectedSeconds == 0 -> minutesRaw(context)
selectedSeconds % DAY_SECONDS == 0 -> daysRaw(context)
selectedSeconds % HOUR_SECONDS == 0 -> hoursRaw(context)
selectedSeconds % MINUTE_SECONDS == 0 -> minutesRaw(context)
else -> secondsRaw(context)
}
) {
"Incorrect format, please check selections"
}
private fun initialTextFieldValue(selectedSeconds: Int) = when {
selectedSeconds == 0 -> TextFieldValue("")
selectedSeconds % DAY_SECONDS == 0 -> {
val text = (selectedSeconds / DAY_SECONDS).toString()
textFieldValueAndSelection(text)
}
selectedSeconds % HOUR_SECONDS == 0 -> {
val text = (selectedSeconds / HOUR_SECONDS).toString()
textFieldValueAndSelection(text)
}
selectedSeconds % MINUTE_SECONDS == 0 -> {
val text = (selectedSeconds / MINUTE_SECONDS).toString()
textFieldValueAndSelection(text)
}
else -> {
val text = selectedSeconds.toString()
textFieldValueAndSelection(text)
}
}
private fun textFieldValueAndSelection(text: String) = TextFieldValue(text = text, selection = TextRange(text.length))
fun buildCustomIntervalEntries(context: Context, showSeconds: Boolean) =
buildList {
if (showSeconds) {
add(secondsRaw(context))
}
add(minutesRaw(context))
add(hoursRaw(context))
add(daysRaw(context))
}.toImmutableList()
private fun daysRaw(context: Context) = context.getString(R.string.days_raw)
private fun hoursRaw(context: Context) = context.getString(R.string.hours_raw)
private fun secondsRaw(context: Context) = context.getString(R.string.seconds_raw)
private fun minutesRaw(context: Context) = context.getString(R.string.minutes_raw)
private fun getMultiplier(context: Context, text: String) = when (text) {
daysRaw(context) -> DAY_SECONDS
hoursRaw(context) -> HOUR_SECONDS
minutesRaw(context) -> MINUTE_SECONDS
else -> 1
}
@Composable
@MyDevices
private fun CustomIntervalPickerAlertDialogPreview() {
AppThemeSurface {
CustomIntervalPickerAlertDialog(alertDialogState = rememberAlertDialogState(),
selectedSeconds = 0,
showSeconds = true,
callback = {}
)
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/dialogs/CustomIntervalPickerDialog.kt | 3939259862 |
package com.simplemobiletools.commons.dialogs
import android.app.Activity
import android.content.Context
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLayoutDirection
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.compose.alert_dialog.AlertDialogState
import com.simplemobiletools.commons.compose.alert_dialog.DialogSurface
import com.simplemobiletools.commons.compose.alert_dialog.dialogTextColor
import com.simplemobiletools.commons.compose.alert_dialog.rememberAlertDialogState
import com.simplemobiletools.commons.compose.components.RadioGroupDialogComponent
import com.simplemobiletools.commons.compose.extensions.MyDevices
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.databinding.DialogFileConflictBinding
import com.simplemobiletools.commons.extensions.baseConfig
import com.simplemobiletools.commons.extensions.beVisibleIf
import com.simplemobiletools.commons.extensions.getAlertDialogBuilder
import com.simplemobiletools.commons.extensions.setupDialogStuff
import com.simplemobiletools.commons.helpers.CONFLICT_KEEP_BOTH
import com.simplemobiletools.commons.helpers.CONFLICT_MERGE
import com.simplemobiletools.commons.helpers.CONFLICT_OVERWRITE
import com.simplemobiletools.commons.helpers.CONFLICT_SKIP
import com.simplemobiletools.commons.models.FileDirItem
import com.simplemobiletools.commons.models.FileDirItemReadOnly
import com.simplemobiletools.commons.models.asReadOnly
import kotlinx.collections.immutable.toImmutableList
class FileConflictDialog(
val activity: Activity, val fileDirItem: FileDirItem, val showApplyToAllCheckbox: Boolean,
val callback: (resolution: Int, applyForAll: Boolean) -> Unit
) {
val view = DialogFileConflictBinding.inflate(activity.layoutInflater, null, false)
init {
view.apply {
val stringBase = if (fileDirItem.isDirectory) R.string.folder_already_exists else R.string.file_already_exists
conflictDialogTitle.text = String.format(activity.getString(stringBase), fileDirItem.name)
conflictDialogApplyToAll.isChecked = activity.baseConfig.lastConflictApplyToAll
conflictDialogApplyToAll.beVisibleIf(showApplyToAllCheckbox)
conflictDialogDivider.root.beVisibleIf(showApplyToAllCheckbox)
conflictDialogRadioMerge.beVisibleIf(fileDirItem.isDirectory)
val resolutionButton = when (activity.baseConfig.lastConflictResolution) {
CONFLICT_OVERWRITE -> conflictDialogRadioOverwrite
CONFLICT_MERGE -> conflictDialogRadioMerge
else -> conflictDialogRadioSkip
}
resolutionButton.isChecked = true
}
activity.getAlertDialogBuilder()
.setPositiveButton(R.string.ok) { _, _ -> dialogConfirmed() }
.setNegativeButton(R.string.cancel, null)
.apply {
activity.setupDialogStuff(view.root, this)
}
}
private fun dialogConfirmed() {
val resolution = when (view.conflictDialogRadioGroup.checkedRadioButtonId) {
view.conflictDialogRadioSkip.id -> CONFLICT_SKIP
view.conflictDialogRadioMerge.id -> CONFLICT_MERGE
view.conflictDialogRadioKeepBoth.id -> CONFLICT_KEEP_BOTH
else -> CONFLICT_OVERWRITE
}
val applyToAll = view.conflictDialogApplyToAll.isChecked
activity.baseConfig.apply {
lastConflictApplyToAll = applyToAll
lastConflictResolution = resolution
}
callback(resolution, applyToAll)
}
}
@Composable
fun FileConflictAlertDialog(
alertDialogState: AlertDialogState,
fileDirItem: FileDirItemReadOnly,
showApplyToAll: Boolean,
modifier: Modifier = Modifier,
callback: (resolution: Int, applyForAll: Boolean) -> Unit
) {
val context = LocalContext.current
var isShowApplyForAllChecked by remember { mutableStateOf(context.baseConfig.lastConflictApplyToAll) }
val selections = remember {
buildFileConflictEntries(context, fileDirItem.isDirectory)
}
val kinds = remember {
selections.values.toImmutableList()
}
val initiallySelected = remember {
requireNotNull(selections[context.baseConfig.lastConflictResolution]) {
"Incorrect format, please check selections"
}
}
val (selected, setSelected) = remember { mutableStateOf(initiallySelected) }
AlertDialog(
onDismissRequest = alertDialogState::hide
) {
DialogSurface {
Box {
Column(
modifier = modifier
.padding(bottom = 64.dp)
.verticalScroll(rememberScrollState())
) {
Text(
text = String.format(
stringResource(id = if (fileDirItem.isDirectory) R.string.folder_already_exists else R.string.file_already_exists),
fileDirItem.name
),
modifier = Modifier
.fillMaxWidth()
.padding(top = 24.dp, bottom = SimpleTheme.dimens.padding.medium)
.padding(horizontal = 24.dp),
color = dialogTextColor,
fontSize = 21.sp
)
RadioGroupDialogComponent(
items = kinds, selected = selected,
setSelected = setSelected,
modifier = Modifier.padding(
vertical = SimpleTheme.dimens.padding.extraLarge,
)
)
if (showApplyToAll) {
SettingsHorizontalDivider()
CompositionLocalProvider(LocalLayoutDirection provides LayoutDirection.Rtl) {
DialogCheckBoxWithRadioAlignmentComponent(
label = stringResource(id = R.string.apply_to_all),
initialValue = isShowApplyForAllChecked,
onChange = { isShowApplyForAllChecked = it },
modifier = Modifier.padding(horizontal = SimpleTheme.dimens.padding.medium)
)
}
}
}
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.End,
modifier = Modifier
.fillMaxWidth()
.padding(
top = SimpleTheme.dimens.padding.extraLarge,
bottom = SimpleTheme.dimens.padding.extraLarge,
end = SimpleTheme.dimens.padding.extraLarge
)
.align(Alignment.BottomStart)
) {
TextButton(onClick = {
alertDialogState.hide()
}) {
Text(text = stringResource(id = R.string.cancel))
}
TextButton(onClick = {
alertDialogState.hide()
callback(selections.filterValues { it == selected }.keys.first(), isShowApplyForAllChecked)
}) {
Text(text = stringResource(id = R.string.ok))
}
}
}
}
}
}
private fun buildFileConflictEntries(context: Context, directory: Boolean) =
buildMap {
this[CONFLICT_SKIP] = context.getString(R.string.skip)
if (directory) {
this[CONFLICT_SKIP] = context.getString(R.string.merge)
}
this[CONFLICT_OVERWRITE] = context.getString(R.string.overwrite)
this[CONFLICT_KEEP_BOTH] = context.getString(R.string.keep_both)
}
@MyDevices
@Composable
private fun FileConflictAlertDialogPreview() {
AppThemeSurface {
FileConflictAlertDialog(
alertDialogState = rememberAlertDialogState(),
fileDirItem = FileDirItem("", name = "test", children = 1).asReadOnly(),
showApplyToAll = true
) { _, _ -> }
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/dialogs/FileConflictDialog.kt | 1794418419 |
package com.simplemobiletools.commons.dialogs
import android.app.Activity
import android.net.Uri
import android.os.Environment
import android.provider.MediaStore
import android.view.View
import android.widget.LinearLayout
import androidx.appcompat.app.AlertDialog
import androidx.exifinterface.media.ExifInterface
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.activities.BaseSimpleActivity
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.*
import com.simplemobiletools.commons.models.FileDirItem
import com.simplemobiletools.commons.views.MyTextView
import java.io.File
import java.util.*
class PropertiesDialog : BasePropertiesDialog {
private var mCountHiddenItems = false
/**
* A File Properties dialog constructor with an optional parameter, usable at 1 file selected
*
* @param activity request activity to avoid some Theme.AppCompat issues
* @param path the file path
* @param countHiddenItems toggle determining if we will count hidden files themselves and their sizes (reasonable only at directory properties)
*/
constructor(activity: Activity, path: String, countHiddenItems: Boolean = false) : super(activity) {
if (!activity.getDoesFilePathExist(path) && !path.startsWith("content://")) {
activity.toast(String.format(activity.getString(R.string.source_file_doesnt_exist), path))
return
}
mCountHiddenItems = countHiddenItems
addProperties(path)
val builder = activity.getAlertDialogBuilder()
.setPositiveButton(R.string.ok, null)
if (!path.startsWith("content://") && path.canModifyEXIF() && activity.isPathOnInternalStorage(path)) {
if ((isRPlus() && Environment.isExternalStorageManager()) || (!isRPlus() && activity.hasPermission(PERMISSION_WRITE_STORAGE))) {
builder.setNeutralButton(R.string.remove_exif, null)
}
}
builder.apply {
mActivity.setupDialogStuff(mDialogView.root, this, R.string.properties) { alertDialog ->
alertDialog.getButton(AlertDialog.BUTTON_NEUTRAL).setOnClickListener {
removeEXIFFromPath(path)
}
}
}
}
private fun addProperties(path: String) {
val fileDirItem = FileDirItem(path, path.getFilenameFromPath(), mActivity.getIsPathDirectory(path))
addProperty(R.string.name, fileDirItem.name)
addProperty(R.string.path, fileDirItem.getParentPath())
addProperty(R.string.size, "…", R.id.properties_size)
ensureBackgroundThread {
val fileCount = fileDirItem.getProperFileCount(mActivity, mCountHiddenItems)
val size = fileDirItem.getProperSize(mActivity, mCountHiddenItems).formatSize()
val directChildrenCount = if (fileDirItem.isDirectory) {
fileDirItem.getDirectChildrenCount(mActivity, mCountHiddenItems).toString()
} else {
0
}
this.mActivity.runOnUiThread {
(mDialogView.propertiesHolder.findViewById<LinearLayout>(R.id.properties_size).findViewById<MyTextView>(R.id.property_value)).text = size
if (fileDirItem.isDirectory) {
(mDialogView.propertiesHolder.findViewById<LinearLayout>(R.id.properties_file_count).findViewById<MyTextView>(R.id.property_value)).text = fileCount.toString()
(mDialogView.propertiesHolder.findViewById<LinearLayout>(R.id.properties_direct_children_count).findViewById<MyTextView>(R.id.property_value)).text =
directChildrenCount.toString()
}
}
if (!fileDirItem.isDirectory) {
val projection = arrayOf(MediaStore.Images.Media.DATE_MODIFIED)
val uri = MediaStore.Files.getContentUri("external")
val selection = "${MediaStore.MediaColumns.DATA} = ?"
val selectionArgs = arrayOf(path)
val cursor = mActivity.contentResolver.query(uri, projection, selection, selectionArgs, null)
cursor?.use {
if (cursor.moveToFirst()) {
val dateModified = cursor.getLongValue(MediaStore.Images.Media.DATE_MODIFIED) * 1000L
updateLastModified(mActivity, mDialogView.root, dateModified)
} else {
updateLastModified(mActivity, mDialogView.root, fileDirItem.getLastModified(mActivity))
}
}
val exif = if (isNougatPlus() && mActivity.isPathOnOTG(fileDirItem.path)) {
ExifInterface((mActivity as BaseSimpleActivity).getFileInputStreamSync(fileDirItem.path)!!)
} else if (isNougatPlus() && fileDirItem.path.startsWith("content://")) {
try {
ExifInterface(mActivity.contentResolver.openInputStream(Uri.parse(fileDirItem.path))!!)
} catch (e: Exception) {
return@ensureBackgroundThread
}
} else if (mActivity.isRestrictedSAFOnlyRoot(path)) {
try {
ExifInterface(mActivity.contentResolver.openInputStream(mActivity.getAndroidSAFUri(path))!!)
} catch (e: Exception) {
return@ensureBackgroundThread
}
} else {
try {
ExifInterface(fileDirItem.path)
} catch (e: Exception) {
return@ensureBackgroundThread
}
}
val latLon = FloatArray(2)
if (exif.getLatLong(latLon)) {
mActivity.runOnUiThread {
addProperty(R.string.gps_coordinates, "${latLon[0]}, ${latLon[1]}")
}
}
val altitude = exif.getAltitude(0.0)
if (altitude != 0.0) {
mActivity.runOnUiThread {
addProperty(R.string.altitude, "${altitude}m")
}
}
}
}
when {
fileDirItem.isDirectory -> {
addProperty(R.string.direct_children_count, "…", R.id.properties_direct_children_count)
addProperty(R.string.files_count, "…", R.id.properties_file_count)
}
fileDirItem.path.isImageSlow() -> {
fileDirItem.getResolution(mActivity)?.let { addProperty(R.string.resolution, it.formatAsResolution()) }
}
fileDirItem.path.isAudioSlow() -> {
fileDirItem.getDuration(mActivity)?.let { addProperty(R.string.duration, it) }
fileDirItem.getTitle(mActivity)?.let { addProperty(R.string.song_title, it) }
fileDirItem.getArtist(mActivity)?.let { addProperty(R.string.artist, it) }
fileDirItem.getAlbum(mActivity)?.let { addProperty(R.string.album, it) }
}
fileDirItem.path.isVideoSlow() -> {
fileDirItem.getDuration(mActivity)?.let { addProperty(R.string.duration, it) }
fileDirItem.getResolution(mActivity)?.let { addProperty(R.string.resolution, it.formatAsResolution()) }
fileDirItem.getArtist(mActivity)?.let { addProperty(R.string.artist, it) }
fileDirItem.getAlbum(mActivity)?.let { addProperty(R.string.album, it) }
}
}
if (fileDirItem.isDirectory) {
addProperty(R.string.last_modified, fileDirItem.getLastModified(mActivity).formatDate(mActivity))
} else {
addProperty(R.string.last_modified, "…", R.id.properties_last_modified)
try {
addExifProperties(path, mActivity)
} catch (e: Exception) {
mActivity.showErrorToast(e)
return
}
if (mActivity.baseConfig.appId.removeSuffix(".debug") == "com.simplemobiletools.filemanager.pro") {
addProperty(R.string.md5, "…", R.id.properties_md5)
ensureBackgroundThread {
val md5 = if (mActivity.isRestrictedSAFOnlyRoot(path)) {
mActivity.contentResolver.openInputStream(mActivity.getAndroidSAFUri(path))?.md5()
} else {
File(path).md5()
}
mActivity.runOnUiThread {
if (md5 != null) {
(mDialogView.propertiesHolder.findViewById<LinearLayout>(R.id.properties_md5).findViewById<MyTextView>(R.id.property_value)).text = md5
} else {
mDialogView.propertiesHolder.findViewById<LinearLayout>(R.id.properties_md5).beGone()
}
}
}
}
}
}
private fun updateLastModified(activity: Activity, view: View, timestamp: Long) {
activity.runOnUiThread {
(view.findViewById<LinearLayout>(R.id.properties_last_modified).findViewById<MyTextView>(R.id.property_value)).text = timestamp.formatDate(activity)
}
}
/**
* A File Properties dialog constructor with an optional parameter, usable at multiple items selected
*
* @param activity request activity to avoid some Theme.AppCompat issues
* @param path the file path
* @param countHiddenItems toggle determining if we will count hidden files themselves and their sizes
*/
constructor(activity: Activity, paths: List<String>, countHiddenItems: Boolean = false) : super(activity) {
mCountHiddenItems = countHiddenItems
val fileDirItems = ArrayList<FileDirItem>(paths.size)
paths.forEach {
val fileDirItem = FileDirItem(it, it.getFilenameFromPath(), activity.getIsPathDirectory(it))
fileDirItems.add(fileDirItem)
}
val isSameParent = isSameParent(fileDirItems)
addProperty(R.string.items_selected, paths.size.toString())
if (isSameParent) {
addProperty(R.string.path, fileDirItems[0].getParentPath())
}
addProperty(R.string.size, "…", R.id.properties_size)
addProperty(R.string.files_count, "…", R.id.properties_file_count)
ensureBackgroundThread {
val fileCount = fileDirItems.sumByInt { it.getProperFileCount(activity, countHiddenItems) }
val size = fileDirItems.sumByLong { it.getProperSize(activity, countHiddenItems) }.formatSize()
activity.runOnUiThread {
(mDialogView.propertiesHolder.findViewById<LinearLayout>(R.id.properties_size).findViewById<MyTextView>(R.id.property_value)).text = size
(mDialogView.propertiesHolder.findViewById<LinearLayout>(R.id.properties_file_count).findViewById<MyTextView>(R.id.property_value)).text = fileCount.toString()
}
}
val builder = activity.getAlertDialogBuilder()
.setPositiveButton(R.string.ok, null)
if (!paths.any { it.startsWith("content://") } && paths.any { it.canModifyEXIF() } && paths.any { activity.isPathOnInternalStorage(it) }) {
if ((isRPlus() && Environment.isExternalStorageManager()) || (!isRPlus() && activity.hasPermission(PERMISSION_WRITE_STORAGE))) {
builder.setNeutralButton(R.string.remove_exif, null)
}
}
builder.apply {
mActivity.setupDialogStuff(mDialogView.root, this, R.string.properties) { alertDialog ->
alertDialog.getButton(AlertDialog.BUTTON_NEUTRAL).setOnClickListener {
removeEXIFFromPaths(paths)
}
}
}
}
private fun addExifProperties(path: String, activity: Activity) {
val exif = if (isNougatPlus() && activity.isPathOnOTG(path)) {
ExifInterface((activity as BaseSimpleActivity).getFileInputStreamSync(path)!!)
} else if (isNougatPlus() && path.startsWith("content://")) {
try {
ExifInterface(activity.contentResolver.openInputStream(Uri.parse(path))!!)
} catch (e: Exception) {
return
}
} else if (activity.isRestrictedSAFOnlyRoot(path)) {
try {
ExifInterface(activity.contentResolver.openInputStream(activity.getAndroidSAFUri(path))!!)
} catch (e: Exception) {
return
}
} else {
ExifInterface(path)
}
val dateTaken = exif.getExifDateTaken(activity)
if (dateTaken.isNotEmpty()) {
addProperty(R.string.date_taken, dateTaken)
}
val cameraModel = exif.getExifCameraModel()
if (cameraModel.isNotEmpty()) {
addProperty(R.string.camera, cameraModel)
}
val exifString = exif.getExifProperties()
if (exifString.isNotEmpty()) {
addProperty(R.string.exif, exifString)
}
}
private fun removeEXIFFromPath(path: String) {
ConfirmationDialog(mActivity, "", R.string.remove_exif_confirmation) {
try {
ExifInterface(path).removeValues()
mActivity.toast(R.string.exif_removed)
mPropertyView.findViewById<LinearLayout>(R.id.properties_holder).removeAllViews()
addProperties(path)
} catch (e: Exception) {
mActivity.showErrorToast(e)
}
}
}
private fun removeEXIFFromPaths(paths: List<String>) {
ConfirmationDialog(mActivity, "", R.string.remove_exif_confirmation) {
try {
paths.filter { mActivity.isPathOnInternalStorage(it) && it.canModifyEXIF() }.forEach {
ExifInterface(it).removeValues()
}
mActivity.toast(R.string.exif_removed)
} catch (e: Exception) {
mActivity.showErrorToast(e)
}
}
}
private fun isSameParent(fileDirItems: List<FileDirItem>): Boolean {
var parent = fileDirItems[0].getParentPath()
for (file in fileDirItems) {
val curParent = file.getParentPath()
if (curParent != parent) {
return false
}
parent = curParent
}
return true
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/dialogs/PropertiesDialog.kt | 3456217615 |
package com.simplemobiletools.commons.dialogs
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.RadioGroup
import androidx.appcompat.app.AlertDialog
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.activities.BaseSimpleActivity
import com.simplemobiletools.commons.databinding.DialogRadioGroupBinding
import com.simplemobiletools.commons.databinding.RadioButtonBinding
import com.simplemobiletools.commons.extensions.*
/**
* A dialog for choosing between internal, root, SD card (optional) storage
*
* @param activity has to be activity to avoid some Theme.AppCompat issues
* @param currPath current path to decide which storage should be preselected
* @param pickSingleOption if only one option like "Internal" is available, select it automatically
* @param callback an anonymous function
*
*/
class StoragePickerDialog(
val activity: BaseSimpleActivity, val currPath: String, val showRoot: Boolean, pickSingleOption: Boolean,
val callback: (pickedPath: String) -> Unit
) {
private val ID_INTERNAL = 1
private val ID_SD = 2
private val ID_OTG = 3
private val ID_ROOT = 4
private lateinit var radioGroup: RadioGroup
private var dialog: AlertDialog? = null
private var defaultSelectedId = 0
private val availableStorages = ArrayList<String>()
init {
availableStorages.add(activity.internalStoragePath)
when {
activity.hasExternalSDCard() -> availableStorages.add(activity.sdCardPath)
activity.hasOTGConnected() -> availableStorages.add("otg")
showRoot -> availableStorages.add("root")
}
if (pickSingleOption && availableStorages.size == 1) {
callback(availableStorages.first())
} else {
initDialog()
}
}
private fun initDialog() {
val inflater = LayoutInflater.from(activity)
val resources = activity.resources
val layoutParams = RadioGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
val view = DialogRadioGroupBinding.inflate(inflater, null, false)
radioGroup = view.dialogRadioGroup
val basePath = currPath.getBasePath(activity)
val internalButton = RadioButtonBinding.inflate(inflater, null, false).root
internalButton.apply {
id = ID_INTERNAL
text = resources.getString(R.string.internal)
isChecked = basePath == context.internalStoragePath
setOnClickListener { internalPicked() }
if (isChecked) {
defaultSelectedId = id
}
}
radioGroup.addView(internalButton, layoutParams)
if (activity.hasExternalSDCard()) {
val sdButton = RadioButtonBinding.inflate(inflater, null, false).root
sdButton.apply {
id = ID_SD
text = resources.getString(R.string.sd_card)
isChecked = basePath == context.sdCardPath
setOnClickListener { sdPicked() }
if (isChecked) {
defaultSelectedId = id
}
}
radioGroup.addView(sdButton, layoutParams)
}
if (activity.hasOTGConnected()) {
val otgButton = RadioButtonBinding.inflate(inflater, null, false).root
otgButton.apply {
id = ID_OTG
text = resources.getString(R.string.usb)
isChecked = basePath == context.otgPath
setOnClickListener { otgPicked() }
if (isChecked) {
defaultSelectedId = id
}
}
radioGroup.addView(otgButton, layoutParams)
}
// allow for example excluding the root folder at the gallery
if (showRoot) {
val rootButton = RadioButtonBinding.inflate(inflater, null, false).root
rootButton.apply {
id = ID_ROOT
text = resources.getString(R.string.root)
isChecked = basePath == "/"
setOnClickListener { rootPicked() }
if (isChecked) {
defaultSelectedId = id
}
}
radioGroup.addView(rootButton, layoutParams)
}
activity.getAlertDialogBuilder().apply {
activity.setupDialogStuff(view.root, this, R.string.select_storage) { alertDialog ->
dialog = alertDialog
}
}
}
private fun internalPicked() {
dialog?.dismiss()
callback(activity.internalStoragePath)
}
private fun sdPicked() {
dialog?.dismiss()
callback(activity.sdCardPath)
}
private fun otgPicked() {
activity.handleOTGPermission {
if (it) {
callback(activity.otgPath)
dialog?.dismiss()
} else {
radioGroup.check(defaultSelectedId)
}
}
}
private fun rootPicked() {
dialog?.dismiss()
callback("/")
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/dialogs/StoragePickerDialog.kt | 3280212474 |
package com.simplemobiletools.commons.dialogs
import android.app.Activity
import androidx.appcompat.app.AlertDialog
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.DialogProperties
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.compose.alert_dialog.*
import com.simplemobiletools.commons.compose.extensions.MyDevices
import com.simplemobiletools.commons.compose.theme.AppThemeSurface
import com.simplemobiletools.commons.databinding.DialogMessageBinding
import com.simplemobiletools.commons.extensions.getAlertDialogBuilder
import com.simplemobiletools.commons.extensions.setupDialogStuff
// similar fo ConfirmationDialog, but has a callback for negative button too
class ConfirmationAdvancedDialog(
activity: Activity, message: String = "", messageId: Int = R.string.proceed_with_deletion, positive: Int = R.string.yes,
negative: Int = R.string.no, val cancelOnTouchOutside: Boolean = true, val callback: (result: Boolean) -> Unit
) {
private var dialog: AlertDialog? = null
init {
val view = DialogMessageBinding.inflate(activity.layoutInflater, null, false)
view.message.text = message.ifEmpty { activity.resources.getString(messageId) }
val builder = activity.getAlertDialogBuilder()
.setPositiveButton(positive) { _, _ -> positivePressed() }
if (negative != 0) {
builder.setNegativeButton(negative) { _, _ -> negativePressed() }
}
if (!cancelOnTouchOutside) {
builder.setOnCancelListener { negativePressed() }
}
builder.apply {
activity.setupDialogStuff(view.root, this, cancelOnTouchOutside = cancelOnTouchOutside) { alertDialog ->
dialog = alertDialog
}
}
}
private fun positivePressed() {
dialog?.dismiss()
callback(true)
}
private fun negativePressed() {
dialog?.dismiss()
callback(false)
}
}
@Composable
fun ConfirmationAdvancedAlertDialog(
alertDialogState: AlertDialogState,
modifier: Modifier = Modifier,
message: String = "",
messageId: Int? = R.string.proceed_with_deletion,
positive: Int? = R.string.yes,
negative: Int? = R.string.no,
cancelOnTouchOutside: Boolean = true,
callback: (result: Boolean) -> Unit
) {
androidx.compose.material3.AlertDialog(
containerColor = dialogContainerColor,
modifier = modifier
.dialogBorder,
properties = DialogProperties(dismissOnClickOutside = cancelOnTouchOutside),
onDismissRequest = {
alertDialogState.hide()
callback(false)
},
shape = dialogShape,
tonalElevation = dialogElevation,
dismissButton = {
if (negative != null) {
TextButton(onClick = {
alertDialogState.hide()
callback(false)
}) {
Text(text = stringResource(id = negative))
}
}
},
confirmButton = {
if (positive != null) {
TextButton(onClick = {
alertDialogState.hide()
callback(true)
}) {
Text(text = stringResource(id = positive))
}
}
},
text = {
Text(
modifier = Modifier.fillMaxWidth(),
text = message.ifEmpty { messageId?.let { stringResource(id = it) }.orEmpty() },
fontSize = 16.sp,
color = dialogTextColor,
)
}
)
}
@Composable
@MyDevices
private fun ConfirmationAdvancedAlertDialogPreview() {
AppThemeSurface {
ConfirmationAdvancedAlertDialog(
alertDialogState = rememberAlertDialogState()
) {}
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/dialogs/ConfirmationAdvancedDialog.kt | 2898977574 |
package com.simplemobiletools.commons.dialogs
import androidx.appcompat.app.AlertDialog
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Visibility
import androidx.compose.material.icons.filled.VisibilityOff
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.unit.sp
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.activities.BaseSimpleActivity
import com.simplemobiletools.commons.compose.alert_dialog.*
import com.simplemobiletools.commons.compose.extensions.MyDevices
import com.simplemobiletools.commons.compose.extensions.andThen
import com.simplemobiletools.commons.compose.theme.AppThemeSurface
import com.simplemobiletools.commons.databinding.DialogEnterPasswordBinding
import com.simplemobiletools.commons.extensions.*
class EnterPasswordDialog(
val activity: BaseSimpleActivity,
private val callback: (password: String) -> Unit,
private val cancelCallback: () -> Unit
) {
private var dialog: AlertDialog? = null
private val view: DialogEnterPasswordBinding = DialogEnterPasswordBinding.inflate(activity.layoutInflater, null, false)
init {
activity.getAlertDialogBuilder()
.setPositiveButton(R.string.ok, null)
.setNegativeButton(R.string.cancel, null)
.apply {
activity.setupDialogStuff(view.root, this, R.string.enter_password) { alertDialog ->
dialog = alertDialog
alertDialog.showKeyboard(view.password)
alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener {
val password = view.password.value
if (password.isEmpty()) {
activity.toast(R.string.empty_password)
return@setOnClickListener
}
callback(password)
}
alertDialog.setOnDismissListener {
cancelCallback()
}
}
}
}
fun dismiss(notify: Boolean = true) {
if (!notify) {
dialog?.setOnDismissListener(null)
}
dialog?.dismiss()
}
fun clearPassword() {
view.password.text?.clear()
}
}
@Composable
fun EnterPasswordAlertDialog(
alertDialogState: AlertDialogState,
modifier: Modifier = Modifier,
callback: (password: String) -> Unit,
cancelCallback: () -> Unit
) {
val localContext = LocalContext.current
val focusRequester = remember { FocusRequester() }
var password by remember { mutableStateOf("") }
var passwordVisible by remember { mutableStateOf(false) }
val visualTransformation by remember {
derivedStateOf {
if (passwordVisible) VisualTransformation.None else PasswordVisualTransformation()
}
}
AlertDialog(
modifier = modifier.dialogBorder,
shape = dialogShape,
containerColor = dialogContainerColor,
tonalElevation = dialogElevation,
onDismissRequest = alertDialogState::hide andThen cancelCallback,
confirmButton = {
TextButton(
onClick = {
if (password.isEmpty()) {
localContext.toast(R.string.empty_password)
} else {
alertDialogState.hide()
callback(password)
}
}
) {
Text(text = stringResource(id = R.string.ok))
}
},
dismissButton = {
TextButton(
onClick = alertDialogState::hide
) {
Text(text = stringResource(id = R.string.cancel))
}
},
title = {
Text(
text = stringResource(id = R.string.enter_password),
color = dialogTextColor,
fontSize = 21.sp,
fontWeight = FontWeight.Bold,
)
},
text = {
OutlinedTextField(
visualTransformation = visualTransformation,
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),
trailingIcon = {
val image = passwordImageVector(passwordVisible)
IconButton(onClick = { passwordVisible = !passwordVisible }) {
Icon(imageVector = image, null)
}
},
modifier = Modifier
.fillMaxWidth()
.focusRequester(focusRequester),
value = password,
onValueChange = {
password = it
},
label = {
Text(text = stringResource(id = R.string.password))
},
singleLine = true
)
}
)
ShowKeyboardWhenDialogIsOpenedAndRequestFocus(focusRequester = focusRequester)
}
private fun passwordImageVector(passwordVisible: Boolean) = if (passwordVisible) {
Icons.Filled.Visibility
} else {
Icons.Filled.VisibilityOff
}
@MyDevices
@Composable
private fun EnterPasswordAlertDialogPreview() {
AppThemeSurface {
EnterPasswordAlertDialog(rememberAlertDialogState(), callback = {}, cancelCallback = {})
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/dialogs/EnterPasswordDialog.kt | 1051114410 |
package com.simplemobiletools.commons.dialogs
import android.app.Activity
import android.view.LayoutInflater
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.DialogProperties
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.compose.alert_dialog.*
import com.simplemobiletools.commons.compose.extensions.MyDevices
import com.simplemobiletools.commons.compose.settings.SettingsHorizontalDivider
import com.simplemobiletools.commons.compose.theme.AppThemeSurface
import com.simplemobiletools.commons.databinding.DialogWhatsNewBinding
import com.simplemobiletools.commons.extensions.getAlertDialogBuilder
import com.simplemobiletools.commons.extensions.setupDialogStuff
import com.simplemobiletools.commons.models.Release
import kotlinx.collections.immutable.ImmutableList
import kotlinx.collections.immutable.toImmutableList
class WhatsNewDialog(val activity: Activity, val releases: List<Release>) {
init {
val view = DialogWhatsNewBinding.inflate(LayoutInflater.from(activity), null, false)
view.whatsNewContent.text = getNewReleases()
activity.getAlertDialogBuilder()
.setPositiveButton(R.string.ok, null)
.apply {
activity.setupDialogStuff(view.root, this, R.string.whats_new, cancelOnTouchOutside = false)
}
}
private fun getNewReleases(): String {
val sb = StringBuilder()
releases.forEach {
val parts = activity.getString(it.textId).split("\n").map(String::trim)
parts.forEach {
sb.append("- $it\n")
}
}
return sb.toString()
}
}
@Composable
fun WhatsNewAlertDialog(
alertDialogState: AlertDialogState,
modifier: Modifier = Modifier,
releases: ImmutableList<Release>
) {
AlertDialog(
onDismissRequest = {},
confirmButton = {
TextButton(onClick = {
alertDialogState.hide()
}) {
Text(text = stringResource(id = R.string.ok))
}
},
properties = DialogProperties(dismissOnBackPress = false, dismissOnClickOutside = false),
containerColor = dialogContainerColor,
shape = dialogShape,
tonalElevation = dialogElevation,
modifier = modifier.dialogBorder,
title = {
Text(
text = stringResource(id = R.string.whats_new),
color = dialogTextColor,
fontSize = 21.sp,
fontWeight = FontWeight.Bold,
)
},
text = {
Column(
modifier = Modifier
.fillMaxWidth()
.verticalScroll(rememberScrollState())
) {
Text(text = getNewReleases(releases), color = dialogTextColor)
SettingsHorizontalDivider()
Text(
text = stringResource(id = R.string.whats_new_disclaimer),
color = dialogTextColor.copy(alpha = 0.7f),
fontSize = 12.sp
)
}
}
)
}
@Composable
private fun getNewReleases(releases: ImmutableList<Release>): String {
val sb = StringBuilder()
releases.forEach { release ->
val parts = stringResource(release.textId).split("\n").map(String::trim)
parts.forEach {
sb.append("- $it\n")
}
}
return sb.toString()
}
@MyDevices
@Composable
private fun WhatsNewAlertDialogPreview() {
AppThemeSurface {
WhatsNewAlertDialog(
alertDialogState = rememberAlertDialogState(), releases =
listOf(
Release(14, R.string.temporarily_show_excluded),
Release(3, R.string.temporarily_show_hidden)
).toImmutableList()
)
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/dialogs/WhatsNewDialog.kt | 3147315187 |
package com.simplemobiletools.commons.dialogs
import android.view.animation.AnimationUtils
import androidx.compose.animation.core.*
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.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Call
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.draw.scale
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.activities.BaseSimpleActivity
import com.simplemobiletools.commons.compose.alert_dialog.*
import com.simplemobiletools.commons.compose.extensions.MyDevices
import com.simplemobiletools.commons.compose.theme.AppThemeSurface
import com.simplemobiletools.commons.databinding.DialogCallConfirmationBinding
import com.simplemobiletools.commons.extensions.applyColorFilter
import com.simplemobiletools.commons.extensions.getAlertDialogBuilder
import com.simplemobiletools.commons.extensions.getProperTextColor
import com.simplemobiletools.commons.extensions.setupDialogStuff
class CallConfirmationDialog(val activity: BaseSimpleActivity, val callee: String, private val callback: () -> Unit) {
private var view = DialogCallConfirmationBinding.inflate(activity.layoutInflater, null, false)
init {
view.callConfirmPhone.applyColorFilter(activity.getProperTextColor())
activity.getAlertDialogBuilder()
.setNegativeButton(R.string.cancel, null)
.apply {
val title = String.format(activity.getString(R.string.confirm_calling_person), callee)
activity.setupDialogStuff(view.root, this, titleText = title) { alertDialog ->
view.callConfirmPhone.apply {
startAnimation(AnimationUtils.loadAnimation(activity, R.anim.shake_pulse_animation))
setOnClickListener {
callback.invoke()
alertDialog.dismiss()
}
}
}
}
}
}
@Composable
fun CallConfirmationAlertDialog(
alertDialogState: AlertDialogState,
callee: String,
modifier: Modifier = Modifier,
callback: () -> Unit
) {
androidx.compose.material3.AlertDialog(
containerColor = dialogContainerColor,
modifier = modifier
.dialogBorder,
onDismissRequest = {
alertDialogState.hide()
callback()
},
shape = dialogShape,
tonalElevation = dialogElevation,
confirmButton = {
TextButton(onClick = {
alertDialogState.hide()
callback()
}) {
Text(text = stringResource(id = R.string.cancel))
}
},
title = {
val title = String.format(stringResource(R.string.confirm_calling_person, callee))
Text(
text = title,
color = dialogTextColor,
fontSize = 21.sp,
fontWeight = FontWeight.Bold,
)
},
text = {
val scale by rememberInfiniteTransition("infiniteTransition").animateFloat(
initialValue = 1f, targetValue = 1.2f, animationSpec = infiniteRepeatable(
animation = tween(500),
repeatMode = RepeatMode.Reverse,
initialStartOffset = StartOffset(1000)
), label = "scale anim"
)
val rotate by rememberInfiniteTransition("rotate").animateFloat(
initialValue = -5f, targetValue = 5f, animationSpec = infiniteRepeatable(
animation = tween(200),
repeatMode = RepeatMode.Reverse
), label = "rotate anim"
)
Box(modifier = Modifier.fillMaxWidth(), contentAlignment = Alignment.Center) {
Box(
modifier = Modifier
.size(64.dp)
.clip(RoundedCornerShape(50))
.clickable {
alertDialogState.hide()
callback()
}
.padding(16.dp)
) {
Image(
Icons.Filled.Call,
contentDescription = null,
colorFilter = ColorFilter.tint(dialogTextColor),
modifier = Modifier
.matchParentSize()
.scale(scale)
.rotate(rotate),
)
}
}
}
)
}
@Composable
@MyDevices
private fun CallConfirmationAlertDialogPreview() {
AppThemeSurface {
CallConfirmationAlertDialog(
alertDialogState = rememberAlertDialogState(),
callee = "Simple Mobile Tools"
) {}
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/dialogs/CallConfirmationDialog.kt | 780696461 |
package com.simplemobiletools.commons.dialogs
import androidx.appcompat.app.AlertDialog
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.activities.BaseSimpleActivity
import com.simplemobiletools.commons.databinding.DialogRenameItemBinding
import com.simplemobiletools.commons.extensions.*
class RenameItemDialog(val activity: BaseSimpleActivity, val path: String, val callback: (newPath: String) -> Unit) {
init {
var ignoreClicks = false
val fullName = path.getFilenameFromPath()
val dotAt = fullName.lastIndexOf(".")
var name = fullName
val view = DialogRenameItemBinding.inflate(activity.layoutInflater, null, false).apply {
if (dotAt > 0 && !activity.getIsPathDirectory(path)) {
name = fullName.substring(0, dotAt)
val extension = fullName.substring(dotAt + 1)
renameItemExtension.setText(extension)
} else {
renameItemExtensionHint.beGone()
}
renameItemName.setText(name)
}
activity.getAlertDialogBuilder()
.setPositiveButton(R.string.ok, null)
.setNegativeButton(R.string.cancel, null)
.apply {
activity.setupDialogStuff(view.root, this, R.string.rename) { alertDialog ->
alertDialog.showKeyboard(view.renameItemName)
alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener {
if (ignoreClicks) {
return@setOnClickListener
}
var newName = view.renameItemName.value
val newExtension = view.renameItemExtension.value
if (newName.isEmpty()) {
activity.toast(R.string.empty_name)
return@setOnClickListener
}
if (!newName.isAValidFilename()) {
activity.toast(R.string.invalid_name)
return@setOnClickListener
}
val updatedPaths = ArrayList<String>()
updatedPaths.add(path)
if (!newExtension.isEmpty()) {
newName += ".$newExtension"
}
if (!activity.getDoesFilePathExist(path)) {
activity.toast(String.format(activity.getString(R.string.source_file_doesnt_exist), path))
return@setOnClickListener
}
val newPath = "${path.getParentPath()}/$newName"
if (path == newPath) {
activity.toast(R.string.name_taken)
return@setOnClickListener
}
if (!path.equals(newPath, ignoreCase = true) && activity.getDoesFilePathExist(newPath)) {
activity.toast(R.string.name_taken)
return@setOnClickListener
}
updatedPaths.add(newPath)
ignoreClicks = true
activity.renameFile(path, newPath, false) { success, _ ->
ignoreClicks = false
if (success) {
callback(newPath)
alertDialog.dismiss()
}
}
}
}
}
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/dialogs/RenameItemDialog.kt | 3723199985 |
package com.simplemobiletools.commons.dialogs
import android.content.Context
import android.view.WindowManager
import android.widget.FrameLayout
import androidx.annotation.ColorInt
import androidx.appcompat.app.AlertDialog
import androidx.compose.foundation.layout.*
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.viewinterop.AndroidViewBinding
import androidx.compose.ui.window.DialogProperties
import androidx.compose.ui.window.DialogWindowProvider
import androidx.core.content.ContextCompat
import androidx.core.view.updateLayoutParams
import com.google.android.material.appbar.MaterialToolbar
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.activities.BaseSimpleActivity
import com.simplemobiletools.commons.compose.alert_dialog.AlertDialogState
import com.simplemobiletools.commons.compose.alert_dialog.DialogSurface
import com.simplemobiletools.commons.compose.alert_dialog.dialogTextColor
import com.simplemobiletools.commons.compose.alert_dialog.rememberAlertDialogState
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.databinding.DialogLineColorPickerBinding
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.interfaces.LineColorPickerListener
class LineColorPickerDialog(
val activity: BaseSimpleActivity, val color: Int, val isPrimaryColorPicker: Boolean, val primaryColors: Int = R.array.md_primary_colors,
val appIconIDs: ArrayList<Int>? = null, val toolbar: MaterialToolbar? = null, val callback: (wasPositivePressed: Boolean, color: Int) -> Unit
) {
private val PRIMARY_COLORS_COUNT = 19
private val DEFAULT_PRIMARY_COLOR_INDEX = 14
private val DEFAULT_SECONDARY_COLOR_INDEX = 6
private val DEFAULT_COLOR_VALUE = activity.resources.getColor(R.color.color_primary)
private var wasDimmedBackgroundRemoved = false
private var dialog: AlertDialog? = null
private var view = DialogLineColorPickerBinding.inflate(activity.layoutInflater, null, false)
init {
view.apply {
hexCode.text = color.toHex()
hexCode.setOnLongClickListener {
activity.copyToClipboard(hexCode.value.substring(1))
true
}
lineColorPickerIcon.beGoneIf(isPrimaryColorPicker)
val indexes = getColorIndexes(color)
val primaryColorIndex = indexes.first
primaryColorChanged(primaryColorIndex)
primaryLineColorPicker.updateColors(getColors(primaryColors), primaryColorIndex)
primaryLineColorPicker.listener = LineColorPickerListener { index, color ->
val secondaryColors = getColorsForIndex(index)
secondaryLineColorPicker.updateColors(secondaryColors)
val newColor = if (isPrimaryColorPicker) secondaryLineColorPicker.getCurrentColor() else color
colorUpdated(newColor)
if (!isPrimaryColorPicker) {
primaryColorChanged(index)
}
}
secondaryLineColorPicker.beVisibleIf(isPrimaryColorPicker)
secondaryLineColorPicker.updateColors(getColorsForIndex(primaryColorIndex), indexes.second)
secondaryLineColorPicker.listener = LineColorPickerListener { _, color -> colorUpdated(color) }
}
activity.getAlertDialogBuilder()
.setPositiveButton(R.string.ok) { dialog, which -> dialogConfirmed() }
.setNegativeButton(R.string.cancel) { dialog, which -> dialogDismissed() }
.setOnCancelListener { dialogDismissed() }
.apply {
activity.setupDialogStuff(view.root, this) { alertDialog ->
dialog = alertDialog
}
}
}
fun getSpecificColor() = view.secondaryLineColorPicker.getCurrentColor()
private fun colorUpdated(color: Int) {
view.hexCode.text = color.toHex()
if (isPrimaryColorPicker) {
if (toolbar != null) {
activity.updateTopBarColors(toolbar, color)
}
if (!wasDimmedBackgroundRemoved) {
dialog?.window?.clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
wasDimmedBackgroundRemoved = true
}
}
}
private fun getColorIndexes(color: Int): Pair<Int, Int> {
if (color == DEFAULT_COLOR_VALUE) {
return getDefaultColorPair()
}
for (i in 0 until PRIMARY_COLORS_COUNT) {
getColorsForIndex(i).indexOfFirst { color == it }.apply {
if (this != -1) {
return Pair(i, this)
}
}
}
return getDefaultColorPair()
}
private fun primaryColorChanged(index: Int) {
view.lineColorPickerIcon.setImageResource(appIconIDs?.getOrNull(index) ?: 0)
}
private fun getDefaultColorPair() = Pair(DEFAULT_PRIMARY_COLOR_INDEX, DEFAULT_SECONDARY_COLOR_INDEX)
private fun dialogDismissed() {
callback(false, 0)
}
private fun dialogConfirmed() {
val targetView = if (isPrimaryColorPicker) view.secondaryLineColorPicker else view.primaryLineColorPicker
val color = targetView.getCurrentColor()
callback(true, color)
}
private fun getColorsForIndex(index: Int) = when (index) {
0 -> getColors(R.array.md_reds)
1 -> getColors(R.array.md_pinks)
2 -> getColors(R.array.md_purples)
3 -> getColors(R.array.md_deep_purples)
4 -> getColors(R.array.md_indigos)
5 -> getColors(R.array.md_blues)
6 -> getColors(R.array.md_light_blues)
7 -> getColors(R.array.md_cyans)
8 -> getColors(R.array.md_teals)
9 -> getColors(R.array.md_greens)
10 -> getColors(R.array.md_light_greens)
11 -> getColors(R.array.md_limes)
12 -> getColors(R.array.md_yellows)
13 -> getColors(R.array.md_ambers)
14 -> getColors(R.array.md_oranges)
15 -> getColors(R.array.md_deep_oranges)
16 -> getColors(R.array.md_browns)
17 -> getColors(R.array.md_blue_greys)
18 -> getColors(R.array.md_greys)
else -> throw RuntimeException("Invalid color id $index")
}
private fun getColors(id: Int) = activity.resources.getIntArray(id).toCollection(ArrayList())
}
@Composable
fun LineColorPickerAlertDialog(
alertDialogState: AlertDialogState,
@ColorInt color: Int,
isPrimaryColorPicker: Boolean,
modifier: Modifier = Modifier,
primaryColors: Int = R.array.md_primary_colors,
appIconIDs: ArrayList<Int>? = null,
onActiveColorChange: (color: Int) -> Unit,
onButtonPressed: (wasPositivePressed: Boolean, color: Int) -> Unit
) {
val view = LocalView.current
val context = LocalContext.current
var wasDimmedBackgroundRemoved by remember { mutableStateOf(false) }
val defaultColor = remember {
ContextCompat.getColor(context, R.color.color_primary)
}
AlertDialog(
modifier = modifier,
onDismissRequest = alertDialogState::hide,
properties = DialogProperties(usePlatformDefaultWidth = false)
) {
DialogSurface {
Column(
Modifier
.fillMaxWidth(0.95f)
.padding(SimpleTheme.dimens.padding.extraLarge)
) {
val dialogTextColor = dialogTextColor
var dialogLineColorPickerBinding by remember { mutableStateOf<DialogLineColorPickerBinding?>(null) }
AndroidViewBinding(
DialogLineColorPickerBinding::inflate, onRelease = {
dialogLineColorPickerBinding = null
}, modifier = Modifier
.fillMaxWidth()
.wrapContentHeight()
) {
root.updateLayoutParams<FrameLayout.LayoutParams> {
height = FrameLayout.LayoutParams.WRAP_CONTENT
}
dialogLineColorPickerBinding = this
fun colorUpdated(color: Int) {
hexCode.text = color.toHex()
onActiveColorChange(color)
if (isPrimaryColorPicker) {
if (!wasDimmedBackgroundRemoved) {
(view.parent as? DialogWindowProvider)?.window?.setDimAmount(0f)
wasDimmedBackgroundRemoved = true
}
}
}
hexCode.setTextColor(dialogTextColor.toArgb())
hexCode.text = color.toHex()
hexCode.setOnLongClickListener {
context.copyToClipboard(hexCode.value.substring(1))
true
}
lineColorPickerIcon.beGoneIf(isPrimaryColorPicker)
val indexes = context.getColorIndexes(color, defaultColor)
val primaryColorIndex = indexes.first
lineColorPickerIcon.setImageResource(appIconIDs?.getOrNull(primaryColorIndex) ?: 0)
primaryLineColorPicker.updateColors(context.getColors(primaryColors), primaryColorIndex)
primaryLineColorPicker.listener = LineColorPickerListener { index, color ->
val secondaryColors = context.getColorsForIndex(index)
secondaryLineColorPicker.updateColors(secondaryColors)
val newColor = if (isPrimaryColorPicker) secondaryLineColorPicker.getCurrentColor() else color
colorUpdated(newColor)
if (!isPrimaryColorPicker) {
lineColorPickerIcon.setImageResource(appIconIDs?.getOrNull(index) ?: 0)
}
}
secondaryLineColorPicker.beVisibleIf(isPrimaryColorPicker)
secondaryLineColorPicker.updateColors(context.getColorsForIndex(primaryColorIndex), indexes.second)
secondaryLineColorPicker.listener = LineColorPickerListener { _, color -> colorUpdated(color) }
}
Row(
Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.End
) {
TextButton(onClick = {
alertDialogState.hide()
onButtonPressed(false, 0)
}) {
Text(text = stringResource(id = R.string.cancel))
}
TextButton(onClick = {
if (dialogLineColorPickerBinding != null) {
val targetView =
if (isPrimaryColorPicker) dialogLineColorPickerBinding!!.secondaryLineColorPicker else dialogLineColorPickerBinding!!.primaryLineColorPicker
onButtonPressed(true, targetView.getCurrentColor())
}
alertDialogState.hide()
}) {
Text(text = stringResource(id = R.string.ok))
}
}
}
}
}
}
private const val PRIMARY_COLORS_COUNT = 19
private const val DEFAULT_PRIMARY_COLOR_INDEX = 14
private const val DEFAULT_SECONDARY_COLOR_INDEX = 6
private fun Context.getColorIndexes(color: Int, defaultColor: Int): Pair<Int, Int> {
if (color == defaultColor) {
return getDefaultColorPair()
}
for (i in 0 until PRIMARY_COLORS_COUNT) {
getColorsForIndex(i).indexOfFirst { color == it }.apply {
if (this != -1) {
return Pair(i, this)
}
}
}
return getDefaultColorPair()
}
private fun getDefaultColorPair() = Pair(DEFAULT_PRIMARY_COLOR_INDEX, DEFAULT_SECONDARY_COLOR_INDEX)
private fun Context.getColorsForIndex(index: Int) = when (index) {
0 -> getColors(R.array.md_reds)
1 -> getColors(R.array.md_pinks)
2 -> getColors(R.array.md_purples)
3 -> getColors(R.array.md_deep_purples)
4 -> getColors(R.array.md_indigos)
5 -> getColors(R.array.md_blues)
6 -> getColors(R.array.md_light_blues)
7 -> getColors(R.array.md_cyans)
8 -> getColors(R.array.md_teals)
9 -> getColors(R.array.md_greens)
10 -> getColors(R.array.md_light_greens)
11 -> getColors(R.array.md_limes)
12 -> getColors(R.array.md_yellows)
13 -> getColors(R.array.md_ambers)
14 -> getColors(R.array.md_oranges)
15 -> getColors(R.array.md_deep_oranges)
16 -> getColors(R.array.md_browns)
17 -> getColors(R.array.md_blue_greys)
18 -> getColors(R.array.md_greys)
else -> throw RuntimeException("Invalid color id $index")
}
private fun Context.getColors(id: Int) = resources.getIntArray(id).toCollection(ArrayList())
@Composable
@MyDevices
private fun LineColorPickerAlertDialogPreview() {
AppThemeSurface {
LineColorPickerAlertDialog(alertDialogState = rememberAlertDialogState(),
color = R.color.color_primary,
isPrimaryColorPicker = true,
onActiveColorChange = {}
) { _, _ -> }
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/dialogs/LineColorPickerDialog.kt | 3071154306 |
package com.simplemobiletools.commons.dialogs
import android.app.Activity
import androidx.appcompat.app.AlertDialog
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.DialogProperties
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.compose.alert_dialog.*
import com.simplemobiletools.commons.compose.extensions.MyDevices
import com.simplemobiletools.commons.compose.extensions.andThen
import com.simplemobiletools.commons.compose.theme.AppThemeSurface
import com.simplemobiletools.commons.compose.theme.SimpleTheme
import com.simplemobiletools.commons.databinding.DialogUpgradeToProBinding
import com.simplemobiletools.commons.extensions.getAlertDialogBuilder
import com.simplemobiletools.commons.extensions.launchUpgradeToProIntent
import com.simplemobiletools.commons.extensions.launchViewIntent
import com.simplemobiletools.commons.extensions.setupDialogStuff
class UpgradeToProDialog(val activity: Activity) {
init {
val view = DialogUpgradeToProBinding.inflate(activity.layoutInflater, null, false).apply {
upgradeToPro.text = activity.getString(R.string.upgrade_to_pro_long)
}
activity.getAlertDialogBuilder()
.setPositiveButton(R.string.upgrade) { _, _ -> upgradeApp() }
.setNeutralButton(R.string.more_info, null) // do not dismiss the dialog on pressing More Info
.setNegativeButton(R.string.later, null)
.apply {
activity.setupDialogStuff(view.root, this, R.string.upgrade_to_pro, cancelOnTouchOutside = false) { alertDialog ->
alertDialog.getButton(AlertDialog.BUTTON_NEUTRAL).setOnClickListener {
moreInfo()
}
}
}
}
private fun upgradeApp() {
activity.launchUpgradeToProIntent()
}
private fun moreInfo() {
activity.launchViewIntent("https://simplemobiletools.com/upgrade_to_pro")
}
}
@Composable
fun UpgradeToProAlertDialog(
alertDialogState: AlertDialogState,
modifier: Modifier = Modifier,
onMoreInfoClick: () -> Unit,
onUpgradeClick: () -> Unit
) {
AlertDialog(
onDismissRequest = {},
text = {
Text(
text = stringResource(id = R.string.upgrade_to_pro_long),
color = dialogTextColor,
fontSize = 16.sp,
)
},
title = {
Text(
text = stringResource(id = R.string.upgrade_to_pro),
color = dialogTextColor,
fontSize = 21.sp,
fontWeight = FontWeight.Bold,
)
},
tonalElevation = dialogElevation,
shape = dialogShape,
containerColor = dialogContainerColor,
confirmButton = {
Row(
Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.End
) {
TextButton(
onClick = onMoreInfoClick, // do not dismiss the dialog on pressing More Info
modifier = Modifier.weight(0.2f)
) {
Text(text = stringResource(id = R.string.more_info))
}
TextButton(
onClick = alertDialogState::hide,
modifier = Modifier.padding(horizontal = SimpleTheme.dimens.padding.medium)
) {
Text(text = stringResource(id = R.string.later))
}
TextButton(
onClick = onUpgradeClick andThen alertDialogState::hide,
) {
Text(text = stringResource(id = R.string.upgrade))
}
}
},
modifier = modifier.dialogBorder,
properties = DialogProperties(dismissOnBackPress = false, dismissOnClickOutside = false)
)
}
@MyDevices
@Composable
private fun UpgradeToProAlertDialogPreview() {
AppThemeSurface {
UpgradeToProAlertDialog(
alertDialogState = rememberAlertDialogState(),
onMoreInfoClick = {},
onUpgradeClick = {},
)
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/dialogs/UpgradeToProDialog.kt | 4261768164 |
package com.simplemobiletools.commons.dialogs
import android.app.Activity
import android.view.View
import android.view.ViewGroup
import android.widget.RadioButton
import android.widget.RadioGroup
import androidx.appcompat.app.AlertDialog
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
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.alert_dialog.AlertDialogState
import com.simplemobiletools.commons.compose.alert_dialog.DialogSurface
import com.simplemobiletools.commons.compose.alert_dialog.dialogTextColor
import com.simplemobiletools.commons.compose.alert_dialog.rememberAlertDialogState
import com.simplemobiletools.commons.compose.components.RadioGroupDialogComponent
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
import com.simplemobiletools.commons.databinding.DialogRadioGroupBinding
import com.simplemobiletools.commons.extensions.getAlertDialogBuilder
import com.simplemobiletools.commons.extensions.onGlobalLayout
import com.simplemobiletools.commons.extensions.setupDialogStuff
import com.simplemobiletools.commons.models.RadioItem
import kotlinx.collections.immutable.ImmutableList
import kotlinx.collections.immutable.toImmutableList
class RadioGroupDialog(
val activity: Activity, val items: ArrayList<RadioItem>, val checkedItemId: Int = -1, val titleId: Int = 0,
showOKButton: Boolean = false, val cancelCallback: (() -> Unit)? = null, val callback: (newValue: Any) -> Unit
) {
private var dialog: AlertDialog? = null
private var wasInit = false
private var selectedItemId = -1
init {
val view = DialogRadioGroupBinding.inflate(activity.layoutInflater, null, false)
view.dialogRadioGroup.apply {
for (i in 0 until items.size) {
val radioButton = (activity.layoutInflater.inflate(R.layout.radio_button, null) as RadioButton).apply {
text = items[i].title
isChecked = items[i].id == checkedItemId
id = i
setOnClickListener { itemSelected(i) }
}
if (items[i].id == checkedItemId) {
selectedItemId = i
}
addView(radioButton, RadioGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT))
}
}
val builder = activity.getAlertDialogBuilder()
.setOnCancelListener { cancelCallback?.invoke() }
if (selectedItemId != -1 && showOKButton) {
builder.setPositiveButton(R.string.ok) { dialog, which -> itemSelected(selectedItemId) }
}
builder.apply {
activity.setupDialogStuff(view.root, this, titleId) { alertDialog ->
dialog = alertDialog
}
}
if (selectedItemId != -1) {
view.dialogRadioHolder.apply {
onGlobalLayout {
scrollY = view.dialogRadioGroup.findViewById<View>(selectedItemId).bottom - height
}
}
}
wasInit = true
}
private fun itemSelected(checkedId: Int) {
if (wasInit) {
callback(items[checkedId].value)
dialog?.dismiss()
}
}
}
@Composable
fun RadioGroupAlertDialog(
alertDialogState: AlertDialogState,
items: ImmutableList<RadioItem>,
modifier: Modifier = Modifier,
selectedItemId: Int = -1,
titleId: Int = 0,
showOKButton: Boolean = false,
cancelCallback: (() -> Unit)? = null,
callback: (newValue: Any) -> Unit
) {
val groupTitles by remember {
derivedStateOf { items.map { it.title } }
}
val (selected, setSelected) = remember { mutableStateOf(items.firstOrNull { it.id == selectedItemId }?.title) }
val shouldShowOkButton = selectedItemId != -1 && showOKButton
AlertDialog(
onDismissRequest = {
cancelCallback?.invoke()
alertDialogState.hide()
},
) {
DialogSurface {
Box {
Column(
modifier = modifier
.padding(bottom = if (shouldShowOkButton) 64.dp else 18.dp)
.verticalScroll(rememberScrollState())
) {
if (titleId != 0) {
Text(
text = stringResource(id = titleId),
modifier = Modifier
.fillMaxWidth()
.padding(top = 24.dp, bottom = SimpleTheme.dimens.padding.medium)
.padding(horizontal = 24.dp),
color = dialogTextColor,
fontSize = 21.sp
)
}
RadioGroupDialogComponent(
items = groupTitles,
selected = selected,
setSelected = { selectedTitle ->
setSelected(selectedTitle)
callback(getSelectedValue(items, selectedTitle))
alertDialogState.hide()
},
modifier = Modifier.padding(
vertical = SimpleTheme.dimens.padding.extraLarge,
)
)
}
if (shouldShowOkButton) {
TextButton(
onClick = {
callback(getSelectedValue(items, selected))
alertDialogState.hide()
},
modifier = Modifier
.align(Alignment.BottomEnd)
.padding(top = SimpleTheme.dimens.padding.extraLarge, bottom = SimpleTheme.dimens.padding.extraLarge, end = SimpleTheme.dimens.padding.extraLarge)
) {
Text(text = stringResource(id = R.string.ok))
}
}
}
}
}
}
private fun getSelectedValue(
items: ImmutableList<RadioItem>,
selected: String?
) = items.first { it.title == selected }.value
@Composable
@MyDevices
private fun RadioGroupDialogAlertDialogPreview(@PreviewParameter(BooleanPreviewParameterProvider::class) showOKButton: Boolean) {
AppThemeSurface {
RadioGroupAlertDialog(
alertDialogState = rememberAlertDialogState(),
items = listOf(
RadioItem(1, "Test"),
RadioItem(2, "Test 2"),
RadioItem(3, "Test 3"),
).toImmutableList(),
selectedItemId = 1,
titleId = R.string.title,
showOKButton = showOKButton,
cancelCallback = {}
) {}
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/dialogs/RadioGroupDialog.kt | 3700790025 |
package com.simplemobiletools.commons.dialogs
import android.app.Activity
import android.content.res.Resources
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.LinearLayout
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.databinding.DialogPropertiesBinding
import com.simplemobiletools.commons.databinding.ItemPropertyBinding
import com.simplemobiletools.commons.extensions.copyToClipboard
import com.simplemobiletools.commons.extensions.getProperTextColor
import com.simplemobiletools.commons.extensions.showLocationOnMap
import com.simplemobiletools.commons.extensions.value
abstract class BasePropertiesDialog(activity: Activity) {
protected val mInflater: LayoutInflater
protected val mPropertyView: ViewGroup
protected val mResources: Resources
protected val mActivity: Activity = activity
protected val mDialogView: DialogPropertiesBinding
init {
mInflater = LayoutInflater.from(activity)
mResources = activity.resources
mDialogView = DialogPropertiesBinding.inflate(mInflater, null, false)
mPropertyView = mDialogView.propertiesHolder
}
protected fun addProperty(labelId: Int, value: String?, viewId: Int = 0) {
if (value == null) {
return
}
ItemPropertyBinding.inflate(mInflater, null, false).apply {
propertyValue.setTextColor(mActivity.getProperTextColor())
propertyLabel.setTextColor(mActivity.getProperTextColor())
propertyLabel.text = mResources.getString(labelId)
propertyValue.text = value
mPropertyView.findViewById<LinearLayout>(R.id.properties_holder).addView(root)
root.setOnLongClickListener {
mActivity.copyToClipboard(propertyValue.value)
true
}
if (labelId == R.string.gps_coordinates) {
root.setOnClickListener {
mActivity.showLocationOnMap(value)
}
}
if (viewId != 0) {
root.id = viewId
}
}
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/dialogs/BasePropertiesDialog.kt | 2440969259 |
@file:SuppressLint("ClickableViewAccessibility")
package com.simplemobiletools.commons.dialogs
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.graphics.Color
import android.view.MotionEvent
import android.view.View
import android.view.View.OnTouchListener
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.FrameLayout
import android.widget.ImageView
import androidx.annotation.ColorInt
import androidx.appcompat.app.AlertDialog
import androidx.compose.foundation.layout.*
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.viewinterop.AndroidViewBinding
import androidx.compose.ui.window.DialogProperties
import androidx.compose.ui.window.DialogWindowProvider
import androidx.core.view.children
import androidx.core.view.updateLayoutParams
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.compose.alert_dialog.AlertDialogState
import com.simplemobiletools.commons.compose.alert_dialog.DialogSurface
import com.simplemobiletools.commons.compose.alert_dialog.dialogBorder
import com.simplemobiletools.commons.compose.alert_dialog.rememberAlertDialogState
import com.simplemobiletools.commons.compose.extensions.MyDevices
import com.simplemobiletools.commons.compose.extensions.config
import com.simplemobiletools.commons.compose.theme.AppThemeSurface
import com.simplemobiletools.commons.compose.theme.SimpleTheme
import com.simplemobiletools.commons.databinding.DialogColorPickerBinding
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.isQPlus
import java.util.LinkedList
private const val RECENT_COLORS_NUMBER = 5
@JvmInline
private value class Hsv(val value: FloatArray) {
fun getColor() = Color.HSVToColor(value)
fun getHue() = value[0]
fun setHue(hue: Float) {
value[0] = hue
}
fun getSat() = value[1]
fun setSat(sat: Float) {
value[1] = sat
}
fun getVal() = value[2]
fun setVal(v: Float) {
value[2] = v
}
}
// forked from https://github.com/yukuku/ambilwarna
class ColorPickerDialog(
val activity: Activity,
color: Int,
val removeDimmedBackground: Boolean = false,
val addDefaultColorButton: Boolean = false,
val currentColorCallback: ((color: Int) -> Unit)? = null,
val callback: (wasPositivePressed: Boolean, color: Int) -> Unit
) {
private val baseConfig = activity.baseConfig
private val currentColorHsv = Hsv(FloatArray(3))
private val backgroundColor = baseConfig.backgroundColor
private var wasDimmedBackgroundRemoved = false
private var dialog: AlertDialog? = null
private val binding = DialogColorPickerBinding.inflate(activity.layoutInflater, null, false)
init {
Color.colorToHSV(color, currentColorHsv.value)
binding.init(
color = color,
backgroundColor = backgroundColor,
recentColors = baseConfig.colorPickerRecentColors,
hsv = currentColorHsv,
currentColorCallback = {
if (removeDimmedBackground && !wasDimmedBackgroundRemoved) {
dialog?.window?.clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
wasDimmedBackgroundRemoved = true
}
currentColorCallback?.invoke(it)
}
)
val textColor = activity.getProperTextColor()
val builder = activity.getAlertDialogBuilder()
.setPositiveButton(R.string.ok) { _, _ -> confirmNewColor() }
.setNegativeButton(R.string.cancel) { _, _ -> dialogDismissed() }
.setOnCancelListener { dialogDismissed() }
.apply {
if (addDefaultColorButton) {
setNeutralButton(R.string.default_color) { _, _ -> confirmDefaultColor() }
}
}
builder.apply {
activity.setupDialogStuff(binding.root, this) { alertDialog ->
dialog = alertDialog
binding.colorPickerArrow.applyColorFilter(textColor)
binding.colorPickerHexArrow.applyColorFilter(textColor)
binding.colorPickerHueCursor.applyColorFilter(textColor)
}
}
}
private fun dialogDismissed() {
callback(false, 0)
}
private fun confirmDefaultColor() {
callback(true, 0)
}
private fun confirmNewColor() {
val hexValue = binding.colorPickerNewHex.value
val newColor = if (hexValue.length == 6) {
Color.parseColor("#$hexValue")
} else {
currentColorHsv.getColor()
}
activity.addRecentColor(newColor)
callback(true, newColor)
}
}
@Composable
fun ColorPickerAlertDialog(
alertDialogState: AlertDialogState,
@ColorInt color: Int,
modifier: Modifier = Modifier,
removeDimmedBackground: Boolean = false,
addDefaultColorButton: Boolean = false,
onActiveColorChange: (color: Int) -> Unit,
onButtonPressed: (wasPositivePressed: Boolean, color: Int) -> Unit
) {
val view = LocalView.current
val context = LocalContext.current
var wasDimmedBackgroundRemoved by remember { mutableStateOf(false) }
AlertDialog(
modifier = modifier
.dialogBorder,
onDismissRequest = alertDialogState::hide,
properties = DialogProperties(usePlatformDefaultWidth = false)
) {
DialogSurface {
Column(
Modifier
.fillMaxWidth(0.95f)
.padding(SimpleTheme.dimens.padding.extraLarge)
) {
var dialogColorPickerBinding by remember { mutableStateOf<DialogColorPickerBinding?>(null) }
val currentColorHsv by remember { derivedStateOf { Hsv(FloatArray(3)).apply { Color.colorToHSV(color, this.value) } } }
AndroidViewBinding(
DialogColorPickerBinding::inflate,
onRelease = {
dialogColorPickerBinding = null
},
modifier = Modifier
.fillMaxWidth()
.wrapContentHeight(),
) {
root.updateLayoutParams<FrameLayout.LayoutParams> {
height = FrameLayout.LayoutParams.WRAP_CONTENT
}
dialogColorPickerBinding = this
init(
color = color,
backgroundColor = context.config.backgroundColor,
recentColors = context.config.colorPickerRecentColors,
hsv = currentColorHsv,
currentColorCallback = {
if (removeDimmedBackground) {
if (!wasDimmedBackgroundRemoved) {
(view.parent as? DialogWindowProvider)?.window?.setDimAmount(0f)
wasDimmedBackgroundRemoved = true
}
}
onActiveColorChange(it)
}
)
val textColor = context.getProperTextColor()
colorPickerArrow.applyColorFilter(textColor)
colorPickerHexArrow.applyColorFilter(textColor)
colorPickerHueCursor.applyColorFilter(textColor)
context.updateTextColors(root)
}
Row(
Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.End
) {
TextButton(onClick = {
alertDialogState.hide()
onButtonPressed(false, 0)
}) {
Text(text = stringResource(id = R.string.cancel))
}
if (addDefaultColorButton) {
TextButton(onClick = {
alertDialogState.hide()
onButtonPressed(true, 0)
}) {
Text(text = stringResource(id = R.string.default_color))
}
}
TextButton(onClick = {
alertDialogState.hide()
val hexValue = dialogColorPickerBinding?.colorPickerNewHex?.value
val newColor = if (hexValue?.length == 6) {
Color.parseColor("#$hexValue")
} else {
currentColorHsv.getColor()
}
context.addRecentColor(newColor)
onButtonPressed(true, newColor)
}) {
Text(text = stringResource(id = R.string.ok))
}
}
}
}
}
}
private fun DialogColorPickerBinding.init(
color: Int,
backgroundColor: Int,
recentColors: List<Int>,
hsv: Hsv,
currentColorCallback: ((color: Int) -> Unit)
) {
var isHueBeingDragged = false
if (isQPlus()) {
root.isForceDarkAllowed = false
}
colorPickerSquare.setHue(hsv.getHue())
colorPickerNewColor.setFillWithStroke(color, backgroundColor)
colorPickerOldColor.setFillWithStroke(color, backgroundColor)
val hexCode = getHexCode(color)
colorPickerOldHex.text = "#$hexCode"
colorPickerOldHex.setOnLongClickListener {
root.context.copyToClipboard(hexCode)
true
}
colorPickerNewHex.setText(hexCode)
setupRecentColors(backgroundColor, recentColors)
colorPickerHue.setOnTouchListener(OnTouchListener { v, event ->
if (event.action == MotionEvent.ACTION_DOWN) {
isHueBeingDragged = true
}
if (event.action == MotionEvent.ACTION_MOVE || event.action == MotionEvent.ACTION_DOWN || event.action == MotionEvent.ACTION_UP) {
var y = event.y
if (y < 0f)
y = 0f
if (y > colorPickerHue.measuredHeight) {
y = colorPickerHue.measuredHeight - 0.001f // to avoid jumping the cursor from bottom to top.
}
var hue = 360f - 360f / colorPickerHue.measuredHeight * y
if (hue == 360f)
hue = 0f
hsv.setHue(hue)
updateHue(hsv, backgroundColor, currentColorCallback)
colorPickerNewHex.setText(getHexCode(hsv.getColor()))
if (event.action == MotionEvent.ACTION_UP) {
isHueBeingDragged = false
}
return@OnTouchListener true
}
false
})
colorPickerSquare.setOnTouchListener(OnTouchListener { v, event ->
if (event.action == MotionEvent.ACTION_MOVE || event.action == MotionEvent.ACTION_DOWN || event.action == MotionEvent.ACTION_UP) {
var x = event.x
var y = event.y
if (x < 0f)
x = 0f
if (x > colorPickerSquare.measuredWidth)
x = colorPickerSquare.measuredWidth.toFloat()
if (y < 0f)
y = 0f
if (y > colorPickerSquare.measuredHeight)
y = colorPickerSquare.measuredHeight.toFloat()
hsv.setSat(1f / colorPickerSquare.measuredWidth * x)
hsv.setVal(1f - 1f / colorPickerSquare.measuredHeight * y)
moveColorPicker(hsv)
colorPickerNewColor.setFillWithStroke(hsv.getColor(), backgroundColor)
colorPickerNewHex.setText(getHexCode(hsv.getColor()))
return@OnTouchListener true
}
false
})
colorPickerNewHex.onTextChangeListener {
if (it.length == 6 && !isHueBeingDragged) {
try {
val newColor = Color.parseColor("#$it")
Color.colorToHSV(newColor, hsv.value)
updateHue(hsv, backgroundColor, currentColorCallback)
moveColorPicker(hsv)
} catch (ignored: Exception) {
}
}
}
root.onGlobalLayout {
moveHuePicker(hsv)
moveColorPicker(hsv)
}
}
private fun DialogColorPickerBinding.setupRecentColors(backgroundColor: Int, recentColors: List<Int>) {
if (recentColors.isNotEmpty()) {
this.recentColors.beVisible()
val childrenToRemove = this.recentColors.children.filter { it is ImageView }.toList()
childrenToRemove.forEach {
this.recentColors.removeView(it)
recentColorsFlow.removeView(it)
}
val squareSize = root.context.resources.getDimensionPixelSize(R.dimen.colorpicker_hue_width)
recentColors.take(RECENT_COLORS_NUMBER).forEach { recentColor ->
val recentColorView = ImageView(root.context)
recentColorView.id = View.generateViewId()
recentColorView.layoutParams = ViewGroup.LayoutParams(squareSize, squareSize)
recentColorView.setFillWithStroke(recentColor, backgroundColor)
recentColorView.setOnClickListener { colorPickerNewHex.setText(getHexCode(recentColor)) }
this.recentColors.addView(recentColorView)
recentColorsFlow.addView(recentColorView)
}
}
}
private fun DialogColorPickerBinding.updateHue(
hsv: Hsv,
backgroundColor: Int,
currentColorCallback: ((color: Int) -> Unit)
) {
colorPickerSquare.setHue(hsv.getHue())
moveHuePicker(hsv)
colorPickerNewColor.setFillWithStroke(hsv.getColor(), backgroundColor)
currentColorCallback.invoke(hsv.getColor())
}
private fun DialogColorPickerBinding.moveHuePicker(hsv: Hsv) {
var y = colorPickerHue.measuredHeight - hsv.getHue() * colorPickerHue.measuredHeight / 360f
if (y == colorPickerHue.measuredHeight.toFloat())
y = 0f
colorPickerHueCursor.x = (colorPickerHue.left - colorPickerHueCursor.width).toFloat()
colorPickerHueCursor.y = colorPickerHue.top + y - colorPickerHueCursor.height / 2
}
private fun DialogColorPickerBinding.moveColorPicker(hsv: Hsv) {
val x = hsv.getSat() * colorPickerSquare.measuredWidth
val y = (1f - hsv.getVal()) * colorPickerSquare.measuredHeight
colorPickerCursor.x = colorPickerSquare.left + x - colorPickerCursor.width / 2
colorPickerCursor.y = colorPickerSquare.top + y - colorPickerCursor.height / 2
}
private fun getHexCode(color: Int) = color.toHex().substring(1)
private fun Context.addRecentColor(color: Int) {
var recentColors = baseConfig.colorPickerRecentColors
recentColors.remove(color)
if (recentColors.size >= RECENT_COLORS_NUMBER) {
val numberOfColorsToDrop = recentColors.size - RECENT_COLORS_NUMBER + 1
recentColors = LinkedList(recentColors.dropLast(numberOfColorsToDrop))
}
recentColors.addFirst(color)
baseConfig.colorPickerRecentColors = recentColors
}
@Composable
@MyDevices
private fun ColorPickerAlertDialogPreview() {
AppThemeSurface {
ColorPickerAlertDialog(
alertDialogState = rememberAlertDialogState(),
color = colorResource(id = R.color.color_primary).toArgb(),
onActiveColorChange = {}
) { _, _ -> }
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/dialogs/ColorPickerDialog.kt | 2121056909 |
package com.simplemobiletools.commons.dialogs
import androidx.appcompat.app.AlertDialog
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.activities.BaseSimpleActivity
import com.simplemobiletools.commons.databinding.DialogRenameItemsBinding
import com.simplemobiletools.commons.extensions.*
// used at renaming folders
class RenameItemsDialog(val activity: BaseSimpleActivity, val paths: ArrayList<String>, val callback: () -> Unit) {
init {
var ignoreClicks = false
val view = DialogRenameItemsBinding.inflate(activity.layoutInflater,null, false)
activity.getAlertDialogBuilder()
.setPositiveButton(R.string.ok, null)
.setNegativeButton(R.string.cancel, null)
.apply {
activity.setupDialogStuff(view.root, this, R.string.rename) { alertDialog ->
alertDialog.showKeyboard(view.renameItemsValue)
alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener {
if (ignoreClicks) {
return@setOnClickListener
}
val valueToAdd = view.renameItemsValue.text.toString()
val append = view.renameItemsRadioGroup.checkedRadioButtonId == view.renameItemsRadioAppend.id
if (valueToAdd.isEmpty()) {
callback()
alertDialog.dismiss()
return@setOnClickListener
}
if (!valueToAdd.isAValidFilename()) {
activity.toast(R.string.invalid_name)
return@setOnClickListener
}
val validPaths = paths.filter { activity.getDoesFilePathExist(it) }
val sdFilePath = validPaths.firstOrNull { activity.isPathOnSD(it) } ?: validPaths.firstOrNull()
if (sdFilePath == null) {
activity.toast(R.string.unknown_error_occurred)
alertDialog.dismiss()
return@setOnClickListener
}
activity.handleSAFDialog(sdFilePath) {
if (!it) {
return@handleSAFDialog
}
ignoreClicks = true
var pathsCnt = validPaths.size
for (path in validPaths) {
val fullName = path.getFilenameFromPath()
var dotAt = fullName.lastIndexOf(".")
if (dotAt == -1) {
dotAt = fullName.length
}
val name = fullName.substring(0, dotAt)
val extension = if (fullName.contains(".")) ".${fullName.getFilenameExtension()}" else ""
val newName = if (append) {
"$name$valueToAdd$extension"
} else {
"$valueToAdd$fullName"
}
val newPath = "${path.getParentPath()}/$newName"
if (activity.getDoesFilePathExist(newPath)) {
continue
}
activity.renameFile(path, newPath, true) { success, _ ->
if (success) {
pathsCnt--
if (pathsCnt == 0) {
callback()
alertDialog.dismiss()
}
} else {
ignoreClicks = false
alertDialog.dismiss()
}
}
}
}
}
}
}
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/dialogs/RenameItemsDialog.kt | 698380655 |
package com.simplemobiletools.commons.dialogs
import android.app.Activity
import android.text.Html
import android.text.method.LinkMovementMethod
import android.widget.TextView
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.size
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.DialogProperties
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.compose.alert_dialog.*
import com.simplemobiletools.commons.compose.components.LinkifyTextComponent
import com.simplemobiletools.commons.compose.extensions.MyDevices
import com.simplemobiletools.commons.compose.extensions.getActivity
import com.simplemobiletools.commons.compose.extensions.rememberMutableInteractionSource
import com.simplemobiletools.commons.compose.theme.AppThemeSurface
import com.simplemobiletools.commons.compose.theme.SimpleTheme
import com.simplemobiletools.commons.databinding.DialogDonateBinding
import com.simplemobiletools.commons.extensions.*
class DonateDialog(val activity: Activity) {
init {
val view = DialogDonateBinding.inflate(activity.layoutInflater, null, false).apply {
dialogDonateImage.applyColorFilter(activity.getProperTextColor())
dialogDonateText.text = Html.fromHtml(activity.getString(R.string.donate_short))
dialogDonateText.movementMethod = LinkMovementMethod.getInstance()
dialogDonateImage.setOnClickListener {
activity.launchViewIntent(R.string.thank_you_url)
}
}
activity.getAlertDialogBuilder()
.setPositiveButton(R.string.purchase) { _, _ -> activity.launchViewIntent(R.string.thank_you_url) }
.setNegativeButton(R.string.later, null)
.apply {
activity.setupDialogStuff(view.root, this, cancelOnTouchOutside = false)
}
}
}
@Composable
fun DonateAlertDialog(
alertDialogState: AlertDialogState,
modifier: Modifier = Modifier
) {
val localContext = LocalContext.current.getActivity()
val donateIntent = {
localContext.launchViewIntent(R.string.thank_you_url)
}
androidx.compose.material3.AlertDialog(
containerColor = dialogContainerColor,
modifier = modifier
.dialogBorder,
properties = DialogProperties(dismissOnClickOutside = false, dismissOnBackPress = false),
onDismissRequest = {},
shape = dialogShape,
tonalElevation = dialogElevation,
dismissButton = {
TextButton(onClick = {
alertDialogState.hide()
}) {
Text(text = stringResource(id = R.string.later))
}
},
confirmButton = {
TextButton(onClick = {
donateIntent()
alertDialogState.hide()
}) {
Text(text = stringResource(id = R.string.purchase))
}
},
title = {
Box(
Modifier.fillMaxWidth(),
contentAlignment = Alignment.Center
) {
Image(
Icons.Filled.Favorite,
contentDescription = null,
modifier = Modifier
.size(SimpleTheme.dimens.icon.large)
.clickable(
indication = null,
interactionSource = rememberMutableInteractionSource(),
onClick = {
donateIntent()
alertDialogState.hide()
}
),
colorFilter = ColorFilter.tint(dialogTextColor)
)
}
},
text = {
val source = stringResource(id = R.string.donate_short)
LinkifyTextComponent(
fontSize = 16.sp,
removeUnderlines = false,
textAlignment = TextView.TEXT_ALIGNMENT_CENTER,
modifier = Modifier.fillMaxWidth()
) {
source.fromHtml()
}
}
)
}
@Composable
@MyDevices
private fun DonateAlertDialogPreview() {
AppThemeSurface {
DonateAlertDialog(alertDialogState = rememberAlertDialogState())
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/dialogs/DonateDialog.kt | 2779162903 |
package com.simplemobiletools.commons.dialogs
import android.view.LayoutInflater
import android.view.WindowManager
import androidx.appcompat.app.AlertDialog
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.activities.BaseSimpleActivity
import com.simplemobiletools.commons.adapters.RenameAdapter
import com.simplemobiletools.commons.databinding.DialogRenameBinding
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.RENAME_PATTERN
import com.simplemobiletools.commons.helpers.RENAME_SIMPLE
import com.simplemobiletools.commons.views.MyViewPager
class RenameDialog(val activity: BaseSimpleActivity, val paths: ArrayList<String>, val useMediaFileExtension: Boolean, val callback: () -> Unit) {
var dialog: AlertDialog? = null
val view = DialogRenameBinding.inflate(LayoutInflater.from(activity), null, false)
var tabsAdapter: RenameAdapter
var viewPager: MyViewPager
init {
view.apply {
viewPager = dialogTabViewPager
tabsAdapter = RenameAdapter(activity, paths)
viewPager.adapter = tabsAdapter
viewPager.onPageChangeListener {
dialogTabLayout.getTabAt(it)!!.select()
}
viewPager.currentItem = activity.baseConfig.lastRenameUsed
if (activity.baseConfig.isUsingSystemTheme) {
dialogTabLayout.setBackgroundColor(activity.resources.getColor(R.color.you_dialog_background_color))
} else {
dialogTabLayout.setBackgroundColor(root.context.getProperBackgroundColor())
}
val textColor = root.context.getProperTextColor()
dialogTabLayout.setTabTextColors(textColor, textColor)
dialogTabLayout.setSelectedTabIndicatorColor(root.context.getProperPrimaryColor())
if (activity.baseConfig.isUsingSystemTheme) {
dialogTabLayout.setBackgroundColor(activity.resources.getColor(R.color.you_dialog_background_color))
}
dialogTabLayout.onTabSelectionChanged(tabSelectedAction = {
viewPager.currentItem = when {
it.text.toString().equals(root.context.resources.getString(R.string.simple_renaming), true) -> RENAME_SIMPLE
else -> RENAME_PATTERN
}
})
}
activity.getAlertDialogBuilder()
.setPositiveButton(R.string.ok, null)
.setNegativeButton(R.string.cancel) { _, _ -> dismissDialog() }
.apply {
activity.setupDialogStuff(view.root, this) { alertDialog ->
dialog = alertDialog
alertDialog.window?.clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM)
alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener {
tabsAdapter.dialogConfirmed(useMediaFileExtension, viewPager.currentItem) {
dismissDialog()
if (it) {
activity.baseConfig.lastRenameUsed = viewPager.currentItem
callback()
}
}
}
}
}
}
private fun dismissDialog() {
dialog?.dismiss()
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/dialogs/RenameDialog.kt | 4265405442 |
package com.simplemobiletools.commons.dialogs
import android.app.Activity
import android.text.format.DateFormat
import androidx.compose.foundation.LocalIndication
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.ripple.LocalRippleTheme
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalLayoutDirection
import androidx.compose.ui.res.dimensionResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.unit.dp
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.compose.alert_dialog.AlertDialogState
import com.simplemobiletools.commons.compose.alert_dialog.DialogSurface
import com.simplemobiletools.commons.compose.alert_dialog.rememberAlertDialogState
import com.simplemobiletools.commons.compose.components.RadioGroupDialogComponent
import com.simplemobiletools.commons.compose.extensions.MyDevices
import com.simplemobiletools.commons.compose.extensions.NoRippleTheme
import com.simplemobiletools.commons.compose.extensions.rememberMutableInteractionSource
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.compose.theme.preferenceLabelColor
import com.simplemobiletools.commons.databinding.DialogChangeDateTimeFormatBinding
import com.simplemobiletools.commons.extensions.baseConfig
import com.simplemobiletools.commons.extensions.getAlertDialogBuilder
import com.simplemobiletools.commons.extensions.setupDialogStuff
import com.simplemobiletools.commons.helpers.*
import java.util.Calendar
import java.util.Locale
import kotlinx.collections.immutable.toImmutableList
class ChangeDateTimeFormatDialog(val activity: Activity, val callback: () -> Unit) {
private val view = DialogChangeDateTimeFormatBinding.inflate(activity.layoutInflater, null, false)
init {
view.apply {
changeDateTimeDialogRadioOne.text = formatDateSample(DATE_FORMAT_ONE)
changeDateTimeDialogRadioTwo.text = formatDateSample(DATE_FORMAT_TWO)
changeDateTimeDialogRadioThree.text = formatDateSample(DATE_FORMAT_THREE)
changeDateTimeDialogRadioFour.text = formatDateSample(DATE_FORMAT_FOUR)
changeDateTimeDialogRadioFive.text = formatDateSample(DATE_FORMAT_FIVE)
changeDateTimeDialogRadioSix.text = formatDateSample(DATE_FORMAT_SIX)
changeDateTimeDialogRadioSeven.text = formatDateSample(DATE_FORMAT_SEVEN)
changeDateTimeDialogRadioEight.text = formatDateSample(DATE_FORMAT_EIGHT)
changeDateTimeDialog24Hour.isChecked = activity.baseConfig.use24HourFormat
val formatButton = when (activity.baseConfig.dateFormat) {
DATE_FORMAT_ONE -> changeDateTimeDialogRadioOne
DATE_FORMAT_TWO -> changeDateTimeDialogRadioTwo
DATE_FORMAT_THREE -> changeDateTimeDialogRadioThree
DATE_FORMAT_FOUR -> changeDateTimeDialogRadioFour
DATE_FORMAT_FIVE -> changeDateTimeDialogRadioFive
DATE_FORMAT_SIX -> changeDateTimeDialogRadioSix
DATE_FORMAT_SEVEN -> changeDateTimeDialogRadioSeven
else -> changeDateTimeDialogRadioEight
}
formatButton.isChecked = true
}
activity.getAlertDialogBuilder()
.setPositiveButton(R.string.ok) { dialog, which -> dialogConfirmed() }
.setNegativeButton(R.string.cancel, null)
.apply {
activity.setupDialogStuff(view.root, this)
}
}
private fun dialogConfirmed() {
activity.baseConfig.dateFormat = when (view.changeDateTimeDialogRadioGroup.checkedRadioButtonId) {
view.changeDateTimeDialogRadioOne.id -> DATE_FORMAT_ONE
view.changeDateTimeDialogRadioTwo.id -> DATE_FORMAT_TWO
view.changeDateTimeDialogRadioThree.id -> DATE_FORMAT_THREE
view.changeDateTimeDialogRadioFour.id -> DATE_FORMAT_FOUR
view.changeDateTimeDialogRadioFive.id -> DATE_FORMAT_FIVE
view.changeDateTimeDialogRadioSix.id -> DATE_FORMAT_SIX
view.changeDateTimeDialogRadioSeven.id -> DATE_FORMAT_SEVEN
else -> DATE_FORMAT_EIGHT
}
activity.baseConfig.use24HourFormat = view.changeDateTimeDialog24Hour.isChecked
callback()
}
private fun formatDateSample(format: String): String {
val cal = Calendar.getInstance(Locale.ENGLISH)
cal.timeInMillis = timeSample
return DateFormat.format(format, cal).toString()
}
}
@Composable
fun ChangeDateTimeFormatAlertDialog(
alertDialogState: AlertDialogState,
is24HourChecked: Boolean,
modifier: Modifier = Modifier,
callback: (selectedFormat: String, is24HourChecked: Boolean) -> Unit
) {
val context = LocalContext.current
val selections = remember {
mapOf(
Pair(DATE_FORMAT_ONE, formatDateSample(DATE_FORMAT_ONE)),
Pair(DATE_FORMAT_TWO, formatDateSample(DATE_FORMAT_TWO)),
Pair(DATE_FORMAT_THREE, formatDateSample(DATE_FORMAT_THREE)),
Pair(DATE_FORMAT_FOUR, formatDateSample(DATE_FORMAT_FOUR)),
Pair(DATE_FORMAT_FIVE, formatDateSample(DATE_FORMAT_FIVE)),
Pair(DATE_FORMAT_SIX, formatDateSample(DATE_FORMAT_SIX)),
Pair(DATE_FORMAT_SEVEN, formatDateSample(DATE_FORMAT_SEVEN)),
Pair(DATE_FORMAT_EIGHT, formatDateSample(DATE_FORMAT_EIGHT)),
)
}
val kinds = remember {
selections.values.toImmutableList()
}
val initiallySelected = remember {
requireNotNull(selections[context.baseConfig.dateFormat]) {
"Incorrect format, please check selections"
}
}
val (selected, setSelected) = remember { mutableStateOf(initiallySelected) }
var is24HoursSelected by remember { mutableStateOf(is24HourChecked) }
AlertDialog(
onDismissRequest = alertDialogState::hide,
) {
DialogSurface {
Box {
Column(
modifier = modifier
.padding(bottom = 64.dp)
.verticalScroll(rememberScrollState())
) {
RadioGroupDialogComponent(
items = kinds, selected = selected,
setSelected = setSelected,
modifier = Modifier.padding(
vertical = SimpleTheme.dimens.padding.extraLarge,
)
)
SettingsHorizontalDivider()
CompositionLocalProvider(LocalLayoutDirection provides LayoutDirection.Rtl) {
DialogCheckBoxWithRadioAlignmentComponent(
label = stringResource(id = R.string.use_24_hour_time_format),
initialValue = is24HoursSelected,
onChange = { is24HoursSelected = it },
modifier = Modifier.padding(horizontal = SimpleTheme.dimens.padding.medium)
)
}
}
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.End,
modifier = Modifier
.fillMaxWidth()
.padding(top = SimpleTheme.dimens.padding.extraLarge, bottom = SimpleTheme.dimens.padding.extraLarge, end = SimpleTheme.dimens.padding.extraLarge)
.align(Alignment.BottomStart)
) {
TextButton(onClick = {
alertDialogState.hide()
}) {
Text(text = stringResource(id = R.string.cancel))
}
TextButton(onClick = {
alertDialogState.hide()
callback(selections.filterValues { it == selected }.keys.first(), is24HoursSelected)
}) {
Text(text = stringResource(id = R.string.ok))
}
}
}
}
}
}
private const val timeSample = 1676419200000 // February 15, 2023
private fun formatDateSample(format: String): String {
val cal = Calendar.getInstance(Locale.ENGLISH)
cal.timeInMillis = timeSample
return DateFormat.format(format, cal).toString()
}
@Composable
internal fun DialogCheckBoxWithRadioAlignmentComponent(
modifier: Modifier = Modifier,
label: String,
initialValue: Boolean = false,
isPreferenceEnabled: Boolean = true,
onChange: ((Boolean) -> Unit)? = null,
checkboxColors: CheckboxColors = CheckboxDefaults.colors(
checkedColor = SimpleTheme.colorScheme.primary,
checkmarkColor = SimpleTheme.colorScheme.surface,
)
) {
val interactionSource = rememberMutableInteractionSource()
val indication = LocalIndication.current
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.fillMaxWidth()
.clickable(
onClick = { onChange?.invoke(!initialValue) },
interactionSource = interactionSource,
indication = indication
)
.then(modifier),
) {
Column(
modifier = Modifier.weight(1f),
verticalArrangement = Arrangement.Center
) {
Text(
modifier = Modifier
.fillMaxWidth(),
text = label,
color = preferenceLabelColor(isEnabled = isPreferenceEnabled),
fontSize = with(LocalDensity.current) {
dimensionResource(id = R.dimen.normal_text_size).toSp()
},
textAlign = TextAlign.End
)
}
CompositionLocalProvider(LocalRippleTheme provides NoRippleTheme) {
Checkbox(
checked = initialValue,
onCheckedChange = { onChange?.invoke(it) },
enabled = isPreferenceEnabled,
colors = checkboxColors,
interactionSource = interactionSource
)
}
}
}
@Composable
@MyDevices
private fun ChangeDateTimeFormatAlertDialogPreview() {
AppThemeSurface {
ChangeDateTimeFormatAlertDialog(alertDialogState = rememberAlertDialogState(), is24HourChecked = true) { _, _ -> }
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/dialogs/ChangeDateTimeFormatDialog.kt | 4197247522 |
package com.simplemobiletools.commons.dialogs
import android.app.Activity
import androidx.appcompat.app.AlertDialog
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.DialogProperties
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.compose.alert_dialog.*
import com.simplemobiletools.commons.compose.extensions.MyDevices
import com.simplemobiletools.commons.compose.theme.AppThemeSurface
import com.simplemobiletools.commons.databinding.DialogMessageBinding
import com.simplemobiletools.commons.extensions.getAlertDialogBuilder
import com.simplemobiletools.commons.extensions.setupDialogStuff
/**
* A simple dialog without any view, just a messageId, a positive button and optionally a negative button
*
* @param activity has to be activity context to avoid some Theme.AppCompat issues
* @param message the dialogs message, can be any String. If empty, messageId is used
* @param messageId the dialogs messageId ID. Used only if message is empty
* @param positive positive buttons text ID
* @param negative negative buttons text ID (optional)
* @param callback an anonymous function
*/
class ConfirmationDialog(
activity: Activity,
message: String = "",
messageId: Int = R.string.proceed_with_deletion, positive: Int = R.string.yes,
negative: Int = R.string.no,
val cancelOnTouchOutside: Boolean = true,
dialogTitle: String = "",
val callback: () -> Unit
) {
private var dialog: AlertDialog? = null
init {
val view = DialogMessageBinding.inflate(activity.layoutInflater, null, false)
view.message.text = message.ifEmpty { activity.resources.getString(messageId) }
val builder = activity.getAlertDialogBuilder()
.setPositiveButton(positive) { _, _ -> dialogConfirmed() }
if (negative != 0) {
builder.setNegativeButton(negative, null)
}
builder.apply {
activity.setupDialogStuff(view.root, this, titleText = dialogTitle, cancelOnTouchOutside = cancelOnTouchOutside) { alertDialog ->
dialog = alertDialog
}
}
}
private fun dialogConfirmed() {
dialog?.dismiss()
callback()
}
}
@Composable
fun ConfirmationAlertDialog(
alertDialogState: AlertDialogState,
modifier: Modifier = Modifier,
message: String = "",
messageId: Int? = R.string.proceed_with_deletion,
positive: Int? = R.string.yes,
negative: Int? = R.string.no,
cancelOnTouchOutside: Boolean = true,
dialogTitle: String = "",
callback: () -> Unit
) {
androidx.compose.material3.AlertDialog(
containerColor = dialogContainerColor,
modifier = modifier
.dialogBorder,
properties = DialogProperties(dismissOnClickOutside = cancelOnTouchOutside),
onDismissRequest = {
alertDialogState.hide()
callback()
},
shape = dialogShape,
tonalElevation = dialogElevation,
dismissButton = {
if (negative != null) {
TextButton(onClick = {
alertDialogState.hide()
callback()
}) {
Text(text = stringResource(id = negative))
}
}
},
confirmButton = {
if (positive != null) {
TextButton(onClick = {
alertDialogState.hide()
callback()
}) {
Text(text = stringResource(id = positive))
}
}
},
title = {
if (dialogTitle.isNotBlank() || dialogTitle.isNotEmpty()) {
Text(
text = dialogTitle,
color = dialogTextColor,
fontSize = 21.sp,
fontWeight = FontWeight.Bold,
)
}
},
text = {
Text(
modifier = Modifier.fillMaxWidth(),
text = message.ifEmpty { messageId?.let { stringResource(id = it) }.orEmpty() },
fontSize = 16.sp,
color = dialogTextColor,
)
}
)
}
@Composable
@MyDevices
private fun ConfirmationAlertDialogPreview() {
AppThemeSurface {
ConfirmationAlertDialog(
alertDialogState = rememberAlertDialogState()
) {}
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/dialogs/ConfirmationDialog.kt | 4170224882 |
package com.simplemobiletools.commons.dialogs
import androidx.appcompat.app.AlertDialog
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.activities.BaseSimpleActivity
import com.simplemobiletools.commons.databinding.DialogExportBlockedNumbersBinding
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.BLOCKED_NUMBERS_EXPORT_EXTENSION
import com.simplemobiletools.commons.helpers.ensureBackgroundThread
import java.io.File
class ExportBlockedNumbersDialog(
val activity: BaseSimpleActivity,
val path: String,
val hidePath: Boolean,
callback: (file: File) -> Unit,
) {
private var realPath = path.ifEmpty { activity.internalStoragePath }
private val config = activity.baseConfig
init {
val view = DialogExportBlockedNumbersBinding.inflate(activity.layoutInflater, null, false).apply {
exportBlockedNumbersFolder.text = activity.humanizePath(realPath)
exportBlockedNumbersFilename.setText("${activity.getString(R.string.blocked_numbers)}_${activity.getCurrentFormattedDateTime()}")
if (hidePath) {
exportBlockedNumbersFolderLabel.beGone()
exportBlockedNumbersFolder.beGone()
} else {
exportBlockedNumbersFolder.setOnClickListener {
FilePickerDialog(activity, realPath, false, showFAB = true) {
exportBlockedNumbersFolder.text = activity.humanizePath(it)
realPath = it
}
}
}
}
activity.getAlertDialogBuilder()
.setPositiveButton(R.string.ok, null)
.setNegativeButton(R.string.cancel, null)
.apply {
activity.setupDialogStuff(view.root, this, R.string.export_blocked_numbers) { alertDialog ->
alertDialog.showKeyboard(view.exportBlockedNumbersFilename)
alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener {
val filename = view.exportBlockedNumbersFilename.value
when {
filename.isEmpty() -> activity.toast(R.string.empty_name)
filename.isAValidFilename() -> {
val file = File(realPath, "$filename$BLOCKED_NUMBERS_EXPORT_EXTENSION")
if (!hidePath && file.exists()) {
activity.toast(R.string.name_taken)
return@setOnClickListener
}
ensureBackgroundThread {
config.lastBlockedNumbersExportPath = file.absolutePath.getParentPath()
callback(file)
alertDialog.dismiss()
}
}
else -> activity.toast(R.string.invalid_name)
}
}
}
}
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/dialogs/ExportBlockedNumbersDialog.kt | 3384665474 |
package com.simplemobiletools.commons.dialogs
import android.app.Activity
import android.text.Html
import android.text.method.LinkMovementMethod
import androidx.appcompat.app.AlertDialog
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.compose.alert_dialog.*
import com.simplemobiletools.commons.compose.components.LinkifyTextComponent
import com.simplemobiletools.commons.compose.extensions.MyDevices
import com.simplemobiletools.commons.compose.theme.AppThemeSurface
import com.simplemobiletools.commons.databinding.DialogTextviewBinding
import com.simplemobiletools.commons.extensions.*
class AppSideloadedDialog(val activity: Activity, val callback: () -> Unit) {
private var dialog: AlertDialog? = null
private val url = "https://play.google.com/store/apps/details?id=${activity.getStringsPackageName()}"
init {
val view = DialogTextviewBinding.inflate(activity.layoutInflater, null, false).apply {
val text = String.format(activity.getString(R.string.sideloaded_app), url)
textView.text = Html.fromHtml(text)
textView.movementMethod = LinkMovementMethod.getInstance()
}
activity.getAlertDialogBuilder()
.setNegativeButton(R.string.cancel) { _, _ -> negativePressed() }
.setPositiveButton(R.string.download, null)
.setOnCancelListener { negativePressed() }
.apply {
activity.setupDialogStuff(view.root, this, R.string.app_corrupt) { alertDialog ->
dialog = alertDialog
alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener {
downloadApp()
}
}
}
}
private fun downloadApp() {
activity.launchViewIntent(url)
}
private fun negativePressed() {
dialog?.dismiss()
callback()
}
}
@Composable
fun AppSideLoadedAlertDialog(
alertDialogState: AlertDialogState,
modifier: Modifier = Modifier,
onDownloadClick: (url: String) -> Unit,
onCancelClick: () -> Unit
) {
val context = LocalContext.current
val url = remember { "https://play.google.com/store/apps/details?id=${context.getStringsPackageName()}" }
AlertDialog(
containerColor = dialogContainerColor,
modifier = modifier
.dialogBorder,
onDismissRequest = alertDialogState::hide,
confirmButton = {
TextButton(onClick = {
alertDialogState.hide()
onDownloadClick(url)
}) {
Text(text = stringResource(id = R.string.download))
}
},
dismissButton = {
TextButton(onClick = {
alertDialogState.hide()
onCancelClick()
}) {
Text(text = stringResource(id = R.string.cancel))
}
},
shape = dialogShape,
text = {
val source = stringResource(id = R.string.sideloaded_app, url)
LinkifyTextComponent(fontSize = 16.sp, removeUnderlines = false) {
source.fromHtml()
}
},
title = {
Text(
modifier = Modifier.fillMaxWidth(),
text = stringResource(id = R.string.app_corrupt),
color = dialogTextColor,
fontSize = 21.sp,
fontWeight = FontWeight.Bold,
)
},
tonalElevation = dialogElevation
)
}
@Composable
@MyDevices
private fun AppSideLoadedAlertDialogPreview() {
AppThemeSurface {
AppSideLoadedAlertDialog(alertDialogState = rememberAlertDialogState(), onDownloadClick = {}) {}
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/dialogs/AppSideloadedDialog.kt | 1583635087 |
package com.simplemobiletools.commons.dialogs
import android.app.Activity
import android.view.LayoutInflater
import androidx.appcompat.app.AlertDialog
import androidx.biometric.auth.AuthPromptHost
import androidx.fragment.app.FragmentActivity
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.adapters.PasswordTypesAdapter
import com.simplemobiletools.commons.databinding.DialogSecurityBinding
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.*
import com.simplemobiletools.commons.interfaces.HashListener
import com.simplemobiletools.commons.views.MyDialogViewPager
class SecurityDialog(
private val activity: Activity,
private val requiredHash: String,
private val showTabIndex: Int,
private val callback: (hash: String, type: Int, success: Boolean) -> Unit
) : HashListener {
private var dialog: AlertDialog? = null
private val view = DialogSecurityBinding.inflate(LayoutInflater.from(activity), null, false)
private var tabsAdapter: PasswordTypesAdapter
private var viewPager: MyDialogViewPager
init {
view.apply {
viewPager = dialogTabViewPager
viewPager.offscreenPageLimit = 2
tabsAdapter = PasswordTypesAdapter(
context = root.context,
requiredHash = requiredHash,
hashListener = this@SecurityDialog,
scrollView = dialogScrollview,
biometricPromptHost = AuthPromptHost(activity as FragmentActivity),
showBiometricIdTab = shouldShowBiometricIdTab(),
showBiometricAuthentication = showTabIndex == PROTECTION_FINGERPRINT && isRPlus()
)
viewPager.adapter = tabsAdapter
viewPager.onPageChangeListener {
dialogTabLayout.getTabAt(it)?.select()
}
viewPager.onGlobalLayout {
updateTabVisibility()
}
if (showTabIndex == SHOW_ALL_TABS) {
val textColor = root.context.getProperTextColor()
if (shouldShowBiometricIdTab()) {
val tabTitle = if (isRPlus()) R.string.biometrics else R.string.fingerprint
dialogTabLayout.addTab(dialogTabLayout.newTab().setText(tabTitle), PROTECTION_FINGERPRINT)
}
if (activity.baseConfig.isUsingSystemTheme) {
dialogTabLayout.setBackgroundColor(activity.resources.getColor(R.color.you_dialog_background_color))
} else {
dialogTabLayout.setBackgroundColor(root.context.getProperBackgroundColor())
}
dialogTabLayout.setTabTextColors(textColor, textColor)
dialogTabLayout.setSelectedTabIndicatorColor(root.context.getProperPrimaryColor())
dialogTabLayout.onTabSelectionChanged(tabSelectedAction = {
viewPager.currentItem = when {
it.text.toString().equals(root.context.resources.getString(R.string.pattern), true) -> PROTECTION_PATTERN
it.text.toString().equals(root.context.resources.getString(R.string.pin), true) -> PROTECTION_PIN
else -> PROTECTION_FINGERPRINT
}
updateTabVisibility()
})
} else {
dialogTabLayout.beGone()
viewPager.currentItem = showTabIndex
viewPager.allowSwiping = false
}
}
activity.getAlertDialogBuilder()
.setOnCancelListener { onCancelFail() }
.setNegativeButton(R.string.cancel) { _, _ -> onCancelFail() }
.apply {
activity.setupDialogStuff(view.root, this) { alertDialog ->
dialog = alertDialog
}
}
}
private fun onCancelFail() {
callback("", 0, false)
dialog?.dismiss()
}
override fun receivedHash(hash: String, type: Int) {
callback(hash, type, true)
if (!activity.isFinishing) {
try {
dialog?.dismiss()
} catch (ignored: Exception) {
}
}
}
private fun updateTabVisibility() {
for (i in 0..2) {
tabsAdapter.isTabVisible(i, viewPager.currentItem == i)
}
}
private fun shouldShowBiometricIdTab(): Boolean {
return if (isRPlus()) {
activity.isBiometricIdAvailable()
} else {
activity.isFingerPrintSensorAvailable()
}
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/dialogs/SecurityDialog.kt | 2549166936 |
package com.simplemobiletools.commons.dialogs
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.TextRange
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.TextFieldValue
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.compose.alert_dialog.*
import com.simplemobiletools.commons.compose.extensions.MyDevices
import com.simplemobiletools.commons.compose.theme.AppThemeSurface
import com.simplemobiletools.commons.models.BlockedNumber
@Composable
fun AddOrEditBlockedNumberAlertDialog(
alertDialogState: AlertDialogState,
blockedNumber: BlockedNumber?,
modifier: Modifier = Modifier,
deleteBlockedNumber: (String) -> Unit,
addBlockedNumber: (String) -> Unit
) {
val focusRequester = remember { FocusRequester() }
var textFieldValue by remember {
mutableStateOf(
TextFieldValue(
text = blockedNumber?.number.orEmpty(),
selection = TextRange(blockedNumber?.number?.length ?: 0)
)
)
}
AlertDialog(
containerColor = dialogContainerColor,
modifier = modifier
.dialogBorder,
onDismissRequest = alertDialogState::hide,
confirmButton = {
TextButton(onClick = {
var newBlockedNumber = textFieldValue.text
if (blockedNumber != null && newBlockedNumber != blockedNumber.number) {
deleteBlockedNumber(blockedNumber.number)
}
if (newBlockedNumber.isNotEmpty()) {
// in case the user also added a '.' in the pattern, remove it
if (newBlockedNumber.contains(".*")) {
newBlockedNumber = newBlockedNumber.replace(".*", "*")
}
addBlockedNumber(newBlockedNumber)
}
alertDialogState.hide()
}) {
Text(text = stringResource(id = R.string.ok))
}
},
dismissButton = {
TextButton(onClick = {
alertDialogState.hide()
}) {
Text(text = stringResource(id = R.string.cancel))
}
},
shape = dialogShape,
text = {
OutlinedTextField(
modifier = Modifier
.fillMaxWidth()
.focusRequester(focusRequester),
value = textFieldValue,
onValueChange = {
textFieldValue = it
},
supportingText = {
Text(
text = stringResource(id = R.string.add_blocked_number_helper_text),
color = dialogTextColor
)
},
label = {
Text(text = stringResource(id = R.string.number))
},
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Phone)
)
},
tonalElevation = dialogElevation
)
ShowKeyboardWhenDialogIsOpenedAndRequestFocus(focusRequester = focusRequester)
}
@Composable
@MyDevices
private fun AddOrEditBlockedNumberAlertDialogPreview() {
AppThemeSurface {
AddOrEditBlockedNumberAlertDialog(
alertDialogState = rememberAlertDialogState(),
blockedNumber = null,
deleteBlockedNumber = {}
) {}
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/dialogs/AddBlockedNumberDialog.kt | 2914747152 |
package com.simplemobiletools.commons.dialogs
import android.os.Environment
import android.os.Parcelable
import android.view.KeyEvent
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.documentfile.provider.DocumentFile
import androidx.recyclerview.widget.LinearLayoutManager
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.activities.BaseSimpleActivity
import com.simplemobiletools.commons.adapters.FilepickerFavoritesAdapter
import com.simplemobiletools.commons.adapters.FilepickerItemsAdapter
import com.simplemobiletools.commons.databinding.DialogFilepickerBinding
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.ensureBackgroundThread
import com.simplemobiletools.commons.models.FileDirItem
import com.simplemobiletools.commons.views.Breadcrumbs
import java.io.File
/**
* The only filepicker constructor with a couple optional parameters
*
* @param activity has to be activity to avoid some Theme.AppCompat issues
* @param currPath initial path of the dialog, defaults to the external storage
* @param pickFile toggle used to determine if we are picking a file or a folder
* @param showHidden toggle for showing hidden items, whose name starts with a dot
* @param showFAB toggle the displaying of a Floating Action Button for creating new folders
* @param callback the callback used for returning the selected file/folder
*/
class FilePickerDialog(
val activity: BaseSimpleActivity,
var currPath: String = Environment.getExternalStorageDirectory().toString(),
val pickFile: Boolean = true,
var showHidden: Boolean = false,
val showFAB: Boolean = false,
val canAddShowHiddenButton: Boolean = false,
val forceShowRoot: Boolean = false,
val showFavoritesButton: Boolean = false,
private val enforceStorageRestrictions: Boolean = true,
val callback: (pickedPath: String) -> Unit
) : Breadcrumbs.BreadcrumbsListener {
private var mFirstUpdate = true
private var mPrevPath = ""
private var mScrollStates = HashMap<String, Parcelable>()
private var mDialog: AlertDialog? = null
private var mDialogView = DialogFilepickerBinding.inflate(activity.layoutInflater, null, false)
init {
if (!activity.getDoesFilePathExist(currPath)) {
currPath = activity.internalStoragePath
}
if (!activity.getIsPathDirectory(currPath)) {
currPath = currPath.getParentPath()
}
// do not allow copying files in the recycle bin manually
if (currPath.startsWith(activity.filesDir.absolutePath)) {
currPath = activity.internalStoragePath
}
mDialogView.filepickerBreadcrumbs.apply {
listener = this@FilePickerDialog
updateFontSize(activity.getTextSize(), false)
isShownInDialog = true
}
tryUpdateItems()
setupFavorites()
val builder = activity.getAlertDialogBuilder()
.setNegativeButton(R.string.cancel, null)
.setOnKeyListener { dialogInterface, i, keyEvent ->
if (keyEvent.action == KeyEvent.ACTION_UP && i == KeyEvent.KEYCODE_BACK) {
val breadcrumbs = mDialogView.filepickerBreadcrumbs
if (breadcrumbs.getItemCount() > 1) {
breadcrumbs.removeBreadcrumb()
currPath = breadcrumbs.getLastItem().path.trimEnd('/')
tryUpdateItems()
} else {
mDialog?.dismiss()
}
}
true
}
if (!pickFile) {
builder.setPositiveButton(R.string.ok, null)
}
if (showFAB) {
mDialogView.filepickerFab.apply {
beVisible()
setOnClickListener { createNewFolder() }
}
}
val secondaryFabBottomMargin = activity.resources.getDimension(if (showFAB) R.dimen.secondary_fab_bottom_margin else R.dimen.activity_margin).toInt()
mDialogView.filepickerFabsHolder.apply {
(layoutParams as CoordinatorLayout.LayoutParams).bottomMargin = secondaryFabBottomMargin
}
mDialogView.filepickerPlaceholder.setTextColor(activity.getProperTextColor())
mDialogView.filepickerFastscroller.updateColors(activity.getProperPrimaryColor())
mDialogView.filepickerFabShowHidden.apply {
beVisibleIf(!showHidden && canAddShowHiddenButton)
setOnClickListener {
activity.handleHiddenFolderPasswordProtection {
beGone()
showHidden = true
tryUpdateItems()
}
}
}
mDialogView.filepickerFavoritesLabel.text = "${activity.getString(R.string.favorites)}:"
mDialogView.filepickerFabShowFavorites.apply {
beVisibleIf(showFavoritesButton && context.baseConfig.favorites.isNotEmpty())
setOnClickListener {
if (mDialogView.filepickerFavoritesHolder.isVisible()) {
hideFavorites()
} else {
showFavorites()
}
}
}
builder.apply {
activity.setupDialogStuff(mDialogView.root, this, getTitle()) { alertDialog ->
mDialog = alertDialog
}
}
if (!pickFile) {
mDialog?.getButton(AlertDialog.BUTTON_POSITIVE)?.setOnClickListener {
verifyPath()
}
}
}
private fun getTitle() = if (pickFile) R.string.select_file else R.string.select_folder
private fun createNewFolder() {
CreateNewFolderDialog(activity, currPath) {
callback(it)
mDialog?.dismiss()
}
}
private fun tryUpdateItems() {
ensureBackgroundThread {
getItems(currPath) {
activity.runOnUiThread {
mDialogView.filepickerPlaceholder.beGone()
updateItems(it as ArrayList<FileDirItem>)
}
}
}
}
private fun updateItems(items: ArrayList<FileDirItem>) {
if (!containsDirectory(items) && !mFirstUpdate && !pickFile && !showFAB) {
verifyPath()
return
}
val sortedItems = items.sortedWith(compareBy({ !it.isDirectory }, { it.name.lowercase() }))
val adapter = FilepickerItemsAdapter(activity, sortedItems, mDialogView.filepickerList) {
if ((it as FileDirItem).isDirectory) {
activity.handleLockedFolderOpening(it.path) { success ->
if (success) {
currPath = it.path
tryUpdateItems()
}
}
} else if (pickFile) {
currPath = it.path
verifyPath()
}
}
val layoutManager = mDialogView.filepickerList.layoutManager as LinearLayoutManager
mScrollStates[mPrevPath.trimEnd('/')] = layoutManager.onSaveInstanceState()!!
mDialogView.apply {
filepickerList.adapter = adapter
filepickerBreadcrumbs.setBreadcrumb(currPath)
if (root.context.areSystemAnimationsEnabled) {
filepickerList.scheduleLayoutAnimation()
}
layoutManager.onRestoreInstanceState(mScrollStates[currPath.trimEnd('/')])
}
mFirstUpdate = false
mPrevPath = currPath
}
private fun verifyPath() {
when {
activity.isRestrictedSAFOnlyRoot(currPath) -> {
val document = activity.getSomeAndroidSAFDocument(currPath) ?: return
sendSuccessForDocumentFile(document)
}
activity.isPathOnOTG(currPath) -> {
val fileDocument = activity.getSomeDocumentFile(currPath) ?: return
sendSuccessForDocumentFile(fileDocument)
}
activity.isAccessibleWithSAFSdk30(currPath) -> {
if (enforceStorageRestrictions) {
activity.handleSAFDialogSdk30(currPath) {
if (it) {
val document = activity.getSomeDocumentSdk30(currPath)
sendSuccessForDocumentFile(document ?: return@handleSAFDialogSdk30)
}
}
} else {
sendSuccessForDirectFile()
}
}
activity.isRestrictedWithSAFSdk30(currPath) -> {
if (enforceStorageRestrictions) {
if (activity.isInDownloadDir(currPath)) {
sendSuccessForDirectFile()
} else {
activity.toast(R.string.system_folder_restriction, Toast.LENGTH_LONG)
}
} else {
sendSuccessForDirectFile()
}
}
else -> {
sendSuccessForDirectFile()
}
}
}
private fun sendSuccessForDocumentFile(document: DocumentFile) {
if ((pickFile && document.isFile) || (!pickFile && document.isDirectory)) {
sendSuccess()
}
}
private fun sendSuccessForDirectFile() {
val file = File(currPath)
if ((pickFile && file.isFile) || (!pickFile && file.isDirectory)) {
sendSuccess()
}
}
private fun sendSuccess() {
currPath = if (currPath.length == 1) {
currPath
} else {
currPath.trimEnd('/')
}
callback(currPath)
mDialog?.dismiss()
}
private fun getItems(path: String, callback: (List<FileDirItem>) -> Unit) {
when {
activity.isRestrictedSAFOnlyRoot(path) -> {
activity.handleAndroidSAFDialog(path) {
activity.getAndroidSAFFileItems(path, showHidden) {
callback(it)
}
}
}
activity.isPathOnOTG(path) -> activity.getOTGItems(path, showHidden, false, callback)
else -> {
val lastModifieds = activity.getFolderLastModifieds(path)
getRegularItems(path, lastModifieds, callback)
}
}
}
private fun getRegularItems(path: String, lastModifieds: HashMap<String, Long>, callback: (List<FileDirItem>) -> Unit) {
val items = ArrayList<FileDirItem>()
val files = File(path).listFiles()?.filterNotNull()
if (files == null) {
callback(items)
return
}
for (file in files) {
if (!showHidden && file.name.startsWith('.')) {
continue
}
val curPath = file.absolutePath
val curName = curPath.getFilenameFromPath()
val size = file.length()
var lastModified = lastModifieds.remove(curPath)
val isDirectory = if (lastModified != null) false else file.isDirectory
if (lastModified == null) {
lastModified = 0 // we don't actually need the real lastModified that badly, do not check file.lastModified()
}
val children = if (isDirectory) file.getDirectChildrenCount(activity, showHidden) else 0
items.add(FileDirItem(curPath, curName, isDirectory, children, size, lastModified))
}
callback(items)
}
private fun containsDirectory(items: List<FileDirItem>) = items.any { it.isDirectory }
private fun setupFavorites() {
FilepickerFavoritesAdapter(activity, activity.baseConfig.favorites.toMutableList(), mDialogView.filepickerFavoritesList) {
currPath = it as String
verifyPath()
}.apply {
mDialogView.filepickerFavoritesList.adapter = this
}
}
private fun showFavorites() {
mDialogView.apply {
filepickerFavoritesHolder.beVisible()
filepickerFilesHolder.beGone()
val drawable = activity.resources.getColoredDrawableWithColor(R.drawable.ic_folder_vector, activity.getProperPrimaryColor().getContrastColor())
filepickerFabShowFavorites.setImageDrawable(drawable)
}
}
private fun hideFavorites() {
mDialogView.apply {
filepickerFavoritesHolder.beGone()
filepickerFilesHolder.beVisible()
val drawable = activity.resources.getColoredDrawableWithColor(R.drawable.ic_star_vector, activity.getProperPrimaryColor().getContrastColor())
filepickerFabShowFavorites.setImageDrawable(drawable)
}
}
override fun breadcrumbClicked(id: Int) {
if (id == 0) {
StoragePickerDialog(activity, currPath, forceShowRoot, true) {
currPath = it
tryUpdateItems()
}
} else {
val item = mDialogView.filepickerBreadcrumbs.getItem(id)
if (currPath != item.path.trimEnd('/')) {
currPath = item.path
tryUpdateItems()
}
}
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/dialogs/FilePickerDialog.kt | 2203769014 |
package com.simplemobiletools.commons.dialogs
import android.os.Bundle
import android.view.ViewGroup
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.ListItem
import androidx.compose.material3.ListItemDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
import androidx.fragment.app.FragmentManager
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.adapters.setupSimpleListItem
import com.simplemobiletools.commons.compose.alert_dialog.dialogContainerColor
import com.simplemobiletools.commons.compose.alert_dialog.dialogTextColor
import com.simplemobiletools.commons.compose.bottom_sheet.BottomSheetColumnDialogSurface
import com.simplemobiletools.commons.compose.bottom_sheet.BottomSheetDialogState
import com.simplemobiletools.commons.compose.bottom_sheet.BottomSheetSpacerEdgeToEdge
import com.simplemobiletools.commons.compose.bottom_sheet.rememberBottomSheetDialogState
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.databinding.ItemSimpleListBinding
import com.simplemobiletools.commons.fragments.BaseBottomSheetDialogFragment
import com.simplemobiletools.commons.models.SimpleListItem
import kotlinx.collections.immutable.ImmutableList
import kotlinx.collections.immutable.toImmutableList
open class BottomSheetChooserDialog : BaseBottomSheetDialogFragment() {
var onItemClick: ((SimpleListItem) -> Unit)? = null
override fun setupContentView(parent: ViewGroup) {
val listItems = arguments?.getParcelableArray(ITEMS) as Array<SimpleListItem>
listItems.forEach { item ->
val view = ItemSimpleListBinding.inflate(layoutInflater, parent, false)
setupSimpleListItem(view, item) {
onItemClick?.invoke(it)
}
parent.addView(view.root)
}
}
override fun onDestroy() {
super.onDestroy()
onItemClick = null
}
companion object {
private const val TAG = "BottomSheetChooserDialog"
private const val ITEMS = "data"
fun createChooser(
fragmentManager: FragmentManager,
title: Int?,
items: Array<SimpleListItem>,
callback: (SimpleListItem) -> Unit
): BottomSheetChooserDialog {
val extras = Bundle().apply {
if (title != null) {
putInt(BOTTOM_SHEET_TITLE, title)
}
putParcelableArray(ITEMS, items)
}
return BottomSheetChooserDialog().apply {
arguments = extras
onItemClick = callback
show(fragmentManager, TAG)
}
}
}
}
@Composable
fun ChooserBottomSheetDialog(
bottomSheetDialogState: BottomSheetDialogState,
items: ImmutableList<SimpleListItem>,
modifier: Modifier = Modifier,
onItemClicked: (SimpleListItem) -> Unit
) {
BottomSheetColumnDialogSurface(modifier) {
Text(
text = stringResource(id = R.string.please_select_destination),
color = dialogTextColor,
fontSize = 21.sp,
fontWeight = FontWeight.Bold,
modifier = Modifier
.padding(SimpleTheme.dimens.padding.extraLarge)
.padding(top = SimpleTheme.dimens.padding.large)
)
for (item in items) {
val color = if (item.selected) SimpleTheme.colorScheme.primary else SimpleTheme.colorScheme.onSurface
ListItem(
modifier = Modifier
.clickable {
onItemClicked(item)
bottomSheetDialogState.close()
},
headlineContent = {
Text(stringResource(id = item.textRes), color = color)
},
leadingContent = {
if (item.imageRes != null) {
Image(
painter = painterResource(id = item.imageRes),
contentDescription = stringResource(id = item.textRes),
colorFilter = ColorFilter.tint(color)
)
}
},
trailingContent = {
if (item.selected) {
Image(
painter = painterResource(id = R.drawable.ic_check_circle_vector),
contentDescription = null,
colorFilter = ColorFilter.tint(color)
)
}
},
colors = ListItemDefaults.colors(containerColor = dialogContainerColor)
)
}
BottomSheetSpacerEdgeToEdge()
}
}
@MyDevices
@Composable
private fun ChooserBottomSheetDialogPreview() {
AppThemeSurface {
val list = remember {
listOf(
SimpleListItem(1, R.string.record_video, R.drawable.ic_camera_vector),
SimpleListItem(2, R.string.record_audio, R.drawable.ic_microphone_vector, selected = true),
SimpleListItem(4, R.string.choose_contact, R.drawable.ic_add_person_vector)
).toImmutableList()
}
ChooserBottomSheetDialog(bottomSheetDialogState = rememberBottomSheetDialogState(), items = list, onItemClicked = {})
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/dialogs/BottomSheetChooserDialog.kt | 1116517937 |
package com.simplemobiletools.commons.dialogs
import android.app.Activity
import androidx.appcompat.app.AlertDialog
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.compose.alert_dialog.*
import com.simplemobiletools.commons.compose.extensions.MyDevices
import com.simplemobiletools.commons.compose.theme.AppThemeSurface
import com.simplemobiletools.commons.databinding.DialogMessageBinding
import com.simplemobiletools.commons.extensions.getAlertDialogBuilder
import com.simplemobiletools.commons.extensions.setupDialogStuff
class PermissionRequiredDialog(
val activity: Activity,
textId: Int,
private val positiveActionCallback: () -> Unit,
private val negativeActionCallback: (() -> Unit)? = null
) {
private var dialog: AlertDialog? = null
init {
val view = DialogMessageBinding.inflate(activity.layoutInflater, null, false)
view.message.text = activity.getString(textId)
activity.getAlertDialogBuilder()
.setPositiveButton(R.string.grant_permission) { _, _ -> positiveActionCallback() }
.setNegativeButton(R.string.cancel) { _, _ -> negativeActionCallback?.invoke() }.apply {
val title = activity.getString(R.string.permission_required)
activity.setupDialogStuff(view.root, this, titleText = title) { alertDialog ->
dialog = alertDialog
}
}
}
}
@Composable
fun PermissionRequiredAlertDialog(
alertDialogState: AlertDialogState,
text: String,
modifier: Modifier = Modifier,
negativeActionCallback: (() -> Unit)? = null,
positiveActionCallback: () -> Unit
) {
AlertDialog(
containerColor = dialogContainerColor,
modifier = modifier
.dialogBorder,
onDismissRequest = alertDialogState::hide,
shape = dialogShape,
tonalElevation = dialogElevation,
dismissButton = {
TextButton(onClick = {
alertDialogState.hide()
negativeActionCallback?.invoke()
}) {
Text(text = stringResource(id = R.string.cancel))
}
},
confirmButton = {
TextButton(onClick = {
alertDialogState.hide()
positiveActionCallback()
}) {
Text(text = stringResource(id = R.string.grant_permission))
}
},
title = {
Text(
text = stringResource(id = R.string.permission_required),
fontSize = 21.sp,
fontWeight = FontWeight.Bold
)
},
text = {
Text(
fontSize = 16.sp,
text = text
)
}
)
}
@Composable
@MyDevices
private fun PermissionRequiredAlertDialogPreview() {
AppThemeSurface {
PermissionRequiredAlertDialog(
alertDialogState = rememberAlertDialogState(),
text = "Test",
negativeActionCallback = {}
) {}
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/dialogs/PermissionRequiredDialog.kt | 1034950389 |
package com.simplemobiletools.commons.dialogs
import android.app.Activity
import android.text.Html
import android.text.Spanned
import androidx.annotation.DrawableRes
import androidx.annotation.StringRes
import androidx.appcompat.app.AlertDialog
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.PreviewParameter
import androidx.compose.ui.tooling.preview.PreviewParameterProvider
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.DialogProperties
import com.bumptech.glide.Glide
import com.bumptech.glide.integration.compose.GlideImage
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.bumptech.glide.request.transition.DrawableCrossFadeFactory
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.activities.BaseSimpleActivity
import com.simplemobiletools.commons.compose.alert_dialog.AlertDialogState
import com.simplemobiletools.commons.compose.alert_dialog.DialogSurface
import com.simplemobiletools.commons.compose.alert_dialog.dialogTextColor
import com.simplemobiletools.commons.compose.alert_dialog.rememberAlertDialogState
import com.simplemobiletools.commons.compose.components.LinkifyTextComponent
import com.simplemobiletools.commons.compose.extensions.MyDevices
import com.simplemobiletools.commons.compose.extensions.andThen
import com.simplemobiletools.commons.compose.theme.AppThemeSurface
import com.simplemobiletools.commons.compose.theme.SimpleTheme
import com.simplemobiletools.commons.databinding.DialogWritePermissionBinding
import com.simplemobiletools.commons.databinding.DialogWritePermissionOtgBinding
import com.simplemobiletools.commons.extensions.fromHtml
import com.simplemobiletools.commons.extensions.getAlertDialogBuilder
import com.simplemobiletools.commons.extensions.humanizePath
import com.simplemobiletools.commons.extensions.setupDialogStuff
class WritePermissionDialog(activity: Activity, val writePermissionDialogMode: WritePermissionDialogMode, val callback: () -> Unit) {
@Immutable
sealed class WritePermissionDialogMode {
@Immutable
data object Otg : WritePermissionDialogMode()
@Immutable
data object SdCard : WritePermissionDialogMode()
@Immutable
data class OpenDocumentTreeSDK30(val path: String) : WritePermissionDialogMode()
@Immutable
data object CreateDocumentSDK30 : WritePermissionDialogMode()
}
private var dialog: AlertDialog? = null
init {
val sdCardView = DialogWritePermissionBinding.inflate(activity.layoutInflater, null, false)
val otgView = DialogWritePermissionOtgBinding.inflate(
activity.layoutInflater,
null,
false
)
var dialogTitle = R.string.confirm_storage_access_title
val glide = Glide.with(activity)
val crossFade = DrawableTransitionOptions.withCrossFade()
when (writePermissionDialogMode) {
WritePermissionDialogMode.Otg -> {
otgView.writePermissionsDialogOtgText.setText(R.string.confirm_usb_storage_access_text)
glide.load(R.drawable.img_write_storage_otg).transition(crossFade).into(otgView.writePermissionsDialogOtgImage)
}
WritePermissionDialogMode.SdCard -> {
glide.load(R.drawable.img_write_storage).transition(crossFade).into(sdCardView.writePermissionsDialogImage)
glide.load(R.drawable.img_write_storage_sd).transition(crossFade).into(sdCardView.writePermissionsDialogImageSd)
}
is WritePermissionDialogMode.OpenDocumentTreeSDK30 -> {
dialogTitle = R.string.confirm_folder_access_title
val humanizedPath = activity.humanizePath(writePermissionDialogMode.path)
otgView.writePermissionsDialogOtgText.text =
Html.fromHtml(activity.getString(R.string.confirm_storage_access_android_text_specific, humanizedPath))
glide.load(R.drawable.img_write_storage_sdk_30).transition(crossFade).into(otgView.writePermissionsDialogOtgImage)
otgView.writePermissionsDialogOtgImage.setOnClickListener {
dialogConfirmed()
}
}
WritePermissionDialogMode.CreateDocumentSDK30 -> {
dialogTitle = R.string.confirm_folder_access_title
otgView.writePermissionsDialogOtgText.text = Html.fromHtml(activity.getString(R.string.confirm_create_doc_for_new_folder_text))
glide.load(R.drawable.img_write_storage_create_doc_sdk_30).transition(crossFade).into(otgView.writePermissionsDialogOtgImage)
otgView.writePermissionsDialogOtgImage.setOnClickListener {
dialogConfirmed()
}
}
}
activity.getAlertDialogBuilder()
.setPositiveButton(R.string.ok) { _, _ -> dialogConfirmed() }
.setOnCancelListener {
BaseSimpleActivity.funAfterSAFPermission?.invoke(false)
BaseSimpleActivity.funAfterSAFPermission = null
}
.apply {
activity.setupDialogStuff(
if (writePermissionDialogMode == WritePermissionDialogMode.SdCard) sdCardView.root else otgView.root,
this,
dialogTitle
) { alertDialog ->
dialog = alertDialog
}
}
}
private fun dialogConfirmed() {
dialog?.dismiss()
callback()
}
}
@Composable
fun WritePermissionAlertDialog(
alertDialogState: AlertDialogState,
writePermissionDialogMode: WritePermissionDialog.WritePermissionDialogMode,
modifier: Modifier = Modifier,
callback: () -> Unit,
onCancelCallback: () -> Unit
) {
val dialogTitle = remember {
adjustDialogTitle(
writePermissionDialogMode = writePermissionDialogMode,
dialogTitle = R.string.confirm_storage_access_title
)
}
val crossFadeTransition = remember {
DrawableTransitionOptions().crossFade(DrawableCrossFadeFactory.Builder(350).setCrossFadeEnabled(true).build())
}
AlertDialog(
onDismissRequest = alertDialogState::hide andThen onCancelCallback,
modifier = modifier
.fillMaxWidth(0.9f),
properties = DialogProperties(usePlatformDefaultWidth = false)
) {
DialogSurface {
Box {
Column(
modifier = modifier
.padding(bottom = 64.dp)
.verticalScroll(rememberScrollState())
) {
Text(
text = stringResource(id = dialogTitle),
color = dialogTextColor,
modifier = Modifier
.padding(horizontal = SimpleTheme.dimens.padding.extraLarge.plus(SimpleTheme.dimens.padding.large))
.padding(top = SimpleTheme.dimens.padding.extraLarge.plus(SimpleTheme.dimens.padding.small)),
fontSize = 21.sp,
fontWeight = FontWeight.Bold,
)
when (writePermissionDialogMode) {
WritePermissionDialog.WritePermissionDialogMode.CreateDocumentSDK30 -> CreateDocumentSDK30(
crossFadeTransition = crossFadeTransition,
onImageClick = alertDialogState::hide andThen callback
)
is WritePermissionDialog.WritePermissionDialogMode.OpenDocumentTreeSDK30 -> OpenDocumentTreeSDK30(
crossFadeTransition = crossFadeTransition,
onImageClick = alertDialogState::hide andThen callback,
path = writePermissionDialogMode.path
)
WritePermissionDialog.WritePermissionDialogMode.Otg -> OTG(crossFadeTransition)
WritePermissionDialog.WritePermissionDialogMode.SdCard -> SDCard(crossFadeTransition)
}
Spacer(Modifier.padding(vertical = SimpleTheme.dimens.padding.extraLarge))
}
TextButton(
onClick = alertDialogState::hide andThen callback,
modifier = Modifier
.padding(
top = SimpleTheme.dimens.padding.extraLarge,
bottom = SimpleTheme.dimens.padding.extraLarge,
end = SimpleTheme.dimens.padding.extraLarge
)
.align(Alignment.BottomEnd)
) {
Text(text = stringResource(id = R.string.ok))
}
}
}
}
}
@Composable
private fun CreateDocumentSDK30(crossFadeTransition: DrawableTransitionOptions, onImageClick: () -> Unit) {
WritePermissionText(stringResource(R.string.confirm_create_doc_for_new_folder_text).fromHtml())
WritePermissionImage(
crossFadeTransition = crossFadeTransition,
drawable = R.drawable.img_write_storage_create_doc_sdk_30,
modifier = Modifier.clickable(onClick = onImageClick)
)
}
@Composable
private fun OpenDocumentTreeSDK30(crossFadeTransition: DrawableTransitionOptions, onImageClick: () -> Unit, path: String) {
val context = LocalContext.current
val view = LocalView.current
val humanizedPath = remember { if (!view.isInEditMode) context.humanizePath(path) else "" }
WritePermissionText(stringResource(R.string.confirm_storage_access_android_text_specific, humanizedPath).fromHtml())
WritePermissionImage(
crossFadeTransition = crossFadeTransition,
drawable = R.drawable.img_write_storage_sdk_30,
modifier = Modifier.clickable(onClick = onImageClick)
)
}
@Composable
private fun SDCard(crossFadeTransition: DrawableTransitionOptions) {
WritePermissionText(R.string.confirm_storage_access_text)
WritePermissionImage(crossFadeTransition = crossFadeTransition, drawable = R.drawable.img_write_storage)
WritePermissionText(R.string.confirm_storage_access_text_sd)
WritePermissionImage(crossFadeTransition = crossFadeTransition, drawable = R.drawable.img_write_storage_sd)
}
@Composable
private fun OTG(
crossFadeTransition: DrawableTransitionOptions
) {
WritePermissionText(R.string.confirm_usb_storage_access_text)
WritePermissionImage(crossFadeTransition = crossFadeTransition, drawable = R.drawable.img_write_storage_otg)
}
@Composable
private fun WritePermissionImage(
modifier: Modifier = Modifier,
crossFadeTransition: DrawableTransitionOptions,
@DrawableRes drawable: Int
) {
GlideImage(
modifier = modifier
.padding(horizontal = SimpleTheme.dimens.padding.extraLarge.plus(SimpleTheme.dimens.padding.large)),
model = drawable,
contentDescription = null,
) { requestBuilder ->
requestBuilder.transition(crossFadeTransition)
}
}
@Composable
private fun WritePermissionText(@StringRes text: Int) {
Text(
text = stringResource(id = text),
color = dialogTextColor,
modifier = Modifier
.padding(horizontal = SimpleTheme.dimens.padding.extraLarge.plus(SimpleTheme.dimens.padding.medium))
.padding(vertical = SimpleTheme.dimens.padding.extraLarge),
)
}
@Composable
private fun WritePermissionText(text: Spanned) {
LinkifyTextComponent(
modifier = Modifier
.padding(horizontal = SimpleTheme.dimens.padding.extraLarge.plus(SimpleTheme.dimens.padding.medium))
.padding(vertical = SimpleTheme.dimens.padding.extraLarge),
) {
text
}
}
private fun adjustDialogTitle(
writePermissionDialogMode: WritePermissionDialog.WritePermissionDialogMode,
dialogTitle: Int
): Int =
when (writePermissionDialogMode) {
WritePermissionDialog.WritePermissionDialogMode.CreateDocumentSDK30 -> R.string.confirm_folder_access_title
is WritePermissionDialog.WritePermissionDialogMode.OpenDocumentTreeSDK30 -> R.string.confirm_folder_access_title
else -> dialogTitle
}
private class WritePermissionDialogModePreviewParameter : PreviewParameterProvider<WritePermissionDialog.WritePermissionDialogMode> {
override val values: Sequence<WritePermissionDialog.WritePermissionDialogMode>
get() = sequenceOf(
WritePermissionDialog.WritePermissionDialogMode.SdCard,
WritePermissionDialog.WritePermissionDialogMode.Otg,
WritePermissionDialog.WritePermissionDialogMode.CreateDocumentSDK30,
WritePermissionDialog.WritePermissionDialogMode.OpenDocumentTreeSDK30(""),
)
}
@Composable
@MyDevices
private fun WritePermissionAlertDialogPreview(@PreviewParameter(WritePermissionDialogModePreviewParameter::class) mode: WritePermissionDialog.WritePermissionDialogMode) {
AppThemeSurface {
WritePermissionAlertDialog(
alertDialogState = rememberAlertDialogState(),
writePermissionDialogMode = WritePermissionDialog.WritePermissionDialogMode.OpenDocumentTreeSDK30("."),
callback = {}
) {}
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/dialogs/WritePermissionDialog.kt | 3522413753 |
package com.simplemobiletools.commons.dialogs
import android.app.Activity
import android.text.Html
import android.text.method.LinkMovementMethod
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
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.size
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Lock
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.DialogProperties
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.compose.alert_dialog.*
import com.simplemobiletools.commons.compose.components.LinkifyTextComponent
import com.simplemobiletools.commons.compose.extensions.MyDevices
import com.simplemobiletools.commons.compose.extensions.composeDonateIntent
import com.simplemobiletools.commons.compose.extensions.rememberMutableInteractionSource
import com.simplemobiletools.commons.compose.theme.AppThemeSurface
import com.simplemobiletools.commons.compose.theme.SimpleTheme
import com.simplemobiletools.commons.databinding.DialogFeatureLockedBinding
import com.simplemobiletools.commons.extensions.*
class FeatureLockedDialog(val activity: Activity, val callback: () -> Unit) {
private var dialog: AlertDialog? = null
init {
val view = DialogFeatureLockedBinding.inflate(activity.layoutInflater, null, false)
view.featureLockedImage.applyColorFilter(activity.getProperTextColor())
activity.getAlertDialogBuilder()
.setPositiveButton(R.string.purchase, null)
.setNegativeButton(R.string.later) { _, _ -> dismissDialog() }
.setOnDismissListener { dismissDialog() }
.apply {
activity.setupDialogStuff(view.root, this, cancelOnTouchOutside = false) { alertDialog ->
dialog = alertDialog
view.featureLockedDescription.text = Html.fromHtml(activity.getString(R.string.features_locked))
view.featureLockedDescription.movementMethod = LinkMovementMethod.getInstance()
alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener {
activity.launchPurchaseThankYouIntent()
}
}
}
}
fun dismissDialog() {
dialog?.dismiss()
callback()
}
}
@Composable
fun FeatureLockedAlertDialog(
alertDialogState: AlertDialogState,
modifier: Modifier = Modifier,
cancelCallback: () -> Unit
) {
val donateIntent = composeDonateIntent()
androidx.compose.material3.AlertDialog(
containerColor = dialogContainerColor,
modifier = modifier
.dialogBorder,
properties = DialogProperties(dismissOnClickOutside = false, dismissOnBackPress = false),
onDismissRequest = cancelCallback,
shape = dialogShape,
tonalElevation = dialogElevation,
dismissButton = {
TextButton(onClick = {
cancelCallback()
alertDialogState.hide()
}) {
Text(text = stringResource(id = R.string.later))
}
},
confirmButton = {
TextButton(onClick = {
donateIntent()
}) {
Text(text = stringResource(id = R.string.purchase))
}
},
title = {
Box(
Modifier.fillMaxWidth(),
contentAlignment = Alignment.Center
) {
Image(
Icons.Filled.Lock,
contentDescription = null,
modifier = Modifier
.size(SimpleTheme.dimens.icon.large)
.clickable(
indication = null,
interactionSource = rememberMutableInteractionSource(),
onClick = {
donateIntent()
}
),
colorFilter = ColorFilter.tint(dialogTextColor)
)
}
},
text = {
val source = stringResource(id = R.string.features_locked)
LinkifyTextComponent(
fontSize = 16.sp,
removeUnderlines = false,
modifier = Modifier.fillMaxWidth(),
textAlignment = TextView.TEXT_ALIGNMENT_CENTER
) {
source.fromHtml()
}
}
)
}
@Composable
@MyDevices
private fun FeatureLockedAlertDialogPreview() {
AppThemeSurface {
FeatureLockedAlertDialog(alertDialogState = rememberAlertDialogState()) {
}
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/dialogs/FeatureLockedDialog.kt | 3708189089 |
package com.simplemobiletools.commons.dialogs
import android.content.ActivityNotFoundException
import android.content.Intent
import android.media.MediaPlayer
import android.net.Uri
import android.view.ViewGroup
import android.widget.RadioGroup
import androidx.appcompat.app.AlertDialog
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.activities.BaseSimpleActivity
import com.simplemobiletools.commons.databinding.DialogSelectAlarmSoundBinding
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.SILENT
import com.simplemobiletools.commons.models.AlarmSound
import com.simplemobiletools.commons.models.RadioItem
import com.simplemobiletools.commons.views.MyCompatRadioButton
class SelectAlarmSoundDialog(
val activity: BaseSimpleActivity, val currentUri: String, val audioStream: Int, val pickAudioIntentId: Int,
val type: Int, val loopAudio: Boolean, val onAlarmPicked: (alarmSound: AlarmSound?) -> Unit,
val onAlarmSoundDeleted: (alarmSound: AlarmSound) -> Unit
) {
private val ADD_NEW_SOUND_ID = -2
private val view = DialogSelectAlarmSoundBinding.inflate(activity.layoutInflater, null, false)
private var systemAlarmSounds = ArrayList<AlarmSound>()
private var yourAlarmSounds = ArrayList<AlarmSound>()
private var mediaPlayer: MediaPlayer? = null
private val config = activity.baseConfig
private var dialog: AlertDialog? = null
init {
activity.getAlarmSounds(type) {
systemAlarmSounds = it
gotSystemAlarms()
}
view.dialogSelectAlarmYourLabel.setTextColor(activity.getProperPrimaryColor())
view.dialogSelectAlarmSystemLabel.setTextColor(activity.getProperPrimaryColor())
addYourAlarms()
activity.getAlertDialogBuilder()
.setOnDismissListener { mediaPlayer?.stop() }
.setPositiveButton(R.string.ok) { _, _ -> dialogConfirmed() }
.setNegativeButton(R.string.cancel, null)
.apply {
activity.setupDialogStuff(view.root, this) { alertDialog ->
dialog = alertDialog
alertDialog.window?.volumeControlStream = audioStream
}
}
}
private fun addYourAlarms() {
view.dialogSelectAlarmYourRadio.removeAllViews()
val token = object : TypeToken<ArrayList<AlarmSound>>() {}.type
yourAlarmSounds = Gson().fromJson<ArrayList<AlarmSound>>(config.yourAlarmSounds, token) ?: ArrayList()
yourAlarmSounds.add(AlarmSound(ADD_NEW_SOUND_ID, activity.getString(R.string.add_new_sound), ""))
yourAlarmSounds.forEach {
addAlarmSound(it, view.dialogSelectAlarmYourRadio)
}
}
private fun gotSystemAlarms() {
systemAlarmSounds.forEach {
addAlarmSound(it, view.dialogSelectAlarmSystemRadio)
}
}
private fun addAlarmSound(alarmSound: AlarmSound, holder: ViewGroup) {
val radioButton = (activity.layoutInflater.inflate(R.layout.item_select_alarm_sound, null) as MyCompatRadioButton).apply {
text = alarmSound.title
isChecked = alarmSound.uri == currentUri
id = alarmSound.id
setColors(activity.getProperTextColor(), activity.getProperPrimaryColor(), activity.getProperBackgroundColor())
setOnClickListener {
alarmClicked(alarmSound)
if (holder == view.dialogSelectAlarmSystemRadio) {
view.dialogSelectAlarmYourRadio.clearCheck()
} else {
view.dialogSelectAlarmSystemRadio.clearCheck()
}
}
if (alarmSound.id != -2 && holder == view.dialogSelectAlarmYourRadio) {
setOnLongClickListener {
val items = arrayListOf(RadioItem(1, context.getString(R.string.remove)))
RadioGroupDialog(activity, items) {
removeAlarmSound(alarmSound)
}
true
}
}
}
holder.addView(radioButton, RadioGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT))
}
private fun alarmClicked(alarmSound: AlarmSound) {
when {
alarmSound.uri == SILENT -> mediaPlayer?.stop()
alarmSound.id == ADD_NEW_SOUND_ID -> {
val action = Intent.ACTION_OPEN_DOCUMENT
val intent = Intent(action).apply {
type = "audio/*"
flags = flags or Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION
}
try {
activity.startActivityForResult(intent, pickAudioIntentId)
} catch (e: ActivityNotFoundException) {
activity.toast(R.string.no_app_found)
}
dialog?.dismiss()
}
else -> try {
mediaPlayer?.reset()
if (mediaPlayer == null) {
mediaPlayer = MediaPlayer().apply {
setAudioStreamType(audioStream)
isLooping = loopAudio
}
}
mediaPlayer?.apply {
setDataSource(activity, Uri.parse(alarmSound.uri))
prepare()
start()
}
} catch (e: Exception) {
activity.showErrorToast(e)
}
}
}
private fun removeAlarmSound(alarmSound: AlarmSound) {
val token = object : TypeToken<ArrayList<AlarmSound>>() {}.type
yourAlarmSounds = Gson().fromJson<ArrayList<AlarmSound>>(config.yourAlarmSounds, token) ?: ArrayList()
yourAlarmSounds.remove(alarmSound)
config.yourAlarmSounds = Gson().toJson(yourAlarmSounds)
addYourAlarms()
if (alarmSound.id == view.dialogSelectAlarmYourRadio.checkedRadioButtonId) {
view.dialogSelectAlarmYourRadio.clearCheck()
view.dialogSelectAlarmSystemRadio.check(systemAlarmSounds.firstOrNull()?.id ?: 0)
}
onAlarmSoundDeleted(alarmSound)
}
private fun dialogConfirmed() {
if (view.dialogSelectAlarmYourRadio.checkedRadioButtonId != -1) {
val checkedId = view.dialogSelectAlarmYourRadio.checkedRadioButtonId
onAlarmPicked(yourAlarmSounds.firstOrNull { it.id == checkedId })
} else {
val checkedId = view.dialogSelectAlarmSystemRadio.checkedRadioButtonId
onAlarmPicked(systemAlarmSounds.firstOrNull { it.id == checkedId })
}
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/dialogs/SelectAlarmSoundDialog.kt | 1170821366 |
package com.simplemobiletools.commons.dialogs
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.sp
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.activities.BaseSimpleActivity
import com.simplemobiletools.commons.compose.alert_dialog.*
import com.simplemobiletools.commons.compose.extensions.MyDevices
import com.simplemobiletools.commons.compose.theme.AppThemeSurface
import com.simplemobiletools.commons.databinding.DialogOpenDeviceSettingsBinding
import com.simplemobiletools.commons.extensions.getAlertDialogBuilder
import com.simplemobiletools.commons.extensions.openDeviceSettings
import com.simplemobiletools.commons.extensions.setupDialogStuff
class OpenDeviceSettingsDialog(val activity: BaseSimpleActivity, message: String) {
init {
activity.apply {
val view = DialogOpenDeviceSettingsBinding.inflate(layoutInflater, null, false)
view.openDeviceSettings.text = message
getAlertDialogBuilder()
.setNegativeButton(R.string.close, null)
.setPositiveButton(R.string.go_to_settings) { _, _ ->
openDeviceSettings()
}.apply {
setupDialogStuff(view.root, this)
}
}
}
}
@Composable
fun OpenDeviceSettingsAlertDialog(
alertDialogState: AlertDialogState,
message: String,
modifier: Modifier = Modifier
) {
val context = LocalContext.current
AlertDialog(
containerColor = dialogContainerColor,
modifier = modifier
.dialogBorder,
onDismissRequest = alertDialogState::hide,
shape = dialogShape,
tonalElevation = dialogElevation,
text = {
Text(
fontSize = 16.sp,
text = message,
color = dialogTextColor
)
},
dismissButton = {
TextButton(onClick = alertDialogState::hide) {
Text(text = stringResource(id = R.string.close))
}
},
confirmButton = {
TextButton(onClick = {
context.openDeviceSettings()
alertDialogState.hide()
}) {
Text(text = stringResource(id = R.string.go_to_settings))
}
},
)
}
@Composable
@MyDevices
private fun OpenDeviceSettingsAlertDialogPreview() {
AppThemeSurface {
OpenDeviceSettingsAlertDialog(
alertDialogState = rememberAlertDialogState(),
message = "Test dialog"
)
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/dialogs/OpenDeviceSettingsDialog.kt | 1760600393 |
package com.simplemobiletools.commons.dialogs
import android.app.Activity
import androidx.appcompat.app.AlertDialog
import androidx.compose.animation.core.animateIntAsState
import androidx.compose.animation.core.tween
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Star
import androidx.compose.material.icons.filled.StarOutline
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment.Companion.CenterHorizontally
import androidx.compose.ui.Alignment.Companion.End
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.DialogProperties
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.compose.alert_dialog.AlertDialogState
import com.simplemobiletools.commons.compose.alert_dialog.DialogSurface
import com.simplemobiletools.commons.compose.alert_dialog.dialogTextColor
import com.simplemobiletools.commons.compose.alert_dialog.rememberAlertDialogState
import com.simplemobiletools.commons.compose.extensions.MyDevices
import com.simplemobiletools.commons.compose.theme.AppThemeSurface
import com.simplemobiletools.commons.compose.theme.Shapes
import com.simplemobiletools.commons.compose.theme.SimpleTheme
import com.simplemobiletools.commons.databinding.DialogRateStarsBinding
import com.simplemobiletools.commons.extensions.*
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
class RateStarsDialog(val activity: Activity) {
private var dialog: AlertDialog? = null
init {
val view = DialogRateStarsBinding.inflate(activity.layoutInflater, null, false).apply {
val primaryColor = activity.getProperPrimaryColor()
arrayOf(rateStar1, rateStar2, rateStar3, rateStar4, rateStar5).forEach {
it.applyColorFilter(primaryColor)
}
rateStar1.setOnClickListener { dialogCancelled(true) }
rateStar2.setOnClickListener { dialogCancelled(true) }
rateStar3.setOnClickListener { dialogCancelled(true) }
rateStar4.setOnClickListener { dialogCancelled(true) }
rateStar5.setOnClickListener {
activity.redirectToRateUs()
dialogCancelled(true)
}
}
activity.getAlertDialogBuilder()
.setNegativeButton(R.string.later) { _, _ -> dialogCancelled(false) }
.setOnCancelListener { dialogCancelled(false) }
.apply {
activity.setupDialogStuff(view.root, this, cancelOnTouchOutside = false) { alertDialog ->
dialog = alertDialog
}
}
}
private fun dialogCancelled(showThankYou: Boolean) {
dialog?.dismiss()
if (showThankYou) {
activity.toast(R.string.thank_you)
activity.baseConfig.wasAppRated = true
}
}
}
@Composable
fun RateStarsAlertDialog(
alertDialogState: AlertDialogState,
modifier: Modifier = Modifier,
onRating: (stars: Int) -> Unit
) {
AlertDialog(
onDismissRequest = alertDialogState::hide,
properties = DialogProperties(
dismissOnBackPress = false,
dismissOnClickOutside = false
),
modifier = modifier
) {
var currentRating by remember { mutableIntStateOf(0) }
val coroutineScope = rememberCoroutineScope()
DialogSurface {
Column {
Text(
text = stringResource(id = R.string.rate_our_app),
modifier = Modifier
.fillMaxWidth()
.padding(top = SimpleTheme.dimens.padding.extraLarge, bottom = SimpleTheme.dimens.padding.large),
textAlign = TextAlign.Center,
color = dialogTextColor,
fontSize = 16.sp
)
StarRating(
modifier = Modifier
.align(CenterHorizontally)
.padding(SimpleTheme.dimens.padding.extraLarge),
currentRating = currentRating,
onRatingChanged = { stars ->
currentRating = stars
coroutineScope.launch {
onRating(stars)
delay(500L)
alertDialogState.hide()
}
}
)
TextButton(
onClick = alertDialogState::hide,
modifier = Modifier
.align(End)
.padding(end = SimpleTheme.dimens.padding.extraLarge, bottom = SimpleTheme.dimens.padding.medium)
) {
Text(text = stringResource(id = R.string.later))
}
}
}
}
}
@Composable
private fun StarRating(
modifier: Modifier = Modifier,
maxRating: Int = 5,
currentRating: Int,
onRatingChanged: (Int) -> Unit,
starsColor: Color = SimpleTheme.colorScheme.primary,
) {
val animatedRating by animateIntAsState(
targetValue = currentRating,
label = "animatedRating",
animationSpec = tween()
)
Row(modifier) {
for (i in 1..maxRating) {
Icon(
imageVector = if (i <= animatedRating) Icons.Filled.Star
else Icons.Filled.StarOutline,
contentDescription = null,
tint = starsColor,
modifier = Modifier
.size(48.dp)
.clip(shape = Shapes.large)
.clickable { onRatingChanged(i) }
.padding(4.dp)
)
}
}
}
@Composable
@MyDevices
private fun RateStarsAlertDialogPreview() {
AppThemeSurface {
RateStarsAlertDialog(alertDialogState = rememberAlertDialogState(), onRating = {})
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/dialogs/RateStarsDialog.kt | 655117504 |
package com.simplemobiletools.commons.dialogs
import android.view.View
import androidx.appcompat.app.AlertDialog
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.activities.BaseSimpleActivity
import com.simplemobiletools.commons.compose.alert_dialog.*
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.databinding.DialogCreateNewFolderBinding
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.isRPlus
import java.io.File
class CreateNewFolderDialog(val activity: BaseSimpleActivity, val path: String, val callback: (path: String) -> Unit) {
init {
val view = DialogCreateNewFolderBinding.inflate(activity.layoutInflater, null, false)
view.folderPath.setText("${activity.humanizePath(path).trimEnd('/')}/")
activity.getAlertDialogBuilder()
.setPositiveButton(R.string.ok, null)
.setNegativeButton(R.string.cancel, null)
.apply {
activity.setupDialogStuff(view.root, this, R.string.create_new_folder) { alertDialog ->
alertDialog.showKeyboard(view.folderName)
alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(View.OnClickListener {
val name = view.folderName.value
when {
name.isEmpty() -> activity.toast(R.string.empty_name)
name.isAValidFilename() -> {
val file = File(path, name)
if (file.exists()) {
activity.toast(R.string.name_taken)
return@OnClickListener
}
createFolder("$path/$name", alertDialog)
}
else -> activity.toast(R.string.invalid_name)
}
})
}
}
}
private fun createFolder(path: String, alertDialog: AlertDialog) {
try {
when {
activity.isRestrictedSAFOnlyRoot(path) && activity.createAndroidSAFDirectory(path) -> sendSuccess(alertDialog, path)
activity.isAccessibleWithSAFSdk30(path) -> activity.handleSAFDialogSdk30(path) {
if (it && activity.createSAFDirectorySdk30(path)) {
sendSuccess(alertDialog, path)
}
}
activity.needsStupidWritePermissions(path) -> activity.handleSAFDialog(path) {
if (it) {
try {
val documentFile = activity.getDocumentFile(path.getParentPath())
val newDir = documentFile?.createDirectory(path.getFilenameFromPath()) ?: activity.getDocumentFile(path)
if (newDir != null) {
sendSuccess(alertDialog, path)
} else {
activity.toast(R.string.unknown_error_occurred)
}
} catch (e: SecurityException) {
activity.showErrorToast(e)
}
}
}
File(path).mkdirs() -> sendSuccess(alertDialog, path)
isRPlus() && activity.isAStorageRootFolder(path.getParentPath()) -> activity.handleSAFCreateDocumentDialogSdk30(path) {
if (it) {
sendSuccess(alertDialog, path)
}
}
else -> activity.toast(activity.getString(R.string.could_not_create_folder, path.getFilenameFromPath()))
}
} catch (e: Exception) {
activity.showErrorToast(e)
}
}
private fun sendSuccess(alertDialog: AlertDialog, path: String) {
callback(path.trimEnd('/'))
alertDialog.dismiss()
}
}
@Composable
fun CreateNewFolderAlertDialog(
alertDialogState: AlertDialogState,
path: String,
modifier: Modifier = Modifier,
callback: (path: String) -> Unit
) {
val focusRequester = remember { FocusRequester() }
val context = LocalContext.current
val view = LocalView.current
var title by remember { mutableStateOf("") }
AlertDialog(
modifier = modifier.dialogBorder,
shape = dialogShape,
containerColor = dialogContainerColor,
tonalElevation = dialogElevation,
onDismissRequest = alertDialogState::hide,
confirmButton = {
TextButton(
onClick = {
alertDialogState.hide()
//add callback
val name = title
when {
name.isEmpty() -> context.toast(R.string.empty_name)
name.isAValidFilename() -> {
val file = File(path, name)
if (file.exists()) {
context.toast(R.string.name_taken)
return@TextButton
}
callback("$path/$name")
}
else -> context.toast(R.string.invalid_name)
}
}
) {
Text(text = stringResource(id = R.string.ok))
}
},
dismissButton = {
TextButton(
onClick = alertDialogState::hide
) {
Text(text = stringResource(id = R.string.cancel))
}
},
title = {
Text(
text = stringResource(id = R.string.create_new_folder),
color = dialogTextColor,
fontSize = 21.sp,
fontWeight = FontWeight.Bold,
)
},
text = {
Column(
Modifier.fillMaxWidth(),
) {
OutlinedTextField(
modifier = Modifier
.fillMaxWidth(),
value = if (!view.isInEditMode) "${context.humanizePath(path).trimEnd('/')}/" else path,
onValueChange = {},
label = {
Text(text = stringResource(id = R.string.folder))
},
enabled = false,
colors = OutlinedTextFieldDefaults.colors(
disabledTextColor = dialogTextColor,
disabledBorderColor = SimpleTheme.colorScheme.primary,
disabledLabelColor = SimpleTheme.colorScheme.primary,
)
)
Spacer(modifier = Modifier.padding(vertical = SimpleTheme.dimens.padding.medium))
OutlinedTextField(
modifier = Modifier
.fillMaxWidth()
.focusRequester(focusRequester),
value = title,
onValueChange = {
title = it
},
label = {
Text(text = stringResource(id = R.string.title))
},
)
}
}
)
ShowKeyboardWhenDialogIsOpenedAndRequestFocus(focusRequester = focusRequester)
}
@MyDevices
@Composable
private fun CreateNewFolderAlertDialogPreview() {
AppThemeSurface {
CreateNewFolderAlertDialog(
alertDialogState = rememberAlertDialogState(),
path = "Internal/"
) {}
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/dialogs/CreateNewFolderDialog.kt | 407768629 |
package com.simplemobiletools.commons.dialogs
import android.app.Activity
import android.text.Html
import android.text.method.LinkMovementMethod
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.DialogProperties
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.compose.alert_dialog.*
import com.simplemobiletools.commons.compose.components.LinkifyTextComponent
import com.simplemobiletools.commons.compose.extensions.MyDevices
import com.simplemobiletools.commons.compose.extensions.composeDonateIntent
import com.simplemobiletools.commons.compose.extensions.config
import com.simplemobiletools.commons.compose.theme.AppThemeSurface
import com.simplemobiletools.commons.databinding.DialogPurchaseThankYouBinding
import com.simplemobiletools.commons.extensions.*
class PurchaseThankYouDialog(val activity: Activity) {
init {
val view = DialogPurchaseThankYouBinding.inflate(activity.layoutInflater, null, false).apply {
var text = activity.getString(R.string.purchase_thank_you)
if (activity.baseConfig.appId.removeSuffix(".debug").endsWith(".pro")) {
text += "<br><br>${activity.getString(R.string.shared_theme_note)}"
}
purchaseThankYou.text = Html.fromHtml(text)
purchaseThankYou.movementMethod = LinkMovementMethod.getInstance()
purchaseThankYou.removeUnderlines()
}
activity.getAlertDialogBuilder()
.setPositiveButton(R.string.purchase) { _, _ -> activity.launchPurchaseThankYouIntent() }
.setNegativeButton(R.string.later, null)
.apply {
activity.setupDialogStuff(view.root, this, cancelOnTouchOutside = false)
}
}
}
@Composable
fun PurchaseThankYouAlertDialog(
alertDialogState: AlertDialogState,
modifier: Modifier = Modifier,
) {
val localContext = LocalContext.current
val donateIntent = composeDonateIntent()
val appId = remember {
localContext.config.appId
}
androidx.compose.material3.AlertDialog(
containerColor = dialogContainerColor,
modifier = modifier
.dialogBorder,
properties = DialogProperties(dismissOnClickOutside = false, dismissOnBackPress = false),
onDismissRequest = {},
shape = dialogShape,
tonalElevation = dialogElevation,
dismissButton = {
TextButton(onClick = {
alertDialogState.hide()
}) {
Text(text = stringResource(id = R.string.later))
}
},
confirmButton = {
TextButton(onClick = {
donateIntent()
alertDialogState.hide()
}) {
Text(text = stringResource(id = R.string.purchase))
}
},
text = {
var text = stringResource(R.string.purchase_thank_you)
if (appId.removeSuffix(".debug").endsWith(".pro")) {
text += "<br><br>${stringResource(R.string.shared_theme_note)}"
}
LinkifyTextComponent(
fontSize = 16.sp,
removeUnderlines = false,
modifier = Modifier.fillMaxWidth()
) {
text.fromHtml()
}
}
)
}
@Composable
@MyDevices
private fun PurchaseThankYouAlertDialogPreview() {
AppThemeSurface {
PurchaseThankYouAlertDialog(alertDialogState = rememberAlertDialogState())
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/dialogs/PurchaseThankYouDialog.kt | 2163085355 |
package com.simplemobiletools.commons.dialogs
import android.app.Activity
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.compose.alert_dialog.*
import com.simplemobiletools.commons.compose.extensions.MyDevices
import com.simplemobiletools.commons.compose.extensions.andThen
import com.simplemobiletools.commons.compose.theme.AppThemeSurface
import com.simplemobiletools.commons.databinding.DialogTextviewBinding
import com.simplemobiletools.commons.extensions.baseConfig
import com.simplemobiletools.commons.extensions.getAlertDialogBuilder
import com.simplemobiletools.commons.extensions.setupDialogStuff
class FolderLockingNoticeDialog(val activity: Activity, val callback: () -> Unit) {
init {
val view = DialogTextviewBinding.inflate(activity.layoutInflater, null, false).apply {
textView.text = activity.getString(R.string.lock_folder_notice)
}
activity.getAlertDialogBuilder()
.setPositiveButton(R.string.ok) { _, _ -> dialogConfirmed() }
.setNegativeButton(R.string.cancel, null)
.apply {
activity.setupDialogStuff(view.root, this, R.string.disclaimer)
}
}
private fun dialogConfirmed() {
activity.baseConfig.wasFolderLockingNoticeShown = true
callback()
}
}
@Composable
fun FolderLockingNoticeAlertDialog(
alertDialogState: AlertDialogState,
modifier: Modifier = Modifier,
callback: () -> Unit
) {
AlertDialog(
modifier = modifier.dialogBorder,
shape = dialogShape,
containerColor = dialogContainerColor,
tonalElevation = dialogElevation,
onDismissRequest = alertDialogState::hide,
confirmButton = {
TextButton(
onClick = alertDialogState::hide andThen callback
) {
Text(text = stringResource(id = R.string.ok))
}
},
dismissButton = {
TextButton(
onClick = alertDialogState::hide
) {
Text(text = stringResource(id = R.string.cancel))
}
},
title = {
Text(
text = stringResource(id = R.string.disclaimer),
color = dialogTextColor,
fontSize = 21.sp,
fontWeight = FontWeight.Bold,
)
},
text = {
Text(
text = stringResource(id = R.string.lock_folder_notice),
color = dialogTextColor,
)
}
)
}
@Composable
@MyDevices
private fun FolderLockingNoticeAlertDialogPreview() {
AppThemeSurface {
FolderLockingNoticeAlertDialog(
alertDialogState = rememberAlertDialogState(),
callback = {},
)
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/dialogs/FolderLockingNoticeDialog.kt | 1632545098 |
package com.simplemobiletools.commons.dialogs
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.activities.BaseSimpleActivity
import com.simplemobiletools.commons.compose.alert_dialog.AlertDialogState
import com.simplemobiletools.commons.compose.alert_dialog.DialogSurface
import com.simplemobiletools.commons.compose.alert_dialog.rememberAlertDialogState
import com.simplemobiletools.commons.compose.components.RadioGroupDialogComponent
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.databinding.DialogChangeViewTypeBinding
import com.simplemobiletools.commons.extensions.baseConfig
import com.simplemobiletools.commons.extensions.getAlertDialogBuilder
import com.simplemobiletools.commons.extensions.setupDialogStuff
import com.simplemobiletools.commons.helpers.VIEW_TYPE_GRID
import com.simplemobiletools.commons.helpers.VIEW_TYPE_LIST
import kotlinx.collections.immutable.ImmutableList
import kotlinx.collections.immutable.toImmutableList
class ChangeViewTypeDialog(val activity: BaseSimpleActivity, val callback: () -> Unit) {
private var view: DialogChangeViewTypeBinding
private var config = activity.baseConfig
init {
view = DialogChangeViewTypeBinding.inflate(activity.layoutInflater, null, false).apply {
val viewToCheck = when (config.viewType) {
VIEW_TYPE_GRID -> changeViewTypeDialogRadioGrid.id
else -> changeViewTypeDialogRadioList.id
}
changeViewTypeDialogRadio.check(viewToCheck)
}
activity.getAlertDialogBuilder()
.setPositiveButton(R.string.ok) { _, _ -> dialogConfirmed() }
.setNegativeButton(R.string.cancel, null)
.apply {
activity.setupDialogStuff(view.root, this)
}
}
private fun dialogConfirmed() {
val viewType = if (view.changeViewTypeDialogRadioGrid.isChecked) {
VIEW_TYPE_GRID
} else {
VIEW_TYPE_LIST
}
config.viewType = viewType
callback()
}
}
@Immutable
data class ViewType(val title: String, val type: Int)
@Composable
fun ChangeViewTypeAlertDialog(
alertDialogState: AlertDialogState,
selectedViewType: Int,
modifier: Modifier = Modifier,
onTypeChosen: (type: Int) -> Unit
) {
val context = LocalContext.current
val items = remember {
listOf(
ViewType(title = context.getString(R.string.grid), type = VIEW_TYPE_GRID),
ViewType(title = context.getString(R.string.list), type = VIEW_TYPE_LIST)
).toImmutableList()
}
val groupTitles by remember {
derivedStateOf { items.map { it.title } }
}
val (selected, setSelected) = remember { mutableStateOf(items.firstOrNull { it.type == selectedViewType }?.title) }
AlertDialog(onDismissRequest = alertDialogState::hide) {
DialogSurface {
Column(
modifier = modifier
.padding(bottom = 18.dp)
.verticalScroll(rememberScrollState())
) {
RadioGroupDialogComponent(
items = groupTitles,
selected = selected,
setSelected = { selectedTitle ->
setSelected(selectedTitle)
},
modifier = Modifier.padding(
vertical = SimpleTheme.dimens.padding.extraLarge,
),
verticalPadding = SimpleTheme.dimens.padding.extraLarge,
)
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.End,
modifier = Modifier
.fillMaxWidth()
.padding(end = SimpleTheme.dimens.padding.extraLarge)
) {
TextButton(onClick = {
alertDialogState.hide()
}) {
Text(text = stringResource(id = R.string.cancel))
}
TextButton(onClick = {
alertDialogState.hide()
onTypeChosen(getSelectedValue(items, selected))
}) {
Text(text = stringResource(id = R.string.ok))
}
}
}
}
}
}
private fun getSelectedValue(
items: ImmutableList<ViewType>,
selected: String?
) = items.first { it.title == selected }.type
@MyDevices
@Composable
private fun ChangeViewTypeAlertDialogPreview() {
AppThemeSurface {
ChangeViewTypeAlertDialog(alertDialogState = rememberAlertDialogState(), selectedViewType = VIEW_TYPE_GRID) {}
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/dialogs/ChangeViewTypeDialog.kt | 3865782115 |
package com.simplemobiletools.commons.dialogs
import androidx.appcompat.app.AlertDialog
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.activities.BaseSimpleActivity
import com.simplemobiletools.commons.databinding.DialogExportSettingsBinding
import com.simplemobiletools.commons.extensions.*
class ExportSettingsDialog(
val activity: BaseSimpleActivity, val defaultFilename: String, val hidePath: Boolean,
callback: (path: String, filename: String) -> Unit
) {
init {
val lastUsedFolder = activity.baseConfig.lastExportedSettingsFolder
var folder = if (lastUsedFolder.isNotEmpty() && activity.getDoesFilePathExist(lastUsedFolder)) {
lastUsedFolder
} else {
activity.internalStoragePath
}
val view = DialogExportSettingsBinding.inflate(activity.layoutInflater, null, false).apply {
exportSettingsFilename.setText(defaultFilename.removeSuffix(".txt"))
if (hidePath) {
exportSettingsPathHint.beGone()
} else {
exportSettingsPath.setText(activity.humanizePath(folder))
exportSettingsPath.setOnClickListener {
FilePickerDialog(activity, folder, false, showFAB = true) {
exportSettingsPath.setText(activity.humanizePath(it))
folder = it
}
}
}
}
activity.getAlertDialogBuilder()
.setPositiveButton(R.string.ok, null)
.setNegativeButton(R.string.cancel, null)
.apply {
activity.setupDialogStuff(view.root, this, R.string.export_settings) { alertDialog ->
alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener {
var filename = view.exportSettingsFilename.value
if (filename.isEmpty()) {
activity.toast(R.string.filename_cannot_be_empty)
return@setOnClickListener
}
filename += ".txt"
val newPath = "${folder.trimEnd('/')}/$filename"
if (!newPath.getFilenameFromPath().isAValidFilename()) {
activity.toast(R.string.filename_invalid_characters)
return@setOnClickListener
}
activity.baseConfig.lastExportedSettingsFolder = folder
if (!hidePath && activity.getDoesFilePathExist(newPath)) {
val title = String.format(activity.getString(R.string.file_already_exists_overwrite), newPath.getFilenameFromPath())
ConfirmationDialog(activity, title) {
callback(newPath, filename)
alertDialog.dismiss()
}
} else {
callback(newPath, filename)
alertDialog.dismiss()
}
}
}
}
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/dialogs/ExportSettingsDialog.kt | 2808159124 |
package com.simplemobiletools.commons.activities
import android.animation.ArgbEvaluator
import android.animation.ValueAnimator
import android.annotation.SuppressLint
import android.app.Activity
import android.app.ActivityManager
import android.app.RecoverableSecurityException
import android.app.role.RoleManager
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.content.res.Configuration
import android.graphics.BitmapFactory
import android.graphics.Color
import android.graphics.PorterDuff
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.DocumentsContract
import android.provider.MediaStore
import android.provider.Settings
import android.telecom.TelecomManager
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.WindowManager
import android.widget.EditText
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.core.app.ActivityCompat
import androidx.core.util.Pair
import androidx.core.view.ScrollingView
import androidx.core.view.WindowInsetsCompat
import androidx.core.widget.NestedScrollView
import androidx.recyclerview.widget.RecyclerView
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.asynctasks.CopyMoveTask
import com.simplemobiletools.commons.compose.extensions.DEVELOPER_PLAY_STORE_URL
import com.simplemobiletools.commons.dialogs.*
import com.simplemobiletools.commons.dialogs.WritePermissionDialog.WritePermissionDialogMode
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.*
import com.simplemobiletools.commons.interfaces.CopyMoveListener
import com.simplemobiletools.commons.models.FAQItem
import com.simplemobiletools.commons.models.FileDirItem
import java.io.File
import java.io.OutputStream
import java.util.regex.Pattern
abstract class BaseSimpleActivity : AppCompatActivity() {
var materialScrollColorAnimation: ValueAnimator? = null
var copyMoveCallback: ((destinationPath: String) -> Unit)? = null
var actionOnPermission: ((granted: Boolean) -> Unit)? = null
var isAskingPermissions = false
var useDynamicTheme = true
var showTransparentTop = false
var isMaterialActivity = false // by material activity we mean translucent navigation bar and opaque status and action bars
var checkedDocumentPath = ""
var currentScrollY = 0
var configItemsToExport = LinkedHashMap<String, Any>()
private var mainCoordinatorLayout: CoordinatorLayout? = null
private var nestedView: View? = null
private var scrollingView: ScrollingView? = null
private var toolbar: Toolbar? = null
private var useTransparentNavigation = false
private var useTopSearchMenu = false
private val GENERIC_PERM_HANDLER = 100
private val DELETE_FILE_SDK_30_HANDLER = 300
private val RECOVERABLE_SECURITY_HANDLER = 301
private val UPDATE_FILE_SDK_30_HANDLER = 302
private val MANAGE_MEDIA_RC = 303
private val TRASH_FILE_SDK_30_HANDLER = 304
companion object {
var funAfterSAFPermission: ((success: Boolean) -> Unit)? = null
var funAfterSdk30Action: ((success: Boolean) -> Unit)? = null
var funAfterUpdate30File: ((success: Boolean) -> Unit)? = null
var funAfterTrash30File: ((success: Boolean) -> Unit)? = null
var funRecoverableSecurity: ((success: Boolean) -> Unit)? = null
var funAfterManageMediaPermission: (() -> Unit)? = null
}
abstract fun getAppIconIDs(): ArrayList<Int>
abstract fun getAppLauncherName(): String
override fun onCreate(savedInstanceState: Bundle?) {
if (useDynamicTheme) {
setTheme(getThemeId(showTransparentTop = showTransparentTop))
}
super.onCreate(savedInstanceState)
if (!packageName.startsWith("com.simplemobiletools.", true)) {
if ((0..50).random() == 10 || baseConfig.appRunCount % 100 == 0) {
val label = "You are using a fake version of the app. For your own safety download the original one from www.simplemobiletools.com. Thanks"
ConfirmationDialog(this, label, positive = R.string.ok, negative = 0) {
launchViewIntent(DEVELOPER_PLAY_STORE_URL)
}
}
}
}
@SuppressLint("NewApi")
override fun onResume() {
super.onResume()
if (useDynamicTheme) {
setTheme(getThemeId(showTransparentTop = showTransparentTop))
val backgroundColor = if (baseConfig.isUsingSystemTheme) {
resources.getColor(R.color.you_background_color, theme)
} else {
baseConfig.backgroundColor
}
updateBackgroundColor(backgroundColor)
}
if (showTransparentTop) {
window.statusBarColor = Color.TRANSPARENT
} else if (!isMaterialActivity) {
val color = if (baseConfig.isUsingSystemTheme) {
resources.getColor(R.color.you_status_bar_color)
} else {
getProperStatusBarColor()
}
updateActionbarColor(color)
}
updateRecentsAppIcon()
var navBarColor = getProperBackgroundColor()
if (isMaterialActivity) {
navBarColor = navBarColor.adjustAlpha(HIGHER_ALPHA)
}
updateNavigationBarColor(navBarColor)
}
override fun onDestroy() {
super.onDestroy()
funAfterSAFPermission = null
actionOnPermission = null
}
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
handleNavigationAndScrolling()
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> {
hideKeyboard()
finish()
}
else -> return super.onOptionsItemSelected(item)
}
return true
}
override fun attachBaseContext(newBase: Context) {
if (newBase.baseConfig.useEnglish && !isTiramisuPlus()) {
super.attachBaseContext(MyContextWrapper(newBase).wrap(newBase, "en"))
} else {
super.attachBaseContext(newBase)
}
}
fun updateBackgroundColor(color: Int = baseConfig.backgroundColor) {
window.decorView.setBackgroundColor(color)
}
fun updateStatusbarColor(color: Int) {
window.statusBarColor = color
if (color.getContrastColor() == DARK_GREY) {
window.decorView.systemUiVisibility = window.decorView.systemUiVisibility.addBit(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR)
} else {
window.decorView.systemUiVisibility = window.decorView.systemUiVisibility.removeBit(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR)
}
}
fun updateActionbarColor(color: Int = getProperStatusBarColor()) {
updateStatusbarColor(color)
setTaskDescription(ActivityManager.TaskDescription(null, null, color))
}
fun updateNavigationBarColor(color: Int) {
window.navigationBarColor = color
updateNavigationBarButtons(color)
}
fun updateNavigationBarButtons(color: Int) {
if (isOreoPlus()) {
if (color.getContrastColor() == DARK_GREY) {
window.decorView.systemUiVisibility = window.decorView.systemUiVisibility.addBit(View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR)
} else {
window.decorView.systemUiVisibility = window.decorView.systemUiVisibility.removeBit(View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR)
}
}
}
// use translucent navigation bar, set the background color to action and status bars
fun updateMaterialActivityViews(
mainCoordinatorLayout: CoordinatorLayout?,
nestedView: View?,
useTransparentNavigation: Boolean,
useTopSearchMenu: Boolean,
) {
this.mainCoordinatorLayout = mainCoordinatorLayout
this.nestedView = nestedView
this.useTransparentNavigation = useTransparentNavigation
this.useTopSearchMenu = useTopSearchMenu
handleNavigationAndScrolling()
val backgroundColor = getProperBackgroundColor()
updateStatusbarColor(backgroundColor)
updateActionbarColor(backgroundColor)
}
private fun handleNavigationAndScrolling() {
if (useTransparentNavigation) {
if (navigationBarHeight > 0 || isUsingGestureNavigation()) {
window.decorView.systemUiVisibility = window.decorView.systemUiVisibility.addBit(View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION)
updateTopBottomInsets(statusBarHeight, navigationBarHeight)
// Don't touch this. Window Inset API often has a domino effect and things will most likely break.
onApplyWindowInsets {
val insets = it.getInsets(WindowInsetsCompat.Type.systemBars() or WindowInsetsCompat.Type.ime())
updateTopBottomInsets(insets.top, insets.bottom)
}
} else {
window.decorView.systemUiVisibility = window.decorView.systemUiVisibility.removeBit(View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION)
updateTopBottomInsets(0, 0)
}
}
}
private fun updateTopBottomInsets(top: Int, bottom: Int) {
nestedView?.run {
setPadding(paddingLeft, paddingTop, paddingRight, bottom)
}
(mainCoordinatorLayout?.layoutParams as? FrameLayout.LayoutParams)?.topMargin = top
}
// colorize the top toolbar and statusbar at scrolling down a bit
fun setupMaterialScrollListener(scrollingView: ScrollingView?, toolbar: Toolbar) {
this.scrollingView = scrollingView
this.toolbar = toolbar
if (scrollingView is RecyclerView) {
scrollingView.setOnScrollChangeListener { v, scrollX, scrollY, oldScrollX, oldScrollY ->
val newScrollY = scrollingView.computeVerticalScrollOffset()
scrollingChanged(newScrollY, currentScrollY)
currentScrollY = newScrollY
}
} else if (scrollingView is NestedScrollView) {
scrollingView.setOnScrollChangeListener { v, scrollX, scrollY, oldScrollX, oldScrollY ->
scrollingChanged(scrollY, oldScrollY)
}
}
}
private fun scrollingChanged(newScrollY: Int, oldScrollY: Int) {
if (newScrollY > 0 && oldScrollY == 0) {
val colorFrom = window.statusBarColor
val colorTo = getColoredMaterialStatusBarColor()
animateTopBarColors(colorFrom, colorTo)
} else if (newScrollY == 0 && oldScrollY > 0) {
val colorFrom = window.statusBarColor
val colorTo = getRequiredStatusBarColor()
animateTopBarColors(colorFrom, colorTo)
}
}
fun animateTopBarColors(colorFrom: Int, colorTo: Int) {
if (toolbar == null) {
return
}
materialScrollColorAnimation?.end()
materialScrollColorAnimation = ValueAnimator.ofObject(ArgbEvaluator(), colorFrom, colorTo)
materialScrollColorAnimation!!.addUpdateListener { animator ->
val color = animator.animatedValue as Int
if (toolbar != null) {
updateTopBarColors(toolbar!!, color)
}
}
materialScrollColorAnimation!!.start()
}
fun getRequiredStatusBarColor(): Int {
return if ((scrollingView is RecyclerView || scrollingView is NestedScrollView) && scrollingView?.computeVerticalScrollOffset() == 0) {
getProperBackgroundColor()
} else {
getColoredMaterialStatusBarColor()
}
}
fun updateTopBarColors(toolbar: Toolbar, color: Int) {
val contrastColor = if (useTopSearchMenu) {
getProperBackgroundColor().getContrastColor()
} else {
color.getContrastColor()
}
if (!useTopSearchMenu) {
updateStatusbarColor(color)
toolbar.setBackgroundColor(color)
toolbar.setTitleTextColor(contrastColor)
toolbar.navigationIcon?.applyColorFilter(contrastColor)
toolbar.collapseIcon = resources.getColoredDrawableWithColor(R.drawable.ic_arrow_left_vector, contrastColor)
}
toolbar.overflowIcon = resources.getColoredDrawableWithColor(R.drawable.ic_three_dots_vector, contrastColor)
val menu = toolbar.menu
for (i in 0 until menu.size()) {
try {
menu.getItem(i)?.icon?.setTint(contrastColor)
} catch (ignored: Exception) {
}
}
}
fun updateStatusBarOnPageChange() {
if (scrollingView is RecyclerView || scrollingView is NestedScrollView) {
val scrollY = scrollingView!!.computeVerticalScrollOffset()
val colorFrom = window.statusBarColor
val colorTo = if (scrollY > 0) {
getColoredMaterialStatusBarColor()
} else {
getRequiredStatusBarColor()
}
animateTopBarColors(colorFrom, colorTo)
currentScrollY = scrollY
}
}
fun setupToolbar(
toolbar: Toolbar,
toolbarNavigationIcon: NavigationIcon = NavigationIcon.None,
statusBarColor: Int = getRequiredStatusBarColor(),
searchMenuItem: MenuItem? = null
) {
val contrastColor = statusBarColor.getContrastColor()
if (toolbarNavigationIcon != NavigationIcon.None) {
val drawableId = if (toolbarNavigationIcon == NavigationIcon.Cross) R.drawable.ic_cross_vector else R.drawable.ic_arrow_left_vector
toolbar.navigationIcon = resources.getColoredDrawableWithColor(drawableId, contrastColor)
toolbar.setNavigationContentDescription(toolbarNavigationIcon.accessibilityResId)
}
toolbar.setNavigationOnClickListener {
hideKeyboard()
finish()
}
updateTopBarColors(toolbar, statusBarColor)
if (!useTopSearchMenu) {
searchMenuItem?.actionView?.findViewById<ImageView>(androidx.appcompat.R.id.search_close_btn)?.apply {
applyColorFilter(contrastColor)
}
searchMenuItem?.actionView?.findViewById<EditText>(androidx.appcompat.R.id.search_src_text)?.apply {
setTextColor(contrastColor)
setHintTextColor(contrastColor.adjustAlpha(MEDIUM_ALPHA))
hint = "${getString(R.string.search)}…"
if (isQPlus()) {
textCursorDrawable = null
}
}
// search underline
searchMenuItem?.actionView?.findViewById<View>(androidx.appcompat.R.id.search_plate)?.apply {
background.setColorFilter(contrastColor, PorterDuff.Mode.MULTIPLY)
}
}
}
fun updateRecentsAppIcon() {
if (baseConfig.isUsingModifiedAppIcon) {
val appIconIDs = getAppIconIDs()
val currentAppIconColorIndex = getCurrentAppIconColorIndex()
if (appIconIDs.size - 1 < currentAppIconColorIndex) {
return
}
val recentsIcon = BitmapFactory.decodeResource(resources, appIconIDs[currentAppIconColorIndex])
val title = getAppLauncherName()
val color = baseConfig.primaryColor
val description = ActivityManager.TaskDescription(title, recentsIcon, color)
setTaskDescription(description)
}
}
fun updateMenuItemColors(menu: Menu?, baseColor: Int = getProperStatusBarColor(), forceWhiteIcons: Boolean = false) {
if (menu == null) {
return
}
var color = baseColor.getContrastColor()
if (forceWhiteIcons) {
color = Color.WHITE
}
for (i in 0 until menu.size()) {
try {
menu.getItem(i)?.icon?.setTint(color)
} catch (ignored: Exception) {
}
}
}
private fun getCurrentAppIconColorIndex(): Int {
val appIconColor = baseConfig.appIconColor
getAppIconColors().forEachIndexed { index, color ->
if (color == appIconColor) {
return index
}
}
return 0
}
fun setTranslucentNavigation() {
window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION, WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, resultData: Intent?) {
super.onActivityResult(requestCode, resultCode, resultData)
val partition = try {
checkedDocumentPath.substring(9, 18)
} catch (e: Exception) {
""
}
val sdOtgPattern = Pattern.compile(SD_OTG_SHORT)
if (requestCode == CREATE_DOCUMENT_SDK_30) {
if (resultCode == Activity.RESULT_OK && resultData != null && resultData.data != null) {
val treeUri = resultData.data
val checkedUri = buildDocumentUriSdk30(checkedDocumentPath)
if (treeUri != checkedUri) {
toast(getString(R.string.wrong_folder_selected, checkedDocumentPath))
return
}
val takeFlags = Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION
applicationContext.contentResolver.takePersistableUriPermission(treeUri, takeFlags)
val funAfter = funAfterSdk30Action
funAfterSdk30Action = null
funAfter?.invoke(true)
} else {
funAfterSdk30Action?.invoke(false)
}
} else if (requestCode == OPEN_DOCUMENT_TREE_FOR_SDK_30) {
if (resultCode == Activity.RESULT_OK && resultData != null && resultData.data != null) {
val treeUri = resultData.data
val checkedUri = createFirstParentTreeUri(checkedDocumentPath)
if (treeUri != checkedUri) {
val level = getFirstParentLevel(checkedDocumentPath)
val firstParentPath = checkedDocumentPath.getFirstParentPath(this, level)
toast(getString(R.string.wrong_folder_selected, humanizePath(firstParentPath)))
return
}
val takeFlags = Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION
applicationContext.contentResolver.takePersistableUriPermission(treeUri, takeFlags)
val funAfter = funAfterSdk30Action
funAfterSdk30Action = null
funAfter?.invoke(true)
} else {
funAfterSdk30Action?.invoke(false)
}
} else if (requestCode == OPEN_DOCUMENT_TREE_FOR_ANDROID_DATA_OR_OBB) {
if (resultCode == Activity.RESULT_OK && resultData != null && resultData.data != null) {
if (isProperAndroidRoot(checkedDocumentPath, resultData.data!!)) {
if (resultData.dataString == baseConfig.OTGTreeUri || resultData.dataString == baseConfig.sdTreeUri) {
val pathToSelect = createAndroidDataOrObbPath(checkedDocumentPath)
toast(getString(R.string.wrong_folder_selected, pathToSelect))
return
}
val treeUri = resultData.data
storeAndroidTreeUri(checkedDocumentPath, treeUri.toString())
val takeFlags = Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION
applicationContext.contentResolver.takePersistableUriPermission(treeUri!!, takeFlags)
funAfterSAFPermission?.invoke(true)
funAfterSAFPermission = null
} else {
toast(getString(R.string.wrong_folder_selected, createAndroidDataOrObbPath(checkedDocumentPath)))
Intent(Intent.ACTION_OPEN_DOCUMENT_TREE).apply {
if (isRPlus()) {
putExtra(DocumentsContract.EXTRA_INITIAL_URI, createAndroidDataOrObbUri(checkedDocumentPath))
}
try {
startActivityForResult(this, requestCode)
} catch (e: Exception) {
showErrorToast(e)
}
}
}
} else {
funAfterSAFPermission?.invoke(false)
}
} else if (requestCode == OPEN_DOCUMENT_TREE_SD) {
if (resultCode == Activity.RESULT_OK && resultData != null && resultData.data != null) {
val isProperPartition = partition.isEmpty() || !sdOtgPattern.matcher(partition).matches() || (sdOtgPattern.matcher(partition)
.matches() && resultData.dataString!!.contains(partition))
if (isProperSDRootFolder(resultData.data!!) && isProperPartition) {
if (resultData.dataString == baseConfig.OTGTreeUri) {
toast(R.string.sd_card_usb_same)
return
}
saveTreeUri(resultData)
funAfterSAFPermission?.invoke(true)
funAfterSAFPermission = null
} else {
toast(R.string.wrong_root_selected)
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT_TREE)
try {
startActivityForResult(intent, requestCode)
} catch (e: Exception) {
showErrorToast(e)
}
}
} else {
funAfterSAFPermission?.invoke(false)
}
} else if (requestCode == OPEN_DOCUMENT_TREE_OTG) {
if (resultCode == Activity.RESULT_OK && resultData != null && resultData.data != null) {
val isProperPartition = partition.isEmpty() || !sdOtgPattern.matcher(partition).matches() || (sdOtgPattern.matcher(partition)
.matches() && resultData.dataString!!.contains(partition))
if (isProperOTGRootFolder(resultData.data!!) && isProperPartition) {
if (resultData.dataString == baseConfig.sdTreeUri) {
funAfterSAFPermission?.invoke(false)
toast(R.string.sd_card_usb_same)
return
}
baseConfig.OTGTreeUri = resultData.dataString!!
baseConfig.OTGPartition = baseConfig.OTGTreeUri.removeSuffix("%3A").substringAfterLast('/').trimEnd('/')
updateOTGPathFromPartition()
val takeFlags = Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION
applicationContext.contentResolver.takePersistableUriPermission(resultData.data!!, takeFlags)
funAfterSAFPermission?.invoke(true)
funAfterSAFPermission = null
} else {
toast(R.string.wrong_root_selected_usb)
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT_TREE)
try {
startActivityForResult(intent, requestCode)
} catch (e: Exception) {
showErrorToast(e)
}
}
} else {
funAfterSAFPermission?.invoke(false)
}
} else if (requestCode == SELECT_EXPORT_SETTINGS_FILE_INTENT && resultCode == Activity.RESULT_OK && resultData != null && resultData.data != null) {
val outputStream = contentResolver.openOutputStream(resultData.data!!)
exportSettingsTo(outputStream, configItemsToExport)
} else if (requestCode == DELETE_FILE_SDK_30_HANDLER) {
funAfterSdk30Action?.invoke(resultCode == Activity.RESULT_OK)
} else if (requestCode == RECOVERABLE_SECURITY_HANDLER) {
funRecoverableSecurity?.invoke(resultCode == Activity.RESULT_OK)
funRecoverableSecurity = null
} else if (requestCode == UPDATE_FILE_SDK_30_HANDLER) {
funAfterUpdate30File?.invoke(resultCode == Activity.RESULT_OK)
} else if (requestCode == MANAGE_MEDIA_RC) {
funAfterManageMediaPermission?.invoke()
} else if (requestCode == TRASH_FILE_SDK_30_HANDLER) {
funAfterTrash30File?.invoke(resultCode == Activity.RESULT_OK)
}
}
private fun saveTreeUri(resultData: Intent) {
val treeUri = resultData.data
baseConfig.sdTreeUri = treeUri.toString()
val takeFlags = Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION
applicationContext.contentResolver.takePersistableUriPermission(treeUri!!, takeFlags)
}
private fun isProperSDRootFolder(uri: Uri) = isExternalStorageDocument(uri) && isRootUri(uri) && !isInternalStorage(uri)
private fun isProperSDFolder(uri: Uri) = isExternalStorageDocument(uri) && !isInternalStorage(uri)
private fun isProperOTGRootFolder(uri: Uri) = isExternalStorageDocument(uri) && isRootUri(uri) && !isInternalStorage(uri)
private fun isProperOTGFolder(uri: Uri) = isExternalStorageDocument(uri) && !isInternalStorage(uri)
private fun isRootUri(uri: Uri) = uri.lastPathSegment?.endsWith(":") ?: false
private fun isInternalStorage(uri: Uri) = isExternalStorageDocument(uri) && DocumentsContract.getTreeDocumentId(uri).contains("primary")
private fun isAndroidDir(uri: Uri) = isExternalStorageDocument(uri) && DocumentsContract.getTreeDocumentId(uri).contains(":Android")
private fun isInternalStorageAndroidDir(uri: Uri) = isInternalStorage(uri) && isAndroidDir(uri)
private fun isOTGAndroidDir(uri: Uri) = isProperOTGFolder(uri) && isAndroidDir(uri)
private fun isSDAndroidDir(uri: Uri) = isProperSDFolder(uri) && isAndroidDir(uri)
private fun isExternalStorageDocument(uri: Uri) = EXTERNAL_STORAGE_PROVIDER_AUTHORITY == uri.authority
private fun isProperAndroidRoot(path: String, uri: Uri): Boolean {
return when {
isPathOnOTG(path) -> isOTGAndroidDir(uri)
isPathOnSD(path) -> isSDAndroidDir(uri)
else -> isInternalStorageAndroidDir(uri)
}
}
fun startAboutActivity(appNameId: Int, licenseMask: Long, versionName: String, faqItems: ArrayList<FAQItem>, showFAQBeforeMail: Boolean) {
hideKeyboard()
Intent(applicationContext, AboutActivity::class.java).apply {
putExtra(APP_ICON_IDS, getAppIconIDs())
putExtra(APP_LAUNCHER_NAME, getAppLauncherName())
putExtra(APP_NAME, getString(appNameId))
putExtra(APP_LICENSES, licenseMask)
putExtra(APP_VERSION_NAME, versionName)
putExtra(APP_FAQ, faqItems)
putExtra(SHOW_FAQ_BEFORE_MAIL, showFAQBeforeMail)
startActivity(this)
}
}
fun startCustomizationActivity() {
if (!packageName.contains("slootelibomelpmis".reversed(), true)) {
if (baseConfig.appRunCount > 100) {
val label = "You are using a fake version of the app. For your own safety download the original one from www.simplemobiletools.com. Thanks"
ConfirmationDialog(this, label, positive = R.string.ok, negative = 0) {
launchViewIntent(DEVELOPER_PLAY_STORE_URL)
}
return
}
}
Intent(applicationContext, CustomizationActivity::class.java).apply {
putExtra(APP_ICON_IDS, getAppIconIDs())
putExtra(APP_LAUNCHER_NAME, getAppLauncherName())
startActivity(this)
}
}
fun handleCustomizeColorsClick() {
if (isOrWasThankYouInstalled()) {
startCustomizationActivity()
} else {
FeatureLockedDialog(this) {}
}
}
@RequiresApi(Build.VERSION_CODES.O)
fun launchCustomizeNotificationsIntent() {
Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS).apply {
putExtra(Settings.EXTRA_APP_PACKAGE, packageName)
startActivity(this)
}
}
@RequiresApi(Build.VERSION_CODES.TIRAMISU)
fun launchChangeAppLanguageIntent() {
try {
Intent(Settings.ACTION_APP_LOCALE_SETTINGS).apply {
data = Uri.fromParts("package", packageName, null)
startActivity(this)
}
} catch (e: Exception) {
openDeviceSettings()
}
}
// synchronous return value determines only if we are showing the SAF dialog, callback result tells if the SD or OTG permission has been granted
fun handleSAFDialog(path: String, callback: (success: Boolean) -> Unit): Boolean {
hideKeyboard()
return if (!packageName.startsWith("com.simplemobiletools")) {
callback(true)
false
} else if (isShowingSAFDialog(path) || isShowingOTGDialog(path)) {
funAfterSAFPermission = callback
true
} else {
callback(true)
false
}
}
fun handleSAFDialogSdk30(path: String, callback: (success: Boolean) -> Unit): Boolean {
hideKeyboard()
return if (!packageName.startsWith("com.simplemobiletools")) {
callback(true)
false
} else if (isShowingSAFDialogSdk30(path)) {
funAfterSdk30Action = callback
true
} else {
callback(true)
false
}
}
fun checkManageMediaOrHandleSAFDialogSdk30(path: String, callback: (success: Boolean) -> Unit): Boolean {
hideKeyboard()
return if (canManageMedia()) {
callback(true)
false
} else {
handleSAFDialogSdk30(path, callback)
}
}
fun handleSAFCreateDocumentDialogSdk30(path: String, callback: (success: Boolean) -> Unit): Boolean {
hideKeyboard()
return if (!packageName.startsWith("com.simplemobiletools")) {
callback(true)
false
} else if (isShowingSAFCreateDocumentDialogSdk30(path)) {
funAfterSdk30Action = callback
true
} else {
callback(true)
false
}
}
fun handleAndroidSAFDialog(path: String, callback: (success: Boolean) -> Unit): Boolean {
hideKeyboard()
return if (!packageName.startsWith("com.simplemobiletools")) {
callback(true)
false
} else if (isShowingAndroidSAFDialog(path)) {
funAfterSAFPermission = callback
true
} else {
callback(true)
false
}
}
fun handleOTGPermission(callback: (success: Boolean) -> Unit) {
hideKeyboard()
if (baseConfig.OTGTreeUri.isNotEmpty()) {
callback(true)
return
}
funAfterSAFPermission = callback
WritePermissionDialog(this, WritePermissionDialogMode.Otg) {
Intent(Intent.ACTION_OPEN_DOCUMENT_TREE).apply {
try {
startActivityForResult(this, OPEN_DOCUMENT_TREE_OTG)
return@apply
} catch (e: Exception) {
type = "*/*"
}
try {
startActivityForResult(this, OPEN_DOCUMENT_TREE_OTG)
} catch (e: ActivityNotFoundException) {
toast(R.string.system_service_disabled, Toast.LENGTH_LONG)
} catch (e: Exception) {
toast(R.string.unknown_error_occurred)
}
}
}
}
@SuppressLint("NewApi")
fun deleteSDK30Uris(uris: List<Uri>, callback: (success: Boolean) -> Unit) {
hideKeyboard()
if (isRPlus()) {
funAfterSdk30Action = callback
try {
val deleteRequest = MediaStore.createDeleteRequest(contentResolver, uris).intentSender
startIntentSenderForResult(deleteRequest, DELETE_FILE_SDK_30_HANDLER, null, 0, 0, 0)
} catch (e: Exception) {
showErrorToast(e)
}
} else {
callback(false)
}
}
@SuppressLint("NewApi")
fun trashSDK30Uris(uris: List<Uri>, toTrash: Boolean, callback: (success: Boolean) -> Unit) {
hideKeyboard()
if (isRPlus()) {
funAfterTrash30File = callback
try {
val trashRequest = MediaStore.createTrashRequest(contentResolver, uris, toTrash).intentSender
startIntentSenderForResult(trashRequest, TRASH_FILE_SDK_30_HANDLER, null, 0, 0, 0)
} catch (e: Exception) {
showErrorToast(e)
}
} else {
callback(false)
}
}
@SuppressLint("NewApi")
fun updateSDK30Uris(uris: List<Uri>, callback: (success: Boolean) -> Unit) {
hideKeyboard()
if (isRPlus()) {
funAfterUpdate30File = callback
try {
val writeRequest = MediaStore.createWriteRequest(contentResolver, uris).intentSender
startIntentSenderForResult(writeRequest, UPDATE_FILE_SDK_30_HANDLER, null, 0, 0, 0)
} catch (e: Exception) {
showErrorToast(e)
}
} else {
callback(false)
}
}
@SuppressLint("NewApi")
fun handleRecoverableSecurityException(callback: (success: Boolean) -> Unit) {
try {
callback.invoke(true)
} catch (securityException: SecurityException) {
if (isQPlus()) {
funRecoverableSecurity = callback
val recoverableSecurityException = securityException as? RecoverableSecurityException ?: throw securityException
val intentSender = recoverableSecurityException.userAction.actionIntent.intentSender
startIntentSenderForResult(intentSender, RECOVERABLE_SECURITY_HANDLER, null, 0, 0, 0)
} else {
callback(false)
}
}
}
@RequiresApi(Build.VERSION_CODES.S)
fun launchMediaManagementIntent(callback: () -> Unit) {
Intent(Settings.ACTION_REQUEST_MANAGE_MEDIA).apply {
data = Uri.parse("package:$packageName")
try {
startActivityForResult(this, MANAGE_MEDIA_RC)
} catch (e: Exception) {
showErrorToast(e)
}
}
funAfterManageMediaPermission = callback
}
fun copyMoveFilesTo(
fileDirItems: ArrayList<FileDirItem>, source: String, destination: String, isCopyOperation: Boolean, copyPhotoVideoOnly: Boolean,
copyHidden: Boolean, callback: (destinationPath: String) -> Unit
) {
if (source == destination) {
toast(R.string.source_and_destination_same)
return
}
if (!getDoesFilePathExist(destination)) {
toast(R.string.invalid_destination)
return
}
handleSAFDialog(destination) {
if (!it) {
copyMoveListener.copyFailed()
return@handleSAFDialog
}
handleSAFDialogSdk30(destination) {
if (!it) {
copyMoveListener.copyFailed()
return@handleSAFDialogSdk30
}
copyMoveCallback = callback
var fileCountToCopy = fileDirItems.size
if (isCopyOperation) {
val recycleBinPath = fileDirItems.first().isRecycleBinPath(this)
if (canManageMedia() && !recycleBinPath) {
val fileUris = getFileUrisFromFileDirItems(fileDirItems)
updateSDK30Uris(fileUris) { sdk30UriSuccess ->
if (sdk30UriSuccess) {
startCopyMove(fileDirItems, destination, isCopyOperation, copyPhotoVideoOnly, copyHidden)
}
}
} else {
startCopyMove(fileDirItems, destination, isCopyOperation, copyPhotoVideoOnly, copyHidden)
}
} else {
if (isPathOnOTG(source) || isPathOnOTG(destination) || isPathOnSD(source) || isPathOnSD(destination) ||
isRestrictedSAFOnlyRoot(source) || isRestrictedSAFOnlyRoot(destination) ||
isAccessibleWithSAFSdk30(source) || isAccessibleWithSAFSdk30(destination) ||
fileDirItems.first().isDirectory
) {
handleSAFDialog(source) { safSuccess ->
if (safSuccess) {
val recycleBinPath = fileDirItems.first().isRecycleBinPath(this)
if (canManageMedia() && !recycleBinPath) {
val fileUris = getFileUrisFromFileDirItems(fileDirItems)
updateSDK30Uris(fileUris) { sdk30UriSuccess ->
if (sdk30UriSuccess) {
startCopyMove(fileDirItems, destination, isCopyOperation, copyPhotoVideoOnly, copyHidden)
}
}
} else {
startCopyMove(fileDirItems, destination, isCopyOperation, copyPhotoVideoOnly, copyHidden)
}
}
}
} else {
try {
checkConflicts(fileDirItems, destination, 0, LinkedHashMap()) {
toast(R.string.moving)
ensureBackgroundThread {
val updatedPaths = ArrayList<String>(fileDirItems.size)
val destinationFolder = File(destination)
for (oldFileDirItem in fileDirItems) {
var newFile = File(destinationFolder, oldFileDirItem.name)
if (newFile.exists()) {
when {
getConflictResolution(it, newFile.absolutePath) == CONFLICT_SKIP -> fileCountToCopy--
getConflictResolution(it, newFile.absolutePath) == CONFLICT_KEEP_BOTH -> newFile = getAlternativeFile(newFile)
else ->
// this file is guaranteed to be on the internal storage, so just delete it this way
newFile.delete()
}
}
if (!newFile.exists() && File(oldFileDirItem.path).renameTo(newFile)) {
if (!baseConfig.keepLastModified) {
newFile.setLastModified(System.currentTimeMillis())
}
updatedPaths.add(newFile.absolutePath)
deleteFromMediaStore(oldFileDirItem.path)
}
}
runOnUiThread {
if (updatedPaths.isEmpty()) {
copyMoveListener.copySucceeded(false, fileCountToCopy == 0, destination, false)
} else {
copyMoveListener.copySucceeded(false, fileCountToCopy <= updatedPaths.size, destination, updatedPaths.size == 1)
}
}
}
}
} catch (e: Exception) {
showErrorToast(e)
}
}
}
}
}
}
fun getAlternativeFile(file: File): File {
var fileIndex = 1
var newFile: File?
do {
val newName = String.format("%s(%d).%s", file.nameWithoutExtension, fileIndex, file.extension)
newFile = File(file.parent, newName)
fileIndex++
} while (getDoesFilePathExist(newFile!!.absolutePath))
return newFile
}
private fun startCopyMove(
files: ArrayList<FileDirItem>,
destinationPath: String,
isCopyOperation: Boolean,
copyPhotoVideoOnly: Boolean,
copyHidden: Boolean
) {
val availableSpace = destinationPath.getAvailableStorageB()
val sumToCopy = files.sumByLong { it.getProperSize(applicationContext, copyHidden) }
if (availableSpace == -1L || sumToCopy < availableSpace) {
checkConflicts(files, destinationPath, 0, LinkedHashMap()) {
toast(if (isCopyOperation) R.string.copying else R.string.moving)
val pair = Pair(files, destinationPath)
handleNotificationPermission { granted ->
if (granted) {
CopyMoveTask(this, isCopyOperation, copyPhotoVideoOnly, it, copyMoveListener, copyHidden).execute(pair)
} else {
PermissionRequiredDialog(this, R.string.allow_notifications_files, { openNotificationSettings() })
}
}
}
} else {
val text = String.format(getString(R.string.no_space), sumToCopy.formatSize(), availableSpace.formatSize())
toast(text, Toast.LENGTH_LONG)
}
}
fun checkConflicts(
files: ArrayList<FileDirItem>, destinationPath: String, index: Int, conflictResolutions: LinkedHashMap<String, Int>,
callback: (resolutions: LinkedHashMap<String, Int>) -> Unit
) {
if (index == files.size) {
callback(conflictResolutions)
return
}
val file = files[index]
val newFileDirItem = FileDirItem("$destinationPath/${file.name}", file.name, file.isDirectory)
ensureBackgroundThread {
if (getDoesFilePathExist(newFileDirItem.path)) {
runOnUiThread {
FileConflictDialog(this, newFileDirItem, files.size > 1) { resolution, applyForAll ->
if (applyForAll) {
conflictResolutions.clear()
conflictResolutions[""] = resolution
checkConflicts(files, destinationPath, files.size, conflictResolutions, callback)
} else {
conflictResolutions[newFileDirItem.path] = resolution
checkConflicts(files, destinationPath, index + 1, conflictResolutions, callback)
}
}
}
} else {
runOnUiThread {
checkConflicts(files, destinationPath, index + 1, conflictResolutions, callback)
}
}
}
}
fun handlePermission(permissionId: Int, callback: (granted: Boolean) -> Unit) {
actionOnPermission = null
if (hasPermission(permissionId)) {
callback(true)
} else {
isAskingPermissions = true
actionOnPermission = callback
ActivityCompat.requestPermissions(this, arrayOf(getPermissionString(permissionId)), GENERIC_PERM_HANDLER)
}
}
fun handlePartialMediaPermissions(permissionIds: Collection<Int>, force: Boolean = false, callback: (granted: Boolean) -> Unit) {
actionOnPermission = null
if (isUpsideDownCakePlus()) {
if (hasPermission(PERMISSION_READ_MEDIA_VISUAL_USER_SELECTED) && !force) {
callback(true)
} else {
isAskingPermissions = true
actionOnPermission = callback
ActivityCompat.requestPermissions(this, permissionIds.map { getPermissionString(it) }.toTypedArray(), GENERIC_PERM_HANDLER)
}
} else {
if (hasAllPermissions(permissionIds)) {
callback(true)
} else {
isAskingPermissions = true
actionOnPermission = callback
ActivityCompat.requestPermissions(this, permissionIds.map { getPermissionString(it) }.toTypedArray(), GENERIC_PERM_HANDLER)
}
}
}
fun handleNotificationPermission(callback: (granted: Boolean) -> Unit) {
if (!isTiramisuPlus()) {
callback(true)
} else {
handlePermission(PERMISSION_POST_NOTIFICATIONS) { granted ->
callback(granted)
}
}
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
isAskingPermissions = false
if (requestCode == GENERIC_PERM_HANDLER && grantResults.isNotEmpty()) {
actionOnPermission?.invoke(grantResults[0] == 0)
}
}
val copyMoveListener = object : CopyMoveListener {
override fun copySucceeded(copyOnly: Boolean, copiedAll: Boolean, destinationPath: String, wasCopyingOneFileOnly: Boolean) {
if (copyOnly) {
toast(
if (copiedAll) {
if (wasCopyingOneFileOnly) {
R.string.copying_success_one
} else {
R.string.copying_success
}
} else {
R.string.copying_success_partial
}
)
} else {
toast(
if (copiedAll) {
if (wasCopyingOneFileOnly) {
R.string.moving_success_one
} else {
R.string.moving_success
}
} else {
R.string.moving_success_partial
}
)
}
copyMoveCallback?.invoke(destinationPath)
copyMoveCallback = null
}
override fun copyFailed() {
toast(R.string.copy_move_failed)
copyMoveCallback = null
}
}
fun checkAppOnSDCard() {
if (!baseConfig.wasAppOnSDShown && isAppInstalledOnSDCard()) {
baseConfig.wasAppOnSDShown = true
ConfirmationDialog(this, "", R.string.app_on_sd_card, R.string.ok, 0) {}
}
}
fun exportSettings(configItems: LinkedHashMap<String, Any>) {
if (isQPlus()) {
configItemsToExport = configItems
ExportSettingsDialog(this, getExportSettingsFilename(), true) { path, filename ->
Intent(Intent.ACTION_CREATE_DOCUMENT).apply {
type = "text/plain"
putExtra(Intent.EXTRA_TITLE, filename)
addCategory(Intent.CATEGORY_OPENABLE)
try {
startActivityForResult(this, SELECT_EXPORT_SETTINGS_FILE_INTENT)
} catch (e: ActivityNotFoundException) {
toast(R.string.system_service_disabled, Toast.LENGTH_LONG)
} catch (e: Exception) {
showErrorToast(e)
}
}
}
} else {
handlePermission(PERMISSION_WRITE_STORAGE) {
if (it) {
ExportSettingsDialog(this, getExportSettingsFilename(), false) { path, filename ->
val file = File(path)
getFileOutputStream(file.toFileDirItem(this), true) {
exportSettingsTo(it, configItems)
}
}
}
}
}
}
private fun exportSettingsTo(outputStream: OutputStream?, configItems: LinkedHashMap<String, Any>) {
if (outputStream == null) {
toast(R.string.unknown_error_occurred)
return
}
ensureBackgroundThread {
outputStream.bufferedWriter().use { out ->
for ((key, value) in configItems) {
out.writeLn("$key=$value")
}
}
toast(R.string.settings_exported_successfully)
}
}
private fun getExportSettingsFilename(): String {
val appName = baseConfig.appId.removeSuffix(".debug").removeSuffix(".pro").removePrefix("com.simplemobiletools.")
return "$appName-settings_${getCurrentFormattedDateTime()}"
}
@SuppressLint("InlinedApi")
protected fun launchSetDefaultDialerIntent() {
if (isQPlus()) {
val roleManager = getSystemService(RoleManager::class.java)
if (roleManager!!.isRoleAvailable(RoleManager.ROLE_DIALER) && !roleManager.isRoleHeld(RoleManager.ROLE_DIALER)) {
val intent = roleManager.createRequestRoleIntent(RoleManager.ROLE_DIALER)
startActivityForResult(intent, REQUEST_CODE_SET_DEFAULT_DIALER)
}
} else {
Intent(TelecomManager.ACTION_CHANGE_DEFAULT_DIALER).putExtra(TelecomManager.EXTRA_CHANGE_DEFAULT_DIALER_PACKAGE_NAME, packageName).apply {
try {
startActivityForResult(this, REQUEST_CODE_SET_DEFAULT_DIALER)
} catch (e: ActivityNotFoundException) {
toast(R.string.no_app_found)
} catch (e: Exception) {
showErrorToast(e)
}
}
}
}
@RequiresApi(Build.VERSION_CODES.Q)
fun setDefaultCallerIdApp() {
val roleManager = getSystemService(RoleManager::class.java)
if (roleManager.isRoleAvailable(RoleManager.ROLE_CALL_SCREENING) && !roleManager.isRoleHeld(RoleManager.ROLE_CALL_SCREENING)) {
val intent = roleManager.createRequestRoleIntent(RoleManager.ROLE_CALL_SCREENING)
startActivityForResult(intent, REQUEST_CODE_SET_DEFAULT_CALLER_ID)
}
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/activities/BaseSimpleActivity.kt | 567904171 |
package com.simplemobiletools.commons.activities
import android.app.Activity
import android.app.Application
import android.content.ActivityNotFoundException
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.widget.Toast
import androidx.activity.compose.setContent
import androidx.activity.viewModels
import androidx.compose.runtime.*
import androidx.compose.ui.platform.LocalContext
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewModelScope
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.compose.alert_dialog.rememberAlertDialogState
import com.simplemobiletools.commons.compose.extensions.enableEdgeToEdgeSimple
import com.simplemobiletools.commons.compose.extensions.onEventValue
import com.simplemobiletools.commons.compose.screens.ManageBlockedNumbersScreen
import com.simplemobiletools.commons.compose.theme.AppThemeSurface
import com.simplemobiletools.commons.dialogs.AddOrEditBlockedNumberAlertDialog
import com.simplemobiletools.commons.dialogs.ExportBlockedNumbersDialog
import com.simplemobiletools.commons.dialogs.FilePickerDialog
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.*
import com.simplemobiletools.commons.models.BlockedNumber
import java.io.FileOutputStream
import java.io.OutputStream
import kotlinx.collections.immutable.ImmutableList
import kotlinx.collections.immutable.toImmutableList
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
class ManageBlockedNumbersActivity : BaseSimpleActivity() {
private val config by lazy {
baseConfig
}
private companion object {
private const val PICK_IMPORT_SOURCE_INTENT = 11
private const val PICK_EXPORT_FILE_INTENT = 21
}
override fun getAppIconIDs() = intent.getIntegerArrayListExtra(APP_ICON_IDS) ?: ArrayList()
override fun getAppLauncherName() = intent.getStringExtra(APP_LAUNCHER_NAME) ?: ""
private val manageBlockedNumbersViewModel by viewModels<ManageBlockedNumbersViewModel>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdgeSimple()
setContent {
val context = LocalContext.current
val blockedNumbers by manageBlockedNumbersViewModel.blockedNumbers.collectAsStateWithLifecycle()
LaunchedEffect(blockedNumbers) {
if (blockedNumbers?.any { blockedNumber -> blockedNumber.number.isBlockedNumberPattern() } == true) {
maybeSetDefaultCallerIdApp()
}
}
val isBlockingHiddenNumbers by config.isBlockingHiddenNumbers.collectAsStateWithLifecycle(initialValue = config.blockHiddenNumbers)
val isBlockingUnknownNumbers by config.isBlockingUnknownNumbers.collectAsStateWithLifecycle(initialValue = config.blockUnknownNumbers)
val isDialer = remember {
config.appId.startsWith("com.simplemobiletools.dialer")
}
val isDefaultDialer: Boolean = onEventValue {
context.isDefaultDialer()
}
AppThemeSurface {
var clickedBlockedNumber by remember { mutableStateOf<BlockedNumber?>(null) }
val addBlockedNumberDialogState = rememberAlertDialogState()
addBlockedNumberDialogState.DialogMember {
AddOrEditBlockedNumberAlertDialog(
alertDialogState = addBlockedNumberDialogState,
blockedNumber = clickedBlockedNumber,
deleteBlockedNumber = { blockedNumber ->
deleteBlockedNumber(blockedNumber)
updateBlockedNumbers()
}
) { blockedNumber ->
addBlockedNumber(blockedNumber)
clickedBlockedNumber = null
updateBlockedNumbers()
}
}
ManageBlockedNumbersScreen(
goBack = ::finish,
onAdd = {
clickedBlockedNumber = null
addBlockedNumberDialogState.show()
},
onImportBlockedNumbers = ::tryImportBlockedNumbers,
onExportBlockedNumbers = ::tryExportBlockedNumbers,
setAsDefault = ::maybeSetDefaultCallerIdApp,
isDialer = isDialer,
hasGivenPermissionToBlock = isDefaultDialer,
isBlockUnknownSelected = isBlockingUnknownNumbers,
onBlockUnknownSelectedChange = { isChecked ->
config.blockUnknownNumbers = isChecked
onCheckedSetCallerIdAsDefault(isChecked)
},
isHiddenSelected = isBlockingHiddenNumbers,
onHiddenSelectedChange = { isChecked ->
config.blockHiddenNumbers = isChecked
onCheckedSetCallerIdAsDefault(isChecked)
},
blockedNumbers = blockedNumbers,
onDelete = { selectedKeys ->
deleteBlockedNumbers(blockedNumbers, selectedKeys)
},
onEdit = { blockedNumber ->
clickedBlockedNumber = blockedNumber
addBlockedNumberDialogState.show()
},
onCopy = { blockedNumber ->
copyToClipboard(blockedNumber.number)
}
)
}
}
}
private fun deleteBlockedNumbers(
blockedNumbers: ImmutableList<BlockedNumber>?,
selectedKeys: Set<Long>
) {
if (blockedNumbers.isNullOrEmpty()) return
blockedNumbers.filter { blockedNumber -> selectedKeys.contains(blockedNumber.id) }
.forEach { blockedNumber ->
deleteBlockedNumber(blockedNumber.number)
}
manageBlockedNumbersViewModel.updateBlockedNumbers()
}
private fun tryImportBlockedNumbers() {
if (isQPlus()) {
Intent(Intent.ACTION_GET_CONTENT).apply {
addCategory(Intent.CATEGORY_OPENABLE)
type = "text/plain"
try {
startActivityForResult(this, PICK_IMPORT_SOURCE_INTENT)
} catch (e: ActivityNotFoundException) {
toast(R.string.system_service_disabled, Toast.LENGTH_LONG)
} catch (e: Exception) {
showErrorToast(e)
}
}
} else {
handlePermission(PERMISSION_READ_STORAGE) { isAllowed ->
if (isAllowed) {
pickFileToImportBlockedNumbers()
}
}
}
}
private fun pickFileToImportBlockedNumbers() {
FilePickerDialog(this) {
importBlockedNumbers(it)
}
}
private fun tryImportBlockedNumbersFromFile(uri: Uri) {
when (uri.scheme) {
"file" -> importBlockedNumbers(uri.path!!)
"content" -> {
val tempFile = getTempFile("blocked", "blocked_numbers.txt")
if (tempFile == null) {
toast(R.string.unknown_error_occurred)
return
}
try {
val inputStream = contentResolver.openInputStream(uri)
val out = FileOutputStream(tempFile)
inputStream!!.copyTo(out)
importBlockedNumbers(tempFile.absolutePath)
} catch (e: Exception) {
showErrorToast(e)
}
}
else -> toast(R.string.invalid_file_format)
}
}
private fun importBlockedNumbers(path: String) {
ensureBackgroundThread {
val result = BlockedNumbersImporter(this).importBlockedNumbers(path)
toast(
when (result) {
BlockedNumbersImporter.ImportResult.IMPORT_OK -> R.string.importing_successful
BlockedNumbersImporter.ImportResult.IMPORT_FAIL -> R.string.no_items_found
}
)
updateBlockedNumbers()
}
}
private fun updateBlockedNumbers() {
manageBlockedNumbersViewModel.updateBlockedNumbers()
}
private fun onCheckedSetCallerIdAsDefault(isChecked: Boolean) {
if (isChecked) {
maybeSetDefaultCallerIdApp()
}
}
private fun maybeSetDefaultCallerIdApp() {
if (isQPlus() && baseConfig.appId.startsWith("com.simplemobiletools.dialer")) {
setDefaultCallerIdApp()
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, resultData: Intent?) {
super.onActivityResult(requestCode, resultCode, resultData)
when {
requestCode == REQUEST_CODE_SET_DEFAULT_DIALER && isDefaultDialer() -> {
updateBlockedNumbers()
}
requestCode == PICK_IMPORT_SOURCE_INTENT && resultCode == Activity.RESULT_OK && resultData != null && resultData.data != null -> {
tryImportBlockedNumbersFromFile(resultData.data!!)
}
requestCode == PICK_EXPORT_FILE_INTENT && resultCode == Activity.RESULT_OK && resultData != null && resultData.data != null -> {
val outputStream = contentResolver.openOutputStream(resultData.data!!)
exportBlockedNumbersTo(outputStream)
}
requestCode == REQUEST_CODE_SET_DEFAULT_CALLER_ID && resultCode != Activity.RESULT_OK -> {
toast(R.string.must_make_default_caller_id_app, length = Toast.LENGTH_LONG)
baseConfig.blockUnknownNumbers = false
baseConfig.blockHiddenNumbers = false
}
}
}
private fun exportBlockedNumbersTo(outputStream: OutputStream?) {
ensureBackgroundThread {
val blockedNumbers = getBlockedNumbers()
if (blockedNumbers.isEmpty()) {
toast(R.string.no_entries_for_exporting)
} else {
BlockedNumbersExporter.exportBlockedNumbers(blockedNumbers, outputStream) {
toast(
when (it) {
ExportResult.EXPORT_OK -> R.string.exporting_successful
else -> R.string.exporting_failed
}
)
}
}
}
}
private fun tryExportBlockedNumbers() {
if (isQPlus()) {
ExportBlockedNumbersDialog(this, baseConfig.lastBlockedNumbersExportPath, true) { file ->
Intent(Intent.ACTION_CREATE_DOCUMENT).apply {
type = "text/plain"
putExtra(Intent.EXTRA_TITLE, file.name)
addCategory(Intent.CATEGORY_OPENABLE)
try {
startActivityForResult(this, PICK_EXPORT_FILE_INTENT)
} catch (e: ActivityNotFoundException) {
toast(R.string.system_service_disabled, Toast.LENGTH_LONG)
} catch (e: Exception) {
showErrorToast(e)
}
}
}
} else {
handlePermission(PERMISSION_WRITE_STORAGE) { isAllowed ->
if (isAllowed) {
ExportBlockedNumbersDialog(this, baseConfig.lastBlockedNumbersExportPath, false) { file ->
getFileOutputStream(file.toFileDirItem(this), true) { out ->
exportBlockedNumbersTo(out)
}
}
}
}
}
}
internal class ManageBlockedNumbersViewModel(
private val application: Application
) : AndroidViewModel(application) {
private val _blockedNumbers: MutableStateFlow<ImmutableList<BlockedNumber>?> = MutableStateFlow(null)
val blockedNumbers = _blockedNumbers.asStateFlow()
init {
updateBlockedNumbers()
}
fun updateBlockedNumbers() {
viewModelScope.launch {
withContext(Dispatchers.IO) {
application.getBlockedNumbersWithContact { list ->
_blockedNumbers.update { list.toImmutableList() }
}
}
}
}
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/activities/ManageBlockedNumbersActivity.kt | 3596387979 |
package com.simplemobiletools.commons.activities
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.runtime.remember
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.compose.extensions.enableEdgeToEdgeSimple
import com.simplemobiletools.commons.compose.screens.ContributorsScreen
import com.simplemobiletools.commons.compose.theme.AppThemeSurface
import com.simplemobiletools.commons.models.LanguageContributor
import kotlinx.collections.immutable.toImmutableList
class ContributorsActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdgeSimple()
setContent {
AppThemeSurface {
val contributors = remember {
languageContributors()
}
val showContributorsLabel = remember {
!resources.getBoolean(R.bool.hide_all_external_links)
}
ContributorsScreen(
goBack = ::finish,
showContributorsLabel = showContributorsLabel,
contributors = contributors,
)
}
}
}
private fun languageContributors() = 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),
LanguageContributor(R.drawable.ic_flag_czech_vector, R.string.translation_czech, R.string.translators_czech),
LanguageContributor(R.drawable.ic_flag_welsh_vector, R.string.translation_welsh, R.string.translators_welsh),
LanguageContributor(R.drawable.ic_flag_danish_vector, R.string.translation_danish, R.string.translators_danish),
LanguageContributor(R.drawable.ic_flag_german_vector, R.string.translation_german, R.string.translators_german),
LanguageContributor(R.drawable.ic_flag_greek_vector, R.string.translation_greek, R.string.translators_greek),
LanguageContributor(R.drawable.ic_flag_spanish_vector, R.string.translation_spanish, R.string.translators_spanish),
LanguageContributor(R.drawable.ic_flag_basque_vector, R.string.translation_basque, R.string.translators_basque),
LanguageContributor(R.drawable.ic_flag_persian_vector, R.string.translation_persian, R.string.translators_persian),
LanguageContributor(R.drawable.ic_flag_finnish_vector, R.string.translation_finnish, R.string.translators_finnish),
LanguageContributor(R.drawable.ic_flag_french_vector, R.string.translation_french, R.string.translators_french),
LanguageContributor(R.drawable.ic_flag_galician_vector, R.string.translation_galician, R.string.translators_galician),
LanguageContributor(R.drawable.ic_flag_hindi_vector, R.string.translation_hindi, R.string.translators_hindi),
LanguageContributor(R.drawable.ic_flag_croatian_vector, R.string.translation_croatian, R.string.translators_croatian),
LanguageContributor(R.drawable.ic_flag_hungarian_vector, R.string.translation_hungarian, R.string.translators_hungarian),
LanguageContributor(R.drawable.ic_flag_indonesian_vector, R.string.translation_indonesian, R.string.translators_indonesian),
LanguageContributor(R.drawable.ic_flag_italian_vector, R.string.translation_italian, R.string.translators_italian),
LanguageContributor(R.drawable.ic_flag_hebrew_vector, R.string.translation_hebrew, R.string.translators_hebrew),
LanguageContributor(R.drawable.ic_flag_japanese_vector, R.string.translation_japanese, R.string.translators_japanese),
LanguageContributor(R.drawable.ic_flag_korean_vector, R.string.translation_korean, R.string.translators_korean),
LanguageContributor(R.drawable.ic_flag_lithuanian_vector, R.string.translation_lithuanian, R.string.translators_lithuanian),
LanguageContributor(R.drawable.ic_flag_nepali_vector, R.string.translation_nepali, R.string.translators_nepali),
LanguageContributor(R.drawable.ic_flag_norwegian_vector, R.string.translation_norwegian, R.string.translators_norwegian),
LanguageContributor(R.drawable.ic_flag_dutch_vector, R.string.translation_dutch, R.string.translators_dutch),
LanguageContributor(R.drawable.ic_flag_polish_vector, R.string.translation_polish, R.string.translators_polish),
LanguageContributor(R.drawable.ic_flag_portuguese_vector, R.string.translation_portuguese, R.string.translators_portuguese),
LanguageContributor(R.drawable.ic_flag_romanian_vector, R.string.translation_romanian, R.string.translators_romanian),
LanguageContributor(R.drawable.ic_flag_russian_vector, R.string.translation_russian, R.string.translators_russian),
LanguageContributor(R.drawable.ic_flag_slovak_vector, R.string.translation_slovak, R.string.translators_slovak),
LanguageContributor(R.drawable.ic_flag_slovenian_vector, R.string.translation_slovenian, R.string.translators_slovenian),
LanguageContributor(R.drawable.ic_flag_swedish_vector, R.string.translation_swedish, R.string.translators_swedish),
LanguageContributor(R.drawable.ic_flag_tamil_vector, R.string.translation_tamil, R.string.translators_tamil),
LanguageContributor(R.drawable.ic_flag_turkish_vector, R.string.translation_turkish, R.string.translators_turkish),
LanguageContributor(R.drawable.ic_flag_ukrainian_vector, R.string.translation_ukrainian, R.string.translators_ukrainian),
LanguageContributor(R.drawable.ic_flag_chinese_hk_vector, R.string.translation_chinese_hk, R.string.translators_chinese_hk),
LanguageContributor(R.drawable.ic_flag_chinese_cn_vector, R.string.translation_chinese_cn, R.string.translators_chinese_cn),
LanguageContributor(R.drawable.ic_flag_chinese_tw_vector, R.string.translation_chinese_tw, R.string.translators_chinese_tw)
).toImmutableList()
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/activities/ContributorsActivity.kt | 412356904 |
package com.simplemobiletools.commons.activities
import android.content.ActivityNotFoundException
import android.content.Intent
import android.content.Intent.*
import android.content.res.Resources
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.platform.LocalContext
import androidx.core.net.toUri
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.compose.alert_dialog.rememberAlertDialogState
import com.simplemobiletools.commons.compose.extensions.enableEdgeToEdgeSimple
import com.simplemobiletools.commons.compose.extensions.rateStarsRedirectAndThankYou
import com.simplemobiletools.commons.compose.screens.*
import com.simplemobiletools.commons.compose.theme.AppThemeSurface
import com.simplemobiletools.commons.dialogs.ConfirmationAdvancedAlertDialog
import com.simplemobiletools.commons.dialogs.RateStarsAlertDialog
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.*
import com.simplemobiletools.commons.models.FAQItem
class AboutActivity : ComponentActivity() {
private val appName get() = intent.getStringExtra(APP_NAME) ?: ""
private var firstVersionClickTS = 0L
private var clicksSinceFirstClick = 0
companion object {
private const val EASTER_EGG_TIME_LIMIT = 3000L
private const val EASTER_EGG_REQUIRED_CLICKS = 7
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdgeSimple()
setContent {
val context = LocalContext.current
val resources = context.resources
AppThemeSurface {
val showExternalLinks = remember { !resources.getBoolean(R.bool.hide_all_external_links) }
val showGoogleRelations = remember { !resources.getBoolean(R.bool.hide_google_relations) }
val onEmailClickAlertDialogState = getOnEmailClickAlertDialogState()
val rateStarsAlertDialogState = getRateStarsAlertDialogState()
val onRateUsClickAlertDialogState = getOnRateUsClickAlertDialogState(rateStarsAlertDialogState::show)
AboutScreen(
goBack = ::finish,
helpUsSection = {
val showHelpUsSection =
remember { showGoogleRelations || !showExternalLinks }
HelpUsSection(
onRateUsClick = {
onRateUsClick(
showConfirmationAdvancedDialog = onRateUsClickAlertDialogState::show,
showRateStarsDialog = rateStarsAlertDialogState::show
)
},
onInviteClick = ::onInviteClick,
onContributorsClick = ::onContributorsClick,
showDonate = resources.getBoolean(R.bool.show_donate_in_about) && showExternalLinks,
onDonateClick = ::onDonateClick,
showInvite = showHelpUsSection,
showRateUs = showHelpUsSection
)
},
aboutSection = {
val setupFAQ = rememberFAQ()
if (!showExternalLinks || setupFAQ) {
AboutSection(setupFAQ = setupFAQ, onFAQClick = ::launchFAQActivity, onEmailClick = {
onEmailClick(onEmailClickAlertDialogState::show)
})
}
},
socialSection = {
if (showExternalLinks) {
SocialSection(
onFacebookClick = ::onFacebookClick,
onGithubClick = ::onGithubClick,
onRedditClick = ::onRedditClick,
onTelegramClick = ::onTelegramClick
)
}
}
) {
val (showWebsite, fullVersion) = showWebsiteAndFullVersion(resources, showExternalLinks)
OtherSection(
showMoreApps = showGoogleRelations,
onMoreAppsClick = ::launchMoreAppsFromUsIntent,
showWebsite = showWebsite,
onWebsiteClick = ::onWebsiteClick,
showPrivacyPolicy = showExternalLinks,
onPrivacyPolicyClick = ::onPrivacyPolicyClick,
onLicenseClick = ::onLicenseClick,
version = fullVersion,
onVersionClick = ::onVersionClick
)
}
}
}
}
@Composable
private fun rememberFAQ() = remember { !(intent.getSerializableExtra(APP_FAQ) as? ArrayList<FAQItem>).isNullOrEmpty() }
@Composable
private fun showWebsiteAndFullVersion(
resources: Resources,
showExternalLinks: Boolean
): Pair<Boolean, String> {
val showWebsite = remember { resources.getBoolean(R.bool.show_donate_in_about) && !showExternalLinks }
var version = intent.getStringExtra(APP_VERSION_NAME) ?: ""
if (baseConfig.appId.removeSuffix(".debug").endsWith(".pro")) {
version += " ${getString(R.string.pro)}"
}
val fullVersion = remember { String.format(getString(R.string.version_placeholder, version)) }
return Pair(showWebsite, fullVersion)
}
@Composable
private fun getRateStarsAlertDialogState() =
rememberAlertDialogState().apply {
DialogMember {
RateStarsAlertDialog(alertDialogState = this, onRating = ::rateStarsRedirectAndThankYou)
}
}
@Composable
private fun getOnEmailClickAlertDialogState() =
rememberAlertDialogState().apply {
DialogMember {
ConfirmationAdvancedAlertDialog(
alertDialogState = this,
message = "${getString(R.string.before_asking_question_read_faq)}\n\n${getString(R.string.make_sure_latest)}",
messageId = null,
positive = R.string.read_faq,
negative = R.string.skip
) { success ->
if (success) {
launchFAQActivity()
} else {
launchEmailIntent()
}
}
}
}
@Composable
private fun getOnRateUsClickAlertDialogState(showRateStarsDialog: () -> Unit) =
rememberAlertDialogState().apply {
DialogMember {
ConfirmationAdvancedAlertDialog(
alertDialogState = this,
message = "${getString(R.string.before_asking_question_read_faq)}\n\n${getString(R.string.make_sure_latest)}",
messageId = null,
positive = R.string.read_faq,
negative = R.string.skip
) { success ->
if (success) {
launchFAQActivity()
} else {
launchRateUsPrompt(showRateStarsDialog)
}
}
}
}
private fun onEmailClick(
showConfirmationAdvancedDialog: () -> Unit
) {
if (intent.getBooleanExtra(SHOW_FAQ_BEFORE_MAIL, false) && !baseConfig.wasBeforeAskingShown) {
baseConfig.wasBeforeAskingShown = true
showConfirmationAdvancedDialog()
} else {
launchEmailIntent()
}
}
private fun launchFAQActivity() {
val faqItems = intent.getSerializableExtra(APP_FAQ) as ArrayList<FAQItem>
Intent(applicationContext, FAQActivity::class.java).apply {
putExtra(APP_ICON_IDS, intent.getIntegerArrayListExtra(APP_ICON_IDS) ?: ArrayList<String>())
putExtra(APP_LAUNCHER_NAME, intent.getStringExtra(APP_LAUNCHER_NAME) ?: "")
putExtra(APP_FAQ, faqItems)
startActivity(this)
}
}
private fun launchEmailIntent() {
val appVersion = String.format(getString(R.string.app_version, intent.getStringExtra(APP_VERSION_NAME)))
val deviceOS = String.format(getString(R.string.device_os), Build.VERSION.RELEASE)
val newline = "\n"
val separator = "------------------------------"
val body = "$appVersion$newline$deviceOS$newline$separator$newline$newline"
val address = if (packageName.startsWith("com.simplemobiletools")) {
getString(R.string.my_email)
} else {
getString(R.string.my_fake_email)
}
val selectorIntent = Intent(ACTION_SENDTO)
.setData("mailto:$address".toUri())
val emailIntent = Intent(ACTION_SEND).apply {
putExtra(EXTRA_EMAIL, arrayOf(address))
putExtra(EXTRA_SUBJECT, appName)
putExtra(EXTRA_TEXT, body)
selector = selectorIntent
}
try {
startActivity(emailIntent)
} catch (e: ActivityNotFoundException) {
val chooser = createChooser(emailIntent, getString(R.string.send_email))
try {
startActivity(chooser)
} catch (e: Exception) {
toast(R.string.no_email_client_found)
}
} catch (e: Exception) {
showErrorToast(e)
}
}
private fun onRateUsClick(
showConfirmationAdvancedDialog: () -> Unit,
showRateStarsDialog: () -> Unit
) {
if (baseConfig.wasBeforeRateShown) {
launchRateUsPrompt(showRateStarsDialog)
} else {
baseConfig.wasBeforeRateShown = true
showConfirmationAdvancedDialog()
}
}
private fun launchRateUsPrompt(
showRateStarsDialog: () -> Unit
) {
if (baseConfig.wasAppRated) {
redirectToRateUs()
} else {
showRateStarsDialog()
}
}
private fun onInviteClick() {
val text = String.format(getString(R.string.share_text), appName, getStoreUrl())
Intent().apply {
action = ACTION_SEND
putExtra(EXTRA_SUBJECT, appName)
putExtra(EXTRA_TEXT, text)
type = "text/plain"
startActivity(createChooser(this, getString(R.string.invite_via)))
}
}
private fun onContributorsClick() {
val intent = Intent(applicationContext, ContributorsActivity::class.java)
startActivity(intent)
}
private fun onDonateClick() {
launchViewIntent(getString(R.string.donate_url))
}
private fun onFacebookClick() {
var link = "https://www.facebook.com/simplemobiletools"
try {
packageManager.getPackageInfo("com.facebook.katana", 0)
link = "fb://page/150270895341774"
} catch (ignored: Exception) {
}
launchViewIntent(link)
}
private fun onGithubClick() {
launchViewIntent("https://github.com/SimpleMobileTools")
}
private fun onRedditClick() {
launchViewIntent("https://www.reddit.com/r/SimpleMobileTools")
}
private fun onTelegramClick() {
launchViewIntent("https://t.me/SimpleMobileTools")
}
private fun onWebsiteClick() {
launchViewIntent("https://simplemobiletools.com/")
}
private fun onPrivacyPolicyClick() {
val appId = baseConfig.appId.removeSuffix(".debug").removeSuffix(".pro").removePrefix("com.simplemobiletools.")
val url = "https://simplemobiletools.com/privacy/$appId.txt"
launchViewIntent(url)
}
private fun onLicenseClick() {
Intent(applicationContext, LicenseActivity::class.java).apply {
putExtra(APP_ICON_IDS, intent.getIntegerArrayListExtra(APP_ICON_IDS) ?: ArrayList<String>())
putExtra(APP_LAUNCHER_NAME, intent.getStringExtra(APP_LAUNCHER_NAME) ?: "")
putExtra(APP_LICENSES, intent.getLongExtra(APP_LICENSES, 0))
startActivity(this)
}
}
private fun onVersionClick() {
if (firstVersionClickTS == 0L) {
firstVersionClickTS = System.currentTimeMillis()
Handler(Looper.getMainLooper()).postDelayed({
firstVersionClickTS = 0L
clicksSinceFirstClick = 0
}, EASTER_EGG_TIME_LIMIT)
}
clicksSinceFirstClick++
if (clicksSinceFirstClick >= EASTER_EGG_REQUIRED_CLICKS) {
toast(R.string.hello)
firstVersionClickTS = 0L
clicksSinceFirstClick = 0
}
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/activities/AboutActivity.kt | 344756980 |
package com.simplemobiletools.commons.activities
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.compose.extensions.enableEdgeToEdgeSimple
import com.simplemobiletools.commons.compose.screens.LicenseScreen
import com.simplemobiletools.commons.compose.theme.AppThemeSurface
import com.simplemobiletools.commons.extensions.launchViewIntent
import com.simplemobiletools.commons.helpers.*
import com.simplemobiletools.commons.models.License
import kotlinx.collections.immutable.toImmutableList
class LicenseActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdgeSimple()
setContent {
val licenseMask = remember { intent.getLongExtra(APP_LICENSES, 0) or LICENSE_KOTLIN }
val thirdPartyLicenses by remember { derivedStateOf { initLicenses().filter { licenseMask and it.id != 0L }.toImmutableList() } }
AppThemeSurface {
LicenseScreen(
goBack = ::finish,
thirdPartyLicenses = thirdPartyLicenses,
onLicenseClick = ::launchViewIntent
)
}
}
}
private fun initLicenses() = 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)
)
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/activities/LicenseActivity.kt | 4132677898 |
package com.simplemobiletools.commons.activities
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.runtime.remember
import com.simplemobiletools.commons.compose.extensions.enableEdgeToEdgeSimple
import com.simplemobiletools.commons.compose.screens.FAQScreen
import com.simplemobiletools.commons.compose.theme.AppThemeSurface
import com.simplemobiletools.commons.helpers.APP_FAQ
import com.simplemobiletools.commons.models.FAQItem
import kotlinx.collections.immutable.toImmutableList
class FAQActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdgeSimple()
setContent {
AppThemeSurface {
val faqItems = remember { intent.getSerializableExtra(APP_FAQ) as ArrayList<FAQItem> }
FAQScreen(
goBack = ::finish,
faqItems = faqItems.toImmutableList()
)
}
}
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/activities/FAQActivity.kt | 805932126 |
package com.simplemobiletools.commons.activities
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.SIDELOADING_TRUE
import com.simplemobiletools.commons.helpers.SIDELOADING_UNCHECKED
abstract class BaseSplashActivity : AppCompatActivity() {
abstract fun initActivity()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (baseConfig.appSideloadingStatus == SIDELOADING_UNCHECKED) {
if (checkAppSideloading()) {
return
}
} else if (baseConfig.appSideloadingStatus == SIDELOADING_TRUE) {
showSideloadingDialog()
return
}
baseConfig.apply {
if (isUsingAutoTheme) {
val isUsingSystemDarkTheme = isUsingSystemDarkTheme()
isUsingSharedTheme = false
textColor = resources.getColor(if (isUsingSystemDarkTheme) R.color.theme_dark_text_color else R.color.theme_light_text_color)
backgroundColor = resources.getColor(if (isUsingSystemDarkTheme) R.color.theme_dark_background_color else R.color.theme_light_background_color)
}
}
if (!baseConfig.isUsingAutoTheme && !baseConfig.isUsingSystemTheme && isThankYouInstalled()) {
getSharedTheme {
if (it != null) {
baseConfig.apply {
wasSharedThemeForced = true
isUsingSharedTheme = true
wasSharedThemeEverActivated = true
textColor = it.textColor
backgroundColor = it.backgroundColor
primaryColor = it.primaryColor
accentColor = it.accentColor
}
if (baseConfig.appIconColor != it.appIconColor) {
baseConfig.appIconColor = it.appIconColor
checkAppIconColor()
}
}
initActivity()
}
} else {
initActivity()
}
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/activities/BaseSplashActivity.kt | 1941986764 |
package com.simplemobiletools.commons.activities
import android.content.Intent
import android.graphics.Color
import android.graphics.drawable.LayerDrawable
import android.graphics.drawable.RippleDrawable
import android.os.Bundle
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.databinding.ActivityCustomizationBinding
import com.simplemobiletools.commons.dialogs.*
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.*
import com.simplemobiletools.commons.models.MyTheme
import com.simplemobiletools.commons.models.RadioItem
import com.simplemobiletools.commons.models.SharedTheme
class CustomizationActivity : BaseSimpleActivity() {
private val THEME_LIGHT = 0
private val THEME_DARK = 1
private val THEME_SOLARIZED = 2
private val THEME_DARK_RED = 3
private val THEME_BLACK_WHITE = 4
private val THEME_CUSTOM = 5
private val THEME_SHARED = 6
private val THEME_WHITE = 7
private val THEME_AUTO = 8
private val THEME_SYSTEM = 9 // Material You
private var curTextColor = 0
private var curBackgroundColor = 0
private var curPrimaryColor = 0
private var curAccentColor = 0
private var curAppIconColor = 0
private var curSelectedThemeId = 0
private var originalAppIconColor = 0
private var lastSavePromptTS = 0L
private var hasUnsavedChanges = false
private var isThankYou = false // show "Apply colors to all Simple apps" in Simple Thank You itself even with "Hide Google relations" enabled
private var predefinedThemes = LinkedHashMap<Int, MyTheme>()
private var curPrimaryLineColorPicker: LineColorPickerDialog? = null
private var storedSharedTheme: SharedTheme? = null
override fun getAppIconIDs() = intent.getIntegerArrayListExtra(APP_ICON_IDS) ?: ArrayList()
override fun getAppLauncherName() = intent.getStringExtra(APP_LAUNCHER_NAME) ?: ""
private val binding by viewBinding(ActivityCustomizationBinding::inflate)
override fun onCreate(savedInstanceState: Bundle?) {
isMaterialActivity = true
super.onCreate(savedInstanceState)
setContentView(binding.root)
setupOptionsMenu()
refreshMenuItems()
updateMaterialActivityViews(binding.customizationCoordinator, binding.customizationHolder, useTransparentNavigation = true, useTopSearchMenu = false)
isThankYou = packageName.removeSuffix(".debug") == "com.simplemobiletools.thankyou"
initColorVariables()
if (isThankYouInstalled()) {
val cursorLoader = getMyContentProviderCursorLoader()
ensureBackgroundThread {
try {
storedSharedTheme = getSharedThemeSync(cursorLoader)
if (storedSharedTheme == null) {
baseConfig.isUsingSharedTheme = false
} else {
baseConfig.wasSharedThemeEverActivated = true
}
runOnUiThread {
setupThemes()
val hideGoogleRelations = resources.getBoolean(R.bool.hide_google_relations) && !isThankYou
binding.applyToAllHolder.beVisibleIf(
storedSharedTheme == null && curSelectedThemeId != THEME_AUTO && curSelectedThemeId != THEME_SYSTEM && !hideGoogleRelations
)
}
} catch (e: Exception) {
toast(R.string.update_thank_you)
finish()
}
}
} else {
setupThemes()
baseConfig.isUsingSharedTheme = false
}
val textColor = if (baseConfig.isUsingSystemTheme) {
getProperTextColor()
} else {
baseConfig.textColor
}
updateLabelColors(textColor)
originalAppIconColor = baseConfig.appIconColor
if (resources.getBoolean(R.bool.hide_google_relations) && !isThankYou) {
binding.applyToAllHolder.beGone()
}
}
override fun onResume() {
super.onResume()
setTheme(getThemeId(getCurrentPrimaryColor()))
if (!baseConfig.isUsingSystemTheme) {
updateBackgroundColor(getCurrentBackgroundColor())
updateActionbarColor(getCurrentStatusBarColor())
}
curPrimaryLineColorPicker?.getSpecificColor()?.apply {
updateActionbarColor(this)
setTheme(getThemeId(this))
}
setupToolbar(binding.customizationToolbar, NavigationIcon.Cross, getColoredMaterialStatusBarColor())
}
private fun refreshMenuItems() {
binding.customizationToolbar.menu.findItem(R.id.save).isVisible = hasUnsavedChanges
}
private fun setupOptionsMenu() {
binding.customizationToolbar.setOnMenuItemClickListener { menuItem ->
when (menuItem.itemId) {
R.id.save -> {
saveChanges(true)
true
}
else -> false
}
}
}
override fun onBackPressed() {
if (hasUnsavedChanges && System.currentTimeMillis() - lastSavePromptTS > SAVE_DISCARD_PROMPT_INTERVAL) {
promptSaveDiscard()
} else {
super.onBackPressed()
}
}
private fun setupThemes() {
predefinedThemes.apply {
if (isSPlus()) {
put(THEME_SYSTEM, getSystemThemeColors())
}
put(THEME_AUTO, getAutoThemeColors())
put(
THEME_LIGHT,
MyTheme(
getString(R.string.light_theme),
R.color.theme_light_text_color,
R.color.theme_light_background_color,
R.color.color_primary,
R.color.color_primary
)
)
put(
THEME_DARK,
MyTheme(
getString(R.string.dark_theme),
R.color.theme_dark_text_color,
R.color.theme_dark_background_color,
R.color.color_primary,
R.color.color_primary
)
)
put(
THEME_DARK_RED,
MyTheme(
getString(R.string.dark_red),
R.color.theme_dark_text_color,
R.color.theme_dark_background_color,
R.color.theme_dark_red_primary_color,
R.color.md_red_700
)
)
put(THEME_WHITE, MyTheme(getString(R.string.white), R.color.dark_grey, android.R.color.white, android.R.color.white, R.color.color_primary))
put(
THEME_BLACK_WHITE,
MyTheme(getString(R.string.black_white), android.R.color.white, android.R.color.black, android.R.color.black, R.color.md_grey_black)
)
put(THEME_CUSTOM, MyTheme(getString(R.string.custom), 0, 0, 0, 0))
if (storedSharedTheme != null) {
put(THEME_SHARED, MyTheme(getString(R.string.shared), 0, 0, 0, 0))
}
}
setupThemePicker()
setupColorsPickers()
}
private fun setupThemePicker() {
curSelectedThemeId = getCurrentThemeId()
binding.customizationTheme.text = getThemeText()
updateAutoThemeFields()
handleAccentColorLayout()
binding.customizationThemeHolder.setOnClickListener {
if (baseConfig.wasAppIconCustomizationWarningShown) {
themePickerClicked()
} else {
ConfirmationDialog(this, "", R.string.app_icon_color_warning, R.string.ok, 0) {
baseConfig.wasAppIconCustomizationWarningShown = true
themePickerClicked()
}
}
}
if (binding.customizationTheme.value == getMaterialYouString()) {
binding.applyToAllHolder.beGone()
}
}
private fun themePickerClicked() {
val items = arrayListOf<RadioItem>()
for ((key, value) in predefinedThemes) {
items.add(RadioItem(key, value.label))
}
RadioGroupDialog(this@CustomizationActivity, items, curSelectedThemeId) {
if (it == THEME_SHARED && !isThankYouInstalled()) {
PurchaseThankYouDialog(this)
return@RadioGroupDialog
}
updateColorTheme(it as Int, true)
if (it != THEME_CUSTOM && it != THEME_SHARED && it != THEME_AUTO && it != THEME_SYSTEM && !baseConfig.wasCustomThemeSwitchDescriptionShown) {
baseConfig.wasCustomThemeSwitchDescriptionShown = true
toast(R.string.changing_color_description)
}
val hideGoogleRelations = resources.getBoolean(R.bool.hide_google_relations) && !isThankYou
binding.applyToAllHolder.beVisibleIf(
curSelectedThemeId != THEME_AUTO && curSelectedThemeId != THEME_SYSTEM && curSelectedThemeId != THEME_SHARED && !hideGoogleRelations
)
updateMenuItemColors(binding.customizationToolbar.menu, getCurrentStatusBarColor())
setupToolbar(binding.customizationToolbar, NavigationIcon.Cross, getCurrentStatusBarColor())
}
}
private fun updateColorTheme(themeId: Int, useStored: Boolean = false) {
curSelectedThemeId = themeId
binding.customizationTheme.text = getThemeText()
resources.apply {
if (curSelectedThemeId == THEME_CUSTOM) {
if (useStored) {
curTextColor = baseConfig.customTextColor
curBackgroundColor = baseConfig.customBackgroundColor
curPrimaryColor = baseConfig.customPrimaryColor
curAccentColor = baseConfig.customAccentColor
curAppIconColor = baseConfig.customAppIconColor
setTheme(getThemeId(curPrimaryColor))
updateMenuItemColors(binding.customizationToolbar.menu, curPrimaryColor)
setupToolbar(binding.customizationToolbar, NavigationIcon.Cross, curPrimaryColor)
setupColorsPickers()
} else {
baseConfig.customPrimaryColor = curPrimaryColor
baseConfig.customAccentColor = curAccentColor
baseConfig.customBackgroundColor = curBackgroundColor
baseConfig.customTextColor = curTextColor
baseConfig.customAppIconColor = curAppIconColor
}
} else if (curSelectedThemeId == THEME_SHARED) {
if (useStored) {
storedSharedTheme?.apply {
curTextColor = textColor
curBackgroundColor = backgroundColor
curPrimaryColor = primaryColor
curAccentColor = accentColor
curAppIconColor = appIconColor
}
setTheme(getThemeId(curPrimaryColor))
setupColorsPickers()
updateMenuItemColors(binding.customizationToolbar.menu, curPrimaryColor)
setupToolbar(binding.customizationToolbar, NavigationIcon.Cross, curPrimaryColor)
}
} else {
val theme = predefinedThemes[curSelectedThemeId]!!
curTextColor = getColor(theme.textColorId)
curBackgroundColor = getColor(theme.backgroundColorId)
if (curSelectedThemeId != THEME_AUTO && curSelectedThemeId != THEME_SYSTEM) {
curPrimaryColor = getColor(theme.primaryColorId)
curAccentColor = getColor(R.color.color_primary)
curAppIconColor = getColor(theme.appIconColorId)
}
setTheme(getThemeId(getCurrentPrimaryColor()))
colorChanged()
updateMenuItemColors(binding.customizationToolbar.menu, getCurrentStatusBarColor())
setupToolbar(binding.customizationToolbar, NavigationIcon.Cross, getCurrentStatusBarColor())
}
}
hasUnsavedChanges = true
refreshMenuItems()
updateLabelColors(getCurrentTextColor())
updateBackgroundColor(getCurrentBackgroundColor())
updateActionbarColor(getCurrentStatusBarColor())
updateAutoThemeFields()
updateApplyToAllColors(getCurrentPrimaryColor())
handleAccentColorLayout()
}
private fun getAutoThemeColors(): MyTheme {
val isUsingSystemDarkTheme = isUsingSystemDarkTheme()
val textColor = if (isUsingSystemDarkTheme) R.color.theme_dark_text_color else R.color.theme_light_text_color
val backgroundColor = if (isUsingSystemDarkTheme) R.color.theme_dark_background_color else R.color.theme_light_background_color
return MyTheme(getString(R.string.auto_light_dark_theme), textColor, backgroundColor, R.color.color_primary, R.color.color_primary)
}
// doesn't really matter what colors we use here, everything will be taken from the system. Use the default dark theme values here.
private fun getSystemThemeColors(): MyTheme {
return MyTheme(
getMaterialYouString(),
R.color.theme_dark_text_color,
R.color.theme_dark_background_color,
R.color.color_primary,
R.color.color_primary
)
}
private fun getCurrentThemeId(): Int {
if (baseConfig.isUsingSharedTheme) {
return THEME_SHARED
} else if ((baseConfig.isUsingSystemTheme && !hasUnsavedChanges) || curSelectedThemeId == THEME_SYSTEM) {
return THEME_SYSTEM
} else if (baseConfig.isUsingAutoTheme || curSelectedThemeId == THEME_AUTO) {
return THEME_AUTO
}
var themeId = THEME_CUSTOM
resources.apply {
for ((key, value) in predefinedThemes.filter { it.key != THEME_CUSTOM && it.key != THEME_SHARED && it.key != THEME_AUTO && it.key != THEME_SYSTEM }) {
if (curTextColor == getColor(value.textColorId) &&
curBackgroundColor == getColor(value.backgroundColorId) &&
curPrimaryColor == getColor(value.primaryColorId) &&
curAppIconColor == getColor(value.appIconColorId)
) {
themeId = key
}
}
}
return themeId
}
private fun getThemeText(): String {
var label = getString(R.string.custom)
for ((key, value) in predefinedThemes) {
if (key == curSelectedThemeId) {
label = value.label
}
}
return label
}
private fun updateAutoThemeFields() {
arrayOf(binding.customizationTextColorHolder, binding.customizationBackgroundColorHolder).forEach {
it.beVisibleIf(curSelectedThemeId != THEME_AUTO && curSelectedThemeId != THEME_SYSTEM)
}
binding.customizationPrimaryColorHolder.beVisibleIf(curSelectedThemeId != THEME_SYSTEM)
}
private fun promptSaveDiscard() {
lastSavePromptTS = System.currentTimeMillis()
ConfirmationAdvancedDialog(this, "", R.string.save_before_closing, R.string.save, R.string.discard) {
if (it) {
saveChanges(true)
} else {
resetColors()
finish()
}
}
}
private fun saveChanges(finishAfterSave: Boolean) {
val didAppIconColorChange = curAppIconColor != originalAppIconColor
baseConfig.apply {
textColor = curTextColor
backgroundColor = curBackgroundColor
primaryColor = curPrimaryColor
accentColor = curAccentColor
appIconColor = curAppIconColor
}
if (didAppIconColorChange) {
checkAppIconColor()
}
if (curSelectedThemeId == THEME_SHARED) {
val newSharedTheme = SharedTheme(curTextColor, curBackgroundColor, curPrimaryColor, curAppIconColor, 0, curAccentColor)
updateSharedTheme(newSharedTheme)
Intent().apply {
action = MyContentProvider.SHARED_THEME_UPDATED
sendBroadcast(this)
}
}
baseConfig.isUsingSharedTheme = curSelectedThemeId == THEME_SHARED
baseConfig.shouldUseSharedTheme = curSelectedThemeId == THEME_SHARED
baseConfig.isUsingAutoTheme = curSelectedThemeId == THEME_AUTO
baseConfig.isUsingSystemTheme = curSelectedThemeId == THEME_SYSTEM
hasUnsavedChanges = false
if (finishAfterSave) {
finish()
} else {
refreshMenuItems()
}
}
private fun resetColors() {
hasUnsavedChanges = false
initColorVariables()
setupColorsPickers()
updateBackgroundColor()
updateActionbarColor()
refreshMenuItems()
updateLabelColors(getCurrentTextColor())
}
private fun initColorVariables() {
curTextColor = baseConfig.textColor
curBackgroundColor = baseConfig.backgroundColor
curPrimaryColor = baseConfig.primaryColor
curAccentColor = baseConfig.accentColor
curAppIconColor = baseConfig.appIconColor
}
private fun setupColorsPickers() {
val textColor = getCurrentTextColor()
val backgroundColor = getCurrentBackgroundColor()
val primaryColor = getCurrentPrimaryColor()
binding.customizationTextColor.setFillWithStroke(textColor, backgroundColor)
binding.customizationPrimaryColor.setFillWithStroke(primaryColor, backgroundColor)
binding.customizationAccentColor.setFillWithStroke(curAccentColor, backgroundColor)
binding.customizationBackgroundColor.setFillWithStroke(backgroundColor, backgroundColor)
binding.customizationAppIconColor.setFillWithStroke(curAppIconColor, backgroundColor)
binding.applyToAll.setTextColor(primaryColor.getContrastColor())
binding.customizationTextColorHolder.setOnClickListener { pickTextColor() }
binding.customizationBackgroundColorHolder.setOnClickListener { pickBackgroundColor() }
binding.customizationPrimaryColorHolder.setOnClickListener { pickPrimaryColor() }
binding.customizationAccentColorHolder.setOnClickListener { pickAccentColor() }
handleAccentColorLayout()
binding.applyToAll.setOnClickListener {
applyToAll()
}
binding.customizationAppIconColorHolder.setOnClickListener {
if (baseConfig.wasAppIconCustomizationWarningShown) {
pickAppIconColor()
} else {
ConfirmationDialog(this, "", R.string.app_icon_color_warning, R.string.ok, 0) {
baseConfig.wasAppIconCustomizationWarningShown = true
pickAppIconColor()
}
}
}
}
private fun hasColorChanged(old: Int, new: Int) = Math.abs(old - new) > 1
private fun colorChanged() {
hasUnsavedChanges = true
setupColorsPickers()
refreshMenuItems()
}
private fun setCurrentTextColor(color: Int) {
curTextColor = color
updateLabelColors(color)
}
private fun setCurrentBackgroundColor(color: Int) {
curBackgroundColor = color
updateBackgroundColor(color)
}
private fun setCurrentPrimaryColor(color: Int) {
curPrimaryColor = color
updateActionbarColor(color)
updateApplyToAllColors(color)
}
private fun updateApplyToAllColors(newColor: Int) {
if (newColor == baseConfig.primaryColor && !baseConfig.isUsingSystemTheme) {
binding.applyToAll.setBackgroundResource(R.drawable.button_background_rounded)
} else {
val applyBackground = resources.getDrawable(R.drawable.button_background_rounded, theme) as RippleDrawable
(applyBackground as LayerDrawable).findDrawableByLayerId(R.id.button_background_holder).applyColorFilter(newColor)
binding.applyToAll.background = applyBackground
}
}
private fun handleAccentColorLayout() {
binding.customizationAccentColorHolder.beVisibleIf(curSelectedThemeId == THEME_WHITE || isCurrentWhiteTheme() || curSelectedThemeId == THEME_BLACK_WHITE || isCurrentBlackAndWhiteTheme())
binding.customizationAccentColorLabel.text = getString(
if (curSelectedThemeId == THEME_WHITE || isCurrentWhiteTheme()) {
R.string.accent_color_white
} else {
R.string.accent_color_black_and_white
}
)
}
private fun isCurrentWhiteTheme() = curTextColor == DARK_GREY && curPrimaryColor == Color.WHITE && curBackgroundColor == Color.WHITE
private fun isCurrentBlackAndWhiteTheme() = curTextColor == Color.WHITE && curPrimaryColor == Color.BLACK && curBackgroundColor == Color.BLACK
private fun pickTextColor() {
ColorPickerDialog(this, curTextColor) { wasPositivePressed, color ->
if (wasPositivePressed) {
if (hasColorChanged(curTextColor, color)) {
setCurrentTextColor(color)
colorChanged()
updateColorTheme(getUpdatedTheme())
}
}
}
}
private fun pickBackgroundColor() {
ColorPickerDialog(this, curBackgroundColor) { wasPositivePressed, color ->
if (wasPositivePressed) {
if (hasColorChanged(curBackgroundColor, color)) {
setCurrentBackgroundColor(color)
colorChanged()
updateColorTheme(getUpdatedTheme())
}
}
}
}
private fun pickPrimaryColor() {
if (!packageName.startsWith("com.simplemobiletools.", true) && baseConfig.appRunCount > 50) {
finish()
return
}
curPrimaryLineColorPicker = LineColorPickerDialog(this, curPrimaryColor, true, toolbar = binding.customizationToolbar) { wasPositivePressed, color ->
curPrimaryLineColorPicker = null
if (wasPositivePressed) {
if (hasColorChanged(curPrimaryColor, color)) {
setCurrentPrimaryColor(color)
colorChanged()
updateColorTheme(getUpdatedTheme())
setTheme(getThemeId(color))
}
updateMenuItemColors(binding.customizationToolbar.menu, color)
setupToolbar(binding.customizationToolbar, NavigationIcon.Cross, color)
} else {
updateActionbarColor(curPrimaryColor)
setTheme(getThemeId(curPrimaryColor))
updateMenuItemColors(binding.customizationToolbar.menu, curPrimaryColor)
setupToolbar(binding.customizationToolbar, NavigationIcon.Cross, curPrimaryColor)
updateTopBarColors(binding.customizationToolbar, curPrimaryColor)
}
}
}
private fun pickAccentColor() {
ColorPickerDialog(this, curAccentColor) { wasPositivePressed, color ->
if (wasPositivePressed) {
if (hasColorChanged(curAccentColor, color)) {
curAccentColor = color
colorChanged()
if (isCurrentWhiteTheme() || isCurrentBlackAndWhiteTheme()) {
updateActionbarColor(getCurrentStatusBarColor())
}
}
}
}
}
private fun pickAppIconColor() {
LineColorPickerDialog(this, curAppIconColor, false, R.array.md_app_icon_colors, getAppIconIDs()) { wasPositivePressed, color ->
if (wasPositivePressed) {
if (hasColorChanged(curAppIconColor, color)) {
curAppIconColor = color
colorChanged()
updateColorTheme(getUpdatedTheme())
}
}
}
}
private fun getUpdatedTheme() = if (curSelectedThemeId == THEME_SHARED) THEME_SHARED else getCurrentThemeId()
private fun applyToAll() {
if (isThankYouInstalled()) {
ConfirmationDialog(this, "", R.string.share_colors_success, R.string.ok, 0) {
Intent().apply {
action = MyContentProvider.SHARED_THEME_ACTIVATED
sendBroadcast(this)
}
if (!predefinedThemes.containsKey(THEME_SHARED)) {
predefinedThemes[THEME_SHARED] = MyTheme(getString(R.string.shared), 0, 0, 0, 0)
}
baseConfig.wasSharedThemeEverActivated = true
binding.applyToAllHolder.beGone()
updateColorTheme(THEME_SHARED)
saveChanges(false)
}
} else {
PurchaseThankYouDialog(this)
}
}
private fun updateLabelColors(textColor: Int) {
arrayListOf(
binding.customizationThemeLabel,
binding.customizationTheme,
binding.customizationTextColorLabel,
binding.customizationBackgroundColorLabel,
binding.customizationPrimaryColorLabel,
binding.customizationAccentColorLabel,
binding.customizationAppIconColorLabel
).forEach {
it.setTextColor(textColor)
}
val primaryColor = getCurrentPrimaryColor()
binding.applyToAll.setTextColor(primaryColor.getContrastColor())
updateApplyToAllColors(primaryColor)
}
private fun getCurrentTextColor() = if (binding.customizationTheme.value == getMaterialYouString()) {
resources.getColor(R.color.you_neutral_text_color)
} else {
curTextColor
}
private fun getCurrentBackgroundColor() = if (binding.customizationTheme.value == getMaterialYouString()) {
resources.getColor(R.color.you_background_color)
} else {
curBackgroundColor
}
private fun getCurrentPrimaryColor() = if (binding.customizationTheme.value == getMaterialYouString()) {
resources.getColor(R.color.you_primary_color)
} else {
curPrimaryColor
}
private fun getCurrentStatusBarColor() = if (binding.customizationTheme.value == getMaterialYouString()) {
resources.getColor(R.color.you_status_bar_color)
} else {
curPrimaryColor
}
private fun getMaterialYouString() = "${getString(R.string.system_default)} (${getString(R.string.material_you)})"
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/activities/CustomizationActivity.kt | 596158304 |
package com.simplemobiletools.commons.views
import android.content.ContentValues
import android.content.Context
import android.provider.MediaStore
import android.util.AttributeSet
import android.widget.RelativeLayout
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.activities.BaseSimpleActivity
import com.simplemobiletools.commons.databinding.TabRenameSimpleBinding
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.interfaces.RenameTab
import com.simplemobiletools.commons.models.Android30RenameFormat
import com.simplemobiletools.commons.models.FileDirItem
import java.io.File
class RenameSimpleTab(context: Context, attrs: AttributeSet) : RelativeLayout(context, attrs), RenameTab {
var ignoreClicks = false
var stopLooping = false // we should request the permission on Android 30+ for all uris at once, not one by one
var activity: BaseSimpleActivity? = null
var paths = ArrayList<String>()
private lateinit var binding: TabRenameSimpleBinding
override fun onFinishInflate() {
super.onFinishInflate()
binding = TabRenameSimpleBinding.bind(this)
context.updateTextColors(binding.renameSimpleHolder)
}
override fun initTab(activity: BaseSimpleActivity, paths: ArrayList<String>) {
this.activity = activity
this.paths = paths
}
override fun dialogConfirmed(useMediaFileExtension: Boolean, callback: (success: Boolean) -> Unit) {
stopLooping = false
val valueToAdd = binding.renameSimpleValue.text.toString()
val append = binding.renameSimpleRadioGroup.checkedRadioButtonId == binding.renameSimpleRadioAppend.id
if (valueToAdd.isEmpty()) {
callback(false)
return
}
if (!valueToAdd.isAValidFilename()) {
activity?.toast(R.string.invalid_name)
return
}
val validPaths = paths.filter { activity?.getDoesFilePathExist(it) == true }
val firstPath = validPaths.firstOrNull()
val sdFilePath = validPaths.firstOrNull { activity?.isPathOnSD(it) == true } ?: firstPath
if (firstPath == null || sdFilePath == null) {
activity?.toast(R.string.unknown_error_occurred)
return
}
activity?.handleSAFDialog(sdFilePath) {
if (!it) {
return@handleSAFDialog
}
activity?.checkManageMediaOrHandleSAFDialogSdk30(firstPath) {
if (!it) {
return@checkManageMediaOrHandleSAFDialogSdk30
}
ignoreClicks = true
var pathsCnt = validPaths.size
for (path in validPaths) {
if (stopLooping) {
return@checkManageMediaOrHandleSAFDialogSdk30
}
val fullName = path.getFilenameFromPath()
var dotAt = fullName.lastIndexOf(".")
if (dotAt == -1) {
dotAt = fullName.length
}
val name = fullName.substring(0, dotAt)
val extension = if (fullName.contains(".")) ".${fullName.getFilenameExtension()}" else ""
val newName = if (append) {
"$name$valueToAdd$extension"
} else {
"$valueToAdd$fullName"
}
val newPath = "${path.getParentPath()}/$newName"
if (activity?.getDoesFilePathExist(newPath) == true) {
continue
}
activity?.renameFile(path, newPath, true) { success, android30Format ->
if (success) {
pathsCnt--
if (pathsCnt == 0) {
callback(true)
}
} else {
ignoreClicks = false
if (android30Format != Android30RenameFormat.NONE) {
stopLooping = true
renameAllFiles(validPaths, append, valueToAdd, android30Format, callback)
}
}
}
}
stopLooping = false
}
}
}
private fun renameAllFiles(
paths: List<String>,
appendString: Boolean,
stringToAdd: String,
android30Format: Android30RenameFormat,
callback: (success: Boolean) -> Unit
) {
val fileDirItems = paths.map { File(it).toFileDirItem(context) }
val uriPairs = context.getUrisPathsFromFileDirItems(fileDirItems)
val validPaths = uriPairs.first
val uris = uriPairs.second
val activity = activity
activity?.updateSDK30Uris(uris) { success ->
if (success) {
try {
uris.forEachIndexed { index, uri ->
val path = validPaths[index]
val fullName = path.getFilenameFromPath()
var dotAt = fullName.lastIndexOf(".")
if (dotAt == -1) {
dotAt = fullName.length
}
val name = fullName.substring(0, dotAt)
val extension = if (fullName.contains(".")) ".${fullName.getFilenameExtension()}" else ""
val newName = if (appendString) {
"$name$stringToAdd$extension"
} else {
"$stringToAdd$fullName"
}
when (android30Format) {
Android30RenameFormat.SAF -> {
val sourceFile = File(path).toFileDirItem(activity)
val newPath = "${path.getParentPath()}/$newName"
val destinationFile = FileDirItem(
newPath,
newName,
sourceFile.isDirectory,
sourceFile.children,
sourceFile.size,
sourceFile.modified
)
if (activity.copySingleFileSdk30(sourceFile, destinationFile)) {
if (!activity.baseConfig.keepLastModified) {
File(newPath).setLastModified(System.currentTimeMillis())
}
activity.contentResolver.delete(uri, null)
activity.updateInMediaStore(path, newPath)
activity.scanPathsRecursively(arrayListOf(newPath))
}
}
Android30RenameFormat.CONTENT_RESOLVER -> {
val values = ContentValues().apply {
put(MediaStore.Images.Media.DISPLAY_NAME, newName)
}
context.contentResolver.update(uri, values, null, null)
}
Android30RenameFormat.NONE -> {
activity.runOnUiThread {
callback(true)
}
return@forEachIndexed
}
}
}
activity.runOnUiThread {
callback(true)
}
} catch (e: Exception) {
activity.runOnUiThread {
activity.showErrorToast(e)
callback(false)
}
}
}
}
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/views/RenameSimpleTab.kt | 1010832445 |
package com.simplemobiletools.commons.views
import android.content.Context
import androidx.recyclerview.widget.RecyclerView
import kotlin.math.max
/**
* RecyclerView GridLayoutManager but with automatic spanCount calculation.
*
* @param context The initiating view's context.
* @param itemWidth: Grid item width in pixels. Will be used to calculate span count.
*/
class AutoGridLayoutManager(
context: Context,
private var itemWidth: Int
) : MyGridLayoutManager(context, 1) {
init {
require(itemWidth >= 0) {
"itemWidth must be >= 0"
}
}
override fun onLayoutChildren(recycler: RecyclerView.Recycler?, state: RecyclerView.State?) {
val width = width
val height = height
if (itemWidth > 0 && width > 0 && height > 0) {
val totalSpace = if (orientation == VERTICAL) {
width - paddingRight - paddingLeft
} else {
height - paddingTop - paddingBottom
}
spanCount = max(1, totalSpace / itemWidth)
}
super.onLayoutChildren(recycler, state)
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/views/AutoGridLayoutManager.kt | 2513065133 |
package com.simplemobiletools.commons.views
import android.content.Context
import android.content.res.ColorStateList
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatCheckBox
import com.simplemobiletools.commons.extensions.adjustAlpha
class MyAppCompatCheckbox : AppCompatCheckBox {
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle)
fun setColors(textColor: Int, accentColor: Int, backgroundColor: Int) {
setTextColor(textColor)
val colorStateList = ColorStateList(
arrayOf(
intArrayOf(-android.R.attr.state_checked),
intArrayOf(android.R.attr.state_checked)
),
intArrayOf(textColor.adjustAlpha(0.6f), accentColor)
)
supportButtonTintList = colorStateList
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/views/MyAppCompatCheckbox.kt | 1120862615 |
package com.simplemobiletools.commons.views
import android.content.Context
import android.util.AttributeSet
import android.widget.SeekBar
import com.simplemobiletools.commons.extensions.applyColorFilter
class MySeekBar : SeekBar {
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle)
fun setColors(textColor: Int, accentColor: Int, backgroundColor: Int) {
progressDrawable.applyColorFilter(accentColor)
thumb?.applyColorFilter(accentColor)
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/views/MySeekBar.kt | 3436164887 |
package com.simplemobiletools.commons.views
import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.widget.ScrollView
class MyScrollView : ScrollView {
var isScrollable = true
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle)
override fun onTouchEvent(ev: MotionEvent): Boolean {
return when (ev.action) {
MotionEvent.ACTION_DOWN -> {
if (isScrollable) {
super.onTouchEvent(ev)
} else {
isScrollable
}
}
else -> super.onTouchEvent(ev)
}
}
override fun onInterceptTouchEvent(ev: MotionEvent?): Boolean {
return if (!isScrollable) {
false
} else {
super.onInterceptTouchEvent(ev)
}
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/views/MyScrollView.kt | 1012441472 |
package com.simplemobiletools.commons.views
import android.content.Context
import android.util.AttributeSet
import android.widget.TextView
class MyTextView : TextView {
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle)
fun setColors(textColor: Int, accentColor: Int, backgroundColor: Int) {
setTextColor(textColor)
setLinkTextColor(accentColor)
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/views/MyTextView.kt | 4121130571 |
package com.simplemobiletools.commons.views
import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import com.duolingo.open.rtlviewpager.RtlViewPager
class MyViewPager : RtlViewPager {
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
override fun onInterceptTouchEvent(ev: MotionEvent): Boolean {
return try {
super.onInterceptTouchEvent(ev)
} catch (ignored: Exception) {
false
}
}
override fun onTouchEvent(ev: MotionEvent): Boolean {
return try {
super.onTouchEvent(ev)
} catch (ignored: Exception) {
false
}
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/views/MyViewPager.kt | 3292664024 |
package com.simplemobiletools.commons.views
import android.content.Context
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatEditText
import com.simplemobiletools.commons.extensions.adjustAlpha
import com.simplemobiletools.commons.extensions.applyColorFilter
import com.simplemobiletools.commons.helpers.MEDIUM_ALPHA
class MyEditText : AppCompatEditText {
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle)
fun setColors(textColor: Int, accentColor: Int, backgroundColor: Int) {
background?.mutate()?.applyColorFilter(accentColor)
// requires android:textCursorDrawable="@null" in xml to color the cursor too
setTextColor(textColor)
setHintTextColor(textColor.adjustAlpha(MEDIUM_ALPHA))
setLinkTextColor(accentColor)
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/views/MyEditText.kt | 2992936106 |
package com.simplemobiletools.commons.views
import android.content.Context
import android.util.AttributeSet
import android.widget.Button
class MyButton : Button {
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle)
fun setColors(textColor: Int, accentColor: Int, backgroundColor: Int) {
setTextColor(textColor)
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/views/MyButton.kt | 3281460876 |
package com.simplemobiletools.commons.views
import android.content.Context
import android.os.Handler
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.ScaleGestureDetector
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.interfaces.RecyclerScrollCallback
// drag selection is based on https://github.com/afollestad/drag-select-recyclerview
open class MyRecyclerView : RecyclerView {
private val AUTO_SCROLL_DELAY = 25L
private var isZoomEnabled = false
private var isDragSelectionEnabled = false
private var zoomListener: MyZoomListener? = null
private var dragListener: MyDragListener? = null
private var autoScrollHandler = Handler()
private var scaleDetector: ScaleGestureDetector
private var dragSelectActive = false
private var lastDraggedIndex = -1
private var minReached = 0
private var maxReached = 0
private var initialSelection = 0
private var hotspotHeight = 0
private var hotspotOffsetTop = 0
private var hotspotOffsetBottom = 0
private var hotspotTopBoundStart = 0
private var hotspotTopBoundEnd = 0
private var hotspotBottomBoundStart = 0
private var hotspotBottomBoundEnd = 0
private var autoScrollVelocity = 0
private var inTopHotspot = false
private var inBottomHotspot = false
private var currScaleFactor = 1.0f
private var lastUp = 0L // allow only pinch zoom, not double tap
// things related to parallax scrolling (for now only in the music player)
// cut from https://github.com/ksoichiro/Android-ObservableScrollView
var recyclerScrollCallback: RecyclerScrollCallback? = null
private var mPrevFirstVisiblePosition = 0
private var mPrevScrolledChildrenHeight = 0
private var mPrevFirstVisibleChildHeight = -1
private var mScrollY = 0
// variables used for fetching additional items at scrolling to the bottom/top
var endlessScrollListener: EndlessScrollListener? = null
private var totalItemCount = 0
private var lastMaxItemIndex = 0
private var linearLayoutManager: LinearLayoutManager? = null
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
init {
hotspotHeight = context.resources.getDimensionPixelSize(R.dimen.dragselect_hotspot_height)
if (layoutManager is LinearLayoutManager) {
linearLayoutManager = layoutManager as LinearLayoutManager
}
val gestureListener = object : MyGestureListener {
override fun getLastUp() = lastUp
override fun getScaleFactor() = currScaleFactor
override fun setScaleFactor(value: Float) {
currScaleFactor = value
}
override fun getZoomListener() = zoomListener
}
scaleDetector = ScaleGestureDetector(context, GestureListener(gestureListener))
}
override fun onMeasure(widthSpec: Int, heightSpec: Int) {
super.onMeasure(widthSpec, heightSpec)
if (hotspotHeight > -1) {
hotspotTopBoundStart = hotspotOffsetTop
hotspotTopBoundEnd = hotspotOffsetTop + hotspotHeight
hotspotBottomBoundStart = measuredHeight - hotspotHeight - hotspotOffsetBottom
hotspotBottomBoundEnd = measuredHeight - hotspotOffsetBottom
}
}
private val autoScrollRunnable = object : Runnable {
override fun run() {
if (inTopHotspot) {
scrollBy(0, -autoScrollVelocity)
autoScrollHandler.postDelayed(this, AUTO_SCROLL_DELAY)
} else if (inBottomHotspot) {
scrollBy(0, autoScrollVelocity)
autoScrollHandler.postDelayed(this, AUTO_SCROLL_DELAY)
}
}
}
fun resetItemCount() {
totalItemCount = 0
}
override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
if (!dragSelectActive) {
try {
super.dispatchTouchEvent(ev)
} catch (ignored: Exception) {
}
}
when (ev.action) {
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
dragSelectActive = false
inTopHotspot = false
inBottomHotspot = false
autoScrollHandler.removeCallbacks(autoScrollRunnable)
currScaleFactor = 1.0f
lastUp = System.currentTimeMillis()
return true
}
MotionEvent.ACTION_MOVE -> {
if (dragSelectActive) {
val itemPosition = getItemPosition(ev)
if (hotspotHeight > -1) {
if (ev.y in hotspotTopBoundStart.toFloat()..hotspotTopBoundEnd.toFloat()) {
inBottomHotspot = false
if (!inTopHotspot) {
inTopHotspot = true
autoScrollHandler.removeCallbacks(autoScrollRunnable)
autoScrollHandler.postDelayed(autoScrollRunnable, AUTO_SCROLL_DELAY)
}
val simulatedFactor = (hotspotTopBoundEnd - hotspotTopBoundStart).toFloat()
val simulatedY = ev.y - hotspotTopBoundStart
autoScrollVelocity = (simulatedFactor - simulatedY).toInt() / 2
} else if (ev.y in hotspotBottomBoundStart.toFloat()..hotspotBottomBoundEnd.toFloat()) {
inTopHotspot = false
if (!inBottomHotspot) {
inBottomHotspot = true
autoScrollHandler.removeCallbacks(autoScrollRunnable)
autoScrollHandler.postDelayed(autoScrollRunnable, AUTO_SCROLL_DELAY)
}
val simulatedY = ev.y + hotspotBottomBoundEnd
val simulatedFactor = (hotspotBottomBoundStart + hotspotBottomBoundEnd).toFloat()
autoScrollVelocity = (simulatedY - simulatedFactor).toInt() / 2
} else if (inTopHotspot || inBottomHotspot) {
autoScrollHandler.removeCallbacks(autoScrollRunnable)
inTopHotspot = false
inBottomHotspot = false
}
}
if (itemPosition != RecyclerView.NO_POSITION && lastDraggedIndex != itemPosition) {
lastDraggedIndex = itemPosition
if (minReached == -1) {
minReached = lastDraggedIndex
}
if (maxReached == -1) {
maxReached = lastDraggedIndex
}
if (lastDraggedIndex > maxReached) {
maxReached = lastDraggedIndex
}
if (lastDraggedIndex < minReached) {
minReached = lastDraggedIndex
}
dragListener?.selectRange(initialSelection, lastDraggedIndex, minReached, maxReached)
if (initialSelection == lastDraggedIndex) {
minReached = lastDraggedIndex
maxReached = lastDraggedIndex
}
}
return true
}
}
}
return if (isZoomEnabled) {
scaleDetector.onTouchEvent(ev)
} else {
true
}
}
fun setupDragListener(dragListener: MyDragListener?) {
isDragSelectionEnabled = dragListener != null
this.dragListener = dragListener
}
fun setupZoomListener(zoomListener: MyZoomListener?) {
isZoomEnabled = zoomListener != null
this.zoomListener = zoomListener
}
fun setDragSelectActive(initialSelection: Int) {
if (dragSelectActive || !isDragSelectionEnabled)
return
lastDraggedIndex = -1
minReached = -1
maxReached = -1
this.initialSelection = initialSelection
dragSelectActive = true
dragListener?.selectItem(initialSelection)
}
private fun getItemPosition(e: MotionEvent): Int {
val v = findChildViewUnder(e.x, e.y) ?: return RecyclerView.NO_POSITION
if (v.tag == null || v.tag !is RecyclerView.ViewHolder) {
throw IllegalStateException("Make sure your adapter makes a call to super.onBindViewHolder(), and doesn't override itemView tags.")
}
val holder = v.tag as RecyclerView.ViewHolder
return holder.adapterPosition
}
override fun onScrollStateChanged(state: Int) {
super.onScrollStateChanged(state)
if (endlessScrollListener != null) {
if (totalItemCount == 0) {
totalItemCount = adapter?.itemCount ?: return
}
if (state == SCROLL_STATE_IDLE) {
val lastVisiblePosition = linearLayoutManager?.findLastVisibleItemPosition() ?: 0
if (lastVisiblePosition != lastMaxItemIndex && lastVisiblePosition == totalItemCount - 1) {
lastMaxItemIndex = lastVisiblePosition
endlessScrollListener!!.updateBottom()
}
val firstVisiblePosition = linearLayoutManager?.findFirstVisibleItemPosition() ?: -1
if (firstVisiblePosition == 0) {
endlessScrollListener!!.updateTop()
}
}
}
}
override fun onScrollChanged(l: Int, t: Int, oldl: Int, oldt: Int) {
super.onScrollChanged(l, t, oldl, oldt)
if (recyclerScrollCallback != null) {
if (childCount > 0) {
val firstVisiblePosition = getChildAdapterPosition(getChildAt(0))
val firstVisibleChild = getChildAt(0)
if (firstVisibleChild != null) {
if (mPrevFirstVisiblePosition < firstVisiblePosition) {
mPrevScrolledChildrenHeight += mPrevFirstVisibleChildHeight
}
if (firstVisiblePosition == 0) {
mPrevFirstVisibleChildHeight = firstVisibleChild.height
mPrevScrolledChildrenHeight = 0
}
if (mPrevFirstVisibleChildHeight < 0) {
mPrevFirstVisibleChildHeight = 0
}
mScrollY = mPrevScrolledChildrenHeight - firstVisibleChild.top
recyclerScrollCallback?.onScrolled(mScrollY)
}
}
}
}
class GestureListener(val gestureListener: MyGestureListener) : ScaleGestureDetector.SimpleOnScaleGestureListener() {
private val ZOOM_IN_THRESHOLD = -0.4f
private val ZOOM_OUT_THRESHOLD = 0.15f
override fun onScale(detector: ScaleGestureDetector): Boolean {
gestureListener.apply {
if (System.currentTimeMillis() - getLastUp() < 1000)
return false
val diff = getScaleFactor() - detector.scaleFactor
if (diff < ZOOM_IN_THRESHOLD && getScaleFactor() == 1.0f) {
getZoomListener()?.zoomIn()
setScaleFactor(detector.scaleFactor)
} else if (diff > ZOOM_OUT_THRESHOLD && getScaleFactor() == 1.0f) {
getZoomListener()?.zoomOut()
setScaleFactor(detector.scaleFactor)
}
}
return false
}
}
interface MyZoomListener {
fun zoomOut()
fun zoomIn()
}
interface MyDragListener {
fun selectItem(position: Int)
fun selectRange(initialSelection: Int, lastDraggedIndex: Int, minReached: Int, maxReached: Int)
}
interface MyGestureListener {
fun getLastUp(): Long
fun getScaleFactor(): Float
fun setScaleFactor(value: Float)
fun getZoomListener(): MyZoomListener?
}
interface EndlessScrollListener {
fun updateTop()
fun updateBottom()
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/views/MyRecyclerView.kt | 3595264010 |
package com.simplemobiletools.commons.views
import android.content.Context
import android.util.AttributeSet
import androidx.recyclerview.widget.GridLayoutManager
open class MyGridLayoutManager : GridLayoutManager {
constructor(context: Context, spanCount: Int) : super(context, spanCount)
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes)
constructor(context: Context, spanCount: Int, orientation: Int, reverseLayout: Boolean) : super(context, spanCount, orientation, reverseLayout)
// fixes crash java.lang.IndexOutOfBoundsException: Inconsistency detected...
// taken from https://stackoverflow.com/a/33985508/1967672
override fun supportsPredictiveItemAnimations() = false
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/views/MyGridLayoutManager.kt | 3266844232 |
package com.simplemobiletools.commons.views
import android.content.Context
import android.util.AttributeSet
import android.widget.AutoCompleteTextView
import com.simplemobiletools.commons.extensions.adjustAlpha
import com.simplemobiletools.commons.extensions.applyColorFilter
class MyAutoCompleteTextView : AutoCompleteTextView {
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle)
fun setColors(textColor: Int, accentColor: Int, backgroundColor: Int) {
background?.mutate()?.applyColorFilter(accentColor)
// requires android:textCursorDrawable="@null" in xml to color the cursor too
setTextColor(textColor)
setHintTextColor(textColor.adjustAlpha(0.5f))
setLinkTextColor(accentColor)
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/views/MyAutoCompleteTextView.kt | 3469922328 |
package com.simplemobiletools.commons.views
import android.content.Context
import android.content.res.ColorStateList
import android.graphics.drawable.ColorDrawable
import android.util.AttributeSet
import android.util.TypedValue
import android.view.LayoutInflater
import android.view.View
import android.widget.HorizontalScrollView
import android.widget.LinearLayout
import androidx.core.content.ContextCompat
import androidx.core.view.ViewCompat
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.databinding.ItemBreadcrumbBinding
import com.simplemobiletools.commons.databinding.ItemBreadcrumbFirstBinding
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.models.FileDirItem
class Breadcrumbs(context: Context, attrs: AttributeSet) : HorizontalScrollView(context, attrs) {
private val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
private val itemsLayout: LinearLayout
private var textColor = context.getProperTextColor()
private var fontSize = resources.getDimension(R.dimen.bigger_text_size)
private var lastPath = ""
private var isLayoutDirty = true
private var isScrollToSelectedItemPending = false
private var isFirstScroll = true
private var stickyRootInitialLeft = 0
private var rootStartPadding = 0
private val textColorStateList: ColorStateList
get() = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_activated), intArrayOf()),
intArrayOf(
textColor,
textColor.adjustAlpha(0.6f)
)
)
var listener: BreadcrumbsListener? = null
var isShownInDialog = false
init {
isHorizontalScrollBarEnabled = false
itemsLayout = LinearLayout(context)
itemsLayout.orientation = LinearLayout.HORIZONTAL
rootStartPadding = paddingStart
itemsLayout.setPaddingRelative(0, paddingTop, paddingEnd, paddingBottom)
setPaddingRelative(0, 0, 0, 0)
addView(itemsLayout, LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT))
onGlobalLayout {
stickyRootInitialLeft = if (itemsLayout.childCount > 0) {
itemsLayout.getChildAt(0).left
} else {
0
}
}
}
private fun recomputeStickyRootLocation(left: Int) {
stickyRootInitialLeft = left
handleRootStickiness(scrollX)
}
private fun handleRootStickiness(scrollX: Int) {
if (scrollX > stickyRootInitialLeft) {
stickRoot(scrollX - stickyRootInitialLeft)
} else {
freeRoot()
}
}
private fun freeRoot() {
if (itemsLayout.childCount > 0) {
itemsLayout.getChildAt(0).translationX = 0f
}
}
private fun stickRoot(translationX: Int) {
if (itemsLayout.childCount > 0) {
val root = itemsLayout.getChildAt(0)
root.translationX = translationX.toFloat()
ViewCompat.setTranslationZ(root, translationZ)
}
}
override fun onScrollChanged(scrollX: Int, scrollY: Int, oldScrollX: Int, oldScrollY: Int) {
super.onScrollChanged(scrollX, scrollY, oldScrollX, oldScrollY)
handleRootStickiness(scrollX)
}
override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
super.onLayout(changed, left, top, right, bottom)
isLayoutDirty = false
if (isScrollToSelectedItemPending) {
scrollToSelectedItem()
isScrollToSelectedItemPending = false
}
recomputeStickyRootLocation(left)
}
private fun scrollToSelectedItem() {
if (isLayoutDirty) {
isScrollToSelectedItemPending = true
return
}
var selectedIndex = itemsLayout.childCount - 1
val cnt = itemsLayout.childCount
for (i in 0 until cnt) {
val child = itemsLayout.getChildAt(i)
if ((child.tag as? FileDirItem)?.path?.trimEnd('/') == lastPath.trimEnd('/')) {
selectedIndex = i
break
}
}
val selectedItemView = itemsLayout.getChildAt(selectedIndex)
val scrollX = if (layoutDirection == View.LAYOUT_DIRECTION_LTR) {
selectedItemView.left - itemsLayout.paddingStart
} else {
selectedItemView.right - width + itemsLayout.paddingStart
}
if (!isFirstScroll && isShown) {
smoothScrollTo(scrollX, 0)
} else {
scrollTo(scrollX, 0)
}
isFirstScroll = false
}
override fun requestLayout() {
isLayoutDirty = true
super.requestLayout()
}
fun setBreadcrumb(fullPath: String) {
lastPath = fullPath
val basePath = fullPath.getBasePath(context)
var currPath = basePath
val tempPath = context.humanizePath(fullPath)
itemsLayout.removeAllViews()
val dirs = tempPath.split("/").dropLastWhile(String::isEmpty)
for (i in dirs.indices) {
val dir = dirs[i]
if (i > 0) {
currPath += dir + "/"
}
if (dir.isEmpty()) {
continue
}
currPath = "${currPath.trimEnd('/')}/"
val item = FileDirItem(currPath, dir, true, 0, 0, 0)
addBreadcrumb(item, i, i > 0)
scrollToSelectedItem()
}
}
private fun addBreadcrumb(item: FileDirItem, index: Int, addPrefix: Boolean) {
if (itemsLayout.childCount == 0) {
val firstItemBgColor = if (isShownInDialog && context.baseConfig.isUsingSystemTheme) {
resources.getColor(R.color.you_dialog_background_color, context.theme)
} else {
context.getProperBackgroundColor()
}
ItemBreadcrumbFirstBinding.inflate(inflater, itemsLayout, false).apply {
resources.apply {
breadcrumbText.background = ContextCompat.getDrawable(context, R.drawable.button_background)
breadcrumbText.background.applyColorFilter(textColor)
elevation = 1f
background = ColorDrawable(firstItemBgColor)
val medium = getDimension(R.dimen.medium_margin).toInt()
breadcrumbText.setPadding(medium, medium, medium, medium)
setPadding(rootStartPadding, 0, 0, 0)
}
isActivated = item.path.trimEnd('/') == lastPath.trimEnd('/')
breadcrumbText.text = item.name
breadcrumbText.setTextColor(textColorStateList)
breadcrumbText.setTextSize(TypedValue.COMPLEX_UNIT_PX, fontSize)
itemsLayout.addView(this.root)
breadcrumbText.setOnClickListener {
if (itemsLayout.getChildAt(index) != null) {
listener?.breadcrumbClicked(index)
}
}
root.tag = item
}
} else {
ItemBreadcrumbBinding.inflate(inflater, itemsLayout, false).apply {
var textToAdd = item.name
if (addPrefix) {
textToAdd = "> $textToAdd"
}
isActivated = item.path.trimEnd('/') == lastPath.trimEnd('/')
breadcrumbText.text = textToAdd
breadcrumbText.setTextColor(textColorStateList)
breadcrumbText.setTextSize(TypedValue.COMPLEX_UNIT_PX, fontSize)
itemsLayout.addView(root)
breadcrumbText.setOnClickListener { v ->
if (itemsLayout.getChildAt(index) != null && itemsLayout.getChildAt(index) == v) {
if ((v.tag as? FileDirItem)?.path?.trimEnd('/') == lastPath.trimEnd('/')) {
scrollToSelectedItem()
} else {
listener?.breadcrumbClicked(index)
}
}
}
root.tag = item
}
}
}
fun updateColor(color: Int) {
textColor = color
setBreadcrumb(lastPath)
}
fun updateFontSize(size: Float, updateTexts: Boolean) {
fontSize = size
if (updateTexts) {
setBreadcrumb(lastPath)
}
}
fun removeBreadcrumb() {
itemsLayout.removeView(itemsLayout.getChildAt(itemsLayout.childCount - 1))
}
fun getItem(index: Int) = itemsLayout.getChildAt(index).tag as FileDirItem
fun getLastItem() = itemsLayout.getChildAt(itemsLayout.childCount - 1).tag as FileDirItem
fun getItemCount() = itemsLayout.childCount
interface BreadcrumbsListener {
fun breadcrumbClicked(id: Int)
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/views/Breadcrumbs.kt | 1718087207 |
package com.simplemobiletools.commons.views
import android.content.Context
import android.content.res.ColorStateList
import android.util.AttributeSet
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.simplemobiletools.commons.extensions.applyColorFilter
import com.simplemobiletools.commons.extensions.getContrastColor
class MyFloatingActionButton : FloatingActionButton {
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle)
fun setColors(textColor: Int, accentColor: Int, backgroundColor: Int) {
backgroundTintList = ColorStateList.valueOf(accentColor)
applyColorFilter(accentColor.getContrastColor())
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/views/MyFloatingActionButton.kt | 1399476892 |
package com.simplemobiletools.commons.views
import android.content.Context
import android.content.res.ColorStateList
import android.util.AttributeSet
import com.google.android.material.textfield.TextInputLayout
import com.simplemobiletools.commons.extensions.adjustAlpha
import com.simplemobiletools.commons.extensions.value
import com.simplemobiletools.commons.helpers.HIGHER_ALPHA
import com.simplemobiletools.commons.helpers.MEDIUM_ALPHA
class MyTextInputLayout : TextInputLayout {
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle)
// we need to use reflection to make some colors work well
fun setColors(textColor: Int, accentColor: Int, backgroundColor: Int) {
try {
editText!!.setTextColor(textColor)
editText!!.backgroundTintList = ColorStateList.valueOf(accentColor)
val hintColor = if (editText!!.value.isEmpty()) textColor.adjustAlpha(HIGHER_ALPHA) else textColor
val defaultTextColor = TextInputLayout::class.java.getDeclaredField("defaultHintTextColor")
defaultTextColor.isAccessible = true
defaultTextColor.set(this, ColorStateList(arrayOf(intArrayOf(0)), intArrayOf(hintColor)))
val focusedTextColor = TextInputLayout::class.java.getDeclaredField("focusedTextColor")
focusedTextColor.isAccessible = true
focusedTextColor.set(this, ColorStateList(arrayOf(intArrayOf(0)), intArrayOf(accentColor)))
val defaultHintTextColor = textColor.adjustAlpha(MEDIUM_ALPHA)
val boxColorState = ColorStateList(
arrayOf(
intArrayOf(android.R.attr.state_active),
intArrayOf(android.R.attr.state_focused)
),
intArrayOf(
defaultHintTextColor,
accentColor
)
)
setEndIconTintList(ColorStateList(arrayOf(intArrayOf(0)), intArrayOf(hintColor)))
setBoxStrokeColorStateList(boxColorState)
defaultTextColor.set(this, ColorStateList(arrayOf(intArrayOf(0)), intArrayOf(defaultHintTextColor)))
setHelperTextColor(ColorStateList.valueOf(textColor))
} catch (e: Exception) {
}
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/views/MyTextInputLayout.kt | 2621356058 |
package com.simplemobiletools.commons.views
import android.content.Context
import android.util.AttributeSet
import androidx.biometric.auth.AuthPromptHost
import androidx.constraintlayout.widget.ConstraintLayout
import com.simplemobiletools.commons.databinding.TabBiometricIdBinding
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.DARK_GREY
import com.simplemobiletools.commons.interfaces.HashListener
import com.simplemobiletools.commons.interfaces.SecurityTab
class BiometricIdTab(context: Context, attrs: AttributeSet) : ConstraintLayout(context, attrs), SecurityTab {
private lateinit var hashListener: HashListener
private lateinit var biometricPromptHost: AuthPromptHost
private lateinit var binding: TabBiometricIdBinding
override fun onFinishInflate() {
super.onFinishInflate()
binding = TabBiometricIdBinding.bind(this)
context.updateTextColors(binding.biometricLockHolder)
val textColor = if (context.isWhiteTheme()) {
DARK_GREY
} else {
context.getProperPrimaryColor().getContrastColor()
}
binding.openBiometricDialog.setTextColor(textColor)
binding.openBiometricDialog.setOnClickListener {
biometricPromptHost.activity?.showBiometricPrompt(successCallback = hashListener::receivedHash)
}
}
override fun initTab(
requiredHash: String,
listener: HashListener,
scrollView: MyScrollView,
biometricPromptHost: AuthPromptHost,
showBiometricAuthentication: Boolean
) {
this.biometricPromptHost = biometricPromptHost
hashListener = listener
if (showBiometricAuthentication) {
binding.openBiometricDialog.performClick()
}
}
override fun visibilityChanged(isVisible: Boolean) {}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/views/BiometricIdTab.kt | 4044671693 |
package com.simplemobiletools.commons.views
import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.widget.AdapterView
import android.widget.TextView
import androidx.appcompat.widget.AppCompatSpinner
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.adapters.MyArrayAdapter
import com.simplemobiletools.commons.extensions.applyColorFilter
class MyAppCompatSpinner : AppCompatSpinner {
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle)
fun setColors(textColor: Int, accentColor: Int, backgroundColor: Int) {
if (adapter == null)
return
val cnt = adapter.count
val items = kotlin.arrayOfNulls<Any>(cnt)
for (i in 0 until cnt)
items[i] = adapter.getItem(i)
val position = selectedItemPosition
val padding = resources.getDimension(R.dimen.activity_margin).toInt()
adapter = MyArrayAdapter(context, android.R.layout.simple_spinner_item, items, textColor, backgroundColor, padding)
setSelection(position)
val superListener = onItemSelectedListener
onItemSelectedListener = object : OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
if (view != null) {
(view as TextView).setTextColor(textColor)
}
superListener?.onItemSelected(parent, view, position, id)
}
override fun onNothingSelected(parent: AdapterView<*>?) {
}
}
background.applyColorFilter(textColor)
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/views/MyAppCompatSpinner.kt | 403900057 |
package com.simplemobiletools.commons.views
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.*
import android.graphics.Shader.TileMode
import android.util.AttributeSet
import android.view.View
class ColorPickerSquare(context: Context, attrs: AttributeSet) : View(context, attrs) {
var paint: Paint? = null
var luar: Shader = LinearGradient(0f, 0f, 0f, measuredHeight.toFloat(), Color.WHITE, Color.BLACK, Shader.TileMode.CLAMP)
val color = floatArrayOf(1f, 1f, 1f)
@SuppressLint("DrawAllocation")
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
if (paint == null) {
paint = Paint()
luar = LinearGradient(0f, 0f, 0f, measuredHeight.toFloat(), Color.WHITE, Color.BLACK, TileMode.CLAMP)
}
val rgb = Color.HSVToColor(color)
val dalam = LinearGradient(0f, 0f, measuredWidth.toFloat(), 0f, Color.WHITE, rgb, TileMode.CLAMP)
val shader = ComposeShader(luar, dalam, PorterDuff.Mode.MULTIPLY)
paint!!.shader = shader
canvas.drawRect(0f, 0f, measuredWidth.toFloat(), measuredHeight.toFloat(), paint!!)
}
fun setHue(hue: Float) {
color[0] = hue
invalidate()
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/views/ColorPickerSquare.kt | 3920195898 |
package com.simplemobiletools.commons.views.bottomactionmenu
import android.content.Context
import android.graphics.Color
import android.graphics.Rect
import android.view.*
import android.view.View.MeasureSpec
import android.widget.ArrayAdapter
import android.widget.FrameLayout
import android.widget.ListView
import android.widget.PopupWindow
import androidx.core.content.ContextCompat
import androidx.core.widget.PopupWindowCompat
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.databinding.ItemActionModePopupBinding
import com.simplemobiletools.commons.extensions.applyColorFilter
import com.simplemobiletools.commons.extensions.windowManager
import com.simplemobiletools.commons.helpers.isRPlus
class BottomActionMenuItemPopup(
private val context: Context,
private val items: List<BottomActionMenuItem>,
private val onSelect: (BottomActionMenuItem) -> Unit,
) {
private val popup = PopupWindow(context, null, android.R.attr.popupMenuStyle)
private var anchorView: View? = null
private var dropDownWidth = ViewGroup.LayoutParams.WRAP_CONTENT
private var dropDownHeight = ViewGroup.LayoutParams.WRAP_CONTENT
private val tempRect = Rect()
private val popupMinWidth: Int
private val popupPaddingBottom: Int
private val popupPaddingStart: Int
private val popupPaddingEnd: Int
private val popupPaddingTop: Int
val isShowing: Boolean
get() = popup.isShowing
private val popupListAdapter = object : ArrayAdapter<BottomActionMenuItem>(context, R.layout.item_action_mode_popup, items) {
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
var view: ItemActionModePopupBinding? = null
if (view == null) {
view = ItemActionModePopupBinding.inflate(LayoutInflater.from(context), parent, false)
}
val item = items[position]
view.cabItem.text = item.title
if (item.icon != View.NO_ID) {
val icon = ContextCompat.getDrawable(context, item.icon)
icon?.applyColorFilter(Color.WHITE)
view.cabItem.setCompoundDrawablesWithIntrinsicBounds(icon, null, null, null)
}
view.root.setOnClickListener {
onSelect.invoke(item)
popup.dismiss()
}
return view.root
}
}
init {
popup.isFocusable = true
popupMinWidth = context.resources.getDimensionPixelSize(R.dimen.cab_popup_menu_min_width)
popupPaddingStart = context.resources.getDimensionPixelSize(R.dimen.smaller_margin)
popupPaddingEnd = context.resources.getDimensionPixelSize(R.dimen.smaller_margin)
popupPaddingTop = context.resources.getDimensionPixelSize(R.dimen.smaller_margin)
popupPaddingBottom = context.resources.getDimensionPixelSize(R.dimen.smaller_margin)
}
fun show(anchorView: View) {
this.anchorView = anchorView
buildDropDown()
PopupWindowCompat.setWindowLayoutType(popup, WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL)
popup.isOutsideTouchable = true
popup.width = dropDownWidth
popup.height = dropDownHeight
var x = 0
var y = 0
val contentView: View = popup.contentView
val windowRect = Rect()
contentView.getWindowVisibleDisplayFrame(windowRect)
val windowW = windowRect.width()
val windowH = windowRect.height()
contentView.measure(
makeDropDownMeasureSpec(dropDownWidth, windowW),
makeDropDownMeasureSpec(dropDownHeight, windowH)
)
val anchorLocation = IntArray(2)
anchorView.getLocationInWindow(anchorLocation)
x += anchorLocation[0]
y += anchorView.height * 2
x -= dropDownWidth - anchorView.width
popup.showAtLocation(contentView, Gravity.BOTTOM, x, y)
}
internal fun dismiss() {
popup.dismiss()
popup.contentView = null
}
private fun buildDropDown() {
var otherHeights = 0
val dropDownList = ListView(context).apply {
adapter = popupListAdapter
isFocusable = true
divider = null
isFocusableInTouchMode = true
clipToPadding = false
isVerticalScrollBarEnabled = true
isHorizontalScrollBarEnabled = false
clipToOutline = true
elevation = 3f
setPaddingRelative(popupPaddingStart, popupPaddingTop, popupPaddingEnd, popupPaddingBottom)
}
val screenWidth = if (isRPlus()) {
context.windowManager.currentWindowMetrics.bounds.width()
} else {
context.windowManager.defaultDisplay.width
}
val width = measureMenuSizeAndGetWidth((0.8 * screenWidth).toInt())
updateContentWidth(width)
popup.contentView = dropDownList
// getMaxAvailableHeight() subtracts the padding, so we put it back
// to get the available height for the whole window.
val padding: Int
val popupBackground = popup.background
padding = if (popupBackground != null) {
popupBackground.getPadding(tempRect)
tempRect.top + tempRect.bottom
} else {
tempRect.setEmpty()
0
}
val maxHeight = popup.getMaxAvailableHeight(anchorView!!, 0)
val listContent = measureHeightOfChildrenCompat(maxHeight - otherHeights)
if (listContent > 0) {
val listPadding = dropDownList.paddingTop + dropDownList.paddingBottom
otherHeights += padding + listPadding
}
dropDownHeight = listContent + otherHeights
dropDownList.layoutParams = ViewGroup.LayoutParams(dropDownWidth, dropDownHeight)
}
private fun updateContentWidth(width: Int) {
val popupBackground = popup.background
dropDownWidth = if (popupBackground != null) {
popupBackground.getPadding(tempRect)
tempRect.left + tempRect.right + width
} else {
width
}
}
/**
* @see androidx.appcompat.widget.DropDownListView.measureHeightOfChildrenCompat
*/
private fun measureHeightOfChildrenCompat(maxHeight: Int): Int {
val parent = FrameLayout(context)
val widthMeasureSpec = MeasureSpec.makeMeasureSpec(dropDownWidth, MeasureSpec.EXACTLY)
// Include the padding of the list
var returnedHeight = 0
val count = popupListAdapter.count
var child: View? = null
var viewType = 0
for (i in 0 until count) {
val positionType = popupListAdapter.getItemViewType(i)
if (positionType != viewType) {
child = null
viewType = positionType
}
child = popupListAdapter.getView(i, child, parent)
// Compute child height spec
val heightMeasureSpec: Int
var childLayoutParams: ViewGroup.LayoutParams? = child.layoutParams
if (childLayoutParams == null) {
childLayoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
child.layoutParams = childLayoutParams
}
heightMeasureSpec = if (childLayoutParams.height > 0) {
MeasureSpec.makeMeasureSpec(
childLayoutParams.height,
MeasureSpec.EXACTLY
)
} else {
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)
}
child.measure(widthMeasureSpec, heightMeasureSpec)
// Since this view was measured directly against the parent measure
// spec, we must measure it again before reuse.
child.forceLayout()
val marginLayoutParams = childLayoutParams as? ViewGroup.MarginLayoutParams
val topMargin = marginLayoutParams?.topMargin ?: 0
val bottomMargin = marginLayoutParams?.bottomMargin ?: 0
val verticalMargin = topMargin + bottomMargin
returnedHeight += child.measuredHeight + verticalMargin
if (returnedHeight >= maxHeight) {
// We went over, figure out which height to return. If returnedHeight >
// maxHeight, then the i'th position did not fit completely.
return maxHeight
}
}
// At this point, we went through the range of children, and they each
// completely fit, so return the returnedHeight
return returnedHeight
}
/**
* @see androidx.appcompat.view.menu.MenuPopup.measureIndividualMenuWidth
*/
private fun measureMenuSizeAndGetWidth(maxAllowedWidth: Int): Int {
val parent = FrameLayout(context)
var maxWidth = popupMinWidth
var itemView: View? = null
var itemType = 0
val widthMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)
val heightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)
for (i in 0 until popupListAdapter.count) {
val positionType: Int = popupListAdapter.getItemViewType(i)
if (positionType != itemType) {
itemType = positionType
itemView = null
}
itemView = popupListAdapter.getView(i, itemView, parent)
itemView.measure(widthMeasureSpec, heightMeasureSpec)
val itemWidth = itemView.measuredWidth
if (itemWidth >= maxAllowedWidth) {
return maxAllowedWidth
} else if (itemWidth > maxWidth) {
maxWidth = itemWidth
}
}
return maxWidth
}
private fun makeDropDownMeasureSpec(measureSpec: Int, maxSize: Int): Int {
return MeasureSpec.makeMeasureSpec(
getDropDownMeasureSpecSize(measureSpec, maxSize),
getDropDownMeasureSpecMode(measureSpec)
)
}
private fun getDropDownMeasureSpecSize(measureSpec: Int, maxSize: Int): Int {
return when (measureSpec) {
ViewGroup.LayoutParams.MATCH_PARENT -> maxSize
else -> MeasureSpec.getSize(measureSpec)
}
}
private fun getDropDownMeasureSpecMode(measureSpec: Int): Int {
return when (measureSpec) {
ViewGroup.LayoutParams.WRAP_CONTENT -> MeasureSpec.UNSPECIFIED
else -> MeasureSpec.EXACTLY
}
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/views/bottomactionmenu/BottomActionMenuItemPopup.kt | 595354859 |
package com.simplemobiletools.commons.views.bottomactionmenu
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.view.accessibility.AccessibilityEvent
import android.widget.PopupWindow
import androidx.annotation.MenuRes
import androidx.core.view.doOnLayout
import androidx.core.view.updateLayoutParams
import androidx.core.widget.PopupWindowCompat
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.simplemobiletools.commons.activities.BaseSimpleActivity
class BottomActionMenuPopup(private val activity: BaseSimpleActivity, items: List<BottomActionMenuItem>) {
private val bottomActionMenuView = BottomActionMenuView(activity)
private val popup = PopupWindow(activity, null, android.R.attr.popupMenuStyle)
private var floatingActionButton: FloatingActionButton? = null
private var underlayView: View? = null
private var callback: BottomActionMenuCallback? = null
constructor(activity: BaseSimpleActivity, @MenuRes menuResId: Int) : this(activity, BottomActionMenuParser(activity).inflate(menuResId))
init {
popup.contentView = bottomActionMenuView
popup.width = ViewGroup.LayoutParams.MATCH_PARENT
popup.height = ViewGroup.LayoutParams.WRAP_CONTENT
popup.isOutsideTouchable = false
popup.setOnDismissListener {
callback?.onViewDestroyed()
floatingActionButton?.show()
}
PopupWindowCompat.setWindowLayoutType(popup, WindowManager.LayoutParams.TYPE_APPLICATION)
bottomActionMenuView.setup(items)
}
fun show(callback: BottomActionMenuCallback? = null, underlayView: View? = null, hideFab: Boolean = true) {
this.callback = callback
callback?.onViewCreated(bottomActionMenuView)
if (hideFab) {
floatingActionButton?.hide() ?: findFABAndHide()
}
bottomActionMenuView.setCallback(callback)
bottomActionMenuView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED)
popup.showAtLocation(bottomActionMenuView, Gravity.BOTTOM or Gravity.FILL_HORIZONTAL, 0, 0)
bottomActionMenuView.show()
underlayView?.let {
this.underlayView = it
adjustUnderlayViewBottomMargin(it, true)
}
}
fun dismiss() {
popup.dismiss()
underlayView?.let {
adjustUnderlayViewBottomMargin(it, false)
}
}
private fun findFABAndHide() {
val parent = activity.findViewById<ViewGroup>(android.R.id.content)
findFab(parent)
floatingActionButton?.hide()
}
private fun findFab(parent: ViewGroup) {
val count = parent.childCount
for (i in 0 until count) {
val child = parent.getChildAt(i)
if (child is FloatingActionButton) {
floatingActionButton = child
break
} else if (child is ViewGroup) {
findFab(child)
}
}
}
private fun adjustUnderlayViewBottomMargin(view: View, showing: Boolean) {
bottomActionMenuView.doOnLayout {
view.updateLayoutParams {
if (this is ViewGroup.MarginLayoutParams) {
val newMargin = if (showing) {
bottomMargin + bottomActionMenuView.height
} else {
bottomMargin - bottomActionMenuView.height
}
if (newMargin >= 0) {
bottomMargin = newMargin
}
}
}
}
}
fun invalidate() {
callback?.onViewCreated(bottomActionMenuView)
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/views/bottomactionmenu/BottomActionMenuPopup.kt | 1258688736 |
package com.simplemobiletools.commons.views.bottomactionmenu
import android.content.Context
import android.util.AttributeSet
import android.util.Xml
import android.view.MenuItem
import android.view.View
import com.simplemobiletools.commons.R
import org.xmlpull.v1.XmlPullParser
internal class BottomActionMenuParser(private val context: Context) {
companion object {
private const val NO_TEXT = ""
private const val MENU_TAG = "menu"
private const val MENU_ITEM_TAG = "item"
}
fun inflate(menuId: Int): List<BottomActionMenuItem> {
val parser = context.resources.getLayout(menuId)
parser.use {
val attrs = Xml.asAttributeSet(parser)
return readContextItems(parser, attrs)
}
}
private fun readContextItems(parser: XmlPullParser, attrs: AttributeSet): List<BottomActionMenuItem> {
val items = mutableListOf<BottomActionMenuItem>()
var eventType = parser.eventType
var tagName: String
// This loop will skip to the menu start tag
do {
if (eventType == XmlPullParser.START_TAG) {
tagName = parser.name
if (tagName == MENU_TAG) {
// Go to next tag
eventType = parser.next()
break
}
throw RuntimeException("Expecting menu, got $tagName")
}
eventType = parser.next()
} while (eventType != XmlPullParser.END_DOCUMENT)
var reachedEndOfMenu = false
while (!reachedEndOfMenu) {
tagName = parser.name
if (eventType == XmlPullParser.END_TAG) {
if (tagName == MENU_TAG) {
reachedEndOfMenu = true
}
}
if (eventType == XmlPullParser.START_TAG) {
when (tagName) {
MENU_ITEM_TAG -> items.add(readBottomActionMenuItem(parser, attrs))
}
}
eventType = parser.next()
}
return items
}
private fun readBottomActionMenuItem(parser: XmlPullParser, attrs: AttributeSet): BottomActionMenuItem {
val typedArray = context.obtainStyledAttributes(attrs, R.styleable.BottomActionMenuItem)
val id = typedArray.getResourceId(R.styleable.BottomActionMenuItem_android_id, View.NO_ID)
val text = typedArray.getString(R.styleable.BottomActionMenuItem_android_title) ?: NO_TEXT
val iconId = typedArray.getResourceId(R.styleable.BottomActionMenuItem_android_icon, View.NO_ID)
val showAsAction = typedArray.getInt(R.styleable.BottomActionMenuItem_showAsAction, -1)
val visible = typedArray.getBoolean(R.styleable.BottomActionMenuItem_android_visible, true)
typedArray.recycle()
parser.require(XmlPullParser.START_TAG, null, MENU_ITEM_TAG)
return BottomActionMenuItem(
id,
text,
iconId,
showAsAction == MenuItem.SHOW_AS_ACTION_ALWAYS || showAsAction == MenuItem.SHOW_AS_ACTION_IF_ROOM,
visible
)
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/views/bottomactionmenu/BottomActionMenuParser.kt | 3412814764 |
package com.simplemobiletools.commons.views.bottomactionmenu
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.TimeInterpolator
import android.content.Context
import android.graphics.Color
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.ViewPropertyAnimator
import android.widget.ImageView
import android.widget.LinearLayout
import androidx.annotation.IdRes
import com.google.android.material.animation.AnimationUtils
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.extensions.applyColorFilter
import com.simplemobiletools.commons.extensions.beVisibleIf
import com.simplemobiletools.commons.extensions.toast
import com.simplemobiletools.commons.extensions.windowManager
import com.simplemobiletools.commons.helpers.isRPlus
class BottomActionMenuView : LinearLayout {
companion object {
private const val ENTER_ANIMATION_DURATION = 225
private const val EXIT_ANIMATION_DURATION = 175
}
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle)
private val inflater = LayoutInflater.from(context)
private val itemsLookup = LinkedHashMap<Int, BottomActionMenuItem>()
private val items: List<BottomActionMenuItem>
get() = itemsLookup.values.toList().sortedWith(compareByDescending<BottomActionMenuItem> {
it.showAsAction
}.thenBy {
it.icon != View.NO_ID
}).filter { it.isVisible }
private var currentAnimator: ViewPropertyAnimator? = null
private var callback: BottomActionMenuCallback? = null
private var itemPopup: BottomActionMenuItemPopup? = null
init {
orientation = HORIZONTAL
elevation = 2f
}
fun setCallback(listener: BottomActionMenuCallback?) {
this.callback = listener
}
fun hide() {
slideDownToGone()
}
fun show() {
slideUpToVisible()
}
private fun slideUpToVisible() {
currentAnimator?.also {
it.cancel()
clearAnimation()
}
animateChildTo(0, ENTER_ANIMATION_DURATION.toLong(), AnimationUtils.LINEAR_OUT_SLOW_IN_INTERPOLATOR, true)
}
private fun slideDownToGone() {
currentAnimator?.also {
currentAnimator?.cancel()
clearAnimation()
}
animateChildTo(
height + (layoutParams as MarginLayoutParams).bottomMargin,
EXIT_ANIMATION_DURATION.toLong(),
AnimationUtils.FAST_OUT_LINEAR_IN_INTERPOLATOR
)
}
private fun animateChildTo(targetY: Int, duration: Long, interpolator: TimeInterpolator, visible: Boolean = false) {
currentAnimator = animate()
.translationY(targetY.toFloat())
.setInterpolator(interpolator)
.setDuration(duration)
.setListener(
object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator) {
currentAnimator = null
beVisibleIf(visible)
}
})
}
fun setup(items: List<BottomActionMenuItem>) {
items.forEach { itemsLookup[it.id] = it }
init()
}
fun add(item: BottomActionMenuItem) {
setItem(item)
}
private fun setItem(item: BottomActionMenuItem?) {
item?.let {
val oldItem = itemsLookup[item.id]
itemsLookup[item.id] = item
if (oldItem != item) {
init()
}
}
}
fun toggleItemVisibility(@IdRes itemId: Int, show: Boolean) {
val item = itemsLookup[itemId]
setItem(item?.copy(isVisible = show))
}
private fun init() {
removeAllViews()
val maxItemsBeforeOverflow = computeMaxItemsBeforeOverflow()
val allItems = items
for (i in allItems.indices) {
if (i <= maxItemsBeforeOverflow) {
drawNormalItem(allItems[i])
} else {
drawOverflowItem(allItems.slice(i until allItems.size))
break
}
}
}
private fun computeMaxItemsBeforeOverflow(): Int {
val itemsToShowAsAction = items.filter { it.showAsAction && it.icon != View.NO_ID }
val itemMinWidth = context.resources.getDimensionPixelSize(R.dimen.cab_item_min_width)
val totalActionWidth = (itemsToShowAsAction.size + 1) * itemMinWidth
val screenWidth = if (isRPlus()) {
context.windowManager.currentWindowMetrics.bounds.width()
} else {
context.windowManager.defaultDisplay.width
}
val result = if (screenWidth > totalActionWidth) {
itemsToShowAsAction.size
} else {
screenWidth / itemMinWidth
}
return result - 1
}
private fun drawNormalItem(item: BottomActionMenuItem) {
(inflater.inflate(R.layout.item_action_mode, this, false) as ImageView).apply {
setupItem(item)
setOnClickListener {
if (itemPopup?.isShowing == true) {
itemPopup?.dismiss()
} else {
callback?.onItemClicked(item)
}
}
setOnLongClickListener {
context.toast(item.title)
true
}
addView(this)
}
}
private fun drawOverflowItem(overFlowItems: List<BottomActionMenuItem>) {
(inflater.inflate(R.layout.item_action_mode, this, false) as ImageView).apply {
setImageResource(R.drawable.ic_three_dots_vector)
val contentDesc = context.getString(R.string.more_info)
contentDescription = contentDesc
applyColorFilter(Color.WHITE)
itemPopup = getOverflowPopup(overFlowItems)
setOnClickListener {
if (itemPopup?.isShowing == true) {
itemPopup?.dismiss()
} else {
itemPopup?.show(it)
}
}
setOnLongClickListener {
context.toast(contentDesc)
true
}
addView(this)
}
}
private fun ImageView.setupItem(item: BottomActionMenuItem) {
id = item.id
contentDescription = item.title
if (item.icon != View.NO_ID) {
setImageResource(item.icon)
}
beVisibleIf(item.isVisible)
applyColorFilter(Color.WHITE)
}
private fun getOverflowPopup(overFlowItems: List<BottomActionMenuItem>): BottomActionMenuItemPopup {
return BottomActionMenuItemPopup(context, overFlowItems) {
callback?.onItemClicked(it)
}
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/views/bottomactionmenu/BottomActionMenuView.kt | 2646923329 |
package com.simplemobiletools.commons.views.bottomactionmenu
import android.view.View
import androidx.annotation.DrawableRes
import androidx.annotation.IdRes
data class BottomActionMenuItem(
@IdRes val id: Int,
val title: String,
@DrawableRes val icon: Int = View.NO_ID,
val showAsAction: Boolean,
val isVisible: Boolean = true,
)
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/views/bottomactionmenu/BottomActionMenuItem.kt | 954772467 |
package com.simplemobiletools.commons.views.bottomactionmenu
interface BottomActionMenuCallback {
fun onItemClicked(item: BottomActionMenuItem) {}
fun onViewCreated(view: BottomActionMenuView) {}
fun onViewDestroyed() {}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/views/bottomactionmenu/BottomActionMenuCallback.kt | 3122509152 |
package com.simplemobiletools.commons.views
import android.content.Context
import android.content.res.ColorStateList
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatRadioButton
import com.simplemobiletools.commons.extensions.adjustAlpha
class MyCompatRadioButton : AppCompatRadioButton {
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle)
fun setColors(textColor: Int, accentColor: Int, backgroundColor: Int) {
setTextColor(textColor)
val colorStateList = ColorStateList(
arrayOf(
intArrayOf(-android.R.attr.state_checked),
intArrayOf(android.R.attr.state_checked)
),
intArrayOf(textColor.adjustAlpha(0.6f), accentColor)
)
supportButtonTintList = colorStateList
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/views/MyCompatRadioButton.kt | 1578580274 |
package com.simplemobiletools.commons.views
import android.app.Activity
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import com.google.android.material.appbar.AppBarLayout
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.activities.BaseSimpleActivity
import com.simplemobiletools.commons.databinding.MenuSearchBinding
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.LOWER_ALPHA
import com.simplemobiletools.commons.helpers.MEDIUM_ALPHA
class MySearchMenu(context: Context, attrs: AttributeSet) : AppBarLayout(context, attrs) {
var isSearchOpen = false
var useArrowIcon = false
var onSearchOpenListener: (() -> Unit)? = null
var onSearchClosedListener: (() -> Unit)? = null
var onSearchTextChangedListener: ((text: String) -> Unit)? = null
var onNavigateBackClickListener: (() -> Unit)? = null
val binding = MenuSearchBinding.inflate(LayoutInflater.from(context), this, true)
fun getToolbar() = binding.topToolbar
fun setupMenu() {
binding.topToolbarSearchIcon.setOnClickListener {
if (isSearchOpen) {
closeSearch()
} else if (useArrowIcon && onNavigateBackClickListener != null) {
onNavigateBackClickListener!!()
} else {
binding.topToolbarSearch.requestFocus()
(context as? Activity)?.showKeyboard(binding.topToolbarSearch)
}
}
post {
binding.topToolbarSearch.setOnFocusChangeListener { v, hasFocus ->
if (hasFocus) {
openSearch()
}
}
}
binding.topToolbarSearch.onTextChangeListener { text ->
onSearchTextChangedListener?.invoke(text)
}
}
fun focusView() {
binding.topToolbarSearch.requestFocus()
}
private fun openSearch() {
isSearchOpen = true
onSearchOpenListener?.invoke()
binding.topToolbarSearchIcon.setImageResource(R.drawable.ic_arrow_left_vector)
binding.topToolbarSearchIcon.contentDescription = resources.getString(R.string.back)
}
fun closeSearch() {
isSearchOpen = false
onSearchClosedListener?.invoke()
binding.topToolbarSearch.setText("")
if (!useArrowIcon) {
binding.topToolbarSearchIcon.setImageResource(R.drawable.ic_search_vector)
binding.topToolbarSearchIcon.contentDescription = resources.getString(R.string.search)
}
(context as? Activity)?.hideKeyboard()
}
fun getCurrentQuery() = binding.topToolbarSearch.text.toString()
fun updateHintText(text: String) {
binding.topToolbarSearch.hint = text
}
fun toggleHideOnScroll(hideOnScroll: Boolean) {
val params = binding.topAppBarLayout.layoutParams as LayoutParams
if (hideOnScroll) {
params.scrollFlags = LayoutParams.SCROLL_FLAG_SCROLL or LayoutParams.SCROLL_FLAG_ENTER_ALWAYS
} else {
params.scrollFlags = params.scrollFlags.removeBit(LayoutParams.SCROLL_FLAG_SCROLL or LayoutParams.SCROLL_FLAG_ENTER_ALWAYS)
}
}
fun toggleForceArrowBackIcon(useArrowBack: Boolean) {
this.useArrowIcon = useArrowBack
val (icon, accessibilityString) = if (useArrowBack) {
Pair(R.drawable.ic_arrow_left_vector, R.string.back)
} else {
Pair(R.drawable.ic_search_vector, R.string.search)
}
binding.topToolbarSearchIcon.setImageResource(icon)
binding.topToolbarSearchIcon.contentDescription = resources.getString(accessibilityString)
}
fun updateColors() {
val backgroundColor = context.getProperBackgroundColor()
val contrastColor = backgroundColor.getContrastColor()
setBackgroundColor(backgroundColor)
binding.topAppBarLayout.setBackgroundColor(backgroundColor)
binding.topToolbarSearchIcon.applyColorFilter(contrastColor)
binding.topToolbarHolder.background?.applyColorFilter(context.getProperPrimaryColor().adjustAlpha(LOWER_ALPHA))
binding.topToolbarSearch.setTextColor(contrastColor)
binding.topToolbarSearch.setHintTextColor(contrastColor.adjustAlpha(MEDIUM_ALPHA))
(context as? BaseSimpleActivity)?.updateTopBarColors(binding.topToolbar, backgroundColor)
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/views/MySearchMenu.kt | 233290568 |
package com.simplemobiletools.commons.views
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.MotionEvent
import android.widget.LinearLayout
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.extensions.isRTLLayout
import com.simplemobiletools.commons.extensions.onGlobalLayout
import com.simplemobiletools.commons.interfaces.LineColorPickerListener
class LineColorPicker @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyle: Int = 0
) : LinearLayout(context, attrs, defStyle) {
private var colorsCount = 0
private var pickerWidth = 0
private var stripeWidth = 0
private var unselectedMargin = 0
private var lastColorIndex = -1
private var wasInit = false
private var colors = ArrayList<Int>()
var listener: LineColorPickerListener? = null
init {
unselectedMargin = context.resources.getDimension(R.dimen.line_color_picker_margin).toInt()
onGlobalLayout {
if (pickerWidth == 0) {
pickerWidth = width
if (colorsCount != 0)
stripeWidth = width / colorsCount
}
if (!wasInit) {
wasInit = true
initColorPicker()
updateItemMargin(lastColorIndex, false)
}
}
orientation = LinearLayout.HORIZONTAL
setOnTouchListener { view, motionEvent ->
when (motionEvent.action) {
MotionEvent.ACTION_MOVE, MotionEvent.ACTION_UP -> {
if (pickerWidth != 0 && stripeWidth != 0) {
touchAt(motionEvent.x.toInt())
}
}
}
true
}
}
fun updateColors(colors: ArrayList<Int>, selectColorIndex: Int = -1) {
this.colors = colors
colorsCount = colors.size
if (pickerWidth != 0) {
stripeWidth = pickerWidth / colorsCount
}
if (selectColorIndex != -1) {
lastColorIndex = selectColorIndex
}
initColorPicker()
updateItemMargin(lastColorIndex, false)
}
// do not remove ": Int", it causes "NoSuchMethodError" for some reason
fun getCurrentColor(): Int = colors[lastColorIndex]
private fun initColorPicker() {
removeAllViews()
val inflater = LayoutInflater.from(context)
colors.forEach {
inflater.inflate(R.layout.empty_image_view, this, false).apply {
setBackgroundColor(it)
addView(this)
}
}
}
private fun touchAt(touchX: Int) {
var colorIndex = touchX / stripeWidth
if (context.isRTLLayout) {
colorIndex = colors.size - colorIndex - 1
}
val index = Math.max(0, Math.min(colorIndex, colorsCount - 1))
if (lastColorIndex != index) {
updateItemMargin(lastColorIndex, true)
lastColorIndex = index
updateItemMargin(index, false)
listener?.colorChanged(index, colors[index])
}
}
private fun updateItemMargin(index: Int, addMargin: Boolean) {
getChildAt(index)?.apply {
(layoutParams as LinearLayout.LayoutParams).apply {
topMargin = if (addMargin) unselectedMargin else 0
bottomMargin = if (addMargin) unselectedMargin else 0
}
requestLayout()
}
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/views/LineColorPicker.kt | 2688837084 |
package com.simplemobiletools.commons.views
import android.annotation.SuppressLint
import android.content.Context
import android.os.Handler
import android.util.AttributeSet
import android.view.MotionEvent
import android.widget.TextView
import androidx.biometric.auth.AuthPromptHost
import androidx.core.os.postDelayed
import com.andrognito.patternlockview.PatternLockView
import com.andrognito.patternlockview.listener.PatternLockViewListener
import com.andrognito.patternlockview.utils.PatternLockUtils
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.databinding.TabPatternBinding
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.PROTECTION_PATTERN
import com.simplemobiletools.commons.interfaces.BaseSecurityTab
import com.simplemobiletools.commons.interfaces.HashListener
class PatternTab(context: Context, attrs: AttributeSet) : BaseSecurityTab(context, attrs) {
private var scrollView: MyScrollView? = null
private lateinit var binding: TabPatternBinding
override val protectionType = PROTECTION_PATTERN
override val defaultTextRes = R.string.insert_pattern
override val wrongTextRes = R.string.wrong_pattern
override val titleTextView: TextView
get() = binding.patternLockTitle
@SuppressLint("ClickableViewAccessibility")
override fun onFinishInflate() {
super.onFinishInflate()
binding = TabPatternBinding.bind(this)
val textColor = context.getProperTextColor()
context.updateTextColors(binding.patternLockHolder)
binding.patternLockView.setOnTouchListener { _, event ->
when (event.action) {
MotionEvent.ACTION_DOWN -> scrollView?.isScrollable = false
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> scrollView?.isScrollable = true
}
false
}
binding.patternLockView.correctStateColor = context.getProperPrimaryColor()
binding.patternLockView.normalStateColor = textColor
binding.patternLockView.addPatternLockListener(object : PatternLockViewListener {
override fun onComplete(pattern: MutableList<PatternLockView.Dot>?) {
receivedHash(PatternLockUtils.patternToSha1(binding.patternLockView, pattern))
}
override fun onCleared() {}
override fun onStarted() {}
override fun onProgress(progressPattern: MutableList<PatternLockView.Dot>?) {}
})
binding.patternLockIcon.applyColorFilter(textColor)
maybeShowCountdown()
}
override fun initTab(
requiredHash: String,
listener: HashListener,
scrollView: MyScrollView,
biometricPromptHost: AuthPromptHost,
showBiometricAuthentication: Boolean
) {
this.requiredHash = requiredHash
this.scrollView = scrollView
computedHash = requiredHash
hashListener = listener
}
override fun onLockedOutChange(lockedOut: Boolean) {
binding.patternLockView.isInputEnabled = !lockedOut
}
private fun receivedHash(newHash: String) {
if (isLockedOut()) {
performHapticFeedback()
return
}
when {
computedHash.isEmpty() -> {
computedHash = newHash
binding.patternLockView.clearPattern()
binding.patternLockTitle.setText(R.string.repeat_pattern)
}
computedHash == newHash -> {
binding.patternLockView.setViewMode(PatternLockView.PatternViewMode.CORRECT)
onCorrectPassword()
}
else -> {
onIncorrectPassword()
binding.patternLockView.setViewMode(PatternLockView.PatternViewMode.WRONG)
Handler().postDelayed(delayInMillis = 1000) {
binding.patternLockView.clearPattern()
if (requiredHash.isEmpty()) {
computedHash = ""
}
}
}
}
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/views/PatternTab.kt | 2644306588 |
package com.simplemobiletools.commons.views
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import kotlin.math.max
/**
* RecyclerView StaggeredGridLayoutManager but with automatic spanCount calculation.
*
* @param context The initiating view's context.
* @param itemSize: Grid item size (width or height, depending on orientation) in pixels. Will be used to calculate span count.
*/
class AutoStaggeredGridLayoutManager(
private var itemSize: Int,
orientation: Int,
) : StaggeredGridLayoutManager(1, orientation) {
init {
require(itemSize >= 0) {
"itemSize must be >= 0"
}
}
override fun onLayoutChildren(recycler: RecyclerView.Recycler?, state: RecyclerView.State?) {
val width = width
val height = height
if (itemSize > 0 && width > 0 && height > 0) {
val totalSpace = if (orientation == VERTICAL) {
width - paddingRight - paddingLeft
} else {
height - paddingTop - paddingBottom
}
postOnAnimation {
spanCount = max(1, totalSpace / itemSize)
}
}
super.onLayoutChildren(recycler, state)
}
// fixes crash java.lang.IndexOutOfBoundsException: Inconsistency detected...
// taken from https://stackoverflow.com/a/33985508/1967672
override fun supportsPredictiveItemAnimations() = false
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/views/AutoStaggeredGridLayoutManager.kt | 1388238311 |
package com.simplemobiletools.commons.views
import android.content.Context
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatImageView
class MySquareImageView : AppCompatImageView {
var isHorizontalScrolling = false
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle)
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
val spec = if (isHorizontalScrolling) heightMeasureSpec else widthMeasureSpec
super.onMeasure(spec, spec)
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/views/MySquareImageView.kt | 3009276916 |
package com.simplemobiletools.commons.views
import android.content.Context
import android.content.Intent
import android.os.Handler
import android.provider.Settings
import android.util.AttributeSet
import android.widget.RelativeLayout
import androidx.biometric.auth.AuthPromptHost
import com.github.ajalt.reprint.core.AuthenticationFailureReason
import com.github.ajalt.reprint.core.AuthenticationListener
import com.github.ajalt.reprint.core.Reprint
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.databinding.TabFingerprintBinding
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.PROTECTION_FINGERPRINT
import com.simplemobiletools.commons.interfaces.HashListener
import com.simplemobiletools.commons.interfaces.SecurityTab
class FingerprintTab(context: Context, attrs: AttributeSet) : RelativeLayout(context, attrs), SecurityTab {
private val RECHECK_PERIOD = 3000L
private val registerHandler = Handler()
lateinit var hashListener: HashListener
private lateinit var binding: TabFingerprintBinding
override fun onFinishInflate() {
super.onFinishInflate()
binding = TabFingerprintBinding.bind(this)
val textColor = context.getProperTextColor()
context.updateTextColors(binding.fingerprintLockHolder)
binding.fingerprintImage.applyColorFilter(textColor)
binding.fingerprintSettings.setOnClickListener {
context.startActivity(Intent(Settings.ACTION_SETTINGS))
}
}
override fun initTab(
requiredHash: String,
listener: HashListener,
scrollView: MyScrollView,
biometricPromptHost: AuthPromptHost,
showBiometricAuthentication: Boolean
) {
hashListener = listener
}
override fun visibilityChanged(isVisible: Boolean) {
if (isVisible) {
checkRegisteredFingerprints()
} else {
Reprint.cancelAuthentication()
}
}
private fun checkRegisteredFingerprints() {
val hasFingerprints = Reprint.hasFingerprintRegistered()
binding.fingerprintSettings.beGoneIf(hasFingerprints)
binding.fingerprintLabel.text = context.getString(if (hasFingerprints) R.string.place_finger else R.string.no_fingerprints_registered)
Reprint.authenticate(object : AuthenticationListener {
override fun onSuccess(moduleTag: Int) {
hashListener.receivedHash("", PROTECTION_FINGERPRINT)
}
override fun onFailure(failureReason: AuthenticationFailureReason?, fatal: Boolean, errorMessage: CharSequence?, moduleTag: Int, errorCode: Int) {
when (failureReason) {
AuthenticationFailureReason.AUTHENTICATION_FAILED -> context.toast(R.string.authentication_failed)
AuthenticationFailureReason.LOCKED_OUT -> context.toast(R.string.authentication_blocked)
else -> {}
}
}
})
registerHandler.postDelayed({
checkRegisteredFingerprints()
}, RECHECK_PERIOD)
}
override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
registerHandler.removeCallbacksAndMessages(null)
Reprint.cancelAuthentication()
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/views/FingerprintTab.kt | 532568451 |
package com.simplemobiletools.commons.views
import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import androidx.viewpager.widget.ViewPager
class MyDialogViewPager : ViewPager {
var allowSwiping = true
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
// disable manual swiping of viewpager at the dialog by swiping over the pattern
override fun onInterceptTouchEvent(ev: MotionEvent) = false
override fun onTouchEvent(ev: MotionEvent): Boolean {
if (!allowSwiping)
return false
try {
return super.onTouchEvent(ev)
} catch (ignored: Exception) {
}
return false
}
// https://stackoverflow.com/a/20784791/1967672
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
var height = 0
for (i in 0 until childCount) {
val child = getChildAt(i)
child.measure(widthMeasureSpec, View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED))
val h = child.measuredHeight
if (h > height) height = h
}
val newHeightMeasureSpec = View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY)
super.onMeasure(widthMeasureSpec, newHeightMeasureSpec)
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/views/MyDialogViewPager.kt | 576377728 |
package com.simplemobiletools.commons.views
import android.content.Context
import android.util.AttributeSet
import androidx.recyclerview.widget.LinearLayoutManager
class MyLinearLayoutManager : LinearLayoutManager {
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes)
constructor(context: Context, orientation: Int, reverseLayout: Boolean) : super(context, orientation, reverseLayout)
// fixes crash java.lang.IndexOutOfBoundsException: Inconsistency detected...
// taken from https://stackoverflow.com/a/33985508/1967672
override fun supportsPredictiveItemAnimations() = false
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/views/MyLinearLayoutManager.kt | 2198207665 |
package com.simplemobiletools.commons.views
import android.content.ContentValues
import android.content.Context
import android.provider.MediaStore
import android.text.format.DateFormat
import android.util.AttributeSet
import android.widget.RelativeLayout
import androidx.exifinterface.media.ExifInterface
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.activities.BaseSimpleActivity
import com.simplemobiletools.commons.databinding.DialogRenameItemsPatternBinding
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.isNougatPlus
import com.simplemobiletools.commons.interfaces.RenameTab
import com.simplemobiletools.commons.models.Android30RenameFormat
import com.simplemobiletools.commons.models.FileDirItem
import java.io.File
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Locale
class RenamePatternTab(context: Context, attrs: AttributeSet) : RelativeLayout(context, attrs), RenameTab {
var ignoreClicks = false
var stopLooping = false // we should request the permission on Android 30+ for all uris at once, not one by one
var currentIncrementalNumber = 1
var numbersCnt = 0
var activity: BaseSimpleActivity? = null
var paths = ArrayList<String>()
private lateinit var binding: DialogRenameItemsPatternBinding
override fun onFinishInflate() {
super.onFinishInflate()
binding = DialogRenameItemsPatternBinding.bind(this)
context.updateTextColors(binding.renameItemsHolder)
}
override fun initTab(activity: BaseSimpleActivity, paths: ArrayList<String>) {
this.activity = activity
this.paths = paths
binding.renameItemsValue.setText(activity.baseConfig.lastRenamePatternUsed)
}
override fun dialogConfirmed(useMediaFileExtension: Boolean, callback: (success: Boolean) -> Unit) {
stopLooping = false
if (ignoreClicks) {
return
}
val newNameRaw = binding.renameItemsValue.value
if (newNameRaw.isEmpty()) {
callback(false)
return
}
val validPaths = paths.filter { activity?.getDoesFilePathExist(it) == true }
val firstPath = validPaths.firstOrNull()
val sdFilePath = validPaths.firstOrNull { activity?.isPathOnSD(it) == true } ?: firstPath
if (firstPath == null || sdFilePath == null) {
activity?.toast(R.string.unknown_error_occurred)
return
}
activity?.baseConfig?.lastRenamePatternUsed = binding.renameItemsValue.value
activity?.handleSAFDialog(sdFilePath) {
if (!it) {
return@handleSAFDialog
}
activity?.checkManageMediaOrHandleSAFDialogSdk30(firstPath) {
if (!it) {
return@checkManageMediaOrHandleSAFDialogSdk30
}
ignoreClicks = true
var pathsCnt = validPaths.size
numbersCnt = pathsCnt.toString().length
for (path in validPaths) {
if (stopLooping) {
return@checkManageMediaOrHandleSAFDialogSdk30
}
try {
val newPath = getNewPath(path, useMediaFileExtension) ?: continue
activity?.renameFile(path, newPath, true) { success, android30Format ->
if (success) {
pathsCnt--
if (pathsCnt == 0) {
callback(true)
}
} else {
ignoreClicks = false
if (android30Format != Android30RenameFormat.NONE) {
currentIncrementalNumber = 1
stopLooping = true
renameAllFiles(validPaths, useMediaFileExtension, android30Format, callback)
}
}
}
} catch (e: Exception) {
activity?.showErrorToast(e)
}
}
stopLooping = false
}
}
}
private fun getNewPath(path: String, useMediaFileExtension: Boolean): String? {
try {
val exif = ExifInterface(path)
var dateTime = if (isNougatPlus()) {
exif.getAttribute(ExifInterface.TAG_DATETIME_ORIGINAL) ?: exif.getAttribute(ExifInterface.TAG_DATETIME)
} else {
exif.getAttribute(ExifInterface.TAG_DATETIME)
}
if (dateTime == null) {
val calendar = Calendar.getInstance(Locale.ENGLISH)
calendar.timeInMillis = File(path).lastModified()
dateTime = DateFormat.format("yyyy:MM:dd kk:mm:ss", calendar).toString()
}
val pattern = if (dateTime.substring(4, 5) == "-") "yyyy-MM-dd kk:mm:ss" else "yyyy:MM:dd kk:mm:ss"
val simpleDateFormat = SimpleDateFormat(pattern, Locale.ENGLISH)
val dt = simpleDateFormat.parse(dateTime.replace("T", " "))
val cal = Calendar.getInstance()
cal.time = dt
val year = cal.get(Calendar.YEAR).toString()
val month = (cal.get(Calendar.MONTH) + 1).ensureTwoDigits()
val day = (cal.get(Calendar.DAY_OF_MONTH)).ensureTwoDigits()
val hours = (cal.get(Calendar.HOUR_OF_DAY)).ensureTwoDigits()
val minutes = (cal.get(Calendar.MINUTE)).ensureTwoDigits()
val seconds = (cal.get(Calendar.SECOND)).ensureTwoDigits()
var newName = binding.renameItemsValue.value
.replace("%Y", year, false)
.replace("%M", month, false)
.replace("%D", day, false)
.replace("%h", hours, false)
.replace("%m", minutes, false)
.replace("%s", seconds, false)
.replace("%i", String.format("%0${numbersCnt}d", currentIncrementalNumber))
if (newName.isEmpty()) {
return null
}
currentIncrementalNumber++
if ((!newName.contains(".") && path.contains(".")) || (useMediaFileExtension && !".${newName.substringAfterLast(".")}".isMediaFile())) {
val extension = path.substringAfterLast(".")
newName += ".$extension"
}
var newPath = "${path.getParentPath()}/$newName"
var currentIndex = 0
while (activity?.getDoesFilePathExist(newPath) == true) {
currentIndex++
var extension = ""
val name = if (newName.contains(".")) {
extension = ".${newName.substringAfterLast(".")}"
newName.substringBeforeLast(".")
} else {
newName
}
newPath = "${path.getParentPath()}/$name~$currentIndex$extension"
}
return newPath
} catch (e: Exception) {
return null
}
}
private fun renameAllFiles(
paths: List<String>,
useMediaFileExtension: Boolean,
android30Format: Android30RenameFormat,
callback: (success: Boolean) -> Unit
) {
val fileDirItems = paths.map { File(it).toFileDirItem(context) }
val uriPairs = context.getUrisPathsFromFileDirItems(fileDirItems)
val validPaths = uriPairs.first
val uris = uriPairs.second
val activity = activity
activity?.updateSDK30Uris(uris) { success ->
if (success) {
try {
uris.forEachIndexed { index, uri ->
val path = validPaths[index]
val newFileName = getNewPath(path, useMediaFileExtension)?.getFilenameFromPath() ?: return@forEachIndexed
when (android30Format) {
Android30RenameFormat.SAF -> {
val sourceFile = File(path).toFileDirItem(context)
val newPath = "${path.getParentPath()}/$newFileName"
val destinationFile = FileDirItem(
newPath,
newFileName,
sourceFile.isDirectory,
sourceFile.children,
sourceFile.size,
sourceFile.modified
)
if (activity.copySingleFileSdk30(sourceFile, destinationFile)) {
if (!activity.baseConfig.keepLastModified) {
File(newPath).setLastModified(System.currentTimeMillis())
}
activity.contentResolver.delete(uri, null)
activity.updateInMediaStore(path, newPath)
activity.scanPathsRecursively(arrayListOf(newPath))
}
}
Android30RenameFormat.CONTENT_RESOLVER -> {
val values = ContentValues().apply {
put(MediaStore.Images.Media.DISPLAY_NAME, newFileName)
}
context.contentResolver.update(uri, values, null, null)
}
Android30RenameFormat.NONE -> {
activity.runOnUiThread {
callback(true)
}
return@forEachIndexed
}
}
}
activity.runOnUiThread {
callback(true)
}
} catch (e: Exception) {
activity.runOnUiThread {
activity.showErrorToast(e)
callback(false)
}
}
}
}
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/views/RenamePatternTab.kt | 3184856890 |
package com.simplemobiletools.commons.views
import android.content.Context
import android.util.AttributeSet
import android.widget.TextView
import android.widget.Toast
import androidx.biometric.auth.AuthPromptHost
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.databinding.TabPinBinding
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.MINIMUM_PIN_LENGTH
import com.simplemobiletools.commons.helpers.PROTECTION_PIN
import com.simplemobiletools.commons.interfaces.BaseSecurityTab
import com.simplemobiletools.commons.interfaces.HashListener
import java.math.BigInteger
import java.security.MessageDigest
import java.util.Locale
class PinTab(context: Context, attrs: AttributeSet) : BaseSecurityTab(context, attrs) {
private var pin = ""
private lateinit var binding: TabPinBinding
override val protectionType = PROTECTION_PIN
override val defaultTextRes = R.string.enter_pin
override val wrongTextRes = R.string.wrong_pin
override val titleTextView: TextView
get() = binding.pinLockTitle
override fun onFinishInflate() {
super.onFinishInflate()
binding = TabPinBinding.bind(this)
val textColor = context.getProperTextColor()
context.updateTextColors(binding.pinLockHolder)
binding.pin0.setOnClickListener { addNumber("0") }
binding.pin1.setOnClickListener { addNumber("1") }
binding.pin2.setOnClickListener { addNumber("2") }
binding.pin3.setOnClickListener { addNumber("3") }
binding.pin4.setOnClickListener { addNumber("4") }
binding.pin5.setOnClickListener { addNumber("5") }
binding.pin6.setOnClickListener { addNumber("6") }
binding.pin7.setOnClickListener { addNumber("7") }
binding.pin8.setOnClickListener { addNumber("8") }
binding.pin9.setOnClickListener { addNumber("9") }
binding.pinC.setOnClickListener { clear() }
binding.pinOk.setOnClickListener { confirmPIN() }
binding.pinOk.applyColorFilter(textColor)
binding.pinLockIcon.applyColorFilter(textColor)
maybeShowCountdown()
}
override fun initTab(
requiredHash: String,
listener: HashListener,
scrollView: MyScrollView,
biometricPromptHost: AuthPromptHost,
showBiometricAuthentication: Boolean
) {
this.requiredHash = requiredHash
computedHash = requiredHash
hashListener = listener
}
private fun addNumber(number: String) {
if (!isLockedOut()) {
if (pin.length < 10) {
pin += number
updatePinCode()
}
}
performHapticFeedback()
}
private fun clear() {
if (pin.isNotEmpty()) {
pin = pin.substring(0, pin.length - 1)
updatePinCode()
}
performHapticFeedback()
}
private fun confirmPIN() {
if (!isLockedOut()) {
val newHash = getHashedPin()
when {
pin.isEmpty() -> {
context.toast(id = R.string.please_enter_pin, length = Toast.LENGTH_LONG)
}
computedHash.isEmpty() && pin.length < MINIMUM_PIN_LENGTH -> {
resetPin()
context.toast(id = R.string.pin_must_be_4_digits_long, length = Toast.LENGTH_LONG)
}
computedHash.isEmpty() -> {
computedHash = newHash
resetPin()
binding.pinLockTitle.setText(R.string.repeat_pin)
}
computedHash == newHash -> {
onCorrectPassword()
}
else -> {
resetPin()
onIncorrectPassword()
if (requiredHash.isEmpty()) {
computedHash = ""
}
}
}
}
performHapticFeedback()
}
private fun resetPin() {
pin = ""
binding.pinLockCurrentPin.text = ""
}
private fun updatePinCode() {
binding.pinLockCurrentPin.text = "*".repeat(pin.length)
}
private fun getHashedPin(): String {
val messageDigest = MessageDigest.getInstance("SHA-1")
messageDigest.update(pin.toByteArray(charset("UTF-8")))
val digest = messageDigest.digest()
val bigInteger = BigInteger(1, digest)
return String.format(Locale.getDefault(), "%0${digest.size * 2}x", bigInteger).lowercase(Locale.getDefault())
}
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/views/PinTab.kt | 3455023298 |
package com.simplemobiletools.commons.helpers
import android.content.Context
import android.content.res.Configuration
import android.os.Environment
import android.text.format.DateFormat
import androidx.core.content.ContextCompat
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.extensions.getInternalStoragePath
import com.simplemobiletools.commons.extensions.getSDCardPath
import com.simplemobiletools.commons.extensions.getSharedPrefs
import com.simplemobiletools.commons.extensions.sharedPreferencesCallback
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.LinkedList
import java.util.Locale
import kotlin.reflect.KProperty0
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.filterNotNull
open class BaseConfig(val context: Context) {
protected val prefs = context.getSharedPrefs()
companion object {
fun newInstance(context: Context) = BaseConfig(context)
}
var appRunCount: Int
get() = prefs.getInt(APP_RUN_COUNT, 0)
set(appRunCount) = prefs.edit().putInt(APP_RUN_COUNT, appRunCount).apply()
var lastVersion: Int
get() = prefs.getInt(LAST_VERSION, 0)
set(lastVersion) = prefs.edit().putInt(LAST_VERSION, lastVersion).apply()
var primaryAndroidDataTreeUri: String
get() = prefs.getString(PRIMARY_ANDROID_DATA_TREE_URI, "")!!
set(uri) = prefs.edit().putString(PRIMARY_ANDROID_DATA_TREE_URI, uri).apply()
var sdAndroidDataTreeUri: String
get() = prefs.getString(SD_ANDROID_DATA_TREE_URI, "")!!
set(uri) = prefs.edit().putString(SD_ANDROID_DATA_TREE_URI, uri).apply()
var otgAndroidDataTreeUri: String
get() = prefs.getString(OTG_ANDROID_DATA_TREE_URI, "")!!
set(uri) = prefs.edit().putString(OTG_ANDROID_DATA_TREE_URI, uri).apply()
var primaryAndroidObbTreeUri: String
get() = prefs.getString(PRIMARY_ANDROID_OBB_TREE_URI, "")!!
set(uri) = prefs.edit().putString(PRIMARY_ANDROID_OBB_TREE_URI, uri).apply()
var sdAndroidObbTreeUri: String
get() = prefs.getString(SD_ANDROID_OBB_TREE_URI, "")!!
set(uri) = prefs.edit().putString(SD_ANDROID_OBB_TREE_URI, uri).apply()
var otgAndroidObbTreeUri: String
get() = prefs.getString(OTG_ANDROID_OBB_TREE_URI, "")!!
set(uri) = prefs.edit().putString(OTG_ANDROID_OBB_TREE_URI, uri).apply()
var sdTreeUri: String
get() = prefs.getString(SD_TREE_URI, "")!!
set(uri) = prefs.edit().putString(SD_TREE_URI, uri).apply()
var OTGTreeUri: String
get() = prefs.getString(OTG_TREE_URI, "")!!
set(OTGTreeUri) = prefs.edit().putString(OTG_TREE_URI, OTGTreeUri).apply()
var OTGPartition: String
get() = prefs.getString(OTG_PARTITION, "")!!
set(OTGPartition) = prefs.edit().putString(OTG_PARTITION, OTGPartition).apply()
var OTGPath: String
get() = prefs.getString(OTG_REAL_PATH, "")!!
set(OTGPath) = prefs.edit().putString(OTG_REAL_PATH, OTGPath).apply()
var sdCardPath: String
get() = prefs.getString(SD_CARD_PATH, getDefaultSDCardPath())!!
set(sdCardPath) = prefs.edit().putString(SD_CARD_PATH, sdCardPath).apply()
private fun getDefaultSDCardPath() = if (prefs.contains(SD_CARD_PATH)) "" else context.getSDCardPath()
var internalStoragePath: String
get() = prefs.getString(INTERNAL_STORAGE_PATH, getDefaultInternalPath())!!
set(internalStoragePath) = prefs.edit().putString(INTERNAL_STORAGE_PATH, internalStoragePath).apply()
private fun getDefaultInternalPath() = if (prefs.contains(INTERNAL_STORAGE_PATH)) "" else context.getInternalStoragePath()
var textColor: Int
get() = prefs.getInt(TEXT_COLOR, ContextCompat.getColor(context, R.color.default_text_color))
set(textColor) = prefs.edit().putInt(TEXT_COLOR, textColor).apply()
var backgroundColor: Int
get() = prefs.getInt(BACKGROUND_COLOR, ContextCompat.getColor(context, R.color.default_background_color))
set(backgroundColor) = prefs.edit().putInt(BACKGROUND_COLOR, backgroundColor).apply()
var primaryColor: Int
get() = prefs.getInt(PRIMARY_COLOR, ContextCompat.getColor(context, R.color.default_primary_color))
set(primaryColor) = prefs.edit().putInt(PRIMARY_COLOR, primaryColor).apply()
var accentColor: Int
get() = prefs.getInt(ACCENT_COLOR, ContextCompat.getColor(context, R.color.default_accent_color))
set(accentColor) = prefs.edit().putInt(ACCENT_COLOR, accentColor).apply()
var lastHandledShortcutColor: Int
get() = prefs.getInt(LAST_HANDLED_SHORTCUT_COLOR, 1)
set(lastHandledShortcutColor) = prefs.edit().putInt(LAST_HANDLED_SHORTCUT_COLOR, lastHandledShortcutColor).apply()
var appIconColor: Int
get() = prefs.getInt(APP_ICON_COLOR, ContextCompat.getColor(context, R.color.default_app_icon_color))
set(appIconColor) {
isUsingModifiedAppIcon = appIconColor != ContextCompat.getColor(context, R.color.color_primary)
prefs.edit().putInt(APP_ICON_COLOR, appIconColor).apply()
}
var lastIconColor: Int
get() = prefs.getInt(LAST_ICON_COLOR, ContextCompat.getColor(context, R.color.color_primary))
set(lastIconColor) = prefs.edit().putInt(LAST_ICON_COLOR, lastIconColor).apply()
var customTextColor: Int
get() = prefs.getInt(CUSTOM_TEXT_COLOR, textColor)
set(customTextColor) = prefs.edit().putInt(CUSTOM_TEXT_COLOR, customTextColor).apply()
var customBackgroundColor: Int
get() = prefs.getInt(CUSTOM_BACKGROUND_COLOR, backgroundColor)
set(customBackgroundColor) = prefs.edit().putInt(CUSTOM_BACKGROUND_COLOR, customBackgroundColor).apply()
var customPrimaryColor: Int
get() = prefs.getInt(CUSTOM_PRIMARY_COLOR, primaryColor)
set(customPrimaryColor) = prefs.edit().putInt(CUSTOM_PRIMARY_COLOR, customPrimaryColor).apply()
var customAccentColor: Int
get() = prefs.getInt(CUSTOM_ACCENT_COLOR, accentColor)
set(customAccentColor) = prefs.edit().putInt(CUSTOM_ACCENT_COLOR, customAccentColor).apply()
var customAppIconColor: Int
get() = prefs.getInt(CUSTOM_APP_ICON_COLOR, appIconColor)
set(customAppIconColor) = prefs.edit().putInt(CUSTOM_APP_ICON_COLOR, customAppIconColor).apply()
var widgetBgColor: Int
get() = prefs.getInt(WIDGET_BG_COLOR, ContextCompat.getColor(context, R.color.default_widget_bg_color))
set(widgetBgColor) = prefs.edit().putInt(WIDGET_BG_COLOR, widgetBgColor).apply()
var widgetTextColor: Int
get() = prefs.getInt(WIDGET_TEXT_COLOR, ContextCompat.getColor(context, R.color.default_widget_text_color))
set(widgetTextColor) = prefs.edit().putInt(WIDGET_TEXT_COLOR, widgetTextColor).apply()
// hidden folder visibility protection
var isHiddenPasswordProtectionOn: Boolean
get() = prefs.getBoolean(PASSWORD_PROTECTION, false)
set(isHiddenPasswordProtectionOn) = prefs.edit().putBoolean(PASSWORD_PROTECTION, isHiddenPasswordProtectionOn).apply()
var hiddenPasswordHash: String
get() = prefs.getString(PASSWORD_HASH, "")!!
set(hiddenPasswordHash) = prefs.edit().putString(PASSWORD_HASH, hiddenPasswordHash).apply()
var hiddenProtectionType: Int
get() = prefs.getInt(PROTECTION_TYPE, PROTECTION_PATTERN)
set(hiddenProtectionType) = prefs.edit().putInt(PROTECTION_TYPE, hiddenProtectionType).apply()
// whole app launch protection
var isAppPasswordProtectionOn: Boolean
get() = prefs.getBoolean(APP_PASSWORD_PROTECTION, false)
set(isAppPasswordProtectionOn) = prefs.edit().putBoolean(APP_PASSWORD_PROTECTION, isAppPasswordProtectionOn).apply()
var appPasswordHash: String
get() = prefs.getString(APP_PASSWORD_HASH, "")!!
set(appPasswordHash) = prefs.edit().putString(APP_PASSWORD_HASH, appPasswordHash).apply()
var appProtectionType: Int
get() = prefs.getInt(APP_PROTECTION_TYPE, PROTECTION_PATTERN)
set(appProtectionType) = prefs.edit().putInt(APP_PROTECTION_TYPE, appProtectionType).apply()
// file delete and move protection
var isDeletePasswordProtectionOn: Boolean
get() = prefs.getBoolean(DELETE_PASSWORD_PROTECTION, false)
set(isDeletePasswordProtectionOn) = prefs.edit().putBoolean(DELETE_PASSWORD_PROTECTION, isDeletePasswordProtectionOn).apply()
var deletePasswordHash: String
get() = prefs.getString(DELETE_PASSWORD_HASH, "")!!
set(deletePasswordHash) = prefs.edit().putString(DELETE_PASSWORD_HASH, deletePasswordHash).apply()
var deleteProtectionType: Int
get() = prefs.getInt(DELETE_PROTECTION_TYPE, PROTECTION_PATTERN)
set(deleteProtectionType) = prefs.edit().putInt(DELETE_PROTECTION_TYPE, deleteProtectionType).apply()
// folder locking
fun addFolderProtection(path: String, hash: String, type: Int) {
prefs.edit()
.putString("$PROTECTED_FOLDER_HASH$path", hash)
.putInt("$PROTECTED_FOLDER_TYPE$path", type)
.apply()
}
fun removeFolderProtection(path: String) {
prefs.edit()
.remove("$PROTECTED_FOLDER_HASH$path")
.remove("$PROTECTED_FOLDER_TYPE$path")
.apply()
}
fun isFolderProtected(path: String) = getFolderProtectionType(path) != PROTECTION_NONE
fun getFolderProtectionHash(path: String) = prefs.getString("$PROTECTED_FOLDER_HASH$path", "") ?: ""
fun getFolderProtectionType(path: String) = prefs.getInt("$PROTECTED_FOLDER_TYPE$path", PROTECTION_NONE)
var lastCopyPath: String
get() = prefs.getString(LAST_COPY_PATH, "")!!
set(lastCopyPath) = prefs.edit().putString(LAST_COPY_PATH, lastCopyPath).apply()
var keepLastModified: Boolean
get() = prefs.getBoolean(KEEP_LAST_MODIFIED, true)
set(keepLastModified) = prefs.edit().putBoolean(KEEP_LAST_MODIFIED, keepLastModified).apply()
var useEnglish: Boolean
get() = prefs.getBoolean(USE_ENGLISH, false)
set(useEnglish) {
wasUseEnglishToggled = true
prefs.edit().putBoolean(USE_ENGLISH, useEnglish).commit()
}
val useEnglishFlow = ::useEnglish.asFlowNonNull()
var wasUseEnglishToggled: Boolean
get() = prefs.getBoolean(WAS_USE_ENGLISH_TOGGLED, false)
set(wasUseEnglishToggled) = prefs.edit().putBoolean(WAS_USE_ENGLISH_TOGGLED, wasUseEnglishToggled).apply()
val wasUseEnglishToggledFlow = ::wasUseEnglishToggled.asFlowNonNull()
var wasSharedThemeEverActivated: Boolean
get() = prefs.getBoolean(WAS_SHARED_THEME_EVER_ACTIVATED, false)
set(wasSharedThemeEverActivated) = prefs.edit().putBoolean(WAS_SHARED_THEME_EVER_ACTIVATED, wasSharedThemeEverActivated).apply()
var isUsingSharedTheme: Boolean
get() = prefs.getBoolean(IS_USING_SHARED_THEME, false)
set(isUsingSharedTheme) = prefs.edit().putBoolean(IS_USING_SHARED_THEME, isUsingSharedTheme).apply()
// used by Simple Thank You, stop using shared Shared Theme if it has been changed in it
var shouldUseSharedTheme: Boolean
get() = prefs.getBoolean(SHOULD_USE_SHARED_THEME, false)
set(shouldUseSharedTheme) = prefs.edit().putBoolean(SHOULD_USE_SHARED_THEME, shouldUseSharedTheme).apply()
var isUsingAutoTheme: Boolean
get() = prefs.getBoolean(IS_USING_AUTO_THEME, false)
set(isUsingAutoTheme) = prefs.edit().putBoolean(IS_USING_AUTO_THEME, isUsingAutoTheme).apply()
var isUsingSystemTheme: Boolean
get() = prefs.getBoolean(IS_USING_SYSTEM_THEME, isSPlus())
set(isUsingSystemTheme) = prefs.edit().putBoolean(IS_USING_SYSTEM_THEME, isUsingSystemTheme).apply()
var wasCustomThemeSwitchDescriptionShown: Boolean
get() = prefs.getBoolean(WAS_CUSTOM_THEME_SWITCH_DESCRIPTION_SHOWN, false)
set(wasCustomThemeSwitchDescriptionShown) = prefs.edit().putBoolean(WAS_CUSTOM_THEME_SWITCH_DESCRIPTION_SHOWN, wasCustomThemeSwitchDescriptionShown)
.apply()
var wasSharedThemeForced: Boolean
get() = prefs.getBoolean(WAS_SHARED_THEME_FORCED, false)
set(wasSharedThemeForced) = prefs.edit().putBoolean(WAS_SHARED_THEME_FORCED, wasSharedThemeForced).apply()
var showInfoBubble: Boolean
get() = prefs.getBoolean(SHOW_INFO_BUBBLE, true)
set(showInfoBubble) = prefs.edit().putBoolean(SHOW_INFO_BUBBLE, showInfoBubble).apply()
var lastConflictApplyToAll: Boolean
get() = prefs.getBoolean(LAST_CONFLICT_APPLY_TO_ALL, true)
set(lastConflictApplyToAll) = prefs.edit().putBoolean(LAST_CONFLICT_APPLY_TO_ALL, lastConflictApplyToAll).apply()
var lastConflictResolution: Int
get() = prefs.getInt(LAST_CONFLICT_RESOLUTION, CONFLICT_SKIP)
set(lastConflictResolution) = prefs.edit().putInt(LAST_CONFLICT_RESOLUTION, lastConflictResolution).apply()
var sorting: Int
get() = prefs.getInt(SORT_ORDER, context.resources.getInteger(R.integer.default_sorting))
set(sorting) = prefs.edit().putInt(SORT_ORDER, sorting).apply()
fun saveCustomSorting(path: String, value: Int) {
if (path.isEmpty()) {
sorting = value
} else {
prefs.edit().putInt(SORT_FOLDER_PREFIX + path.toLowerCase(), value).apply()
}
}
fun getFolderSorting(path: String) = prefs.getInt(SORT_FOLDER_PREFIX + path.toLowerCase(), sorting)
fun removeCustomSorting(path: String) {
prefs.edit().remove(SORT_FOLDER_PREFIX + path.toLowerCase()).apply()
}
fun hasCustomSorting(path: String) = prefs.contains(SORT_FOLDER_PREFIX + path.toLowerCase())
var hadThankYouInstalled: Boolean
get() = prefs.getBoolean(HAD_THANK_YOU_INSTALLED, false)
set(hadThankYouInstalled) = prefs.edit().putBoolean(HAD_THANK_YOU_INSTALLED, hadThankYouInstalled).apply()
var skipDeleteConfirmation: Boolean
get() = prefs.getBoolean(SKIP_DELETE_CONFIRMATION, false)
set(skipDeleteConfirmation) = prefs.edit().putBoolean(SKIP_DELETE_CONFIRMATION, skipDeleteConfirmation).apply()
var enablePullToRefresh: Boolean
get() = prefs.getBoolean(ENABLE_PULL_TO_REFRESH, true)
set(enablePullToRefresh) = prefs.edit().putBoolean(ENABLE_PULL_TO_REFRESH, enablePullToRefresh).apply()
var scrollHorizontally: Boolean
get() = prefs.getBoolean(SCROLL_HORIZONTALLY, false)
set(scrollHorizontally) = prefs.edit().putBoolean(SCROLL_HORIZONTALLY, scrollHorizontally).apply()
var preventPhoneFromSleeping: Boolean
get() = prefs.getBoolean(PREVENT_PHONE_FROM_SLEEPING, true)
set(preventPhoneFromSleeping) = prefs.edit().putBoolean(PREVENT_PHONE_FROM_SLEEPING, preventPhoneFromSleeping).apply()
var lastUsedViewPagerPage: Int
get() = prefs.getInt(LAST_USED_VIEW_PAGER_PAGE, context.resources.getInteger(R.integer.default_viewpager_page))
set(lastUsedViewPagerPage) = prefs.edit().putInt(LAST_USED_VIEW_PAGER_PAGE, lastUsedViewPagerPage).apply()
var use24HourFormat: Boolean
get() = prefs.getBoolean(USE_24_HOUR_FORMAT, DateFormat.is24HourFormat(context))
set(use24HourFormat) = prefs.edit().putBoolean(USE_24_HOUR_FORMAT, use24HourFormat).apply()
var isSundayFirst: Boolean
get() {
val isSundayFirst = Calendar.getInstance(Locale.getDefault()).firstDayOfWeek == Calendar.SUNDAY
return prefs.getBoolean(SUNDAY_FIRST, isSundayFirst)
}
set(sundayFirst) = prefs.edit().putBoolean(SUNDAY_FIRST, sundayFirst).apply()
var wasAlarmWarningShown: Boolean
get() = prefs.getBoolean(WAS_ALARM_WARNING_SHOWN, false)
set(wasAlarmWarningShown) = prefs.edit().putBoolean(WAS_ALARM_WARNING_SHOWN, wasAlarmWarningShown).apply()
var wasReminderWarningShown: Boolean
get() = prefs.getBoolean(WAS_REMINDER_WARNING_SHOWN, false)
set(wasReminderWarningShown) = prefs.edit().putBoolean(WAS_REMINDER_WARNING_SHOWN, wasReminderWarningShown).apply()
var useSameSnooze: Boolean
get() = prefs.getBoolean(USE_SAME_SNOOZE, true)
set(useSameSnooze) = prefs.edit().putBoolean(USE_SAME_SNOOZE, useSameSnooze).apply()
var snoozeTime: Int
get() = prefs.getInt(SNOOZE_TIME, 10)
set(snoozeDelay) = prefs.edit().putInt(SNOOZE_TIME, snoozeDelay).apply()
var vibrateOnButtonPress: Boolean
get() = prefs.getBoolean(VIBRATE_ON_BUTTON_PRESS, context.resources.getBoolean(R.bool.default_vibrate_on_press))
set(vibrateOnButton) = prefs.edit().putBoolean(VIBRATE_ON_BUTTON_PRESS, vibrateOnButton).apply()
var yourAlarmSounds: String
get() = prefs.getString(YOUR_ALARM_SOUNDS, "")!!
set(yourAlarmSounds) = prefs.edit().putString(YOUR_ALARM_SOUNDS, yourAlarmSounds).apply()
var isUsingModifiedAppIcon: Boolean
get() = prefs.getBoolean(IS_USING_MODIFIED_APP_ICON, false)
set(isUsingModifiedAppIcon) = prefs.edit().putBoolean(IS_USING_MODIFIED_APP_ICON, isUsingModifiedAppIcon).apply()
var appId: String
get() = prefs.getString(APP_ID, "")!!
set(appId) = prefs.edit().putString(APP_ID, appId).apply()
var initialWidgetHeight: Int
get() = prefs.getInt(INITIAL_WIDGET_HEIGHT, 0)
set(initialWidgetHeight) = prefs.edit().putInt(INITIAL_WIDGET_HEIGHT, initialWidgetHeight).apply()
var widgetIdToMeasure: Int
get() = prefs.getInt(WIDGET_ID_TO_MEASURE, 0)
set(widgetIdToMeasure) = prefs.edit().putInt(WIDGET_ID_TO_MEASURE, widgetIdToMeasure).apply()
var wasOrangeIconChecked: Boolean
get() = prefs.getBoolean(WAS_ORANGE_ICON_CHECKED, false)
set(wasOrangeIconChecked) = prefs.edit().putBoolean(WAS_ORANGE_ICON_CHECKED, wasOrangeIconChecked).apply()
var wasAppOnSDShown: Boolean
get() = prefs.getBoolean(WAS_APP_ON_SD_SHOWN, false)
set(wasAppOnSDShown) = prefs.edit().putBoolean(WAS_APP_ON_SD_SHOWN, wasAppOnSDShown).apply()
var wasBeforeAskingShown: Boolean
get() = prefs.getBoolean(WAS_BEFORE_ASKING_SHOWN, false)
set(wasBeforeAskingShown) = prefs.edit().putBoolean(WAS_BEFORE_ASKING_SHOWN, wasBeforeAskingShown).apply()
var wasBeforeRateShown: Boolean
get() = prefs.getBoolean(WAS_BEFORE_RATE_SHOWN, false)
set(wasBeforeRateShown) = prefs.edit().putBoolean(WAS_BEFORE_RATE_SHOWN, wasBeforeRateShown).apply()
var wasInitialUpgradeToProShown: Boolean
get() = prefs.getBoolean(WAS_INITIAL_UPGRADE_TO_PRO_SHOWN, false)
set(wasInitialUpgradeToProShown) = prefs.edit().putBoolean(WAS_INITIAL_UPGRADE_TO_PRO_SHOWN, wasInitialUpgradeToProShown).apply()
var wasAppIconCustomizationWarningShown: Boolean
get() = prefs.getBoolean(WAS_APP_ICON_CUSTOMIZATION_WARNING_SHOWN, false)
set(wasAppIconCustomizationWarningShown) = prefs.edit().putBoolean(WAS_APP_ICON_CUSTOMIZATION_WARNING_SHOWN, wasAppIconCustomizationWarningShown)
.apply()
var appSideloadingStatus: Int
get() = prefs.getInt(APP_SIDELOADING_STATUS, SIDELOADING_UNCHECKED)
set(appSideloadingStatus) = prefs.edit().putInt(APP_SIDELOADING_STATUS, appSideloadingStatus).apply()
var dateFormat: String
get() = prefs.getString(DATE_FORMAT, getDefaultDateFormat())!!
set(dateFormat) = prefs.edit().putString(DATE_FORMAT, dateFormat).apply()
private fun getDefaultDateFormat(): String {
val format = DateFormat.getDateFormat(context)
val pattern = (format as SimpleDateFormat).toLocalizedPattern()
return when (pattern.lowercase().replace(" ", "")) {
"d.M.y" -> DATE_FORMAT_ONE
"dd/mm/y" -> DATE_FORMAT_TWO
"mm/dd/y" -> DATE_FORMAT_THREE
"y-mm-dd" -> DATE_FORMAT_FOUR
"dmmmmy" -> DATE_FORMAT_FIVE
"mmmmdy" -> DATE_FORMAT_SIX
"mm-dd-y" -> DATE_FORMAT_SEVEN
"dd-mm-y" -> DATE_FORMAT_EIGHT
else -> DATE_FORMAT_ONE
}
}
var wasOTGHandled: Boolean
get() = prefs.getBoolean(WAS_OTG_HANDLED, false)
set(wasOTGHandled) = prefs.edit().putBoolean(WAS_OTG_HANDLED, wasOTGHandled).apply()
var wasUpgradedFromFreeShown: Boolean
get() = prefs.getBoolean(WAS_UPGRADED_FROM_FREE_SHOWN, false)
set(wasUpgradedFromFreeShown) = prefs.edit().putBoolean(WAS_UPGRADED_FROM_FREE_SHOWN, wasUpgradedFromFreeShown).apply()
var wasRateUsPromptShown: Boolean
get() = prefs.getBoolean(WAS_RATE_US_PROMPT_SHOWN, false)
set(wasRateUsPromptShown) = prefs.edit().putBoolean(WAS_RATE_US_PROMPT_SHOWN, wasRateUsPromptShown).apply()
var wasAppRated: Boolean
get() = prefs.getBoolean(WAS_APP_RATED, false)
set(wasAppRated) = prefs.edit().putBoolean(WAS_APP_RATED, wasAppRated).apply()
var wasSortingByNumericValueAdded: Boolean
get() = prefs.getBoolean(WAS_SORTING_BY_NUMERIC_VALUE_ADDED, false)
set(wasSortingByNumericValueAdded) = prefs.edit().putBoolean(WAS_SORTING_BY_NUMERIC_VALUE_ADDED, wasSortingByNumericValueAdded).apply()
var wasFolderLockingNoticeShown: Boolean
get() = prefs.getBoolean(WAS_FOLDER_LOCKING_NOTICE_SHOWN, false)
set(wasFolderLockingNoticeShown) = prefs.edit().putBoolean(WAS_FOLDER_LOCKING_NOTICE_SHOWN, wasFolderLockingNoticeShown).apply()
var lastRenameUsed: Int
get() = prefs.getInt(LAST_RENAME_USED, RENAME_SIMPLE)
set(lastRenameUsed) = prefs.edit().putInt(LAST_RENAME_USED, lastRenameUsed).apply()
var lastRenamePatternUsed: String
get() = prefs.getString(LAST_RENAME_PATTERN_USED, "")!!
set(lastRenamePatternUsed) = prefs.edit().putString(LAST_RENAME_PATTERN_USED, lastRenamePatternUsed).apply()
var lastExportedSettingsFolder: String
get() = prefs.getString(LAST_EXPORTED_SETTINGS_FOLDER, "")!!
set(lastExportedSettingsFolder) = prefs.edit().putString(LAST_EXPORTED_SETTINGS_FOLDER, lastExportedSettingsFolder).apply()
var lastBlockedNumbersExportPath: String
get() = prefs.getString(LAST_BLOCKED_NUMBERS_EXPORT_PATH, "")!!
set(lastBlockedNumbersExportPath) = prefs.edit().putString(LAST_BLOCKED_NUMBERS_EXPORT_PATH, lastBlockedNumbersExportPath).apply()
var blockUnknownNumbers: Boolean
get() = prefs.getBoolean(BLOCK_UNKNOWN_NUMBERS, false)
set(blockUnknownNumbers) = prefs.edit().putBoolean(BLOCK_UNKNOWN_NUMBERS, blockUnknownNumbers).apply()
val isBlockingUnknownNumbers: Flow<Boolean> = ::blockUnknownNumbers.asFlowNonNull()
var blockHiddenNumbers: Boolean
get() = prefs.getBoolean(BLOCK_HIDDEN_NUMBERS, false)
set(blockHiddenNumbers) = prefs.edit().putBoolean(BLOCK_HIDDEN_NUMBERS, blockHiddenNumbers).apply()
val isBlockingHiddenNumbers: Flow<Boolean> = ::blockHiddenNumbers.asFlowNonNull()
var fontSize: Int
get() = prefs.getInt(FONT_SIZE, context.resources.getInteger(R.integer.default_font_size))
set(size) = prefs.edit().putInt(FONT_SIZE, size).apply()
// notify the users about new SMS Messenger and Voice Recorder released
var wasMessengerRecorderShown: Boolean
get() = prefs.getBoolean(WAS_MESSENGER_RECORDER_SHOWN, false)
set(wasMessengerRecorderShown) = prefs.edit().putBoolean(WAS_MESSENGER_RECORDER_SHOWN, wasMessengerRecorderShown).apply()
var defaultTab: Int
get() = prefs.getInt(DEFAULT_TAB, TAB_LAST_USED)
set(defaultTab) = prefs.edit().putInt(DEFAULT_TAB, defaultTab).apply()
var startNameWithSurname: Boolean
get() = prefs.getBoolean(START_NAME_WITH_SURNAME, false)
set(startNameWithSurname) = prefs.edit().putBoolean(START_NAME_WITH_SURNAME, startNameWithSurname).apply()
var favorites: MutableSet<String>
get() = prefs.getStringSet(FAVORITES, HashSet())!!
set(favorites) = prefs.edit().remove(FAVORITES).putStringSet(FAVORITES, favorites).apply()
var showCallConfirmation: Boolean
get() = prefs.getBoolean(SHOW_CALL_CONFIRMATION, false)
set(showCallConfirmation) = prefs.edit().putBoolean(SHOW_CALL_CONFIRMATION, showCallConfirmation).apply()
// color picker last used colors
var colorPickerRecentColors: LinkedList<Int>
get(): LinkedList<Int> {
val defaultList = arrayListOf(
ContextCompat.getColor(context, R.color.md_red_700),
ContextCompat.getColor(context, R.color.md_blue_700),
ContextCompat.getColor(context, R.color.md_green_700),
ContextCompat.getColor(context, R.color.md_yellow_700),
ContextCompat.getColor(context, R.color.md_orange_700)
)
return LinkedList(prefs.getString(COLOR_PICKER_RECENT_COLORS, null)?.lines()?.map { it.toInt() } ?: defaultList)
}
set(recentColors) = prefs.edit().putString(COLOR_PICKER_RECENT_COLORS, recentColors.joinToString(separator = "\n")).apply()
val colorPickerRecentColorsFlow = ::colorPickerRecentColors.asFlowNonNull()
var ignoredContactSources: HashSet<String>
get() = prefs.getStringSet(IGNORED_CONTACT_SOURCES, hashSetOf(".")) as HashSet
set(ignoreContactSources) = prefs.edit().remove(IGNORED_CONTACT_SOURCES).putStringSet(IGNORED_CONTACT_SOURCES, ignoreContactSources).apply()
var showContactThumbnails: Boolean
get() = prefs.getBoolean(SHOW_CONTACT_THUMBNAILS, true)
set(showContactThumbnails) = prefs.edit().putBoolean(SHOW_CONTACT_THUMBNAILS, showContactThumbnails).apply()
var showPhoneNumbers: Boolean
get() = prefs.getBoolean(SHOW_PHONE_NUMBERS, false)
set(showPhoneNumbers) = prefs.edit().putBoolean(SHOW_PHONE_NUMBERS, showPhoneNumbers).apply()
var showOnlyContactsWithNumbers: Boolean
get() = prefs.getBoolean(SHOW_ONLY_CONTACTS_WITH_NUMBERS, false)
set(showOnlyContactsWithNumbers) = prefs.edit().putBoolean(SHOW_ONLY_CONTACTS_WITH_NUMBERS, showOnlyContactsWithNumbers).apply()
var lastUsedContactSource: String
get() = prefs.getString(LAST_USED_CONTACT_SOURCE, "")!!
set(lastUsedContactSource) = prefs.edit().putString(LAST_USED_CONTACT_SOURCE, lastUsedContactSource).apply()
var onContactClick: Int
get() = prefs.getInt(ON_CONTACT_CLICK, ON_CLICK_VIEW_CONTACT)
set(onContactClick) = prefs.edit().putInt(ON_CONTACT_CLICK, onContactClick).apply()
var showContactFields: Int
get() = prefs.getInt(
SHOW_CONTACT_FIELDS,
SHOW_FIRST_NAME_FIELD or SHOW_SURNAME_FIELD or SHOW_PHONE_NUMBERS_FIELD or SHOW_EMAILS_FIELD or
SHOW_ADDRESSES_FIELD or SHOW_EVENTS_FIELD or SHOW_NOTES_FIELD or SHOW_GROUPS_FIELD or SHOW_CONTACT_SOURCE_FIELD
)
set(showContactFields) = prefs.edit().putInt(SHOW_CONTACT_FIELDS, showContactFields).apply()
var showDialpadButton: Boolean
get() = prefs.getBoolean(SHOW_DIALPAD_BUTTON, true)
set(showDialpadButton) = prefs.edit().putBoolean(SHOW_DIALPAD_BUTTON, showDialpadButton).apply()
var wasLocalAccountInitialized: Boolean
get() = prefs.getBoolean(WAS_LOCAL_ACCOUNT_INITIALIZED, false)
set(wasLocalAccountInitialized) = prefs.edit().putBoolean(WAS_LOCAL_ACCOUNT_INITIALIZED, wasLocalAccountInitialized).apply()
var lastExportPath: String
get() = prefs.getString(LAST_EXPORT_PATH, "")!!
set(lastExportPath) = prefs.edit().putString(LAST_EXPORT_PATH, lastExportPath).apply()
var speedDial: String
get() = prefs.getString(SPEED_DIAL, "")!!
set(speedDial) = prefs.edit().putString(SPEED_DIAL, speedDial).apply()
var showPrivateContacts: Boolean
get() = prefs.getBoolean(SHOW_PRIVATE_CONTACTS, true)
set(showPrivateContacts) = prefs.edit().putBoolean(SHOW_PRIVATE_CONTACTS, showPrivateContacts).apply()
var mergeDuplicateContacts: Boolean
get() = prefs.getBoolean(MERGE_DUPLICATE_CONTACTS, true)
set(mergeDuplicateContacts) = prefs.edit().putBoolean(MERGE_DUPLICATE_CONTACTS, mergeDuplicateContacts).apply()
var favoritesContactsOrder: String
get() = prefs.getString(FAVORITES_CONTACTS_ORDER, "")!!
set(order) = prefs.edit().putString(FAVORITES_CONTACTS_ORDER, order).apply()
var isCustomOrderSelected: Boolean
get() = prefs.getBoolean(FAVORITES_CUSTOM_ORDER_SELECTED, false)
set(selected) = prefs.edit().putBoolean(FAVORITES_CUSTOM_ORDER_SELECTED, selected).apply()
var viewType: Int
get() = prefs.getInt(VIEW_TYPE, VIEW_TYPE_LIST)
set(viewType) = prefs.edit().putInt(VIEW_TYPE, viewType).apply()
var contactsGridColumnCount: Int
get() = prefs.getInt(CONTACTS_GRID_COLUMN_COUNT, getDefaultContactColumnsCount())
set(contactsGridColumnCount) = prefs.edit().putInt(CONTACTS_GRID_COLUMN_COUNT, contactsGridColumnCount).apply()
private fun getDefaultContactColumnsCount(): Int {
val isPortrait = context.resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT
return if (isPortrait) {
context.resources.getInteger(R.integer.contacts_grid_columns_count_portrait)
} else {
context.resources.getInteger(R.integer.contacts_grid_columns_count_landscape)
}
}
var autoBackup: Boolean
get() = prefs.getBoolean(AUTO_BACKUP, false)
set(autoBackup) = prefs.edit().putBoolean(AUTO_BACKUP, autoBackup).apply()
var autoBackupFolder: String
get() = prefs.getString(AUTO_BACKUP_FOLDER, Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).absolutePath)!!
set(autoBackupFolder) = prefs.edit().putString(AUTO_BACKUP_FOLDER, autoBackupFolder).apply()
var autoBackupFilename: String
get() = prefs.getString(AUTO_BACKUP_FILENAME, "")!!
set(autoBackupFilename) = prefs.edit().putString(AUTO_BACKUP_FILENAME, autoBackupFilename).apply()
var lastAutoBackupTime: Long
get() = prefs.getLong(LAST_AUTO_BACKUP_TIME, 0L)
set(lastAutoBackupTime) = prefs.edit().putLong(LAST_AUTO_BACKUP_TIME, lastAutoBackupTime).apply()
var passwordRetryCount: Int
get() = prefs.getInt(PASSWORD_RETRY_COUNT, 0)
set(passwordRetryCount) = prefs.edit().putInt(PASSWORD_RETRY_COUNT, passwordRetryCount).apply()
var passwordCountdownStartMs: Long
get() = prefs.getLong(PASSWORD_COUNTDOWN_START_MS, 0L)
set(passwordCountdownStartMs) = prefs.edit().putLong(PASSWORD_COUNTDOWN_START_MS, passwordCountdownStartMs).apply()
protected fun <T> KProperty0<T>.asFlow(emitOnCollect: Boolean = false): Flow<T?> = prefs.run { sharedPreferencesCallback(sendOnCollect = emitOnCollect) { [email protected]() } }
protected fun <T> KProperty0<T>.asFlowNonNull(emitOnCollect: Boolean = false): Flow<T> = asFlow(emitOnCollect).filterNotNull()
}
| CT/commons/src/main/kotlin/com/simplemobiletools/commons/helpers/BaseConfig.kt | 547304164 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.