path
stringlengths
4
297
contentHash
stringlengths
1
10
content
stringlengths
0
13M
CT/commons/src/main/kotlin/com/simplemobiletools/commons/models/contacts/Contact.kt
3047053170
package com.simplemobiletools.commons.models.contacts import android.graphics.Bitmap import android.provider.ContactsContract import android.telephony.PhoneNumberUtils import com.simplemobiletools.commons.extensions.normalizePhoneNumber import com.simplemobiletools.commons.extensions.normalizeString import com.simplemobiletools.commons.helpers.* import com.simplemobiletools.commons.models.PhoneNumber import kotlinx.serialization.Contextual import kotlinx.serialization.Serializable @Serializable data class Contact( var id: Int, var prefix: String= "", var firstName: String= "", var middleName: String= "", var surname: String= "", var suffix: String= "", var nickname: String= "", var photoUri: String= "", var phoneNumbers: ArrayList<PhoneNumber> = arrayListOf(), var emails: ArrayList<Email> = arrayListOf(), var addresses: ArrayList<Address> = arrayListOf(), var events: ArrayList<Event> = arrayListOf(), var source: String= "", var starred: Int = 0, var contactId: Int, var thumbnailUri: String= "", @Contextual var photo: Bitmap? = null, var notes: String= "", var groups: ArrayList<Group> = arrayListOf(), var organization: Organization = Organization("",""), var websites: ArrayList<String> = arrayListOf(), var IMs: ArrayList<IM> = arrayListOf(), var mimetype: String = "", var ringtone: String? = "" ) : Comparable<Contact> { val rawId = id val name = getNameToDisplay() var birthdays = events.filter { it.type == ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY }.map { it.value }.toMutableList() as ArrayList<String> var anniversaries = events.filter { it.type == ContactsContract.CommonDataKinds.Event.TYPE_ANNIVERSARY }.map { it.value }.toMutableList() as ArrayList<String> companion object { var sorting = 0 var startWithSurname = false } override fun compareTo(other: Contact): Int { var result = when { sorting and SORT_BY_FIRST_NAME != 0 -> { val firstString = firstName.normalizeString() val secondString = other.firstName.normalizeString() compareUsingStrings(firstString, secondString, other) } sorting and SORT_BY_MIDDLE_NAME != 0 -> { val firstString = middleName.normalizeString() val secondString = other.middleName.normalizeString() compareUsingStrings(firstString, secondString, other) } sorting and SORT_BY_SURNAME != 0 -> { val firstString = surname.normalizeString() val secondString = other.surname.normalizeString() compareUsingStrings(firstString, secondString, other) } sorting and SORT_BY_FULL_NAME != 0 -> { val firstString = getNameToDisplay().normalizeString() val secondString = other.getNameToDisplay().normalizeString() compareUsingStrings(firstString, secondString, other) } else -> compareUsingIds(other) } if (sorting and SORT_DESCENDING != 0) { result *= -1 } return result } private fun compareUsingStrings(firstString: String, secondString: String, other: Contact): Int { var firstValue = firstString var secondValue = secondString if (firstValue.isEmpty() && firstName.isEmpty() && middleName.isEmpty() && surname.isEmpty()) { val fullCompany = getFullCompany() if (fullCompany.isNotEmpty()) { firstValue = fullCompany.normalizeString() } else if (emails.isNotEmpty()) { firstValue = emails.first().value } } if (secondValue.isEmpty() && other.firstName.isEmpty() && other.middleName.isEmpty() && other.surname.isEmpty()) { val otherFullCompany = other.getFullCompany() if (otherFullCompany.isNotEmpty()) { secondValue = otherFullCompany.normalizeString() } else if (other.emails.isNotEmpty()) { secondValue = other.emails.first().value } } return if (firstValue.firstOrNull()?.isLetter() == true && secondValue.firstOrNull()?.isLetter() == false) { -1 } else if (firstValue.firstOrNull()?.isLetter() == false && secondValue.firstOrNull()?.isLetter() == true) { 1 } else { if (firstValue.isEmpty() && secondValue.isNotEmpty()) { 1 } else if (firstValue.isNotEmpty() && secondValue.isEmpty()) { -1 } else { if (firstValue.equals(secondValue, ignoreCase = true)) { getNameToDisplay().compareTo(other.getNameToDisplay(), true) } else { firstValue.compareTo(secondValue, true) } } } } private fun compareUsingIds(other: Contact): Int { val firstId = id val secondId = other.id return firstId.compareTo(secondId) } fun getBubbleText() = when { sorting and SORT_BY_FIRST_NAME != 0 -> firstName sorting and SORT_BY_MIDDLE_NAME != 0 -> middleName else -> surname } fun getNameToDisplay(): String { val firstMiddle = "$firstName $middleName".trim() val firstPart = if (startWithSurname) { if (surname.isNotEmpty() && firstMiddle.isNotEmpty()) { "$surname," } else { surname } } else { firstMiddle } val lastPart = if (startWithSurname) firstMiddle else surname val suffixComma = if (suffix.isEmpty()) "" else ", $suffix" val fullName = "$prefix $firstPart $lastPart$suffixComma".trim() val organization = getFullCompany() val email = emails.firstOrNull()?.value?.trim() val phoneNumber = phoneNumbers.firstOrNull()?.normalizedNumber return when { fullName.isNotBlank() -> fullName organization.isNotBlank() -> organization !email.isNullOrBlank() -> email !phoneNumber.isNullOrBlank() -> phoneNumber else -> return "" } } // photos stored locally always have different hashcodes. Avoid constantly refreshing the contact lists as the app thinks something changed. fun getHashWithoutPrivatePhoto(): Int { val photoToUse = if (isPrivate()) null else photo return copy(photo = photoToUse).hashCode() } fun getStringToCompare(): String { val photoToUse = if (isPrivate()) null else photo return copy( id = 0, prefix = "", firstName = getNameToDisplay().toLowerCase(), middleName = "", surname = "", suffix = "", nickname = "", photoUri = "", phoneNumbers = ArrayList(), emails = ArrayList(), events = ArrayList(), source = "", addresses = ArrayList(), starred = 0, contactId = 0, thumbnailUri = "", photo = photoToUse, notes = "", groups = ArrayList(), websites = ArrayList(), organization = Organization("", ""), IMs = ArrayList(), ringtone = "" ).toString() } fun getHashToCompare() = getStringToCompare().hashCode() fun getFullCompany(): String { var fullOrganization = if (organization.company.isEmpty()) "" else "${organization.company}, " fullOrganization += organization.jobPosition return fullOrganization.trim().trimEnd(',') } fun isABusinessContact() = prefix.isEmpty() && firstName.isEmpty() && middleName.isEmpty() && surname.isEmpty() && suffix.isEmpty() && organization.isNotEmpty() fun doesContainPhoneNumber(text: String, convertLetters: Boolean = false): Boolean { return if (text.isNotEmpty()) { val normalizedText = if (convertLetters) text.normalizePhoneNumber() else text phoneNumbers.any { PhoneNumberUtils.compare(it.normalizedNumber, normalizedText) || it.value.contains(text) || it.normalizedNumber.contains(normalizedText) || it.value.normalizePhoneNumber().contains(normalizedText) } } else { false } } fun doesHavePhoneNumber(text: String): Boolean { return if (text.isNotEmpty()) { val normalizedText = text.normalizePhoneNumber() if (normalizedText.isEmpty()) { phoneNumbers.map { it.normalizedNumber }.any { phoneNumber -> phoneNumber == text } } else { phoneNumbers.map { it.normalizedNumber }.any { phoneNumber -> PhoneNumberUtils.compare(phoneNumber.normalizePhoneNumber(), normalizedText) || phoneNumber == text || phoneNumber.normalizePhoneNumber() == normalizedText || phoneNumber == normalizedText } } } else { false } } fun isPrivate() = source == SMT_PRIVATE fun getSignatureKey() = if (photoUri.isNotEmpty()) photoUri else hashCode() fun getPrimaryNumber(): String? { val primaryNumber = phoneNumbers.firstOrNull { it.isPrimary } return primaryNumber?.normalizedNumber ?: phoneNumbers.firstOrNull()?.normalizedNumber } }
CT/commons/src/main/kotlin/com/simplemobiletools/commons/models/contacts/Address.kt
3041531046
package com.simplemobiletools.commons.models.contacts import kotlinx.serialization.Serializable @Serializable data class Address(var value: String, var type: Int, var label: String)
CT/commons/src/main/kotlin/com/simplemobiletools/commons/models/contacts/Event.kt
3973221739
package com.simplemobiletools.commons.models.contacts import kotlinx.serialization.Serializable @Serializable data class Event(var value: String, var type: Int)
CT/commons/src/main/kotlin/com/simplemobiletools/commons/models/contacts/ContactSource.kt
473862672
package com.simplemobiletools.commons.models.contacts import com.simplemobiletools.commons.helpers.SMT_PRIVATE data class ContactSource(var name: String, var type: String, var publicName: String, var count: Int = 0) { fun getFullIdentifier(): String { return if (type == SMT_PRIVATE) { type } else { "$name:$type" } } }
CT/commons/src/main/kotlin/com/simplemobiletools/commons/models/contacts/Organization.kt
72133067
package com.simplemobiletools.commons.models.contacts import kotlinx.serialization.Serializable @Serializable data class Organization(var company: String, var jobPosition: String) { fun isEmpty() = company.isEmpty() && jobPosition.isEmpty() fun isNotEmpty() = !isEmpty() }
CT/commons/src/main/kotlin/com/simplemobiletools/commons/models/contacts/PhoneNumberConverter.kt
1129964785
package com.simplemobiletools.commons.models.contacts import androidx.annotation.Keep // need for hacky parsing of no longer minified PhoneNumber model in Converters.kt @Keep data class PhoneNumberConverter(var a: String, var b: Int, var c: String, var d: String, var e: Boolean = false)
CT/commons/src/main/kotlin/com/simplemobiletools/commons/models/SimpleListItem.kt
1757584637
package com.simplemobiletools.commons.models import android.os.Parcelable import androidx.compose.runtime.Immutable import kotlinx.parcelize.Parcelize @Parcelize @Immutable data class SimpleListItem(val id: Int, val textRes: Int, val imageRes: Int? = null, val selected: Boolean = false) : Parcelable { companion object { fun areItemsTheSame(old: SimpleListItem, new: SimpleListItem): Boolean { return old.id == new.id } fun areContentsTheSame(old: SimpleListItem, new: SimpleListItem): Boolean { return old.imageRes == new.imageRes && old.textRes == new.textRes && old.selected == new.selected } } }
CT/commons/src/main/kotlin/com/simplemobiletools/commons/models/MyTheme.kt
3717262889
package com.simplemobiletools.commons.models data class MyTheme(val label: String, val textColorId: Int, val backgroundColorId: Int, val primaryColorId: Int, val appIconColorId: Int)
CT/commons/src/main/kotlin/com/simplemobiletools/commons/models/PhoneNumber.kt
1099608615
package com.simplemobiletools.commons.models import kotlinx.serialization.Serializable @Serializable data class PhoneNumber( var value: String, var type: Int, var label: String, var normalizedNumber: String, var isPrimary: Boolean = false )
CT/commons/src/main/kotlin/com/simplemobiletools/commons/models/Release.kt
3124372028
package com.simplemobiletools.commons.models import androidx.compose.runtime.Immutable @Immutable data class Release(val id: Int, val textId: Int)
CT/commons/src/main/kotlin/com/simplemobiletools/commons/models/Android30RenameFormat.kt
3710251935
package com.simplemobiletools.commons.models enum class Android30RenameFormat { SAF, CONTENT_RESOLVER, NONE }
CT/commons/src/main/kotlin/com/simplemobiletools/commons/models/SharedTheme.kt
3569708171
package com.simplemobiletools.commons.models data class SharedTheme( val textColor: Int, val backgroundColor: Int, val primaryColor: Int, val appIconColor: Int, val lastUpdatedTS: Int = 0, val accentColor: Int )
CT/commons/src/main/kotlin/com/simplemobiletools/commons/models/AlarmSound.kt
3630447922
package com.simplemobiletools.commons.models data class AlarmSound(val id: Int, var title: String, var uri: String)
CT/commons/src/main/kotlin/com/simplemobiletools/commons/models/RadioItem.kt
1593185985
package com.simplemobiletools.commons.models import androidx.compose.runtime.Immutable @Immutable data class RadioItem(val id: Int, val title: String, val value: Any = id)
CT/commons/src/main/kotlin/com/simplemobiletools/commons/models/LanguageContributor.kt
460642583
package com.simplemobiletools.commons.models import androidx.annotation.DrawableRes import androidx.annotation.StringRes import androidx.compose.runtime.Immutable @Immutable data class LanguageContributor(@DrawableRes val iconId: Int, @StringRes val labelId: Int, @StringRes val contributorsId: Int)
CT/commons/src/main/kotlin/com/simplemobiletools/commons/models/FileDirItem.kt
2377535186
package com.simplemobiletools.commons.models import android.content.Context import android.net.Uri import android.provider.MediaStore import androidx.compose.runtime.Immutable import com.bumptech.glide.signature.ObjectKey import com.simplemobiletools.commons.extensions.* import com.simplemobiletools.commons.helpers.* import java.io.File open class FileDirItem( val path: String, val name: String = "", var isDirectory: Boolean = false, var children: Int = 0, var size: Long = 0L, var modified: Long = 0L, var mediaStoreId: Long = 0L ) : Comparable<FileDirItem> { companion object { var sorting = 0 } override fun toString() = "FileDirItem(path=$path, name=$name, isDirectory=$isDirectory, children=$children, size=$size, modified=$modified, mediaStoreId=$mediaStoreId)" override fun compareTo(other: FileDirItem): Int { return if (isDirectory && !other.isDirectory) { -1 } else if (!isDirectory && other.isDirectory) { 1 } else { var result: Int when { sorting and SORT_BY_NAME != 0 -> { result = if (sorting and SORT_USE_NUMERIC_VALUE != 0) { AlphanumericComparator().compare(name.normalizeString().lowercase(), other.name.normalizeString().lowercase()) } else { name.normalizeString().lowercase().compareTo(other.name.normalizeString().lowercase()) } } sorting and SORT_BY_SIZE != 0 -> result = when { size == other.size -> 0 size > other.size -> 1 else -> -1 } sorting and SORT_BY_DATE_MODIFIED != 0 -> { result = when { modified == other.modified -> 0 modified > other.modified -> 1 else -> -1 } } else -> { result = getExtension().lowercase().compareTo(other.getExtension().lowercase()) } } if (sorting and SORT_DESCENDING != 0) { result *= -1 } result } } fun getExtension() = if (isDirectory) name else path.substringAfterLast('.', "") fun getBubbleText(context: Context, dateFormat: String? = null, timeFormat: String? = null) = when { sorting and SORT_BY_SIZE != 0 -> size.formatSize() sorting and SORT_BY_DATE_MODIFIED != 0 -> modified.formatDate(context, dateFormat, timeFormat) sorting and SORT_BY_EXTENSION != 0 -> getExtension().lowercase() else -> name } fun getProperSize(context: Context, countHidden: Boolean): Long { return when { context.isRestrictedSAFOnlyRoot(path) -> context.getAndroidSAFFileSize(path) context.isPathOnOTG(path) -> context.getDocumentFile(path)?.getItemSize(countHidden) ?: 0 isNougatPlus() && path.startsWith("content://") -> { try { context.contentResolver.openInputStream(Uri.parse(path))?.available()?.toLong() ?: 0L } catch (e: Exception) { context.getSizeFromContentUri(Uri.parse(path)) } } else -> File(path).getProperSize(countHidden) } } fun getProperFileCount(context: Context, countHidden: Boolean): Int { return when { context.isRestrictedSAFOnlyRoot(path) -> context.getAndroidSAFFileCount(path, countHidden) context.isPathOnOTG(path) -> context.getDocumentFile(path)?.getFileCount(countHidden) ?: 0 else -> File(path).getFileCount(countHidden) } } fun getDirectChildrenCount(context: Context, countHiddenItems: Boolean): Int { return when { context.isRestrictedSAFOnlyRoot(path) -> context.getAndroidSAFDirectChildrenCount(path, countHiddenItems) context.isPathOnOTG(path) -> context.getDocumentFile(path)?.listFiles()?.filter { if (countHiddenItems) true else !it.name!!.startsWith(".") }?.size ?: 0 else -> File(path).getDirectChildrenCount(context, countHiddenItems) } } fun getLastModified(context: Context): Long { return when { context.isRestrictedSAFOnlyRoot(path) -> context.getAndroidSAFLastModified(path) context.isPathOnOTG(path) -> context.getFastDocumentFile(path)?.lastModified() ?: 0L isNougatPlus() && path.startsWith("content://") -> context.getMediaStoreLastModified(path) else -> File(path).lastModified() } } fun getParentPath() = path.getParentPath() fun getDuration(context: Context) = context.getDuration(path)?.getFormattedDuration() fun getFileDurationSeconds(context: Context) = context.getDuration(path) fun getArtist(context: Context) = context.getArtist(path) fun getAlbum(context: Context) = context.getAlbum(path) fun getTitle(context: Context) = context.getTitle(path) fun getResolution(context: Context) = context.getResolution(path) fun getVideoResolution(context: Context) = context.getVideoResolution(path) fun getImageResolution(context: Context) = context.getImageResolution(path) fun getPublicUri(context: Context) = context.getDocumentFile(path)?.uri ?: "" fun getSignature(): String { val lastModified = if (modified > 1) { modified } else { File(path).lastModified() } return "$path-$lastModified-$size" } fun getKey() = ObjectKey(getSignature()) fun assembleContentUri(): Uri { val uri = when { path.isImageFast() -> MediaStore.Images.Media.EXTERNAL_CONTENT_URI path.isVideoFast() -> MediaStore.Video.Media.EXTERNAL_CONTENT_URI else -> MediaStore.Files.getContentUri("external") } return Uri.withAppendedPath(uri, mediaStoreId.toString()) } } fun FileDirItem.asReadOnly() = FileDirItemReadOnly( path = path, name = name, isDirectory = isDirectory, children = children, size = size, modified = modified, mediaStoreId = mediaStoreId ) fun FileDirItemReadOnly.asFileDirItem() = FileDirItem( path = path, name = name, isDirectory = isDirectory, children = children, size = size, modified = modified, mediaStoreId = mediaStoreId ) @Immutable class FileDirItemReadOnly( path: String, name: String = "", isDirectory: Boolean = false, children: Int = 0, size: Long = 0L, modified: Long = 0L, mediaStoreId: Long = 0L ) : FileDirItem(path, name, isDirectory, children, size, modified, mediaStoreId)
CT/commons/src/main/kotlin/com/simplemobiletools/commons/models/FAQItem.kt
3586274804
package com.simplemobiletools.commons.models import androidx.compose.runtime.Immutable import java.io.Serializable @Immutable data class FAQItem(val title: Any, val text: Any) : Serializable { companion object { private const val serialVersionUID = -6553345863512345L } }
CT/commons/src/main/kotlin/com/simplemobiletools/commons/receivers/SharedThemeReceiver.kt
1087092333
package com.simplemobiletools.commons.receivers import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import com.simplemobiletools.commons.extensions.baseConfig import com.simplemobiletools.commons.extensions.checkAppIconColor import com.simplemobiletools.commons.extensions.getSharedTheme import com.simplemobiletools.commons.helpers.MyContentProvider class SharedThemeReceiver : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { context.baseConfig.apply { val oldColor = appIconColor if (intent.action == MyContentProvider.SHARED_THEME_ACTIVATED) { if (!wasSharedThemeForced) { wasSharedThemeForced = true isUsingSharedTheme = true wasSharedThemeEverActivated = true context.getSharedTheme { if (it != null) { textColor = it.textColor backgroundColor = it.backgroundColor primaryColor = it.primaryColor accentColor = it.accentColor appIconColor = it.appIconColor checkAppIconColorChanged(oldColor, appIconColor, context) } } } } else if (intent.action == MyContentProvider.SHARED_THEME_UPDATED) { if (isUsingSharedTheme) { context.getSharedTheme { if (it != null) { textColor = it.textColor backgroundColor = it.backgroundColor primaryColor = it.primaryColor accentColor = it.accentColor appIconColor = it.appIconColor checkAppIconColorChanged(oldColor, appIconColor, context) } } } } } } private fun checkAppIconColorChanged(oldColor: Int, newColor: Int, context: Context) { if (oldColor != newColor) { context.checkAppIconColor() } } }
CT/commons/src/main/kotlin/com/simplemobiletools/commons/extensions/ViewPager.kt
3305656841
package com.simplemobiletools.commons.extensions import androidx.viewpager.widget.ViewPager fun ViewPager.onPageChangeListener(pageChangedAction: (newPosition: Int) -> Unit) = addOnPageChangeListener(object : ViewPager.OnPageChangeListener { override fun onPageScrollStateChanged(state: Int) {} override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {} override fun onPageSelected(position: Int) { pageChangedAction(position) } })
CT/commons/src/main/kotlin/com/simplemobiletools/commons/extensions/Context-styling.kt
2333811704
package com.simplemobiletools.commons.extensions import android.annotation.SuppressLint import android.content.ComponentName import android.content.Context import android.content.pm.PackageManager import android.content.res.Configuration import android.graphics.Color import android.view.ViewGroup import androidx.loader.content.CursorLoader import com.simplemobiletools.commons.R import com.simplemobiletools.commons.helpers.* import com.simplemobiletools.commons.models.SharedTheme import com.simplemobiletools.commons.views.* // handle system default theme (Material You) specially as the color is taken from the system, not hardcoded by us fun Context.getProperTextColor() = if (baseConfig.isUsingSystemTheme) { resources.getColor(R.color.you_neutral_text_color, theme) } else { baseConfig.textColor } fun Context.getProperBackgroundColor() = if (baseConfig.isUsingSystemTheme) { resources.getColor(R.color.you_background_color, theme) } else { baseConfig.backgroundColor } fun Context.getProperPrimaryColor() = when { baseConfig.isUsingSystemTheme -> resources.getColor(R.color.you_primary_color, theme) isWhiteTheme() || isBlackAndWhiteTheme() -> baseConfig.accentColor else -> baseConfig.primaryColor } fun Context.getProperStatusBarColor() = when { baseConfig.isUsingSystemTheme -> resources.getColor(R.color.you_status_bar_color, theme) else -> getProperBackgroundColor() } // get the color of the statusbar with material activity, if the layout is scrolled down a bit fun Context.getColoredMaterialStatusBarColor(): Int { return if (baseConfig.isUsingSystemTheme) { resources.getColor(R.color.you_status_bar_color, theme) } else { getProperPrimaryColor() } } fun Context.updateTextColors(viewGroup: ViewGroup) { val textColor = when { baseConfig.isUsingSystemTheme -> getProperTextColor() else -> baseConfig.textColor } val backgroundColor = baseConfig.backgroundColor val accentColor = when { isWhiteTheme() || isBlackAndWhiteTheme() -> baseConfig.accentColor else -> getProperPrimaryColor() } val cnt = viewGroup.childCount (0 until cnt).map { viewGroup.getChildAt(it) }.forEach { when (it) { is MyTextView -> it.setColors(textColor, accentColor, backgroundColor) is MyAppCompatSpinner -> it.setColors(textColor, accentColor, backgroundColor) is MyCompatRadioButton -> it.setColors(textColor, accentColor, backgroundColor) is MyAppCompatCheckbox -> it.setColors(textColor, accentColor, backgroundColor) is MyEditText -> it.setColors(textColor, accentColor, backgroundColor) is MyAutoCompleteTextView -> it.setColors(textColor, accentColor, backgroundColor) is MyFloatingActionButton -> it.setColors(textColor, accentColor, backgroundColor) is MySeekBar -> it.setColors(textColor, accentColor, backgroundColor) is MyButton -> it.setColors(textColor, accentColor, backgroundColor) is MyTextInputLayout -> it.setColors(textColor, accentColor, backgroundColor) is ViewGroup -> updateTextColors(it) } } } fun Context.isBlackAndWhiteTheme() = baseConfig.textColor == Color.WHITE && baseConfig.primaryColor == Color.BLACK && baseConfig.backgroundColor == Color.BLACK fun Context.isWhiteTheme() = baseConfig.textColor == DARK_GREY && baseConfig.primaryColor == Color.WHITE && baseConfig.backgroundColor == Color.WHITE fun Context.isUsingSystemDarkTheme() = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_YES != 0 fun Context.getTimePickerDialogTheme() = when { baseConfig.isUsingSystemTheme -> if (isUsingSystemDarkTheme()) { R.style.MyTimePickerMaterialTheme_Dark } else { R.style.MyDateTimePickerMaterialTheme } baseConfig.backgroundColor.getContrastColor() == Color.WHITE -> R.style.MyDialogTheme_Dark else -> R.style.MyDialogTheme } fun Context.getDatePickerDialogTheme() = when { baseConfig.isUsingSystemTheme -> R.style.MyDateTimePickerMaterialTheme baseConfig.backgroundColor.getContrastColor() == Color.WHITE -> R.style.MyDialogTheme_Dark else -> R.style.MyDialogTheme } fun Context.getPopupMenuTheme(): Int { return if (isSPlus() && baseConfig.isUsingSystemTheme) { R.style.AppTheme_YouPopupMenuStyle } else if (isWhiteTheme()) { R.style.AppTheme_PopupMenuLightStyle } else { R.style.AppTheme_PopupMenuDarkStyle } } fun Context.getSharedTheme(callback: (sharedTheme: SharedTheme?) -> Unit) { if (!isThankYouInstalled()) { callback(null) } else { val cursorLoader = getMyContentProviderCursorLoader() ensureBackgroundThread { callback(getSharedThemeSync(cursorLoader)) } } } fun Context.getSharedThemeSync(cursorLoader: CursorLoader): SharedTheme? { val cursor = cursorLoader.loadInBackground() cursor?.use { if (cursor.moveToFirst()) { try { val textColor = cursor.getIntValue(MyContentProvider.COL_TEXT_COLOR) val backgroundColor = cursor.getIntValue(MyContentProvider.COL_BACKGROUND_COLOR) val primaryColor = cursor.getIntValue(MyContentProvider.COL_PRIMARY_COLOR) val accentColor = cursor.getIntValue(MyContentProvider.COL_ACCENT_COLOR) val appIconColor = cursor.getIntValue(MyContentProvider.COL_APP_ICON_COLOR) val lastUpdatedTS = cursor.getIntValue(MyContentProvider.COL_LAST_UPDATED_TS) return SharedTheme(textColor, backgroundColor, primaryColor, appIconColor, lastUpdatedTS, accentColor) } catch (e: Exception) { } } } return null } fun Context.checkAppIconColor() { val appId = baseConfig.appId if (appId.isNotEmpty() && baseConfig.lastIconColor != baseConfig.appIconColor) { getAppIconColors().forEachIndexed { index, color -> toggleAppIconColor(appId, index, color, false) } getAppIconColors().forEachIndexed { index, color -> if (baseConfig.appIconColor == color) { toggleAppIconColor(appId, index, color, true) } } } } fun Context.toggleAppIconColor(appId: String, colorIndex: Int, color: Int, enable: Boolean) { val className = "${appId.removeSuffix(".debug")}.activities.SplashActivity${appIconColorStrings[colorIndex]}" val state = if (enable) PackageManager.COMPONENT_ENABLED_STATE_ENABLED else PackageManager.COMPONENT_ENABLED_STATE_DISABLED try { packageManager.setComponentEnabledSetting(ComponentName(appId, className), state, PackageManager.DONT_KILL_APP) if (enable) { baseConfig.lastIconColor = color } } catch (e: Exception) { } } fun Context.getAppIconColors() = resources.getIntArray(R.array.md_app_icon_colors).toCollection(ArrayList()) @SuppressLint("NewApi") fun Context.getBottomNavigationBackgroundColor(): Int { val baseColor = baseConfig.backgroundColor val bottomColor = when { baseConfig.isUsingSystemTheme -> resources.getColor(R.color.you_status_bar_color, theme) baseColor == Color.WHITE -> resources.getColor(R.color.bottom_tabs_light_background) else -> baseConfig.backgroundColor.lightenColor(4) } return bottomColor }
CT/commons/src/main/kotlin/com/simplemobiletools/commons/extensions/Context-contacts.kt
3735766862
package com.simplemobiletools.commons.extensions import android.annotation.TargetApi import android.content.Context import android.content.Intent import android.database.Cursor import android.net.Uri import android.os.Build import android.os.Handler import android.os.Looper import android.provider.ContactsContract import android.telephony.PhoneNumberUtils import com.simplemobiletools.commons.R import com.simplemobiletools.commons.activities.BaseSimpleActivity import com.simplemobiletools.commons.databases.ContactsDatabase import com.simplemobiletools.commons.dialogs.CallConfirmationDialog import com.simplemobiletools.commons.dialogs.RadioGroupDialog import com.simplemobiletools.commons.helpers.* import com.simplemobiletools.commons.interfaces.ContactsDao import com.simplemobiletools.commons.interfaces.GroupsDao import com.simplemobiletools.commons.models.RadioItem import com.simplemobiletools.commons.models.contacts.Contact import com.simplemobiletools.commons.models.contacts.ContactSource import com.simplemobiletools.commons.models.contacts.Organization import com.simplemobiletools.commons.models.contacts.SocialAction import java.io.File val Context.contactsDB: ContactsDao get() = ContactsDatabase.getInstance(applicationContext).ContactsDao() val Context.groupsDB: GroupsDao get() = ContactsDatabase.getInstance(applicationContext).GroupsDao() fun Context.getEmptyContact(): Contact { val originalContactSource = if (hasContactPermissions()) baseConfig.lastUsedContactSource else SMT_PRIVATE val organization = Organization("", "") return Contact( 0, "", "", "", "", "", "", "", ArrayList(), ArrayList(), ArrayList(), ArrayList(), originalContactSource, 0, 0, "", null, "", ArrayList(), organization, ArrayList(), ArrayList(), DEFAULT_MIMETYPE, null ) } fun Context.sendAddressIntent(address: String) { val location = Uri.encode(address) val uri = Uri.parse("geo:0,0?q=$location") Intent(Intent.ACTION_VIEW, uri).apply { launchActivityIntent(this) } } fun Context.openWebsiteIntent(url: String) { val website = if (url.startsWith("http")) { url } else { "https://$url" } Intent(Intent.ACTION_VIEW).apply { data = Uri.parse(website) launchActivityIntent(this) } } fun Context.getLookupUriRawId(dataUri: Uri): Int { val lookupKey = getLookupKeyFromUri(dataUri) if (lookupKey != null) { val uri = lookupContactUri(lookupKey, this) if (uri != null) { return getContactUriRawId(uri) } } return -1 } fun Context.getContactUriRawId(uri: Uri): Int { val projection = arrayOf(ContactsContract.Contacts.NAME_RAW_CONTACT_ID) var cursor: Cursor? = null try { cursor = contentResolver.query(uri, projection, null, null, null) if (cursor!!.moveToFirst()) { return cursor.getIntValue(ContactsContract.Contacts.NAME_RAW_CONTACT_ID) } } catch (ignored: Exception) { } finally { cursor?.close() } return -1 } // from https://android.googlesource.com/platform/packages/apps/Dialer/+/68038172793ee0e2ab3e2e56ddfbeb82879d1f58/java/com/android/contacts/common/util/UriUtils.java fun getLookupKeyFromUri(lookupUri: Uri): String? { return if (!isEncodedContactUri(lookupUri)) { val segments = lookupUri.pathSegments if (segments.size < 3) null else Uri.encode(segments[2]) } else { null } } fun isEncodedContactUri(uri: Uri?): Boolean { if (uri == null) { return false } val lastPathSegment = uri.lastPathSegment ?: return false return lastPathSegment == "encoded" } fun lookupContactUri(lookup: String, context: Context): Uri? { val lookupUri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, lookup) return try { ContactsContract.Contacts.lookupContact(context.contentResolver, lookupUri) } catch (e: Exception) { null } } fun Context.getCachePhoto(): File { val imagesFolder = File(cacheDir, "my_cache") if (!imagesFolder.exists()) { imagesFolder.mkdirs() } val file = File(imagesFolder, "Photo_${System.currentTimeMillis()}.jpg") file.createNewFile() return file } fun Context.getPhotoThumbnailSize(): Int { val uri = ContactsContract.DisplayPhoto.CONTENT_MAX_DIMENSIONS_URI val projection = arrayOf(ContactsContract.DisplayPhoto.THUMBNAIL_MAX_DIM) var cursor: Cursor? = null try { cursor = contentResolver.query(uri, projection, null, null, null) if (cursor?.moveToFirst() == true) { return cursor.getIntValue(ContactsContract.DisplayPhoto.THUMBNAIL_MAX_DIM) } } catch (ignored: Exception) { } finally { cursor?.close() } return 0 } fun Context.hasContactPermissions() = hasPermission(PERMISSION_READ_CONTACTS) && hasPermission(PERMISSION_WRITE_CONTACTS) fun Context.getPublicContactSource(source: String, callback: (String) -> Unit) { when (source) { SMT_PRIVATE -> callback(getString(R.string.phone_storage_hidden)) else -> { ContactsHelper(this).getContactSources { var newSource = source for (contactSource in it) { if (contactSource.name == source && contactSource.type == TELEGRAM_PACKAGE) { newSource = getString(R.string.telegram) break } else if (contactSource.name == source && contactSource.type == VIBER_PACKAGE) { newSource = getString(R.string.viber) break } } Handler(Looper.getMainLooper()).post { callback(newSource) } } } } } fun Context.getPublicContactSourceSync(source: String, contactSources: ArrayList<ContactSource>): String { return when (source) { SMT_PRIVATE -> getString(R.string.phone_storage_hidden) else -> { var newSource = source for (contactSource in contactSources) { if (contactSource.name == source && contactSource.type == TELEGRAM_PACKAGE) { newSource = getString(R.string.telegram) break } else if (contactSource.name == source && contactSource.type == VIBER_PACKAGE) { newSource = getString(R.string.viber) break } } return newSource } } } fun Context.sendSMSToContacts(contacts: ArrayList<Contact>) { val numbers = StringBuilder() contacts.forEach { val number = it.phoneNumbers.firstOrNull { it.type == ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE } ?: it.phoneNumbers.firstOrNull() if (number != null) { numbers.append("${Uri.encode(number.value)};") } } val uriString = "smsto:${numbers.toString().trimEnd(';')}" Intent(Intent.ACTION_SENDTO, Uri.parse(uriString)).apply { launchActivityIntent(this) } } fun Context.sendEmailToContacts(contacts: ArrayList<Contact>) { val emails = ArrayList<String>() contacts.forEach { it.emails.forEach { if (it.value.isNotEmpty()) { emails.add(it.value) } } } Intent(Intent.ACTION_SEND_MULTIPLE).apply { type = "message/rfc822" putExtra(Intent.EXTRA_EMAIL, emails.toTypedArray()) launchActivityIntent(this) } } fun Context.getTempFile(filename: String = DEFAULT_FILE_NAME): File? { val folder = File(cacheDir, "contacts") if (!folder.exists()) { if (!folder.mkdir()) { toast(R.string.unknown_error_occurred) return null } } return File(folder, filename) } fun Context.addContactsToGroup(contacts: ArrayList<Contact>, groupId: Long) { val publicContacts = contacts.filter { !it.isPrivate() }.toMutableList() as ArrayList<Contact> val privateContacts = contacts.filter { it.isPrivate() }.toMutableList() as ArrayList<Contact> if (publicContacts.isNotEmpty()) { ContactsHelper(this).addContactsToGroup(publicContacts, groupId) } if (privateContacts.isNotEmpty()) { LocalContactsHelper(this).addContactsToGroup(privateContacts, groupId) } } fun Context.removeContactsFromGroup(contacts: ArrayList<Contact>, groupId: Long) { val publicContacts = contacts.filter { !it.isPrivate() }.toMutableList() as ArrayList<Contact> val privateContacts = contacts.filter { it.isPrivate() }.toMutableList() as ArrayList<Contact> if (publicContacts.isNotEmpty() && hasContactPermissions()) { ContactsHelper(this).removeContactsFromGroup(publicContacts, groupId) } if (privateContacts.isNotEmpty()) { LocalContactsHelper(this).removeContactsFromGroup(privateContacts, groupId) } } fun Context.getContactPublicUri(contact: Contact): Uri { val lookupKey = if (contact.isPrivate()) { "local_${contact.id}" } else { SimpleContactsHelper(this).getContactLookupKey(contact.id.toString()) } return Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, lookupKey) } fun Context.getVisibleContactSources(): ArrayList<String> { val sources = getAllContactSources() val ignoredContactSources = baseConfig.ignoredContactSources return ArrayList(sources).filter { !ignoredContactSources.contains(it.getFullIdentifier()) } .map { it.name }.toMutableList() as ArrayList<String> } fun Context.getAllContactSources(): ArrayList<ContactSource> { val sources = ContactsHelper(this).getDeviceContactSources() sources.add(getPrivateContactSource()) return sources.toMutableList() as ArrayList<ContactSource> } fun Context.getPrivateContactSource() = ContactSource(SMT_PRIVATE, SMT_PRIVATE, getString(R.string.phone_storage_hidden)) fun Context.getSocialActions(id: Int): ArrayList<SocialAction> { val uri = ContactsContract.Data.CONTENT_URI val projection = arrayOf( ContactsContract.Data._ID, ContactsContract.Data.DATA3, ContactsContract.Data.MIMETYPE, ContactsContract.Data.ACCOUNT_TYPE_AND_DATA_SET ) val socialActions = ArrayList<SocialAction>() var curActionId = 0 val selection = "${ContactsContract.Data.RAW_CONTACT_ID} = ?" val selectionArgs = arrayOf(id.toString()) queryCursor(uri, projection, selection, selectionArgs, null, true) { cursor -> val mimetype = cursor.getStringValue(ContactsContract.Data.MIMETYPE) val type = when (mimetype) { // WhatsApp "vnd.android.cursor.item/vnd.com.whatsapp.profile" -> SOCIAL_MESSAGE "vnd.android.cursor.item/vnd.com.whatsapp.voip.call" -> SOCIAL_VOICE_CALL "vnd.android.cursor.item/vnd.com.whatsapp.video.call" -> SOCIAL_VIDEO_CALL // Viber "vnd.android.cursor.item/vnd.com.viber.voip.viber_number_call" -> SOCIAL_VOICE_CALL "vnd.android.cursor.item/vnd.com.viber.voip.viber_out_call_viber" -> SOCIAL_VOICE_CALL "vnd.android.cursor.item/vnd.com.viber.voip.viber_out_call_none_viber" -> SOCIAL_VOICE_CALL "vnd.android.cursor.item/vnd.com.viber.voip.viber_number_message" -> SOCIAL_MESSAGE // Signal "vnd.android.cursor.item/vnd.org.thoughtcrime.securesms.contact" -> SOCIAL_MESSAGE "vnd.android.cursor.item/vnd.org.thoughtcrime.securesms.call" -> SOCIAL_VOICE_CALL // Telegram "vnd.android.cursor.item/vnd.org.telegram.messenger.android.call" -> SOCIAL_VOICE_CALL "vnd.android.cursor.item/vnd.org.telegram.messenger.android.call.video" -> SOCIAL_VIDEO_CALL "vnd.android.cursor.item/vnd.org.telegram.messenger.android.profile" -> SOCIAL_MESSAGE // Threema "vnd.android.cursor.item/vnd.ch.threema.app.profile" -> SOCIAL_MESSAGE "vnd.android.cursor.item/vnd.ch.threema.app.call" -> SOCIAL_VOICE_CALL else -> return@queryCursor } val label = cursor.getStringValue(ContactsContract.Data.DATA3) val realID = cursor.getLongValue(ContactsContract.Data._ID) val packageName = cursor.getStringValue(ContactsContract.Data.ACCOUNT_TYPE_AND_DATA_SET) val socialAction = SocialAction(curActionId++, type, label, mimetype, realID, packageName) socialActions.add(socialAction) } return socialActions } fun BaseSimpleActivity.initiateCall(contact: Contact, onStartCallIntent: (phoneNumber: String) -> Unit) { val numbers = contact.phoneNumbers if (numbers.size == 1) { onStartCallIntent(numbers.first().value) } else if (numbers.size > 1) { val primaryNumber = contact.phoneNumbers.find { it.isPrimary } if (primaryNumber != null) { onStartCallIntent(primaryNumber.value) } else { val items = ArrayList<RadioItem>() numbers.forEachIndexed { index, phoneNumber -> items.add(RadioItem(index, "${phoneNumber.value} (${getPhoneNumberTypeText(phoneNumber.type, phoneNumber.label)})", phoneNumber.value)) } RadioGroupDialog(this, items) { onStartCallIntent(it as String) } } } } fun BaseSimpleActivity.tryInitiateCall(contact: Contact, onStartCallIntent: (phoneNumber: String) -> Unit) { if (baseConfig.showCallConfirmation) { CallConfirmationDialog(this, contact.getNameToDisplay()) { initiateCall(contact, onStartCallIntent) } } else { initiateCall(contact, onStartCallIntent) } } fun Context.isContactBlocked(contact: Contact, callback: (Boolean) -> Unit) { val phoneNumbers = contact.phoneNumbers.map { PhoneNumberUtils.stripSeparators(it.value) } getBlockedNumbersWithContact { blockedNumbersWithContact -> val blockedNumbers = blockedNumbersWithContact.map { it.number } val allNumbersBlocked = phoneNumbers.all { it in blockedNumbers } callback(allNumbersBlocked) } } @TargetApi(Build.VERSION_CODES.N) fun Context.blockContact(contact: Contact): Boolean { var contactBlocked = true ensureBackgroundThread { contact.phoneNumbers.forEach { val numberBlocked = addBlockedNumber(PhoneNumberUtils.stripSeparators(it.value)) contactBlocked = contactBlocked && numberBlocked } } return contactBlocked } @TargetApi(Build.VERSION_CODES.N) fun Context.unblockContact(contact: Contact): Boolean { var contactUnblocked = true ensureBackgroundThread { contact.phoneNumbers.forEach { val numberUnblocked = deleteBlockedNumber(PhoneNumberUtils.stripSeparators(it.value)) contactUnblocked = contactUnblocked && numberUnblocked } } return contactUnblocked }
CT/commons/src/main/kotlin/com/simplemobiletools/commons/extensions/Activity-sdk30.kt
1616867598
package com.simplemobiletools.commons.extensions import android.content.ContentValues import android.provider.MediaStore import com.simplemobiletools.commons.R import com.simplemobiletools.commons.activities.BaseSimpleActivity import com.simplemobiletools.commons.models.FileDirItem import java.io.File import java.io.InputStream import java.io.OutputStream fun BaseSimpleActivity.copySingleFileSdk30(source: FileDirItem, destination: FileDirItem): Boolean { val directory = destination.getParentPath() if (!createDirectorySync(directory)) { val error = String.format(getString(R.string.could_not_create_folder), directory) showErrorToast(error) return false } var inputStream: InputStream? = null var out: OutputStream? = null try { out = getFileOutputStreamSync(destination.path, source.path.getMimeType()) inputStream = getFileInputStreamSync(source.path)!! var copiedSize = 0L val buffer = ByteArray(DEFAULT_BUFFER_SIZE) var bytes = inputStream.read(buffer) while (bytes >= 0) { out!!.write(buffer, 0, bytes) copiedSize += bytes bytes = inputStream.read(buffer) } out?.flush() return if (source.size == copiedSize && getDoesFilePathExist(destination.path)) { if (baseConfig.keepLastModified) { copyOldLastModified(source.path, destination.path) val lastModified = File(source.path).lastModified() if (lastModified != 0L) { File(destination.path).setLastModified(lastModified) } } true } else { false } } finally { inputStream?.close() out?.close() } } fun BaseSimpleActivity.copyOldLastModified(sourcePath: String, destinationPath: String) { val projection = arrayOf(MediaStore.Images.Media.DATE_TAKEN, MediaStore.Images.Media.DATE_MODIFIED) val uri = MediaStore.Files.getContentUri("external") val selection = "${MediaStore.MediaColumns.DATA} = ?" var selectionArgs = arrayOf(sourcePath) val cursor = applicationContext.contentResolver.query(uri, projection, selection, selectionArgs, null) cursor?.use { if (cursor.moveToFirst()) { val dateTaken = cursor.getLongValue(MediaStore.Images.Media.DATE_TAKEN) val dateModified = cursor.getIntValue(MediaStore.Images.Media.DATE_MODIFIED) val values = ContentValues().apply { put(MediaStore.Images.Media.DATE_TAKEN, dateTaken) put(MediaStore.Images.Media.DATE_MODIFIED, dateModified) } selectionArgs = arrayOf(destinationPath) applicationContext.contentResolver.update(uri, values, selection, selectionArgs) } } }
CT/commons/src/main/kotlin/com/simplemobiletools/commons/extensions/Resources.kt
1426882333
package com.simplemobiletools.commons.extensions import android.content.res.Resources import android.graphics.Bitmap import android.graphics.Canvas import android.graphics.PorterDuff import android.graphics.PorterDuffColorFilter import android.graphics.drawable.Drawable fun Resources.getColoredBitmap(resourceId: Int, newColor: Int): Bitmap { val drawable = getDrawable(resourceId) val bitmap = Bitmap.createBitmap(drawable.intrinsicWidth, drawable.intrinsicHeight, Bitmap.Config.ARGB_8888) val canvas = Canvas(bitmap) drawable.setBounds(0, 0, canvas.width, canvas.height) drawable.colorFilter = PorterDuffColorFilter(newColor, PorterDuff.Mode.SRC_IN) drawable.draw(canvas) return bitmap } fun Resources.getColoredDrawable(drawableId: Int, colorId: Int, alpha: Int = 255) = getColoredDrawableWithColor(drawableId, getColor(colorId), alpha) fun Resources.getColoredDrawableWithColor(drawableId: Int, color: Int, alpha: Int = 255): Drawable { val drawable = getDrawable(drawableId) drawable.mutate().applyColorFilter(color) drawable.mutate().alpha = alpha return drawable } fun Resources.hasNavBar(): Boolean { val id = getIdentifier("config_showNavigationBar", "bool", "android") return id > 0 && getBoolean(id) } fun Resources.getNavBarHeight(): Int { val id = getIdentifier("navigation_bar_height", "dimen", "android") return if (id > 0 && hasNavBar()) { getDimensionPixelSize(id) } else 0 }
CT/commons/src/main/kotlin/com/simplemobiletools/commons/extensions/App.kt
3552360586
package com.simplemobiletools.commons.extensions import android.app.Application import com.simplemobiletools.commons.helpers.isNougatPlus import java.util.* fun Application.checkUseEnglish() { if (baseConfig.useEnglish && !isNougatPlus()) { val conf = resources.configuration conf.locale = Locale.ENGLISH resources.updateConfiguration(conf, resources.displayMetrics) } }
CT/commons/src/main/kotlin/com/simplemobiletools/commons/extensions/Point.kt
3382841635
package com.simplemobiletools.commons.extensions import android.graphics.Point fun Point.formatAsResolution() = "$x x $y ${getMPx()}" fun Point.getMPx(): String { val px = x * y / 1000000f val rounded = Math.round(px * 10) / 10f return "(${rounded}MP)" }
CT/commons/src/main/kotlin/com/simplemobiletools/commons/extensions/BufferedWriter.kt
468660471
package com.simplemobiletools.commons.extensions import java.io.BufferedWriter fun BufferedWriter.writeLn(line: String) { write(line) newLine() }
CT/commons/src/main/kotlin/com/simplemobiletools/commons/extensions/AlertDialog.kt
22609286
package com.simplemobiletools.commons.extensions import android.view.WindowManager import androidx.appcompat.app.AlertDialog import androidx.appcompat.widget.AppCompatEditText // in dialogs, lets use findViewById, because while some dialogs use MyEditText, material theme dialogs use TextInputEditText so the system takes care of it fun AlertDialog.showKeyboard(editText: AppCompatEditText) { window!!.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE) editText.apply { requestFocus() onGlobalLayout { setSelection(text.toString().length) } } } fun AlertDialog.hideKeyboard() { window!!.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN) }
CT/commons/src/main/kotlin/com/simplemobiletools/commons/extensions/Context.kt
3920653500
package com.simplemobiletools.commons.extensions import android.Manifest import android.annotation.TargetApi import android.app.Activity import android.app.NotificationManager import android.app.role.RoleManager import android.content.* import android.content.pm.PackageManager import android.content.pm.ShortcutManager import android.content.res.Configuration import android.database.Cursor import android.graphics.BitmapFactory import android.graphics.Point import android.media.MediaMetadataRetriever import android.media.RingtoneManager import android.net.Uri import android.os.* import android.provider.BaseColumns import android.provider.BlockedNumberContract.BlockedNumbers import android.provider.ContactsContract.CommonDataKinds.BaseTypes import android.provider.ContactsContract.CommonDataKinds.Phone import android.provider.DocumentsContract import android.provider.MediaStore.* import android.provider.OpenableColumns import android.provider.Settings import android.telecom.TelecomManager import android.telephony.PhoneNumberUtils import android.view.View import android.view.WindowManager import android.widget.ImageView import android.widget.TextView import android.widget.Toast import androidx.annotation.RequiresApi import androidx.biometric.BiometricManager import androidx.core.content.ContextCompat import androidx.core.content.FileProvider import androidx.core.content.res.ResourcesCompat import androidx.core.os.bundleOf import androidx.exifinterface.media.ExifInterface import androidx.loader.content.CursorLoader import com.github.ajalt.reprint.core.Reprint import com.google.gson.Gson import com.google.gson.reflect.TypeToken import com.simplemobiletools.commons.R import com.simplemobiletools.commons.helpers.* import com.simplemobiletools.commons.models.AlarmSound import com.simplemobiletools.commons.models.BlockedNumber import java.io.File import java.text.SimpleDateFormat import java.util.* fun Context.getSharedPrefs() = getSharedPreferences(PREFS_KEY, Context.MODE_PRIVATE) val Context.isRTLLayout: Boolean get() = resources.configuration.layoutDirection == View.LAYOUT_DIRECTION_RTL val Context.areSystemAnimationsEnabled: Boolean get() = Settings.Global.getFloat(contentResolver, Settings.Global.ANIMATOR_DURATION_SCALE, 0f) > 0f fun Context.toast(id: Int, length: Int = Toast.LENGTH_SHORT) { toast(getString(id), length) } fun Context.toast(msg: String, length: Int = Toast.LENGTH_SHORT) { try { if (isOnMainThread()) { doToast(this, msg, length) } else { Handler(Looper.getMainLooper()).post { doToast(this, msg, length) } } } catch (e: Exception) { } } private fun doToast(context: Context, message: String, length: Int) { if (context is Activity) { if (!context.isFinishing && !context.isDestroyed) { Toast.makeText(context, message, length).show() } } else { Toast.makeText(context, message, length).show() } } fun Context.showErrorToast(msg: String, length: Int = Toast.LENGTH_LONG) { toast(String.format(getString(R.string.error), msg), length) } fun Context.showErrorToast(exception: Exception, length: Int = Toast.LENGTH_LONG) { showErrorToast(exception.toString(), length) } val Context.baseConfig: BaseConfig get() = BaseConfig.newInstance(this) val Context.sdCardPath: String get() = baseConfig.sdCardPath val Context.internalStoragePath: String get() = baseConfig.internalStoragePath val Context.otgPath: String get() = baseConfig.OTGPath fun Context.isFingerPrintSensorAvailable() = Reprint.isHardwarePresent() fun Context.isBiometricIdAvailable(): Boolean = when (BiometricManager.from(this).canAuthenticate(BiometricManager.Authenticators.BIOMETRIC_WEAK)) { BiometricManager.BIOMETRIC_SUCCESS, BiometricManager.BIOMETRIC_STATUS_UNKNOWN -> true else -> false } fun Context.getLatestMediaId(uri: Uri = Files.getContentUri("external")): Long { val projection = arrayOf( BaseColumns._ID ) try { val cursor = queryCursorDesc(uri, projection, BaseColumns._ID, 1) cursor?.use { if (cursor.moveToFirst()) { return cursor.getLongValue(BaseColumns._ID) } } } catch (ignored: Exception) { } return 0 } private fun Context.queryCursorDesc( uri: Uri, projection: Array<String>, sortColumn: String, limit: Int, ): Cursor? { return if (isRPlus()) { val queryArgs = bundleOf( ContentResolver.QUERY_ARG_LIMIT to limit, ContentResolver.QUERY_ARG_SORT_DIRECTION to ContentResolver.QUERY_SORT_DIRECTION_DESCENDING, ContentResolver.QUERY_ARG_SORT_COLUMNS to arrayOf(sortColumn), ) contentResolver.query(uri, projection, queryArgs, null) } else { val sortOrder = "$sortColumn DESC LIMIT $limit" contentResolver.query(uri, projection, null, null, sortOrder) } } fun Context.getLatestMediaByDateId(uri: Uri = Files.getContentUri("external")): Long { val projection = arrayOf( BaseColumns._ID ) try { val cursor = queryCursorDesc(uri, projection, Images.ImageColumns.DATE_TAKEN, 1) cursor?.use { if (cursor.moveToFirst()) { return cursor.getLongValue(BaseColumns._ID) } } } catch (ignored: Exception) { } return 0 } // some helper functions were taken from https://github.com/iPaulPro/aFileChooser/blob/master/aFileChooser/src/com/ipaulpro/afilechooser/utils/FileUtils.java fun Context.getRealPathFromURI(uri: Uri): String? { if (uri.scheme == "file") { return uri.path } if (isDownloadsDocument(uri)) { val id = DocumentsContract.getDocumentId(uri) if (id.areDigitsOnly()) { val newUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), id.toLong()) val path = getDataColumn(newUri) if (path != null) { return path } } } else if (isExternalStorageDocument(uri)) { val documentId = DocumentsContract.getDocumentId(uri) val parts = documentId.split(":") if (parts[0].equals("primary", true)) { return "${Environment.getExternalStorageDirectory().absolutePath}/${parts[1]}" } } else if (isMediaDocument(uri)) { val documentId = DocumentsContract.getDocumentId(uri) val split = documentId.split(":").dropLastWhile { it.isEmpty() }.toTypedArray() val type = split[0] val contentUri = when (type) { "video" -> Video.Media.EXTERNAL_CONTENT_URI "audio" -> Audio.Media.EXTERNAL_CONTENT_URI else -> Images.Media.EXTERNAL_CONTENT_URI } val selection = "_id=?" val selectionArgs = arrayOf(split[1]) val path = getDataColumn(contentUri, selection, selectionArgs) if (path != null) { return path } } return getDataColumn(uri) } fun Context.getDataColumn(uri: Uri, selection: String? = null, selectionArgs: Array<String>? = null): String? { try { val projection = arrayOf(Files.FileColumns.DATA) val cursor = contentResolver.query(uri, projection, selection, selectionArgs, null) cursor?.use { if (cursor.moveToFirst()) { val data = cursor.getStringValue(Files.FileColumns.DATA) if (data != "null") { return data } } } } catch (e: Exception) { } return null } private fun isMediaDocument(uri: Uri) = uri.authority == "com.android.providers.media.documents" private fun isDownloadsDocument(uri: Uri) = uri.authority == "com.android.providers.downloads.documents" private fun isExternalStorageDocument(uri: Uri) = uri.authority == "com.android.externalstorage.documents" fun Context.hasPermission(permId: Int) = ContextCompat.checkSelfPermission(this, getPermissionString(permId)) == PackageManager.PERMISSION_GRANTED fun Context.hasAllPermissions(permIds: Collection<Int>) = permIds.all(this::hasPermission) fun Context.getPermissionString(id: Int) = when (id) { PERMISSION_READ_STORAGE -> Manifest.permission.READ_EXTERNAL_STORAGE PERMISSION_WRITE_STORAGE -> Manifest.permission.WRITE_EXTERNAL_STORAGE PERMISSION_CAMERA -> Manifest.permission.CAMERA PERMISSION_RECORD_AUDIO -> Manifest.permission.RECORD_AUDIO PERMISSION_READ_CONTACTS -> Manifest.permission.READ_CONTACTS PERMISSION_WRITE_CONTACTS -> Manifest.permission.WRITE_CONTACTS PERMISSION_READ_CALENDAR -> Manifest.permission.READ_CALENDAR PERMISSION_WRITE_CALENDAR -> Manifest.permission.WRITE_CALENDAR PERMISSION_CALL_PHONE -> Manifest.permission.CALL_PHONE PERMISSION_READ_CALL_LOG -> Manifest.permission.READ_CALL_LOG PERMISSION_WRITE_CALL_LOG -> Manifest.permission.WRITE_CALL_LOG PERMISSION_GET_ACCOUNTS -> Manifest.permission.GET_ACCOUNTS PERMISSION_READ_SMS -> Manifest.permission.READ_SMS PERMISSION_SEND_SMS -> Manifest.permission.SEND_SMS PERMISSION_READ_PHONE_STATE -> Manifest.permission.READ_PHONE_STATE PERMISSION_MEDIA_LOCATION -> if (isQPlus()) Manifest.permission.ACCESS_MEDIA_LOCATION else "" PERMISSION_POST_NOTIFICATIONS -> Manifest.permission.POST_NOTIFICATIONS PERMISSION_READ_MEDIA_IMAGES -> Manifest.permission.READ_MEDIA_IMAGES PERMISSION_READ_MEDIA_VIDEO -> Manifest.permission.READ_MEDIA_VIDEO PERMISSION_READ_MEDIA_AUDIO -> Manifest.permission.READ_MEDIA_AUDIO PERMISSION_ACCESS_COARSE_LOCATION -> Manifest.permission.ACCESS_COARSE_LOCATION PERMISSION_ACCESS_FINE_LOCATION -> Manifest.permission.ACCESS_FINE_LOCATION PERMISSION_READ_MEDIA_VISUAL_USER_SELECTED -> Manifest.permission.READ_MEDIA_VISUAL_USER_SELECTED PERMISSION_READ_SYNC_SETTINGS -> Manifest.permission.READ_SYNC_SETTINGS else -> "" } fun Context.launchActivityIntent(intent: Intent) { try { startActivity(intent) } catch (e: ActivityNotFoundException) { toast(R.string.no_app_found) } catch (e: Exception) { showErrorToast(e) } } fun Context.getFilePublicUri(file: File, applicationId: String): Uri { // for images/videos/gifs try getting a media content uri first, like content://media/external/images/media/438 // if media content uri is null, get our custom uri like content://com.simplemobiletools.gallery.provider/external_files/emulated/0/DCIM/IMG_20171104_233915.jpg var uri = if (file.isMediaFile()) { getMediaContentUri(file.absolutePath) } else { getMediaContent(file.absolutePath, Files.getContentUri("external")) } if (uri == null) { uri = FileProvider.getUriForFile(this, "$applicationId.provider", file) } return uri!! } fun Context.getMediaContentUri(path: String): Uri? { val uri = when { path.isImageFast() -> Images.Media.EXTERNAL_CONTENT_URI path.isVideoFast() -> Video.Media.EXTERNAL_CONTENT_URI else -> Files.getContentUri("external") } return getMediaContent(path, uri) } fun Context.getMediaContent(path: String, uri: Uri): Uri? { val projection = arrayOf(Images.Media._ID) val selection = Images.Media.DATA + "= ?" val selectionArgs = arrayOf(path) try { val cursor = contentResolver.query(uri, projection, selection, selectionArgs, null) cursor?.use { if (cursor.moveToFirst()) { val id = cursor.getIntValue(Images.Media._ID).toString() return Uri.withAppendedPath(uri, id) } } } catch (e: Exception) { } return null } fun Context.queryCursor( uri: Uri, projection: Array<String>, selection: String? = null, selectionArgs: Array<String>? = null, sortOrder: String? = null, showErrors: Boolean = false, callback: (cursor: Cursor) -> Unit ) { try { val cursor = contentResolver.query(uri, projection, selection, selectionArgs, sortOrder) cursor?.use { if (cursor.moveToFirst()) { do { callback(cursor) } while (cursor.moveToNext()) } } } catch (e: Exception) { if (showErrors) { showErrorToast(e) } } } @RequiresApi(Build.VERSION_CODES.O) fun Context.queryCursor( uri: Uri, projection: Array<String>, queryArgs: Bundle, showErrors: Boolean = false, callback: (cursor: Cursor) -> Unit ) { try { val cursor = contentResolver.query(uri, projection, queryArgs, null) cursor?.use { if (cursor.moveToFirst()) { do { callback(cursor) } while (cursor.moveToNext()) } } } catch (e: Exception) { if (showErrors) { showErrorToast(e) } } } fun Context.getFilenameFromUri(uri: Uri): String { return if (uri.scheme == "file") { File(uri.toString()).name } else { getFilenameFromContentUri(uri) ?: uri.lastPathSegment ?: "" } } fun Context.getMimeTypeFromUri(uri: Uri): String { var mimetype = uri.path?.getMimeType() ?: "" if (mimetype.isEmpty()) { try { mimetype = contentResolver.getType(uri) ?: "" } catch (e: IllegalStateException) { } } return mimetype } fun Context.ensurePublicUri(path: String, applicationId: String): Uri? { return when { hasProperStoredAndroidTreeUri(path) && isRestrictedSAFOnlyRoot(path) -> { getAndroidSAFUri(path) } hasProperStoredDocumentUriSdk30(path) && isAccessibleWithSAFSdk30(path) -> { createDocumentUriUsingFirstParentTreeUri(path) } isPathOnOTG(path) -> { getDocumentFile(path)?.uri } else -> { val uri = Uri.parse(path) if (uri.scheme == "content") { uri } else { val newPath = if (uri.toString().startsWith("/")) uri.toString() else uri.path val file = File(newPath) getFilePublicUri(file, applicationId) } } } } fun Context.ensurePublicUri(uri: Uri, applicationId: String): Uri { return if (uri.scheme == "content") { uri } else { val file = File(uri.path) getFilePublicUri(file, applicationId) } } fun Context.getFilenameFromContentUri(uri: Uri): String? { val projection = arrayOf( OpenableColumns.DISPLAY_NAME ) try { val cursor = contentResolver.query(uri, projection, null, null, null) cursor?.use { if (cursor.moveToFirst()) { return cursor.getStringValue(OpenableColumns.DISPLAY_NAME) } } } catch (e: Exception) { } return null } fun Context.getSizeFromContentUri(uri: Uri): Long { val projection = arrayOf(OpenableColumns.SIZE) try { val cursor = contentResolver.query(uri, projection, null, null, null) cursor?.use { if (cursor.moveToFirst()) { return cursor.getLongValue(OpenableColumns.SIZE) } } } catch (e: Exception) { } return 0L } fun Context.getMyContentProviderCursorLoader() = CursorLoader(this, MyContentProvider.MY_CONTENT_URI, null, null, null, null) fun Context.getMyContactsCursor(favoritesOnly: Boolean, withPhoneNumbersOnly: Boolean) = try { val getFavoritesOnly = if (favoritesOnly) "1" else "0" val getWithPhoneNumbersOnly = if (withPhoneNumbersOnly) "1" else "0" val args = arrayOf(getFavoritesOnly, getWithPhoneNumbersOnly) CursorLoader(this, MyContactsContentProvider.CONTACTS_CONTENT_URI, null, null, args, null).loadInBackground() } catch (e: Exception) { null } fun Context.getCurrentFormattedDateTime(): String { val simpleDateFormat = SimpleDateFormat("yyyy_MM_dd_HH_mm_ss", Locale.getDefault()) return simpleDateFormat.format(Date(System.currentTimeMillis())) } fun Context.updateSDCardPath() { ensureBackgroundThread { val oldPath = baseConfig.sdCardPath baseConfig.sdCardPath = getSDCardPath() if (oldPath != baseConfig.sdCardPath) { baseConfig.sdTreeUri = "" } } } fun Context.getUriMimeType(path: String, newUri: Uri): String { var mimeType = path.getMimeType() if (mimeType.isEmpty()) { mimeType = getMimeTypeFromUri(newUri) } return mimeType } fun Context.isThankYouInstalled() = isPackageInstalled("com.simplemobiletools.thankyou") fun Context.isOrWasThankYouInstalled(): Boolean { return when { resources.getBoolean(R.bool.pretend_thank_you_installed) -> true baseConfig.hadThankYouInstalled -> true isThankYouInstalled() -> { baseConfig.hadThankYouInstalled = true true } else -> false } } fun Context.isAProApp() = packageName.startsWith("com.simplemobiletools.") && packageName.removeSuffix(".debug").endsWith(".pro") fun Context.getCustomizeColorsString(): String { val textId = if (isOrWasThankYouInstalled()) { R.string.customize_colors } else { R.string.customize_colors_locked } return getString(textId) } fun Context.addLockedLabelIfNeeded(stringId: Int): String { return if (isOrWasThankYouInstalled()) { getString(stringId) } else { "${getString(stringId)} (${getString(R.string.feature_locked)})" } } fun Context.isPackageInstalled(pkgName: String): Boolean { return try { packageManager.getPackageInfo(pkgName, 0) true } catch (e: Exception) { false } } // format day bits to strings like "Mon, Tue, Wed" fun Context.getSelectedDaysString(bitMask: Int): String { val dayBits = arrayListOf(MONDAY_BIT, TUESDAY_BIT, WEDNESDAY_BIT, THURSDAY_BIT, FRIDAY_BIT, SATURDAY_BIT, SUNDAY_BIT) val weekDays = resources.getStringArray(R.array.week_days_short).toList() as ArrayList<String> if (baseConfig.isSundayFirst) { dayBits.moveLastItemToFront() weekDays.moveLastItemToFront() } var days = "" dayBits.forEachIndexed { index, bit -> if (bitMask and bit != 0) { days += "${weekDays[index]}, " } } return days.trim().trimEnd(',') } fun Context.formatMinutesToTimeString(totalMinutes: Int) = formatSecondsToTimeString(totalMinutes * 60) fun Context.formatSecondsToTimeString(totalSeconds: Int): String { val days = totalSeconds / DAY_SECONDS val hours = (totalSeconds % DAY_SECONDS) / HOUR_SECONDS val minutes = (totalSeconds % HOUR_SECONDS) / MINUTE_SECONDS val seconds = totalSeconds % MINUTE_SECONDS val timesString = StringBuilder() if (days > 0) { val daysString = String.format(resources.getQuantityString(R.plurals.days, days, days)) timesString.append("$daysString, ") } if (hours > 0) { val hoursString = String.format(resources.getQuantityString(R.plurals.hours, hours, hours)) timesString.append("$hoursString, ") } if (minutes > 0) { val minutesString = String.format(resources.getQuantityString(R.plurals.minutes, minutes, minutes)) timesString.append("$minutesString, ") } if (seconds > 0) { val secondsString = String.format(resources.getQuantityString(R.plurals.seconds, seconds, seconds)) timesString.append(secondsString) } var result = timesString.toString().trim().trimEnd(',') if (result.isEmpty()) { result = String.format(resources.getQuantityString(R.plurals.minutes, 0, 0)) } return result } fun Context.getFormattedMinutes(minutes: Int, showBefore: Boolean = true) = getFormattedSeconds(if (minutes == -1) minutes else minutes * 60, showBefore) fun Context.getFormattedSeconds(seconds: Int, showBefore: Boolean = true) = when (seconds) { -1 -> getString(R.string.no_reminder) 0 -> getString(R.string.at_start) else -> { when { seconds < 0 && seconds > -60 * 60 * 24 -> { val minutes = -seconds / 60 getString(R.string.during_day_at).format(minutes / 60, minutes % 60) } seconds % YEAR_SECONDS == 0 -> { val base = if (showBefore) R.plurals.years_before else R.plurals.by_years resources.getQuantityString(base, seconds / YEAR_SECONDS, seconds / YEAR_SECONDS) } seconds % MONTH_SECONDS == 0 -> { val base = if (showBefore) R.plurals.months_before else R.plurals.by_months resources.getQuantityString(base, seconds / MONTH_SECONDS, seconds / MONTH_SECONDS) } seconds % WEEK_SECONDS == 0 -> { val base = if (showBefore) R.plurals.weeks_before else R.plurals.by_weeks resources.getQuantityString(base, seconds / WEEK_SECONDS, seconds / WEEK_SECONDS) } seconds % DAY_SECONDS == 0 -> { val base = if (showBefore) R.plurals.days_before else R.plurals.by_days resources.getQuantityString(base, seconds / DAY_SECONDS, seconds / DAY_SECONDS) } seconds % HOUR_SECONDS == 0 -> { val base = if (showBefore) R.plurals.hours_before else R.plurals.by_hours resources.getQuantityString(base, seconds / HOUR_SECONDS, seconds / HOUR_SECONDS) } seconds % MINUTE_SECONDS == 0 -> { val base = if (showBefore) R.plurals.minutes_before else R.plurals.by_minutes resources.getQuantityString(base, seconds / MINUTE_SECONDS, seconds / MINUTE_SECONDS) } else -> { val base = if (showBefore) R.plurals.seconds_before else R.plurals.by_seconds resources.getQuantityString(base, seconds, seconds) } } } } fun Context.getDefaultAlarmTitle(type: Int): String { val alarmString = getString(R.string.alarm) return try { RingtoneManager.getRingtone(this, RingtoneManager.getDefaultUri(type))?.getTitle(this) ?: alarmString } catch (e: Exception) { alarmString } } fun Context.getDefaultAlarmSound(type: Int) = AlarmSound(0, getDefaultAlarmTitle(type), RingtoneManager.getDefaultUri(type).toString()) fun Context.grantReadUriPermission(uriString: String) { try { // ensure custom reminder sounds play well grantUriPermission("com.android.systemui", Uri.parse(uriString), Intent.FLAG_GRANT_READ_URI_PERMISSION) } catch (ignored: Exception) { } } fun Context.storeNewYourAlarmSound(resultData: Intent): AlarmSound { val uri = resultData.data var filename = getFilenameFromUri(uri!!) if (filename.isEmpty()) { filename = getString(R.string.alarm) } val token = object : TypeToken<ArrayList<AlarmSound>>() {}.type val yourAlarmSounds = Gson().fromJson<ArrayList<AlarmSound>>(baseConfig.yourAlarmSounds, token) ?: ArrayList() val newAlarmSoundId = (yourAlarmSounds.maxByOrNull { it.id }?.id ?: YOUR_ALARM_SOUNDS_MIN_ID) + 1 val newAlarmSound = AlarmSound(newAlarmSoundId, filename, uri.toString()) if (yourAlarmSounds.firstOrNull { it.uri == uri.toString() } == null) { yourAlarmSounds.add(newAlarmSound) } baseConfig.yourAlarmSounds = Gson().toJson(yourAlarmSounds) val takeFlags = Intent.FLAG_GRANT_READ_URI_PERMISSION contentResolver.takePersistableUriPermission(uri, takeFlags) return newAlarmSound } @RequiresApi(Build.VERSION_CODES.N) fun Context.saveImageRotation(path: String, degrees: Int): Boolean { if (!needsStupidWritePermissions(path)) { saveExifRotation(ExifInterface(path), degrees) return true } else if (isNougatPlus()) { val documentFile = getSomeDocumentFile(path) if (documentFile != null) { val parcelFileDescriptor = contentResolver.openFileDescriptor(documentFile.uri, "rw") val fileDescriptor = parcelFileDescriptor!!.fileDescriptor saveExifRotation(ExifInterface(fileDescriptor), degrees) return true } } return false } fun Context.saveExifRotation(exif: ExifInterface, degrees: Int) { val orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL) val orientationDegrees = (orientation.degreesFromOrientation() + degrees) % 360 exif.setAttribute(ExifInterface.TAG_ORIENTATION, orientationDegrees.orientationFromDegrees()) exif.saveAttributes() } fun Context.getLaunchIntent() = packageManager.getLaunchIntentForPackage(baseConfig.appId) fun Context.getCanAppBeUpgraded() = proPackages.contains(baseConfig.appId.removeSuffix(".debug").removePrefix("com.simplemobiletools.")) fun Context.getProUrl() = "https://play.google.com/store/apps/details?id=${baseConfig.appId.removeSuffix(".debug")}.pro" fun Context.getStoreUrl() = "https://play.google.com/store/apps/details?id=${packageName.removeSuffix(".debug")}" fun Context.getTimeFormat() = if (baseConfig.use24HourFormat) TIME_FORMAT_24 else TIME_FORMAT_12 fun Context.getResolution(path: String): Point? { return if (path.isImageFast() || path.isImageSlow()) { getImageResolution(path) } else if (path.isVideoFast() || path.isVideoSlow()) { getVideoResolution(path) } else { null } } fun Context.getImageResolution(path: String): Point? { val options = BitmapFactory.Options() options.inJustDecodeBounds = true if (isRestrictedSAFOnlyRoot(path)) { BitmapFactory.decodeStream(contentResolver.openInputStream(getAndroidSAFUri(path)), null, options) } else { BitmapFactory.decodeFile(path, options) } val width = options.outWidth val height = options.outHeight return if (width > 0 && height > 0) { Point(options.outWidth, options.outHeight) } else { null } } fun Context.getVideoResolution(path: String): Point? { var point = try { val retriever = MediaMetadataRetriever() if (isRestrictedSAFOnlyRoot(path)) { retriever.setDataSource(this, getAndroidSAFUri(path)) } else { retriever.setDataSource(path) } val width = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH)!!.toInt() val height = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT)!!.toInt() Point(width, height) } catch (ignored: Exception) { null } if (point == null && path.startsWith("content://", true)) { try { val fd = contentResolver.openFileDescriptor(Uri.parse(path), "r")?.fileDescriptor val retriever = MediaMetadataRetriever() retriever.setDataSource(fd) val width = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH)!!.toInt() val height = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT)!!.toInt() point = Point(width, height) } catch (ignored: Exception) { } } return point } fun Context.getDuration(path: String): Int? { val projection = arrayOf( MediaColumns.DURATION ) val uri = getFileUri(path) val selection = if (path.startsWith("content://")) "${BaseColumns._ID} = ?" else "${MediaColumns.DATA} = ?" val selectionArgs = if (path.startsWith("content://")) arrayOf(path.substringAfterLast("/")) else arrayOf(path) try { val cursor = contentResolver.query(uri, projection, selection, selectionArgs, null) cursor?.use { if (cursor.moveToFirst()) { return Math.round(cursor.getIntValue(MediaColumns.DURATION) / 1000.toDouble()).toInt() } } } catch (ignored: Exception) { } return try { val retriever = MediaMetadataRetriever() retriever.setDataSource(path) Math.round(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)!!.toInt() / 1000f) } catch (ignored: Exception) { null } } fun Context.getTitle(path: String): String? { val projection = arrayOf( MediaColumns.TITLE ) val uri = getFileUri(path) val selection = if (path.startsWith("content://")) "${BaseColumns._ID} = ?" else "${MediaColumns.DATA} = ?" val selectionArgs = if (path.startsWith("content://")) arrayOf(path.substringAfterLast("/")) else arrayOf(path) try { val cursor = contentResolver.query(uri, projection, selection, selectionArgs, null) cursor?.use { if (cursor.moveToFirst()) { return cursor.getStringValue(MediaColumns.TITLE) } } } catch (ignored: Exception) { } return try { val retriever = MediaMetadataRetriever() retriever.setDataSource(path) retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE) } catch (ignored: Exception) { null } } fun Context.getArtist(path: String): String? { val projection = arrayOf( Audio.Media.ARTIST ) val uri = getFileUri(path) val selection = if (path.startsWith("content://")) "${BaseColumns._ID} = ?" else "${MediaColumns.DATA} = ?" val selectionArgs = if (path.startsWith("content://")) arrayOf(path.substringAfterLast("/")) else arrayOf(path) try { val cursor = contentResolver.query(uri, projection, selection, selectionArgs, null) cursor?.use { if (cursor.moveToFirst()) { return cursor.getStringValue(Audio.Media.ARTIST) } } } catch (ignored: Exception) { } return try { val retriever = MediaMetadataRetriever() retriever.setDataSource(path) retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST) } catch (ignored: Exception) { null } } fun Context.getAlbum(path: String): String? { val projection = arrayOf( Audio.Media.ALBUM ) val uri = getFileUri(path) val selection = if (path.startsWith("content://")) "${BaseColumns._ID} = ?" else "${MediaColumns.DATA} = ?" val selectionArgs = if (path.startsWith("content://")) arrayOf(path.substringAfterLast("/")) else arrayOf(path) try { val cursor = contentResolver.query(uri, projection, selection, selectionArgs, null) cursor?.use { if (cursor.moveToFirst()) { return cursor.getStringValue(Audio.Media.ALBUM) } } } catch (ignored: Exception) { } return try { val retriever = MediaMetadataRetriever() retriever.setDataSource(path) retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUM) } catch (ignored: Exception) { null } } fun Context.getMediaStoreLastModified(path: String): Long { val projection = arrayOf( MediaColumns.DATE_MODIFIED ) val uri = getFileUri(path) val selection = "${BaseColumns._ID} = ?" val selectionArgs = arrayOf(path.substringAfterLast("/")) try { val cursor = contentResolver.query(uri, projection, selection, selectionArgs, null) cursor?.use { if (cursor.moveToFirst()) { return cursor.getLongValue(MediaColumns.DATE_MODIFIED) * 1000 } } } catch (ignored: Exception) { } return 0 } fun Context.getStringsPackageName() = getString(R.string.package_name) fun Context.getFontSizeText() = getString( when (baseConfig.fontSize) { FONT_SIZE_SMALL -> R.string.small FONT_SIZE_MEDIUM -> R.string.medium FONT_SIZE_LARGE -> R.string.large else -> R.string.extra_large } ) fun Context.getTextSize() = when (baseConfig.fontSize) { FONT_SIZE_SMALL -> resources.getDimension(R.dimen.smaller_text_size) FONT_SIZE_MEDIUM -> resources.getDimension(R.dimen.bigger_text_size) FONT_SIZE_LARGE -> resources.getDimension(R.dimen.big_text_size) else -> resources.getDimension(R.dimen.extra_big_text_size) } val Context.telecomManager: TelecomManager get() = getSystemService(Context.TELECOM_SERVICE) as TelecomManager val Context.windowManager: WindowManager get() = getSystemService(Context.WINDOW_SERVICE) as WindowManager val Context.notificationManager: NotificationManager get() = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager val Context.shortcutManager: ShortcutManager get() = getSystemService(ShortcutManager::class.java) as ShortcutManager val Context.portrait get() = resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT val Context.navigationBarOnSide: Boolean get() = usableScreenSize.x < realScreenSize.x && usableScreenSize.x > usableScreenSize.y val Context.navigationBarOnBottom: Boolean get() = usableScreenSize.y < realScreenSize.y val Context.navigationBarHeight: Int get() = if (navigationBarOnBottom && navigationBarSize.y != usableScreenSize.y) navigationBarSize.y else 0 val Context.navigationBarWidth: Int get() = if (navigationBarOnSide) navigationBarSize.x else 0 val Context.navigationBarSize: Point get() = when { navigationBarOnSide -> Point(newNavigationBarHeight, usableScreenSize.y) navigationBarOnBottom -> Point(usableScreenSize.x, newNavigationBarHeight) else -> Point() } val Context.newNavigationBarHeight: Int get() { var navigationBarHeight = 0 val resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android") if (resourceId > 0) { navigationBarHeight = resources.getDimensionPixelSize(resourceId) } return navigationBarHeight } val Context.statusBarHeight: Int get() { var statusBarHeight = 0 val resourceId = resources.getIdentifier("status_bar_height", "dimen", "android") if (resourceId > 0) { statusBarHeight = resources.getDimensionPixelSize(resourceId) } return statusBarHeight } val Context.actionBarHeight: Int get() { val styledAttributes = theme.obtainStyledAttributes(intArrayOf(android.R.attr.actionBarSize)) val actionBarHeight = styledAttributes.getDimension(0, 0f) styledAttributes.recycle() return actionBarHeight.toInt() } val Context.usableScreenSize: Point get() { val size = Point() windowManager.defaultDisplay.getSize(size) return size } val Context.realScreenSize: Point get() { val size = Point() windowManager.defaultDisplay.getRealSize(size) return size } fun Context.isUsingGestureNavigation(): Boolean { return try { val resourceId = resources.getIdentifier("config_navBarInteractionMode", "integer", "android") if (resourceId > 0) { resources.getInteger(resourceId) == 2 } else { false } } catch (e: Exception) { false } } fun Context.getCornerRadius() = resources.getDimension(R.dimen.rounded_corner_radius_small) // we need the Default Dialer functionality only in Simple Dialer and in Simple Contacts for now fun Context.isDefaultDialer(): Boolean { return if (!packageName.startsWith("com.simplemobiletools.contacts") && !packageName.startsWith("com.simplemobiletools.dialer")) { true } else if ((packageName.startsWith("com.simplemobiletools.contacts") || packageName.startsWith("com.simplemobiletools.dialer")) && isQPlus()) { val roleManager = getSystemService(RoleManager::class.java) roleManager!!.isRoleAvailable(RoleManager.ROLE_DIALER) && roleManager.isRoleHeld(RoleManager.ROLE_DIALER) } else { telecomManager.defaultDialerPackage == packageName } } fun Context.getContactsHasMap(withComparableNumbers: Boolean = false, callback: (HashMap<String, String>) -> Unit) { ContactsHelper(this).getContacts(showOnlyContactsWithNumbers = true) { contactList -> val privateContacts: HashMap<String, String> = HashMap() for (contact in contactList) { for (phoneNumber in contact.phoneNumbers) { var number = PhoneNumberUtils.stripSeparators(phoneNumber.value) if (withComparableNumbers) { number = number.trimToComparableNumber() } privateContacts[number] = contact.name } } callback(privateContacts) } } @TargetApi(Build.VERSION_CODES.N) fun Context.getBlockedNumbersWithContact(callback: (ArrayList<BlockedNumber>) -> Unit) { getContactsHasMap(true) { contacts -> val blockedNumbers = ArrayList<BlockedNumber>() if (!isNougatPlus() || !isDefaultDialer()) { callback(blockedNumbers) } val uri = BlockedNumbers.CONTENT_URI val projection = arrayOf( BlockedNumbers.COLUMN_ID, BlockedNumbers.COLUMN_ORIGINAL_NUMBER, BlockedNumbers.COLUMN_E164_NUMBER, ) queryCursor(uri, projection) { cursor -> val id = cursor.getLongValue(BlockedNumbers.COLUMN_ID) val number = cursor.getStringValue(BlockedNumbers.COLUMN_ORIGINAL_NUMBER) ?: "" val normalizedNumber = cursor.getStringValue(BlockedNumbers.COLUMN_E164_NUMBER) ?: number val comparableNumber = normalizedNumber.trimToComparableNumber() val contactName = contacts[comparableNumber] val blockedNumber = BlockedNumber(id, number, normalizedNumber, comparableNumber, contactName) blockedNumbers.add(blockedNumber) } val blockedNumbersPair = blockedNumbers.partition { it.contactName != null } val blockedNumbersWithNameSorted = blockedNumbersPair.first.sortedBy { it.contactName } val blockedNumbersNoNameSorted = blockedNumbersPair.second.sortedBy { it.number } callback(ArrayList(blockedNumbersWithNameSorted + blockedNumbersNoNameSorted)) } } @TargetApi(Build.VERSION_CODES.N) fun Context.getBlockedNumbers(): ArrayList<BlockedNumber> { val blockedNumbers = ArrayList<BlockedNumber>() if (!isNougatPlus() || !isDefaultDialer()) { return blockedNumbers } val uri = BlockedNumbers.CONTENT_URI val projection = arrayOf( BlockedNumbers.COLUMN_ID, BlockedNumbers.COLUMN_ORIGINAL_NUMBER, BlockedNumbers.COLUMN_E164_NUMBER ) queryCursor(uri, projection) { cursor -> val id = cursor.getLongValue(BlockedNumbers.COLUMN_ID) val number = cursor.getStringValue(BlockedNumbers.COLUMN_ORIGINAL_NUMBER) ?: "" val normalizedNumber = cursor.getStringValue(BlockedNumbers.COLUMN_E164_NUMBER) ?: number val comparableNumber = normalizedNumber.trimToComparableNumber() val blockedNumber = BlockedNumber(id, number, normalizedNumber, comparableNumber) blockedNumbers.add(blockedNumber) } return blockedNumbers } @TargetApi(Build.VERSION_CODES.N) fun Context.addBlockedNumber(number: String): Boolean { ContentValues().apply { put(BlockedNumbers.COLUMN_ORIGINAL_NUMBER, number) if (number.isPhoneNumber()) { put(BlockedNumbers.COLUMN_E164_NUMBER, PhoneNumberUtils.normalizeNumber(number)) } try { contentResolver.insert(BlockedNumbers.CONTENT_URI, this) } catch (e: Exception) { showErrorToast(e) return false } } return true } @TargetApi(Build.VERSION_CODES.N) fun Context.deleteBlockedNumber(number: String): Boolean { val selection = "${BlockedNumbers.COLUMN_ORIGINAL_NUMBER} = ?" val selectionArgs = arrayOf(number) return if (isNumberBlocked(number)) { val deletedRowCount = contentResolver.delete(BlockedNumbers.CONTENT_URI, selection, selectionArgs) deletedRowCount > 0 } else { true } } fun Context.isNumberBlocked(number: String, blockedNumbers: ArrayList<BlockedNumber> = getBlockedNumbers()): Boolean { if (!isNougatPlus()) { return false } val numberToCompare = number.trimToComparableNumber() return blockedNumbers.any { numberToCompare == it.numberToCompare || numberToCompare == it.number || PhoneNumberUtils.stripSeparators(number) == it.number } || isNumberBlockedByPattern(number, blockedNumbers) } fun Context.isNumberBlockedByPattern(number: String, blockedNumbers: ArrayList<BlockedNumber> = getBlockedNumbers()): Boolean { for (blockedNumber in blockedNumbers) { val num = blockedNumber.number if (num.isBlockedNumberPattern()) { val pattern = num.replace("+", "\\+").replace("*", ".*") if (number.matches(pattern.toRegex())) { return true } } } return false } fun Context.copyToClipboard(text: String) { val clip = ClipData.newPlainText(getString(R.string.simple_commons), text) (getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager).setPrimaryClip(clip) val toastText = String.format(getString(R.string.value_copied_to_clipboard_show), text) toast(toastText) } fun Context.getPhoneNumberTypeText(type: Int, label: String): String { return if (type == BaseTypes.TYPE_CUSTOM) { label } else { getString( when (type) { Phone.TYPE_MOBILE -> R.string.mobile Phone.TYPE_HOME -> R.string.home Phone.TYPE_WORK -> R.string.work Phone.TYPE_MAIN -> R.string.main_number Phone.TYPE_FAX_WORK -> R.string.work_fax Phone.TYPE_FAX_HOME -> R.string.home_fax Phone.TYPE_PAGER -> R.string.pager else -> R.string.other } ) } } fun Context.updateBottomTabItemColors(view: View?, isActive: Boolean, drawableId: Int? = null) { val color = if (isActive) { getProperPrimaryColor() } else { getProperTextColor() } if (drawableId != null) { val drawable = ResourcesCompat.getDrawable(resources, drawableId, theme) view?.findViewById<ImageView>(R.id.tab_item_icon)?.setImageDrawable(drawable) } view?.findViewById<ImageView>(R.id.tab_item_icon)?.applyColorFilter(color) view?.findViewById<TextView>(R.id.tab_item_label)?.setTextColor(color) } fun Context.sendEmailIntent(recipient: String) { Intent(Intent.ACTION_SENDTO).apply { data = Uri.fromParts(KEY_MAILTO, recipient, null) launchActivityIntent(this) } } fun Context.openNotificationSettings() { if (isOreoPlus()) { val intent = Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS) intent.putExtra(Settings.EXTRA_APP_PACKAGE, packageName) startActivity(intent) } else { // For Android versions below Oreo, you can't directly open the app's notification settings. // You can open the general notification settings instead. val intent = Intent(Settings.ACTION_SETTINGS) startActivity(intent) } } fun Context.getTempFile(folderName: String, filename: String): File? { val folder = File(cacheDir, folderName) if (!folder.exists()) { if (!folder.mkdir()) { toast(R.string.unknown_error_occurred) return null } } return File(folder, filename) } fun Context.openDeviceSettings() { val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply { data = Uri.fromParts("package", packageName, null) } try { startActivity(intent) } catch (e: Exception) { showErrorToast(e) } } @RequiresApi(Build.VERSION_CODES.S) fun Context.openRequestExactAlarmSettings(appId: String) { if (isSPlus()) { val uri = Uri.fromParts("package", appId, null) val intent = Intent(Settings.ACTION_REQUEST_SCHEDULE_EXACT_ALARM) intent.data = uri startActivity(intent) } } fun Context.canUseFullScreenIntent(): Boolean { return !isUpsideDownCakePlus() || notificationManager.canUseFullScreenIntent() } @RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE) fun Context.openFullScreenIntentSettings(appId: String) { if (isUpsideDownCakePlus()) { val uri = Uri.fromParts("package", appId, null) val intent = Intent(Settings.ACTION_MANAGE_APP_USE_FULL_SCREEN_INTENT) intent.data = uri startActivity(intent) } }
CT/commons/src/main/kotlin/com/simplemobiletools/commons/extensions/SeekBar.kt
1821892594
package com.simplemobiletools.commons.extensions import android.widget.SeekBar fun SeekBar.onSeekBarChangeListener(seekBarChangeListener: (progress: Int) -> Unit) = setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener { override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) { seekBarChangeListener(progress) } override fun onStartTrackingTouch(seekBar: SeekBar) {} override fun onStopTrackingTouch(seekBar: SeekBar) {} })
CT/commons/src/main/kotlin/com/simplemobiletools/commons/extensions/File.kt
533036373
package com.simplemobiletools.commons.extensions import android.content.Context import com.simplemobiletools.commons.helpers.* import com.simplemobiletools.commons.models.FileDirItem import java.io.File import java.util.* fun File.isMediaFile() = absolutePath.isMediaFile() fun File.isGif() = absolutePath.endsWith(".gif", true) fun File.isApng() = absolutePath.endsWith(".apng", true) fun File.isVideoFast() = videoExtensions.any { absolutePath.endsWith(it, true) } fun File.isImageFast() = photoExtensions.any { absolutePath.endsWith(it, true) } fun File.isAudioFast() = audioExtensions.any { absolutePath.endsWith(it, true) } fun File.isRawFast() = rawExtensions.any { absolutePath.endsWith(it, true) } fun File.isSvg() = absolutePath.isSvg() fun File.isPortrait() = absolutePath.isPortrait() fun File.isImageSlow() = absolutePath.isImageFast() || getMimeType().startsWith("image") fun File.isVideoSlow() = absolutePath.isVideoFast() || getMimeType().startsWith("video") fun File.isAudioSlow() = absolutePath.isAudioFast() || getMimeType().startsWith("audio") fun File.getMimeType() = absolutePath.getMimeType() fun File.getProperSize(countHiddenItems: Boolean): Long { return if (isDirectory) { getDirectorySize(this, countHiddenItems) } else { length() } } private fun getDirectorySize(dir: File, countHiddenItems: Boolean): Long { var size = 0L if (dir.exists()) { val files = dir.listFiles() if (files != null) { for (i in files.indices) { if (files[i].isDirectory) { size += getDirectorySize(files[i], countHiddenItems) } else if (!files[i].name.startsWith('.') && !dir.name.startsWith('.') || countHiddenItems) { size += files[i].length() } } } } return size } fun File.getFileCount(countHiddenItems: Boolean): Int { return if (isDirectory) { getDirectoryFileCount(this, countHiddenItems) } else { 1 } } private fun getDirectoryFileCount(dir: File, countHiddenItems: Boolean): Int { var count = -1 if (dir.exists()) { val files = dir.listFiles() if (files != null) { count++ for (i in files.indices) { val file = files[i] if (file.isDirectory) { count++ count += getDirectoryFileCount(file, countHiddenItems) } else if (!file.name.startsWith('.') || countHiddenItems) { count++ } } } } return count } fun File.getDirectChildrenCount(context: Context, countHiddenItems: Boolean): Int { val fileCount = if (context.isRestrictedSAFOnlyRoot(path)) { context.getAndroidSAFDirectChildrenCount( path, countHiddenItems ) } else { listFiles()?.filter { if (countHiddenItems) { true } else { !it.name.startsWith('.') } }?.size ?: 0 } return fileCount } fun File.toFileDirItem(context: Context) = FileDirItem(absolutePath, name, context.getIsPathDirectory(absolutePath), 0, length(), lastModified()) fun File.containsNoMedia(): Boolean { return if (!isDirectory) { false } else { File(this, NOMEDIA).exists() } } fun File.doesThisOrParentHaveNoMedia( folderNoMediaStatuses: HashMap<String, Boolean>, callback: ((path: String, hasNoMedia: Boolean) -> Unit)? ): Boolean { var curFile = this while (true) { val noMediaPath = "${curFile.absolutePath}/$NOMEDIA" val hasNoMedia = if (folderNoMediaStatuses.keys.contains(noMediaPath)) { folderNoMediaStatuses[noMediaPath]!! } else { val contains = curFile.containsNoMedia() callback?.invoke(curFile.absolutePath, contains) contains } if (hasNoMedia) { return true } curFile = curFile.parentFile ?: break if (curFile.absolutePath == "/") { break } } return false } fun File.doesParentHaveNoMedia(): Boolean { var curFile = parentFile while (true) { if (curFile?.containsNoMedia() == true) { return true } curFile = curFile?.parentFile ?: break if (curFile.absolutePath == "/") { break } } return false } fun File.getDigest(algorithm: String): String? { return try { inputStream().getDigest(algorithm) } catch (e: Exception) { null } } fun File.md5() = this.getDigest(MD5)
CT/commons/src/main/kotlin/com/simplemobiletools/commons/extensions/View.kt
2528512062
package com.simplemobiletools.commons.extensions import android.content.Context import android.view.HapticFeedbackConstants import android.view.View import android.view.ViewTreeObserver import com.simplemobiletools.commons.R import com.simplemobiletools.commons.helpers.SHORT_ANIMATION_DURATION fun View.beInvisibleIf(beInvisible: Boolean) = if (beInvisible) beInvisible() else beVisible() fun View.beVisibleIf(beVisible: Boolean) = if (beVisible) beVisible() else beGone() fun View.beGoneIf(beGone: Boolean) = beVisibleIf(!beGone) fun View.beInvisible() { visibility = View.INVISIBLE } fun View.beVisible() { visibility = View.VISIBLE } fun View.beGone() { visibility = View.GONE } fun View.onGlobalLayout(callback: () -> Unit) { viewTreeObserver?.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener { override fun onGlobalLayout() { if (viewTreeObserver != null) { viewTreeObserver.removeOnGlobalLayoutListener(this) callback() } } }) } fun View.isVisible() = visibility == View.VISIBLE fun View.isInvisible() = visibility == View.INVISIBLE fun View.isGone() = visibility == View.GONE fun View.performHapticFeedback() = performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY, HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) fun View.fadeIn() { animate().alpha(1f).setDuration(SHORT_ANIMATION_DURATION).withStartAction { beVisible() }.start() } fun View.fadeOut() { animate().alpha(0f).setDuration(SHORT_ANIMATION_DURATION).withEndAction { beGone() }.start() } fun View.setupViewBackground(context: Context) { background = if (context.baseConfig.isUsingSystemTheme) { resources.getDrawable(R.drawable.selector_clickable_you) } else { resources.getDrawable(R.drawable.selector_clickable) } }
CT/commons/src/main/kotlin/com/simplemobiletools/commons/extensions/Int.kt
1648520321
package com.simplemobiletools.commons.extensions import android.content.Context import android.content.res.ColorStateList import android.graphics.Color import android.media.ExifInterface import android.os.Handler import android.os.Looper import android.text.format.DateFormat import android.text.format.DateUtils import android.text.format.Time import androidx.core.os.postDelayed import com.simplemobiletools.commons.helpers.DARK_GREY import java.text.DecimalFormat import java.util.Calendar import java.util.Locale import java.util.Random fun Int.getContrastColor(): Int { val y = (299 * Color.red(this) + 587 * Color.green(this) + 114 * Color.blue(this)) / 1000 return if (y >= 149 && this != Color.BLACK) DARK_GREY else Color.WHITE } fun Int.toHex() = String.format("#%06X", 0xFFFFFF and this).toUpperCase() fun Int.adjustAlpha(factor: Float): Int { val alpha = Math.round(Color.alpha(this) * factor) val red = Color.red(this) val green = Color.green(this) val blue = Color.blue(this) return Color.argb(alpha, red, green, blue) } fun Int.getFormattedDuration(forceShowHours: Boolean = false): String { val sb = StringBuilder(8) val hours = this / 3600 val minutes = this % 3600 / 60 val seconds = this % 60 if (this >= 3600) { sb.append(String.format(Locale.getDefault(), "%02d", hours)).append(":") } else if (forceShowHours) { sb.append("0:") } sb.append(String.format(Locale.getDefault(), "%02d", minutes)) sb.append(":").append(String.format(Locale.getDefault(), "%02d", seconds)) return sb.toString() } fun Int.formatSize(): String { if (this <= 0) { return "0 B" } val units = arrayOf("B", "kB", "MB", "GB", "TB") val digitGroups = (Math.log10(toDouble()) / Math.log10(1024.0)).toInt() return "${DecimalFormat("#,##0.#").format(this / Math.pow(1024.0, digitGroups.toDouble()))} ${units[digitGroups]}" } fun Int.formatDate(context: Context, dateFormat: String? = null, timeFormat: String? = null): String { val useDateFormat = dateFormat ?: context.baseConfig.dateFormat val useTimeFormat = timeFormat ?: context.getTimeFormat() val cal = Calendar.getInstance(Locale.ENGLISH) cal.timeInMillis = this * 1000L return DateFormat.format("$useDateFormat, $useTimeFormat", cal).toString() } // if the given date is today, we show only the time. Else we show the date and optionally the time too fun Int.formatDateOrTime(context: Context, hideTimeAtOtherDays: Boolean, showYearEvenIfCurrent: Boolean): String { val cal = Calendar.getInstance(Locale.ENGLISH) cal.timeInMillis = this * 1000L return if (DateUtils.isToday(this * 1000L)) { DateFormat.format(context.getTimeFormat(), cal).toString() } else { var format = context.baseConfig.dateFormat if (!showYearEvenIfCurrent && isThisYear()) { format = format.replace("y", "").trim().trim('-').trim('.').trim('/') } if (!hideTimeAtOtherDays) { format += ", ${context.getTimeFormat()}" } DateFormat.format(format, cal).toString() } } fun Int.isThisYear(): Boolean { val time = Time() time.set(this * 1000L) val thenYear = time.year time.set(System.currentTimeMillis()) return (thenYear == time.year) } fun Int.addBitIf(add: Boolean, bit: Int) = if (add) { addBit(bit) } else { removeBit(bit) } // TODO: how to do "bits & ~bit" in kotlin? fun Int.removeBit(bit: Int) = addBit(bit) - bit fun Int.addBit(bit: Int) = this or bit fun Int.flipBit(bit: Int) = if (this and bit == 0) addBit(bit) else removeBit(bit) fun ClosedRange<Int>.random() = Random().nextInt(endInclusive - start) + start // taken from https://stackoverflow.com/a/40964456/1967672 fun Int.darkenColor(factor: Int = 8): Int { if (this == Color.WHITE || this == Color.BLACK) { return this } val DARK_FACTOR = factor var hsv = FloatArray(3) Color.colorToHSV(this, hsv) val hsl = hsv2hsl(hsv) hsl[2] -= DARK_FACTOR / 100f if (hsl[2] < 0) hsl[2] = 0f hsv = hsl2hsv(hsl) return Color.HSVToColor(hsv) } fun Int.lightenColor(factor: Int = 8): Int { if (this == Color.WHITE || this == Color.BLACK) { return this } val LIGHT_FACTOR = factor var hsv = FloatArray(3) Color.colorToHSV(this, hsv) val hsl = hsv2hsl(hsv) hsl[2] += LIGHT_FACTOR / 100f if (hsl[2] < 0) hsl[2] = 0f hsv = hsl2hsv(hsl) return Color.HSVToColor(hsv) } private fun hsl2hsv(hsl: FloatArray): FloatArray { val hue = hsl[0] var sat = hsl[1] val light = hsl[2] sat *= if (light < .5) light else 1 - light return floatArrayOf(hue, 2f * sat / (light + sat), light + sat) } private fun hsv2hsl(hsv: FloatArray): FloatArray { val hue = hsv[0] val sat = hsv[1] val value = hsv[2] val newHue = (2f - sat) * value var newSat = sat * value / if (newHue < 1f) newHue else 2f - newHue if (newSat > 1f) newSat = 1f return floatArrayOf(hue, newSat, newHue / 2f) } fun Int.orientationFromDegrees() = when (this) { 270 -> ExifInterface.ORIENTATION_ROTATE_270 180 -> ExifInterface.ORIENTATION_ROTATE_180 90 -> ExifInterface.ORIENTATION_ROTATE_90 else -> ExifInterface.ORIENTATION_NORMAL }.toString() fun Int.degreesFromOrientation() = when (this) { ExifInterface.ORIENTATION_ROTATE_270 -> 270 ExifInterface.ORIENTATION_ROTATE_180 -> 180 ExifInterface.ORIENTATION_ROTATE_90 -> 90 else -> 0 } fun Int.ensureTwoDigits(): String { return if (toString().length == 1) { "0$this" } else { toString() } } fun Int.getColorStateList(): ColorStateList { val states = arrayOf( intArrayOf(android.R.attr.state_enabled), intArrayOf(-android.R.attr.state_enabled), intArrayOf(-android.R.attr.state_checked), intArrayOf(android.R.attr.state_pressed) ) val colors = intArrayOf(this, this, this, this) return ColorStateList(states, colors) } fun Int.countdown(intervalMillis: Long, callback: (count: Int) -> Unit) { callback(this) if (this == 0) { return } Handler(Looper.getMainLooper()).postDelayed(intervalMillis) { (this - 1).countdown(intervalMillis, callback) } }
CT/commons/src/main/kotlin/com/simplemobiletools/commons/extensions/RemoteViews.kt
1602882271
package com.simplemobiletools.commons.extensions import android.graphics.Color import android.view.View import android.widget.RemoteViews fun RemoteViews.setBackgroundColor(id: Int, color: Int) { setInt(id, "setBackgroundColor", color) } fun RemoteViews.setTextSize(id: Int, size: Float) { setFloat(id, "setTextSize", size) } fun RemoteViews.setText(id: Int, text: String) { setTextViewText(id, text) } fun RemoteViews.setVisibleIf(id: Int, beVisible: Boolean) { val visibility = if (beVisible) View.VISIBLE else View.GONE setViewVisibility(id, visibility) } fun RemoteViews.applyColorFilter(id: Int, color: Int) { setInt(id, "setColorFilter", color) setInt(id, "setImageAlpha", Color.alpha(color)) }
CT/commons/src/main/kotlin/com/simplemobiletools/commons/extensions/Cursor.kt
4261146913
package com.simplemobiletools.commons.extensions import android.database.Cursor fun Cursor.getStringValue(key: String) = getString(getColumnIndex(key)) fun Cursor.getStringValueOrNull(key: String) = if (isNull(getColumnIndex(key))) null else getString(getColumnIndex(key)) fun Cursor.getIntValue(key: String) = getInt(getColumnIndex(key)) fun Cursor.getIntValueOrNull(key: String) = if (isNull(getColumnIndex(key))) null else getInt(getColumnIndex(key)) fun Cursor.getLongValue(key: String) = getLong(getColumnIndex(key)) fun Cursor.getLongValueOrNull(key: String) = if (isNull(getColumnIndex(key))) null else getLong(getColumnIndex(key)) fun Cursor.getBlobValue(key: String) = getBlob(getColumnIndex(key))
CT/commons/src/main/kotlin/com/simplemobiletools/commons/extensions/String.kt
2697913186
package com.simplemobiletools.commons.extensions import android.content.Context import android.graphics.Bitmap import android.graphics.BitmapFactory import android.graphics.Point import android.os.Build import android.os.StatFs import android.provider.MediaStore import android.telephony.PhoneNumberUtils import android.text.* import android.text.style.ForegroundColorSpan import android.widget.TextView import com.bumptech.glide.signature.ObjectKey import com.simplemobiletools.commons.helpers.* import java.io.File import java.text.DateFormat import java.text.Normalizer import java.text.SimpleDateFormat import java.util.Locale import java.util.regex.Pattern import org.joda.time.DateTime import org.joda.time.Years import org.joda.time.format.DateTimeFormat fun String.getFilenameFromPath() = substring(lastIndexOf("/") + 1) fun String.getFilenameExtension() = substring(lastIndexOf(".") + 1) fun String.getBasePath(context: Context): String { return when { startsWith(context.internalStoragePath) -> context.internalStoragePath context.isPathOnSD(this) -> context.sdCardPath context.isPathOnOTG(this) -> context.otgPath else -> "/" } } fun String.getFirstParentDirName(context: Context, level: Int): String? { val basePath = getBasePath(context) val startIndex = basePath.length + 1 return if (length > startIndex) { val pathWithoutBasePath = substring(startIndex) val pathSegments = pathWithoutBasePath.split("/") if (level < pathSegments.size) { pathSegments.slice(0..level).joinToString("/") } else { null } } else { null } } fun String.getFirstParentPath(context: Context, level: Int): String { val basePath = getBasePath(context) val startIndex = basePath.length + 1 return if (length > startIndex) { val pathWithoutBasePath = substring(basePath.length + 1) val pathSegments = pathWithoutBasePath.split("/") val firstParentPath = if (level < pathSegments.size) { pathSegments.slice(0..level).joinToString("/") } else { pathWithoutBasePath } "$basePath/$firstParentPath" } else { basePath } } fun String.isAValidFilename(): Boolean { val ILLEGAL_CHARACTERS = charArrayOf('/', '\n', '\r', '\t', '\u0000', '`', '?', '*', '\\', '<', '>', '|', '\"', ':') ILLEGAL_CHARACTERS.forEach { if (contains(it)) return false } return true } fun String.getOTGPublicPath(context: Context) = "${context.baseConfig.OTGTreeUri}/document/${context.baseConfig.OTGPartition}%3A${substring(context.baseConfig.OTGPath.length).replace("/", "%2F")}" fun String.isMediaFile() = isImageFast() || isVideoFast() || isGif() || isRawFast() || isSvg() || isPortrait() fun String.isWebP() = endsWith(".webp", true) fun String.isGif() = endsWith(".gif", true) fun String.isPng() = endsWith(".png", true) fun String.isApng() = endsWith(".apng", true) fun String.isJpg() = endsWith(".jpg", true) or endsWith(".jpeg", true) fun String.isSvg() = endsWith(".svg", true) fun String.isPortrait() = getFilenameFromPath().contains("portrait", true) && File(this).parentFile?.name?.startsWith("img_", true) == true // fast extension checks, not guaranteed to be accurate fun String.isVideoFast() = videoExtensions.any { endsWith(it, true) } fun String.isImageFast() = photoExtensions.any { endsWith(it, true) } fun String.isAudioFast() = audioExtensions.any { endsWith(it, true) } fun String.isRawFast() = rawExtensions.any { endsWith(it, true) } fun String.isImageSlow() = isImageFast() || getMimeType().startsWith("image") || startsWith(MediaStore.Images.Media.EXTERNAL_CONTENT_URI.toString()) fun String.isVideoSlow() = isVideoFast() || getMimeType().startsWith("video") || startsWith(MediaStore.Video.Media.EXTERNAL_CONTENT_URI.toString()) fun String.isAudioSlow() = isAudioFast() || getMimeType().startsWith("audio") || startsWith(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI.toString()) fun String.canModifyEXIF() = extensionsSupportingEXIF.any { endsWith(it, true) } fun String.getCompressionFormat() = when (getFilenameExtension().toLowerCase()) { "png" -> Bitmap.CompressFormat.PNG "webp" -> Bitmap.CompressFormat.WEBP else -> Bitmap.CompressFormat.JPEG } fun String.areDigitsOnly() = matches(Regex("[0-9]+")) fun String.areLettersOnly() = matches(Regex("[a-zA-Z]+")) fun String.getGenericMimeType(): String { if (!contains("/")) return this val type = substring(0, indexOf("/")) return "$type/*" } fun String.getParentPath() = removeSuffix("/${getFilenameFromPath()}") fun String.relativizeWith(path: String) = this.substring(path.length) fun String.containsNoMedia() = File(this).containsNoMedia() fun String.doesThisOrParentHaveNoMedia(folderNoMediaStatuses: HashMap<String, Boolean>, callback: ((path: String, hasNoMedia: Boolean) -> Unit)?) = File(this).doesThisOrParentHaveNoMedia(folderNoMediaStatuses, callback) fun String.getImageResolution(context: Context): Point? { val options = BitmapFactory.Options() options.inJustDecodeBounds = true if (context.isRestrictedSAFOnlyRoot(this)) { BitmapFactory.decodeStream(context.contentResolver.openInputStream(context.getAndroidSAFUri(this)), null, options) } else { BitmapFactory.decodeFile(this, options) } val width = options.outWidth val height = options.outHeight return if (width > 0 && height > 0) { Point(options.outWidth, options.outHeight) } else { null } } fun String.getPublicUri(context: Context) = context.getDocumentFile(this)?.uri ?: "" fun String.substringTo(cnt: Int): String { return if (isEmpty()) { "" } else { substring(0, Math.min(length, cnt)) } } fun String.highlightTextPart(textToHighlight: String, color: Int, highlightAll: Boolean = false, ignoreCharsBetweenDigits: Boolean = false): SpannableString { val spannableString = SpannableString(this) if (textToHighlight.isEmpty()) { return spannableString } var startIndex = normalizeString().indexOf(textToHighlight, 0, true) val indexes = ArrayList<Int>() while (startIndex >= 0) { if (startIndex != -1) { indexes.add(startIndex) } startIndex = normalizeString().indexOf(textToHighlight, startIndex + textToHighlight.length, true) if (!highlightAll) { break } } // handle cases when we search for 643, but in reality the string contains it like 6-43 if (ignoreCharsBetweenDigits && indexes.isEmpty()) { try { val regex = TextUtils.join("(\\D*)", textToHighlight.toCharArray().toTypedArray()) val pattern = Pattern.compile(regex) val result = pattern.matcher(normalizeString()) if (result.find()) { spannableString.setSpan(ForegroundColorSpan(color), result.start(), result.end(), Spannable.SPAN_EXCLUSIVE_INCLUSIVE) } } catch (ignored: Exception) { } return spannableString } indexes.forEach { val endIndex = Math.min(it + textToHighlight.length, length) try { spannableString.setSpan(ForegroundColorSpan(color), it, endIndex, Spannable.SPAN_EXCLUSIVE_INCLUSIVE) } catch (ignored: IndexOutOfBoundsException) { } } return spannableString } fun String.searchMatches(textToHighlight: String): ArrayList<Int> { val indexes = arrayListOf<Int>() var indexOf = indexOf(textToHighlight, 0, true) var offset = 0 while (offset < length && indexOf != -1) { indexOf = indexOf(textToHighlight, offset, true) if (indexOf == -1) { break } else { indexes.add(indexOf) } offset = indexOf + 1 } return indexes } fun String.getFileSignature(lastModified: Long? = null) = ObjectKey(getFileKey(lastModified)) fun String.getFileKey(lastModified: Long? = null): String { val file = File(this) val modified = if (lastModified != null && lastModified > 0) { lastModified } else { file.lastModified() } return "${file.absolutePath}$modified" } fun String.getAvailableStorageB(): Long { return try { val stat = StatFs(this) val bytesAvailable = stat.blockSizeLong * stat.availableBlocksLong bytesAvailable } catch (e: Exception) { -1L } } // remove diacritics, for example č -> c fun String.normalizeString() = Normalizer.normalize(this, Normalizer.Form.NFD).replace(normalizeRegex, "") // checks if string is a phone number fun String.isPhoneNumber(): Boolean { return this.matches("^[0-9+\\-\\)\\( *#]+\$".toRegex()) } // if we are comparing phone numbers, compare just the last 9 digits fun String.trimToComparableNumber(): String { // don't trim if it's not a phone number if (!this.isPhoneNumber()) { return this } val normalizedNumber = this.normalizeString() val startIndex = Math.max(0, normalizedNumber.length - 9) return normalizedNumber.substring(startIndex) } // get the contact names first letter at showing the placeholder without image fun String.getNameLetter() = normalizeString().toCharArray().getOrNull(0)?.toString()?.toUpperCase(Locale.getDefault()) ?: "A" fun String.normalizePhoneNumber() = PhoneNumberUtils.normalizeNumber(this) fun String.highlightTextFromNumbers(textToHighlight: String, primaryColor: Int): SpannableString { val spannableString = SpannableString(this) val digits = PhoneNumberUtils.convertKeypadLettersToDigits(this) if (digits.contains(textToHighlight)) { val startIndex = digits.indexOf(textToHighlight, 0, true) val endIndex = Math.min(startIndex + textToHighlight.length, length) try { spannableString.setSpan(ForegroundColorSpan(primaryColor), startIndex, endIndex, Spannable.SPAN_EXCLUSIVE_INCLUSIVE) } catch (ignored: IndexOutOfBoundsException) { } } return spannableString } fun String.getDateTimeFromDateString(showYearsSince: Boolean, viewToUpdate: TextView? = null): DateTime { val dateFormats = getDateFormats() var date = DateTime() for (format in dateFormats) { try { date = DateTime.parse(this, DateTimeFormat.forPattern(format)) val formatter = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.getDefault()) var localPattern = (formatter as SimpleDateFormat).toLocalizedPattern() val hasYear = format.contains("y") if (!hasYear) { localPattern = localPattern.replace("y", "").replace(",", "").trim() date = date.withYear(DateTime().year) } var formattedString = date.toString(localPattern) if (showYearsSince && hasYear) { formattedString += " (${Years.yearsBetween(date, DateTime.now()).years})" } viewToUpdate?.text = formattedString break } catch (ignored: Exception) { } } return date } fun String.getMimeType(): String { val typesMap = HashMap<String, String>().apply { put("323", "text/h323") put("3g2", "video/3gpp2") put("3gp", "video/3gpp") put("3gp2", "video/3gpp2") put("3gpp", "video/3gpp") put("7z", "application/x-7z-compressed") put("aa", "audio/audible") put("aac", "audio/aac") put("aaf", "application/octet-stream") put("aax", "audio/vnd.audible.aax") put("ac3", "audio/ac3") put("aca", "application/octet-stream") put("accda", "application/msaccess.addin") put("accdb", "application/msaccess") put("accdc", "application/msaccess.cab") put("accde", "application/msaccess") put("accdr", "application/msaccess.runtime") put("accdt", "application/msaccess") put("accdw", "application/msaccess.webapplication") put("accft", "application/msaccess.ftemplate") put("acx", "application/internet-property-stream") put("addin", "text/xml") put("ade", "application/msaccess") put("adobebridge", "application/x-bridge-url") put("adp", "application/msaccess") put("adt", "audio/vnd.dlna.adts") put("adts", "audio/aac") put("afm", "application/octet-stream") put("ai", "application/postscript") put("aif", "audio/aiff") put("aifc", "audio/aiff") put("aiff", "audio/aiff") put("air", "application/vnd.adobe.air-application-installer-package+zip") put("amc", "application/mpeg") put("anx", "application/annodex") put("apk", "application/vnd.android.package-archive") put("application", "application/x-ms-application") put("art", "image/x-jg") put("asa", "application/xml") put("asax", "application/xml") put("ascx", "application/xml") put("asd", "application/octet-stream") put("asf", "video/x-ms-asf") put("ashx", "application/xml") put("asi", "application/octet-stream") put("asm", "text/plain") put("asmx", "application/xml") put("aspx", "application/xml") put("asr", "video/x-ms-asf") put("asx", "video/x-ms-asf") put("atom", "application/atom+xml") put("au", "audio/basic") put("avi", "video/x-msvideo") put("axa", "audio/annodex") put("axs", "application/olescript") put("axv", "video/annodex") put("bas", "text/plain") put("bcpio", "application/x-bcpio") put("bin", "application/octet-stream") put("bmp", "image/bmp") put("c", "text/plain") put("cab", "application/octet-stream") put("caf", "audio/x-caf") put("calx", "application/vnd.ms-office.calx") put("cat", "application/vnd.ms-pki.seccat") put("cc", "text/plain") put("cd", "text/plain") put("cdda", "audio/aiff") put("cdf", "application/x-cdf") put("cer", "application/x-x509-ca-cert") put("cfg", "text/plain") put("chm", "application/octet-stream") put("class", "application/x-java-applet") put("clp", "application/x-msclip") put("cmd", "text/plain") put("cmx", "image/x-cmx") put("cnf", "text/plain") put("cod", "image/cis-cod") put("config", "application/xml") put("contact", "text/x-ms-contact") put("coverage", "application/xml") put("cpio", "application/x-cpio") put("cpp", "text/plain") put("crd", "application/x-mscardfile") put("crl", "application/pkix-crl") put("crt", "application/x-x509-ca-cert") put("cs", "text/plain") put("csdproj", "text/plain") put("csh", "application/x-csh") put("csproj", "text/plain") put("css", "text/css") put("csv", "text/csv") put("cur", "application/octet-stream") put("cxx", "text/plain") put("dat", "application/octet-stream") put("datasource", "application/xml") put("dbproj", "text/plain") put("dcr", "application/x-director") put("def", "text/plain") put("deploy", "application/octet-stream") put("der", "application/x-x509-ca-cert") put("dgml", "application/xml") put("dib", "image/bmp") put("dif", "video/x-dv") put("dir", "application/x-director") put("disco", "text/xml") put("divx", "video/divx") put("dll", "application/x-msdownload") put("dll.config", "text/xml") put("dlm", "text/dlm") put("dng", "image/x-adobe-dng") put("doc", "application/msword") put("docm", "application/vnd.ms-word.document.macroEnabled.12") put("docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document") put("dot", "application/msword") put("dotm", "application/vnd.ms-word.template.macroEnabled.12") put("dotx", "application/vnd.openxmlformats-officedocument.wordprocessingml.template") put("dsp", "application/octet-stream") put("dsw", "text/plain") put("dtd", "text/xml") put("dtsconfig", "text/xml") put("dv", "video/x-dv") put("dvi", "application/x-dvi") put("dwf", "drawing/x-dwf") put("dwp", "application/octet-stream") put("dxr", "application/x-director") put("eml", "message/rfc822") put("emz", "application/octet-stream") put("eot", "application/vnd.ms-fontobject") put("eps", "application/postscript") put("etl", "application/etl") put("etx", "text/x-setext") put("evy", "application/envoy") put("exe", "application/octet-stream") put("exe.config", "text/xml") put("fdf", "application/vnd.fdf") put("fif", "application/fractals") put("filters", "application/xml") put("fla", "application/octet-stream") put("flac", "audio/flac") put("flr", "x-world/x-vrml") put("flv", "video/x-flv") put("fsscript", "application/fsharp-script") put("fsx", "application/fsharp-script") put("generictest", "application/xml") put("gif", "image/gif") put("group", "text/x-ms-group") put("gsm", "audio/x-gsm") put("gtar", "application/x-gtar") put("gz", "application/x-gzip") put("h", "text/plain") put("hdf", "application/x-hdf") put("hdml", "text/x-hdml") put("hhc", "application/x-oleobject") put("hhk", "application/octet-stream") put("hhp", "application/octet-stream") put("hlp", "application/winhlp") put("hpp", "text/plain") put("hqx", "application/mac-binhex40") put("hta", "application/hta") put("htc", "text/x-component") put("htm", "text/html") put("html", "text/html") put("htt", "text/webviewhtml") put("hxa", "application/xml") put("hxc", "application/xml") put("hxd", "application/octet-stream") put("hxe", "application/xml") put("hxf", "application/xml") put("hxh", "application/octet-stream") put("hxi", "application/octet-stream") put("hxk", "application/xml") put("hxq", "application/octet-stream") put("hxr", "application/octet-stream") put("hxs", "application/octet-stream") put("hxt", "text/html") put("hxv", "application/xml") put("hxw", "application/octet-stream") put("hxx", "text/plain") put("i", "text/plain") put("ico", "image/x-icon") put("ics", "text/calendar") put("idl", "text/plain") put("ief", "image/ief") put("iii", "application/x-iphone") put("inc", "text/plain") put("inf", "application/octet-stream") put("ini", "text/plain") put("inl", "text/plain") put("ins", "application/x-internet-signup") put("ipa", "application/x-itunes-ipa") put("ipg", "application/x-itunes-ipg") put("ipproj", "text/plain") put("ipsw", "application/x-itunes-ipsw") put("iqy", "text/x-ms-iqy") put("isp", "application/x-internet-signup") put("ite", "application/x-itunes-ite") put("itlp", "application/x-itunes-itlp") put("itms", "application/x-itunes-itms") put("itpc", "application/x-itunes-itpc") put("ivf", "video/x-ivf") put("jar", "application/java-archive") put("java", "application/octet-stream") put("jck", "application/liquidmotion") put("jcz", "application/liquidmotion") put("jfif", "image/pjpeg") put("jnlp", "application/x-java-jnlp-file") put("jpb", "application/octet-stream") put("jpe", "image/jpeg") put("jpeg", "image/jpeg") put("jpg", "image/jpeg") put("js", "application/javascript") put("json", "application/json") put("jsx", "text/jscript") put("jsxbin", "text/plain") put("latex", "application/x-latex") put("library-ms", "application/windows-library+xml") put("lit", "application/x-ms-reader") put("loadtest", "application/xml") put("lpk", "application/octet-stream") put("lsf", "video/x-la-asf") put("lst", "text/plain") put("lsx", "video/x-la-asf") put("lzh", "application/octet-stream") put("m13", "application/x-msmediaview") put("m14", "application/x-msmediaview") put("m1v", "video/mpeg") put("m2t", "video/vnd.dlna.mpeg-tts") put("m2ts", "video/vnd.dlna.mpeg-tts") put("m2v", "video/mpeg") put("m3u", "audio/x-mpegurl") put("m3u8", "audio/x-mpegurl") put("m4a", "audio/m4a") put("m4b", "audio/m4b") put("m4p", "audio/m4p") put("m4r", "audio/x-m4r") put("m4v", "video/x-m4v") put("mac", "image/x-macpaint") put("mak", "text/plain") put("man", "application/x-troff-man") put("manifest", "application/x-ms-manifest") put("map", "text/plain") put("master", "application/xml") put("mda", "application/msaccess") put("mdb", "application/x-msaccess") put("mde", "application/msaccess") put("mdp", "application/octet-stream") put("me", "application/x-troff-me") put("mfp", "application/x-shockwave-flash") put("mht", "message/rfc822") put("mhtml", "message/rfc822") put("mid", "audio/mid") put("midi", "audio/mid") put("mix", "application/octet-stream") put("mk", "text/plain") put("mkv", "video/x-matroska") put("mmf", "application/x-smaf") put("mno", "text/xml") put("mny", "application/x-msmoney") put("mod", "video/mpeg") put("mov", "video/quicktime") put("movie", "video/x-sgi-movie") put("mp2", "video/mpeg") put("mp2v", "video/mpeg") put("mp3", "audio/mpeg") put("mp4", "video/mp4") put("mp4v", "video/mp4") put("mpa", "video/mpeg") put("mpe", "video/mpeg") put("mpeg", "video/mpeg") put("mpf", "application/vnd.ms-mediapackage") put("mpg", "video/mpeg") put("mpp", "application/vnd.ms-project") put("mpv2", "video/mpeg") put("mqv", "video/quicktime") put("ms", "application/x-troff-ms") put("msi", "application/octet-stream") put("mso", "application/octet-stream") put("mts", "video/vnd.dlna.mpeg-tts") put("mtx", "application/xml") put("mvb", "application/x-msmediaview") put("mvc", "application/x-miva-compiled") put("mxp", "application/x-mmxp") put("nc", "application/x-netcdf") put("nsc", "video/x-ms-asf") put("nws", "message/rfc822") put("ocx", "application/octet-stream") put("oda", "application/oda") put("odb", "application/vnd.oasis.opendocument.database") put("odc", "application/vnd.oasis.opendocument.chart") put("odf", "application/vnd.oasis.opendocument.formula") put("odg", "application/vnd.oasis.opendocument.graphics") put("odh", "text/plain") put("odi", "application/vnd.oasis.opendocument.image") put("odl", "text/plain") put("odm", "application/vnd.oasis.opendocument.text-master") put("odp", "application/vnd.oasis.opendocument.presentation") put("ods", "application/vnd.oasis.opendocument.spreadsheet") put("odt", "application/vnd.oasis.opendocument.text") put("oga", "audio/ogg") put("ogg", "audio/ogg") put("ogv", "video/ogg") put("ogx", "application/ogg") put("one", "application/onenote") put("onea", "application/onenote") put("onepkg", "application/onenote") put("onetmp", "application/onenote") put("onetoc", "application/onenote") put("onetoc2", "application/onenote") put("opus", "audio/ogg") put("orderedtest", "application/xml") put("osdx", "application/opensearchdescription+xml") put("otf", "application/font-sfnt") put("otg", "application/vnd.oasis.opendocument.graphics-template") put("oth", "application/vnd.oasis.opendocument.text-web") put("otp", "application/vnd.oasis.opendocument.presentation-template") put("ots", "application/vnd.oasis.opendocument.spreadsheet-template") put("ott", "application/vnd.oasis.opendocument.text-template") put("oxt", "application/vnd.openofficeorg.extension") put("p10", "application/pkcs10") put("p12", "application/x-pkcs12") put("p7b", "application/x-pkcs7-certificates") put("p7c", "application/pkcs7-mime") put("p7m", "application/pkcs7-mime") put("p7r", "application/x-pkcs7-certreqresp") put("p7s", "application/pkcs7-signature") put("pbm", "image/x-portable-bitmap") put("pcast", "application/x-podcast") put("pct", "image/pict") put("pcx", "application/octet-stream") put("pcz", "application/octet-stream") put("pdf", "application/pdf") put("pfb", "application/octet-stream") put("pfm", "application/octet-stream") put("pfx", "application/x-pkcs12") put("pgm", "image/x-portable-graymap") put("php", "text/plain") put("pic", "image/pict") put("pict", "image/pict") put("pkgdef", "text/plain") put("pkgundef", "text/plain") put("pko", "application/vnd.ms-pki.pko") put("pls", "audio/scpls") put("pma", "application/x-perfmon") put("pmc", "application/x-perfmon") put("pml", "application/x-perfmon") put("pmr", "application/x-perfmon") put("pmw", "application/x-perfmon") put("png", "image/png") put("pnm", "image/x-portable-anymap") put("pnt", "image/x-macpaint") put("pntg", "image/x-macpaint") put("pnz", "image/png") put("pot", "application/vnd.ms-powerpoint") put("potm", "application/vnd.ms-powerpoint.template.macroEnabled.12") put("potx", "application/vnd.openxmlformats-officedocument.presentationml.template") put("ppa", "application/vnd.ms-powerpoint") put("ppam", "application/vnd.ms-powerpoint.addin.macroEnabled.12") put("ppm", "image/x-portable-pixmap") put("pps", "application/vnd.ms-powerpoint") put("ppsm", "application/vnd.ms-powerpoint.slideshow.macroEnabled.12") put("ppsx", "application/vnd.openxmlformats-officedocument.presentationml.slideshow") put("ppt", "application/vnd.ms-powerpoint") put("pptm", "application/vnd.ms-powerpoint.presentation.macroEnabled.12") put("pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation") put("prf", "application/pics-rules") put("prm", "application/octet-stream") put("prx", "application/octet-stream") put("ps", "application/postscript") put("psc1", "application/PowerShell") put("psd", "application/octet-stream") put("psess", "application/xml") put("psm", "application/octet-stream") put("psp", "application/octet-stream") put("pub", "application/x-mspublisher") put("pwz", "application/vnd.ms-powerpoint") put("py", "text/plain") put("qht", "text/x-html-insertion") put("qhtm", "text/x-html-insertion") put("qt", "video/quicktime") put("qti", "image/x-quicktime") put("qtif", "image/x-quicktime") put("qtl", "application/x-quicktimeplayer") put("qxd", "application/octet-stream") put("ra", "audio/x-pn-realaudio") put("ram", "audio/x-pn-realaudio") put("rar", "application/x-rar-compressed") put("ras", "image/x-cmu-raster") put("rat", "application/rat-file") put("rb", "text/plain") put("rc", "text/plain") put("rc2", "text/plain") put("rct", "text/plain") put("rdlc", "application/xml") put("reg", "text/plain") put("resx", "application/xml") put("rf", "image/vnd.rn-realflash") put("rgb", "image/x-rgb") put("rgs", "text/plain") put("rm", "application/vnd.rn-realmedia") put("rmi", "audio/mid") put("rmp", "application/vnd.rn-rn_music_package") put("roff", "application/x-troff") put("rpm", "audio/x-pn-realaudio-plugin") put("rqy", "text/x-ms-rqy") put("rtf", "application/rtf") put("rtx", "text/richtext") put("ruleset", "application/xml") put("s", "text/plain") put("safariextz", "application/x-safari-safariextz") put("scd", "application/x-msschedule") put("scr", "text/plain") put("sct", "text/scriptlet") put("sd2", "audio/x-sd2") put("sdp", "application/sdp") put("sea", "application/octet-stream") put("searchConnector-ms", "application/windows-search-connector+xml") put("setpay", "application/set-payment-initiation") put("setreg", "application/set-registration-initiation") put("settings", "application/xml") put("sgimb", "application/x-sgimb") put("sgml", "text/sgml") put("sh", "application/x-sh") put("shar", "application/x-shar") put("shtml", "text/html") put("sit", "application/x-stuffit") put("sitemap", "application/xml") put("skin", "application/xml") put("sldm", "application/vnd.ms-powerpoint.slide.macroEnabled.12") put("sldx", "application/vnd.openxmlformats-officedocument.presentationml.slide") put("slk", "application/vnd.ms-excel") put("sln", "text/plain") put("slupkg-ms", "application/x-ms-license") put("smd", "audio/x-smd") put("smi", "application/octet-stream") put("smx", "audio/x-smd") put("smz", "audio/x-smd") put("snd", "audio/basic") put("snippet", "application/xml") put("snp", "application/octet-stream") put("sol", "text/plain") put("sor", "text/plain") put("spc", "application/x-pkcs7-certificates") put("spl", "application/futuresplash") put("spx", "audio/ogg") put("src", "application/x-wais-source") put("srf", "text/plain") put("ssisdeploymentmanifest", "text/xml") put("ssm", "application/streamingmedia") put("sst", "application/vnd.ms-pki.certstore") put("stl", "application/vnd.ms-pki.stl") put("sv4cpio", "application/x-sv4cpio") put("sv4crc", "application/x-sv4crc") put("svc", "application/xml") put("svg", "image/svg+xml") put("swf", "application/x-shockwave-flash") put("t", "application/x-troff") put("tar", "application/x-tar") put("tcl", "application/x-tcl") put("testrunconfig", "application/xml") put("testsettings", "application/xml") put("tex", "application/x-tex") put("texi", "application/x-texinfo") put("texinfo", "application/x-texinfo") put("tgz", "application/x-compressed") put("thmx", "application/vnd.ms-officetheme") put("thn", "application/octet-stream") put("tif", "image/tiff") put("tiff", "image/tiff") put("tlh", "text/plain") put("tli", "text/plain") put("toc", "application/octet-stream") put("tr", "application/x-troff") put("trm", "application/x-msterminal") put("trx", "application/xml") put("ts", "video/vnd.dlna.mpeg-tts") put("tsv", "text/tab-separated-values") put("ttf", "application/font-sfnt") put("tts", "video/vnd.dlna.mpeg-tts") put("txt", "text/plain") put("u32", "application/octet-stream") put("uls", "text/iuls") put("user", "text/plain") put("ustar", "application/x-ustar") put("vb", "text/plain") put("vbdproj", "text/plain") put("vbk", "video/mpeg") put("vbproj", "text/plain") put("vbs", "text/vbscript") put("vcf", "text/x-vcard") put("vcproj", "application/xml") put("vcs", "text/calendar") put("vcxproj", "application/xml") put("vddproj", "text/plain") put("vdp", "text/plain") put("vdproj", "text/plain") put("vdx", "application/vnd.ms-visio.viewer") put("vml", "text/xml") put("vscontent", "application/xml") put("vsct", "text/xml") put("vsd", "application/vnd.visio") put("vsi", "application/ms-vsi") put("vsix", "application/vsix") put("vsixlangpack", "text/xml") put("vsixmanifest", "text/xml") put("vsmdi", "application/xml") put("vspscc", "text/plain") put("vss", "application/vnd.visio") put("vsscc", "text/plain") put("vssettings", "text/xml") put("vssscc", "text/plain") put("vst", "application/vnd.visio") put("vstemplate", "text/xml") put("vsto", "application/x-ms-vsto") put("vsw", "application/vnd.visio") put("vsx", "application/vnd.visio") put("vtx", "application/vnd.visio") put("wav", "audio/wav") put("wave", "audio/wav") put("wax", "audio/x-ms-wax") put("wbk", "application/msword") put("wbmp", "image/vnd.wap.wbmp") put("wcm", "application/vnd.ms-works") put("wdb", "application/vnd.ms-works") put("wdp", "image/vnd.ms-photo") put("webarchive", "application/x-safari-webarchive") put("webm", "video/webm") put("webp", "image/webp") put("webtest", "application/xml") put("wiq", "application/xml") put("wiz", "application/msword") put("wks", "application/vnd.ms-works") put("wlmp", "application/wlmoviemaker") put("wlpginstall", "application/x-wlpg-detect") put("wlpginstall3", "application/x-wlpg3-detect") put("wm", "video/x-ms-wm") put("wma", "audio/x-ms-wma") put("wmd", "application/x-ms-wmd") put("wmf", "application/x-msmetafile") put("wml", "text/vnd.wap.wml") put("wmlc", "application/vnd.wap.wmlc") put("wmls", "text/vnd.wap.wmlscript") put("wmlsc", "application/vnd.wap.wmlscriptc") put("wmp", "video/x-ms-wmp") put("wmv", "video/x-ms-wmv") put("wmx", "video/x-ms-wmx") put("wmz", "application/x-ms-wmz") put("woff", "application/font-woff") put("wpl", "application/vnd.ms-wpl") put("wps", "application/vnd.ms-works") put("wri", "application/x-mswrite") put("wrl", "x-world/x-vrml") put("wrz", "x-world/x-vrml") put("wsc", "text/scriptlet") put("wsdl", "text/xml") put("wvx", "video/x-ms-wvx") put("x", "application/directx") put("xaf", "x-world/x-vrml") put("xaml", "application/xaml+xml") put("xap", "application/x-silverlight-app") put("xbap", "application/x-ms-xbap") put("xbm", "image/x-xbitmap") put("xdr", "text/plain") put("xht", "application/xhtml+xml") put("xhtml", "application/xhtml+xml") put("xla", "application/vnd.ms-excel") put("xlam", "application/vnd.ms-excel.addin.macroEnabled.12") put("xlc", "application/vnd.ms-excel") put("xld", "application/vnd.ms-excel") put("xlk", "application/vnd.ms-excel") put("xll", "application/vnd.ms-excel") put("xlm", "application/vnd.ms-excel") put("xls", "application/vnd.ms-excel") put("xlsb", "application/vnd.ms-excel.sheet.binary.macroEnabled.12") put("xlsm", "application/vnd.ms-excel.sheet.macroEnabled.12") put("xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") put("xlt", "application/vnd.ms-excel") put("xltm", "application/vnd.ms-excel.template.macroEnabled.12") put("xltx", "application/vnd.openxmlformats-officedocument.spreadsheetml.template") put("xlw", "application/vnd.ms-excel") put("xml", "text/xml") put("xmta", "application/xml") put("xof", "x-world/x-vrml") put("xoml", "text/plain") put("xpm", "image/x-xpixmap") put("xps", "application/vnd.ms-xpsdocument") put("xrm-ms", "text/xml") put("xsc", "application/xml") put("xsd", "text/xml") put("xsf", "text/xml") put("xsl", "text/xml") put("xslt", "text/xml") put("xsn", "application/octet-stream") put("xss", "application/xml") put("xspf", "application/xspf+xml") put("xtp", "application/octet-stream") put("xwd", "image/x-xwindowdump") put("z", "application/x-compress") put("zip", "application/zip") } return typesMap[getFilenameExtension().toLowerCase()] ?: "" } fun String.isBlockedNumberPattern() = contains("*") fun String?.fromHtml(): Spanned = when { this == null -> SpannableString("") Build.VERSION.SDK_INT >= Build.VERSION_CODES.N -> Html.fromHtml(this, Html.FROM_HTML_MODE_LEGACY) else -> Html.fromHtml(this) }
CT/commons/src/main/kotlin/com/simplemobiletools/commons/extensions/Bitmap.kt
487551861
package com.simplemobiletools.commons.extensions import android.graphics.Bitmap import java.io.ByteArrayOutputStream fun Bitmap.getByteArray(): ByteArray { var baos: ByteArrayOutputStream? = null try { baos = ByteArrayOutputStream() compress(Bitmap.CompressFormat.JPEG, 80, baos) return baos.toByteArray() } finally { baos?.close() } }
CT/commons/src/main/kotlin/com/simplemobiletools/commons/extensions/Context-storage-sdk30.kt
4204712970
package com.simplemobiletools.commons.extensions import android.content.Context import android.net.Uri import android.os.Environment import android.provider.DocumentsContract import android.provider.MediaStore import androidx.documentfile.provider.DocumentFile import com.simplemobiletools.commons.helpers.EXTERNAL_STORAGE_PROVIDER_AUTHORITY import com.simplemobiletools.commons.helpers.isRPlus import com.simplemobiletools.commons.helpers.isSPlus import com.simplemobiletools.commons.models.FileDirItem import java.io.File private const val DOWNLOAD_DIR = "Download" private const val ANDROID_DIR = "Android" private val DIRS_INACCESSIBLE_WITH_SAF_SDK_30 = listOf(DOWNLOAD_DIR, ANDROID_DIR) fun Context.hasProperStoredFirstParentUri(path: String): Boolean { val firstParentUri = createFirstParentTreeUri(path) return contentResolver.persistedUriPermissions.any { it.uri.toString() == firstParentUri.toString() } } fun Context.isAccessibleWithSAFSdk30(path: String): Boolean { if (path.startsWith(recycleBinPath) || isExternalStorageManager()) { return false } val level = getFirstParentLevel(path) val firstParentDir = path.getFirstParentDirName(this, level) val firstParentPath = path.getFirstParentPath(this, level) val isValidName = firstParentDir != null val isDirectory = File(firstParentPath).isDirectory val isAnAccessibleDirectory = DIRS_INACCESSIBLE_WITH_SAF_SDK_30.all { !firstParentDir.equals(it, true) } return isRPlus() && isValidName && isDirectory && isAnAccessibleDirectory } fun Context.getFirstParentLevel(path: String): Int { return when { isRPlus() && (isInAndroidDir(path) || isInSubFolderInDownloadDir(path)) -> 1 else -> 0 } } fun Context.isRestrictedWithSAFSdk30(path: String): Boolean { if (path.startsWith(recycleBinPath) || isExternalStorageManager()) { return false } val level = getFirstParentLevel(path) val firstParentDir = path.getFirstParentDirName(this, level) val firstParentPath = path.getFirstParentPath(this, level) val isInvalidName = firstParentDir == null val isDirectory = File(firstParentPath).isDirectory val isARestrictedDirectory = DIRS_INACCESSIBLE_WITH_SAF_SDK_30.any { firstParentDir.equals(it, true) } return isRPlus() && (isInvalidName || (isDirectory && isARestrictedDirectory)) } fun Context.isInDownloadDir(path: String): Boolean { if (path.startsWith(recycleBinPath)) { return false } val firstParentDir = path.getFirstParentDirName(this, 0) return firstParentDir.equals(DOWNLOAD_DIR, true) } fun Context.isInSubFolderInDownloadDir(path: String): Boolean { if (path.startsWith(recycleBinPath)) { return false } val firstParentDir = path.getFirstParentDirName(this, 1) return if (firstParentDir == null) { false } else { val startsWithDownloadDir = firstParentDir.startsWith(DOWNLOAD_DIR, true) val hasAtLeast1PathSegment = firstParentDir.split("/").filter { it.isNotEmpty() }.size > 1 val firstParentPath = path.getFirstParentPath(this, 1) startsWithDownloadDir && hasAtLeast1PathSegment && File(firstParentPath).isDirectory } } fun Context.isInAndroidDir(path: String): Boolean { if (path.startsWith(recycleBinPath)) { return false } val firstParentDir = path.getFirstParentDirName(this, 0) return firstParentDir.equals(ANDROID_DIR, true) } fun isExternalStorageManager(): Boolean { return isRPlus() && Environment.isExternalStorageManager() } // is the app a Media Management App on Android 12+? fun Context.canManageMedia(): Boolean { return isSPlus() && MediaStore.canManageMedia(this) } fun Context.createFirstParentTreeUriUsingRootTree(fullPath: String): Uri { val storageId = getSAFStorageId(fullPath) val level = getFirstParentLevel(fullPath) val rootParentDirName = fullPath.getFirstParentDirName(this, level) val treeUri = DocumentsContract.buildTreeDocumentUri(EXTERNAL_STORAGE_PROVIDER_AUTHORITY, "$storageId:") val documentId = "${storageId}:$rootParentDirName" return DocumentsContract.buildDocumentUriUsingTree(treeUri, documentId) } fun Context.createFirstParentTreeUri(fullPath: String): Uri { val storageId = getSAFStorageId(fullPath) val level = getFirstParentLevel(fullPath) val rootParentDirName = fullPath.getFirstParentDirName(this, level) val firstParentId = "$storageId:$rootParentDirName" return DocumentsContract.buildTreeDocumentUri(EXTERNAL_STORAGE_PROVIDER_AUTHORITY, firstParentId) } fun Context.createDocumentUriUsingFirstParentTreeUri(fullPath: String): Uri { val storageId = getSAFStorageId(fullPath) val relativePath = when { fullPath.startsWith(internalStoragePath) -> fullPath.substring(internalStoragePath.length).trim('/') else -> fullPath.substringAfter(storageId).trim('/') } val treeUri = createFirstParentTreeUri(fullPath) val documentId = "${storageId}:$relativePath" return DocumentsContract.buildDocumentUriUsingTree(treeUri, documentId) } fun Context.getSAFDocumentId(path: String): String { val basePath = path.getBasePath(this) val relativePath = path.substring(basePath.length).trim('/') val storageId = getSAFStorageId(path) return "$storageId:$relativePath" } fun Context.createSAFDirectorySdk30(path: String): Boolean { return try { val treeUri = createFirstParentTreeUri(path) val parentPath = path.getParentPath() if (!getDoesFilePathExistSdk30(parentPath)) { createSAFDirectorySdk30(parentPath) } val documentId = getSAFDocumentId(parentPath) val parentUri = DocumentsContract.buildDocumentUriUsingTree(treeUri, documentId) DocumentsContract.createDocument(contentResolver, parentUri, DocumentsContract.Document.MIME_TYPE_DIR, path.getFilenameFromPath()) != null } catch (e: IllegalStateException) { showErrorToast(e) false } } fun Context.createSAFFileSdk30(path: String): Boolean { return try { val treeUri = createFirstParentTreeUri(path) val parentPath = path.getParentPath() if (!getDoesFilePathExistSdk30(parentPath)) { createSAFDirectorySdk30(parentPath) } val documentId = getSAFDocumentId(parentPath) val parentUri = DocumentsContract.buildDocumentUriUsingTree(treeUri, documentId) DocumentsContract.createDocument(contentResolver, parentUri, path.getMimeType(), path.getFilenameFromPath()) != null } catch (e: IllegalStateException) { showErrorToast(e) false } } fun Context.getDoesFilePathExistSdk30(path: String): Boolean { return when { isAccessibleWithSAFSdk30(path) -> getFastDocumentSdk30(path)?.exists() ?: false else -> File(path).exists() } } fun Context.getSomeDocumentSdk30(path: String): DocumentFile? = getFastDocumentSdk30(path) ?: getDocumentSdk30(path) fun Context.getFastDocumentSdk30(path: String): DocumentFile? { val uri = createDocumentUriUsingFirstParentTreeUri(path) return DocumentFile.fromSingleUri(this, uri) } fun Context.getDocumentSdk30(path: String): DocumentFile? { val level = getFirstParentLevel(path) val firstParentPath = path.getFirstParentPath(this, level) var relativePath = path.substring(firstParentPath.length) if (relativePath.startsWith(File.separator)) { relativePath = relativePath.substring(1) } return try { val treeUri = createFirstParentTreeUri(path) var document = DocumentFile.fromTreeUri(applicationContext, treeUri) val parts = relativePath.split("/").filter { it.isNotEmpty() } for (part in parts) { document = document?.findFile(part) } document } catch (ignored: Exception) { null } } fun Context.deleteDocumentWithSAFSdk30(fileDirItem: FileDirItem, allowDeleteFolder: Boolean, callback: ((wasSuccess: Boolean) -> Unit)?) { try { var fileDeleted = false if (fileDirItem.isDirectory.not() || allowDeleteFolder) { val fileUri = createDocumentUriUsingFirstParentTreeUri(fileDirItem.path) fileDeleted = DocumentsContract.deleteDocument(contentResolver, fileUri) } if (fileDeleted) { deleteFromMediaStore(fileDirItem.path) callback?.invoke(true) } } catch (e: Exception) { callback?.invoke(false) showErrorToast(e) } } fun Context.renameDocumentSdk30(oldPath: String, newPath: String): Boolean { return try { val treeUri = createFirstParentTreeUri(oldPath) val documentId = getSAFDocumentId(oldPath) val parentUri = DocumentsContract.buildDocumentUriUsingTree(treeUri, documentId) DocumentsContract.renameDocument(contentResolver, parentUri, newPath.getFilenameFromPath()) != null } catch (e: IllegalStateException) { showErrorToast(e) false } } fun Context.hasProperStoredDocumentUriSdk30(path: String): Boolean { val documentUri = buildDocumentUriSdk30(path) return contentResolver.persistedUriPermissions.any { it.uri.toString() == documentUri.toString() } } fun Context.buildDocumentUriSdk30(fullPath: String): Uri { val storageId = getSAFStorageId(fullPath) val relativePath = when { fullPath.startsWith(internalStoragePath) -> fullPath.substring(internalStoragePath.length).trim('/') else -> fullPath.substringAfter(storageId).trim('/') } val documentId = "${storageId}:$relativePath" return DocumentsContract.buildDocumentUri(EXTERNAL_STORAGE_PROVIDER_AUTHORITY, documentId) } fun Context.getPicturesDirectoryPath(fullPath: String): String { val basePath = fullPath.getBasePath(this) return File(basePath, Environment.DIRECTORY_PICTURES).absolutePath }
CT/commons/src/main/kotlin/com/simplemobiletools/commons/extensions/Binding.kt
1313117904
package com.simplemobiletools.commons.extensions import android.app.Activity import android.view.LayoutInflater import androidx.viewbinding.ViewBinding inline fun <T : ViewBinding> Activity.viewBinding(crossinline bindingInflater: (LayoutInflater) -> T) = lazy(LazyThreadSafetyMode.NONE) { bindingInflater.invoke(layoutInflater) }
CT/commons/src/main/kotlin/com/simplemobiletools/commons/extensions/Any.kt
4076079568
package com.simplemobiletools.commons.extensions // extensions used mostly at importing app settings for now fun Any.toBoolean() = toString() == "true" fun Any.toInt() = Integer.parseInt(toString()) fun Any.toStringSet() = toString().split(",".toRegex()).toSet()
CT/commons/src/main/kotlin/com/simplemobiletools/commons/extensions/Long.kt
254445831
package com.simplemobiletools.commons.extensions import android.content.Context import android.text.format.DateFormat import java.text.DecimalFormat import java.util.* fun Long.formatSize(): String { if (this <= 0) { return "0 B" } val units = arrayOf("B", "kB", "MB", "GB", "TB") val digitGroups = (Math.log10(toDouble()) / Math.log10(1024.0)).toInt() return "${DecimalFormat("#,##0.#").format(this / Math.pow(1024.0, digitGroups.toDouble()))} ${units[digitGroups]}" } fun Long.formatDate(context: Context, dateFormat: String? = null, timeFormat: String? = null): String { val useDateFormat = dateFormat ?: context.baseConfig.dateFormat val useTimeFormat = timeFormat ?: context.getTimeFormat() val cal = Calendar.getInstance(Locale.ENGLISH) cal.timeInMillis = this return DateFormat.format("$useDateFormat, $useTimeFormat", cal).toString() }
CT/commons/src/main/kotlin/com/simplemobiletools/commons/extensions/InputStream.kt
805498360
package com.simplemobiletools.commons.extensions import com.simplemobiletools.commons.helpers.MD5 import java.io.InputStream import java.security.MessageDigest fun InputStream.getDigest(algorithm: String): String { return use { fis -> val md = MessageDigest.getInstance(algorithm) val buffer = ByteArray(8192) generateSequence { when (val bytesRead = fis.read(buffer)) { -1 -> null else -> bytesRead } }.forEach { bytesRead -> md.update(buffer, 0, bytesRead) } md.digest().joinToString("") { "%02x".format(it) } } } fun InputStream.md5(): String = this.getDigest(MD5)
CT/commons/src/main/kotlin/com/simplemobiletools/commons/extensions/List.kt
3455182540
package com.simplemobiletools.commons.extensions import java.util.* fun List<String>.getMimeType(): String { val mimeGroups = HashSet<String>(size) val subtypes = HashSet<String>(size) forEach { val parts = it.getMimeType().split("/") if (parts.size == 2) { mimeGroups.add(parts.getOrElse(0) { "" }) subtypes.add(parts.getOrElse(1) { "" }) } else { return "*/*" } } return when { subtypes.size == 1 -> "${mimeGroups.first()}/${subtypes.first()}" mimeGroups.size == 1 -> "${mimeGroups.first()}/*" else -> "*/*" } }
CT/commons/src/main/kotlin/com/simplemobiletools/commons/extensions/DocumentFile.kt
522705125
package com.simplemobiletools.commons.extensions import androidx.documentfile.provider.DocumentFile fun DocumentFile.getItemSize(countHiddenItems: Boolean): Long { return if (isDirectory) { getDirectorySize(this, countHiddenItems) } else { length() } } private fun getDirectorySize(dir: DocumentFile, countHiddenItems: Boolean): Long { var size = 0L if (dir.exists()) { val files = dir.listFiles() for (i in files.indices) { val file = files[i] if (file.isDirectory) { size += getDirectorySize(file, countHiddenItems) } else if (!file.name!!.startsWith(".") || countHiddenItems) { size += file.length() } } } return size } fun DocumentFile.getFileCount(countHiddenItems: Boolean): Int { return if (isDirectory) { getDirectoryFileCount(this, countHiddenItems) } else { 1 } } private fun getDirectoryFileCount(dir: DocumentFile, countHiddenItems: Boolean): Int { var count = 0 if (dir.exists()) { val files = dir.listFiles() for (i in files.indices) { val file = files[i] if (file.isDirectory) { count++ count += getDirectoryFileCount(file, countHiddenItems) } else if (!file.name!!.startsWith(".") || countHiddenItems) { count++ } } } return count }
CT/commons/src/main/kotlin/com/simplemobiletools/commons/extensions/TabLayout.kt
1380947379
package com.simplemobiletools.commons.extensions import com.google.android.material.tabs.TabLayout fun TabLayout.onTabSelectionChanged( tabUnselectedAction: ((inactiveTab: TabLayout.Tab) -> Unit)? = null, tabSelectedAction: ((activeTab: TabLayout.Tab) -> Unit)? = null ) = setOnTabSelectedListener(object : TabLayout.OnTabSelectedListener { override fun onTabSelected(tab: TabLayout.Tab) { tabSelectedAction?.invoke(tab) } override fun onTabUnselected(tab: TabLayout.Tab) { tabUnselectedAction?.invoke(tab) } override fun onTabReselected(tab: TabLayout.Tab) { tabSelectedAction?.invoke(tab) } })
CT/commons/src/main/kotlin/com/simplemobiletools/commons/extensions/EditText.kt
18849800
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/Activity-themes.kt
3252968979
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/Editable.kt
1925476729
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/SharedPreferencesProducerExtensions.kt
166101770
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/ImageView.kt
3102956018
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/TextView.kt
3259821595
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/Context-storage.kt
4228828839
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/ExifInterface.kt
3636544368
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/Activity.kt
1112282100
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/ArrayList.kt
399733624
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/FileDirItem.kt
1570722835
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/Drawable.kt
736366954
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/adapters/PasswordTypesAdapter.kt
3537525164
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/MyRecyclerViewAdapter.kt
3235398067
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/FilepickerItemsAdapter.kt
1779674330
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/FilepickerFavoritesAdapter.kt
2092934499
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/SimpleListItemAdapter.kt
1649484597
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/MyArrayAdapter.kt
2774995207
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/RenameAdapter.kt
1937438383
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/MyRecyclerViewListAdapter.kt
3812672634
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/dialogs/CustomIntervalPickerDialog.kt
3939259862
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/FileConflictDialog.kt
1794418419
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/PropertiesDialog.kt
3456217615
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/StoragePickerDialog.kt
3280212474
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/ConfirmationAdvancedDialog.kt
2898977574
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/EnterPasswordDialog.kt
1051114410
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/WhatsNewDialog.kt
3147315187
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/CallConfirmationDialog.kt
780696461
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/RenameItemDialog.kt
3723199985
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/LineColorPickerDialog.kt
3071154306
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/UpgradeToProDialog.kt
4261768164
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/RadioGroupDialog.kt
3700790025
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/BasePropertiesDialog.kt
2440969259
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/ColorPickerDialog.kt
2121056909
@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/RenameItemsDialog.kt
698380655
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/DonateDialog.kt
2779162903
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/RenameDialog.kt
4265405442
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/ChangeDateTimeFormatDialog.kt
4197247522
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/ConfirmationDialog.kt
4170224882
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/ExportBlockedNumbersDialog.kt
3384665474
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/AppSideloadedDialog.kt
1583635087
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/SecurityDialog.kt
2549166936
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/AddBlockedNumberDialog.kt
2914747152
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/FilePickerDialog.kt
2203769014
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/BottomSheetChooserDialog.kt
1116517937
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/PermissionRequiredDialog.kt
1034950389
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/WritePermissionDialog.kt
3522413753
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/FeatureLockedDialog.kt
3708189089
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/SelectAlarmSoundDialog.kt
1170821366
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/OpenDeviceSettingsDialog.kt
1760600393
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/RateStarsDialog.kt
655117504
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/CreateNewFolderDialog.kt
407768629
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/PurchaseThankYouDialog.kt
2163085355
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/FolderLockingNoticeDialog.kt
1632545098
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/ChangeViewTypeDialog.kt
3865782115
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/ExportSettingsDialog.kt
2808159124
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() } } } } } }