path
stringlengths 4
297
| contentHash
stringlengths 1
10
| content
stringlengths 0
13M
|
---|---|---|
CT/commons/src/main/kotlin/com/simplemobiletools/commons/activities/BaseSimpleActivity.kt | 567904171 | package com.simplemobiletools.commons.activities
import android.animation.ArgbEvaluator
import android.animation.ValueAnimator
import android.annotation.SuppressLint
import android.app.Activity
import android.app.ActivityManager
import android.app.RecoverableSecurityException
import android.app.role.RoleManager
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.content.res.Configuration
import android.graphics.BitmapFactory
import android.graphics.Color
import android.graphics.PorterDuff
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.DocumentsContract
import android.provider.MediaStore
import android.provider.Settings
import android.telecom.TelecomManager
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.WindowManager
import android.widget.EditText
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.core.app.ActivityCompat
import androidx.core.util.Pair
import androidx.core.view.ScrollingView
import androidx.core.view.WindowInsetsCompat
import androidx.core.widget.NestedScrollView
import androidx.recyclerview.widget.RecyclerView
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.asynctasks.CopyMoveTask
import com.simplemobiletools.commons.compose.extensions.DEVELOPER_PLAY_STORE_URL
import com.simplemobiletools.commons.dialogs.*
import com.simplemobiletools.commons.dialogs.WritePermissionDialog.WritePermissionDialogMode
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.*
import com.simplemobiletools.commons.interfaces.CopyMoveListener
import com.simplemobiletools.commons.models.FAQItem
import com.simplemobiletools.commons.models.FileDirItem
import java.io.File
import java.io.OutputStream
import java.util.regex.Pattern
abstract class BaseSimpleActivity : AppCompatActivity() {
var materialScrollColorAnimation: ValueAnimator? = null
var copyMoveCallback: ((destinationPath: String) -> Unit)? = null
var actionOnPermission: ((granted: Boolean) -> Unit)? = null
var isAskingPermissions = false
var useDynamicTheme = true
var showTransparentTop = false
var isMaterialActivity = false // by material activity we mean translucent navigation bar and opaque status and action bars
var checkedDocumentPath = ""
var currentScrollY = 0
var configItemsToExport = LinkedHashMap<String, Any>()
private var mainCoordinatorLayout: CoordinatorLayout? = null
private var nestedView: View? = null
private var scrollingView: ScrollingView? = null
private var toolbar: Toolbar? = null
private var useTransparentNavigation = false
private var useTopSearchMenu = false
private val GENERIC_PERM_HANDLER = 100
private val DELETE_FILE_SDK_30_HANDLER = 300
private val RECOVERABLE_SECURITY_HANDLER = 301
private val UPDATE_FILE_SDK_30_HANDLER = 302
private val MANAGE_MEDIA_RC = 303
private val TRASH_FILE_SDK_30_HANDLER = 304
companion object {
var funAfterSAFPermission: ((success: Boolean) -> Unit)? = null
var funAfterSdk30Action: ((success: Boolean) -> Unit)? = null
var funAfterUpdate30File: ((success: Boolean) -> Unit)? = null
var funAfterTrash30File: ((success: Boolean) -> Unit)? = null
var funRecoverableSecurity: ((success: Boolean) -> Unit)? = null
var funAfterManageMediaPermission: (() -> Unit)? = null
}
abstract fun getAppIconIDs(): ArrayList<Int>
abstract fun getAppLauncherName(): String
override fun onCreate(savedInstanceState: Bundle?) {
if (useDynamicTheme) {
setTheme(getThemeId(showTransparentTop = showTransparentTop))
}
super.onCreate(savedInstanceState)
if (!packageName.startsWith("com.simplemobiletools.", true)) {
if ((0..50).random() == 10 || baseConfig.appRunCount % 100 == 0) {
val label = "You are using a fake version of the app. For your own safety download the original one from www.simplemobiletools.com. Thanks"
ConfirmationDialog(this, label, positive = R.string.ok, negative = 0) {
launchViewIntent(DEVELOPER_PLAY_STORE_URL)
}
}
}
}
@SuppressLint("NewApi")
override fun onResume() {
super.onResume()
if (useDynamicTheme) {
setTheme(getThemeId(showTransparentTop = showTransparentTop))
val backgroundColor = if (baseConfig.isUsingSystemTheme) {
resources.getColor(R.color.you_background_color, theme)
} else {
baseConfig.backgroundColor
}
updateBackgroundColor(backgroundColor)
}
if (showTransparentTop) {
window.statusBarColor = Color.TRANSPARENT
} else if (!isMaterialActivity) {
val color = if (baseConfig.isUsingSystemTheme) {
resources.getColor(R.color.you_status_bar_color)
} else {
getProperStatusBarColor()
}
updateActionbarColor(color)
}
updateRecentsAppIcon()
var navBarColor = getProperBackgroundColor()
if (isMaterialActivity) {
navBarColor = navBarColor.adjustAlpha(HIGHER_ALPHA)
}
updateNavigationBarColor(navBarColor)
}
override fun onDestroy() {
super.onDestroy()
funAfterSAFPermission = null
actionOnPermission = null
}
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
handleNavigationAndScrolling()
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> {
hideKeyboard()
finish()
}
else -> return super.onOptionsItemSelected(item)
}
return true
}
override fun attachBaseContext(newBase: Context) {
if (newBase.baseConfig.useEnglish && !isTiramisuPlus()) {
super.attachBaseContext(MyContextWrapper(newBase).wrap(newBase, "en"))
} else {
super.attachBaseContext(newBase)
}
}
fun updateBackgroundColor(color: Int = baseConfig.backgroundColor) {
window.decorView.setBackgroundColor(color)
}
fun updateStatusbarColor(color: Int) {
window.statusBarColor = color
if (color.getContrastColor() == DARK_GREY) {
window.decorView.systemUiVisibility = window.decorView.systemUiVisibility.addBit(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR)
} else {
window.decorView.systemUiVisibility = window.decorView.systemUiVisibility.removeBit(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR)
}
}
fun updateActionbarColor(color: Int = getProperStatusBarColor()) {
updateStatusbarColor(color)
setTaskDescription(ActivityManager.TaskDescription(null, null, color))
}
fun updateNavigationBarColor(color: Int) {
window.navigationBarColor = color
updateNavigationBarButtons(color)
}
fun updateNavigationBarButtons(color: Int) {
if (isOreoPlus()) {
if (color.getContrastColor() == DARK_GREY) {
window.decorView.systemUiVisibility = window.decorView.systemUiVisibility.addBit(View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR)
} else {
window.decorView.systemUiVisibility = window.decorView.systemUiVisibility.removeBit(View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR)
}
}
}
// use translucent navigation bar, set the background color to action and status bars
fun updateMaterialActivityViews(
mainCoordinatorLayout: CoordinatorLayout?,
nestedView: View?,
useTransparentNavigation: Boolean,
useTopSearchMenu: Boolean,
) {
this.mainCoordinatorLayout = mainCoordinatorLayout
this.nestedView = nestedView
this.useTransparentNavigation = useTransparentNavigation
this.useTopSearchMenu = useTopSearchMenu
handleNavigationAndScrolling()
val backgroundColor = getProperBackgroundColor()
updateStatusbarColor(backgroundColor)
updateActionbarColor(backgroundColor)
}
private fun handleNavigationAndScrolling() {
if (useTransparentNavigation) {
if (navigationBarHeight > 0 || isUsingGestureNavigation()) {
window.decorView.systemUiVisibility = window.decorView.systemUiVisibility.addBit(View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION)
updateTopBottomInsets(statusBarHeight, navigationBarHeight)
// Don't touch this. Window Inset API often has a domino effect and things will most likely break.
onApplyWindowInsets {
val insets = it.getInsets(WindowInsetsCompat.Type.systemBars() or WindowInsetsCompat.Type.ime())
updateTopBottomInsets(insets.top, insets.bottom)
}
} else {
window.decorView.systemUiVisibility = window.decorView.systemUiVisibility.removeBit(View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION)
updateTopBottomInsets(0, 0)
}
}
}
private fun updateTopBottomInsets(top: Int, bottom: Int) {
nestedView?.run {
setPadding(paddingLeft, paddingTop, paddingRight, bottom)
}
(mainCoordinatorLayout?.layoutParams as? FrameLayout.LayoutParams)?.topMargin = top
}
// colorize the top toolbar and statusbar at scrolling down a bit
fun setupMaterialScrollListener(scrollingView: ScrollingView?, toolbar: Toolbar) {
this.scrollingView = scrollingView
this.toolbar = toolbar
if (scrollingView is RecyclerView) {
scrollingView.setOnScrollChangeListener { v, scrollX, scrollY, oldScrollX, oldScrollY ->
val newScrollY = scrollingView.computeVerticalScrollOffset()
scrollingChanged(newScrollY, currentScrollY)
currentScrollY = newScrollY
}
} else if (scrollingView is NestedScrollView) {
scrollingView.setOnScrollChangeListener { v, scrollX, scrollY, oldScrollX, oldScrollY ->
scrollingChanged(scrollY, oldScrollY)
}
}
}
private fun scrollingChanged(newScrollY: Int, oldScrollY: Int) {
if (newScrollY > 0 && oldScrollY == 0) {
val colorFrom = window.statusBarColor
val colorTo = getColoredMaterialStatusBarColor()
animateTopBarColors(colorFrom, colorTo)
} else if (newScrollY == 0 && oldScrollY > 0) {
val colorFrom = window.statusBarColor
val colorTo = getRequiredStatusBarColor()
animateTopBarColors(colorFrom, colorTo)
}
}
fun animateTopBarColors(colorFrom: Int, colorTo: Int) {
if (toolbar == null) {
return
}
materialScrollColorAnimation?.end()
materialScrollColorAnimation = ValueAnimator.ofObject(ArgbEvaluator(), colorFrom, colorTo)
materialScrollColorAnimation!!.addUpdateListener { animator ->
val color = animator.animatedValue as Int
if (toolbar != null) {
updateTopBarColors(toolbar!!, color)
}
}
materialScrollColorAnimation!!.start()
}
fun getRequiredStatusBarColor(): Int {
return if ((scrollingView is RecyclerView || scrollingView is NestedScrollView) && scrollingView?.computeVerticalScrollOffset() == 0) {
getProperBackgroundColor()
} else {
getColoredMaterialStatusBarColor()
}
}
fun updateTopBarColors(toolbar: Toolbar, color: Int) {
val contrastColor = if (useTopSearchMenu) {
getProperBackgroundColor().getContrastColor()
} else {
color.getContrastColor()
}
if (!useTopSearchMenu) {
updateStatusbarColor(color)
toolbar.setBackgroundColor(color)
toolbar.setTitleTextColor(contrastColor)
toolbar.navigationIcon?.applyColorFilter(contrastColor)
toolbar.collapseIcon = resources.getColoredDrawableWithColor(R.drawable.ic_arrow_left_vector, contrastColor)
}
toolbar.overflowIcon = resources.getColoredDrawableWithColor(R.drawable.ic_three_dots_vector, contrastColor)
val menu = toolbar.menu
for (i in 0 until menu.size()) {
try {
menu.getItem(i)?.icon?.setTint(contrastColor)
} catch (ignored: Exception) {
}
}
}
fun updateStatusBarOnPageChange() {
if (scrollingView is RecyclerView || scrollingView is NestedScrollView) {
val scrollY = scrollingView!!.computeVerticalScrollOffset()
val colorFrom = window.statusBarColor
val colorTo = if (scrollY > 0) {
getColoredMaterialStatusBarColor()
} else {
getRequiredStatusBarColor()
}
animateTopBarColors(colorFrom, colorTo)
currentScrollY = scrollY
}
}
fun setupToolbar(
toolbar: Toolbar,
toolbarNavigationIcon: NavigationIcon = NavigationIcon.None,
statusBarColor: Int = getRequiredStatusBarColor(),
searchMenuItem: MenuItem? = null
) {
val contrastColor = statusBarColor.getContrastColor()
if (toolbarNavigationIcon != NavigationIcon.None) {
val drawableId = if (toolbarNavigationIcon == NavigationIcon.Cross) R.drawable.ic_cross_vector else R.drawable.ic_arrow_left_vector
toolbar.navigationIcon = resources.getColoredDrawableWithColor(drawableId, contrastColor)
toolbar.setNavigationContentDescription(toolbarNavigationIcon.accessibilityResId)
}
toolbar.setNavigationOnClickListener {
hideKeyboard()
finish()
}
updateTopBarColors(toolbar, statusBarColor)
if (!useTopSearchMenu) {
searchMenuItem?.actionView?.findViewById<ImageView>(androidx.appcompat.R.id.search_close_btn)?.apply {
applyColorFilter(contrastColor)
}
searchMenuItem?.actionView?.findViewById<EditText>(androidx.appcompat.R.id.search_src_text)?.apply {
setTextColor(contrastColor)
setHintTextColor(contrastColor.adjustAlpha(MEDIUM_ALPHA))
hint = "${getString(R.string.search)}…"
if (isQPlus()) {
textCursorDrawable = null
}
}
// search underline
searchMenuItem?.actionView?.findViewById<View>(androidx.appcompat.R.id.search_plate)?.apply {
background.setColorFilter(contrastColor, PorterDuff.Mode.MULTIPLY)
}
}
}
fun updateRecentsAppIcon() {
if (baseConfig.isUsingModifiedAppIcon) {
val appIconIDs = getAppIconIDs()
val currentAppIconColorIndex = getCurrentAppIconColorIndex()
if (appIconIDs.size - 1 < currentAppIconColorIndex) {
return
}
val recentsIcon = BitmapFactory.decodeResource(resources, appIconIDs[currentAppIconColorIndex])
val title = getAppLauncherName()
val color = baseConfig.primaryColor
val description = ActivityManager.TaskDescription(title, recentsIcon, color)
setTaskDescription(description)
}
}
fun updateMenuItemColors(menu: Menu?, baseColor: Int = getProperStatusBarColor(), forceWhiteIcons: Boolean = false) {
if (menu == null) {
return
}
var color = baseColor.getContrastColor()
if (forceWhiteIcons) {
color = Color.WHITE
}
for (i in 0 until menu.size()) {
try {
menu.getItem(i)?.icon?.setTint(color)
} catch (ignored: Exception) {
}
}
}
private fun getCurrentAppIconColorIndex(): Int {
val appIconColor = baseConfig.appIconColor
getAppIconColors().forEachIndexed { index, color ->
if (color == appIconColor) {
return index
}
}
return 0
}
fun setTranslucentNavigation() {
window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION, WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, resultData: Intent?) {
super.onActivityResult(requestCode, resultCode, resultData)
val partition = try {
checkedDocumentPath.substring(9, 18)
} catch (e: Exception) {
""
}
val sdOtgPattern = Pattern.compile(SD_OTG_SHORT)
if (requestCode == CREATE_DOCUMENT_SDK_30) {
if (resultCode == Activity.RESULT_OK && resultData != null && resultData.data != null) {
val treeUri = resultData.data
val checkedUri = buildDocumentUriSdk30(checkedDocumentPath)
if (treeUri != checkedUri) {
toast(getString(R.string.wrong_folder_selected, checkedDocumentPath))
return
}
val takeFlags = Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION
applicationContext.contentResolver.takePersistableUriPermission(treeUri, takeFlags)
val funAfter = funAfterSdk30Action
funAfterSdk30Action = null
funAfter?.invoke(true)
} else {
funAfterSdk30Action?.invoke(false)
}
} else if (requestCode == OPEN_DOCUMENT_TREE_FOR_SDK_30) {
if (resultCode == Activity.RESULT_OK && resultData != null && resultData.data != null) {
val treeUri = resultData.data
val checkedUri = createFirstParentTreeUri(checkedDocumentPath)
if (treeUri != checkedUri) {
val level = getFirstParentLevel(checkedDocumentPath)
val firstParentPath = checkedDocumentPath.getFirstParentPath(this, level)
toast(getString(R.string.wrong_folder_selected, humanizePath(firstParentPath)))
return
}
val takeFlags = Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION
applicationContext.contentResolver.takePersistableUriPermission(treeUri, takeFlags)
val funAfter = funAfterSdk30Action
funAfterSdk30Action = null
funAfter?.invoke(true)
} else {
funAfterSdk30Action?.invoke(false)
}
} else if (requestCode == OPEN_DOCUMENT_TREE_FOR_ANDROID_DATA_OR_OBB) {
if (resultCode == Activity.RESULT_OK && resultData != null && resultData.data != null) {
if (isProperAndroidRoot(checkedDocumentPath, resultData.data!!)) {
if (resultData.dataString == baseConfig.OTGTreeUri || resultData.dataString == baseConfig.sdTreeUri) {
val pathToSelect = createAndroidDataOrObbPath(checkedDocumentPath)
toast(getString(R.string.wrong_folder_selected, pathToSelect))
return
}
val treeUri = resultData.data
storeAndroidTreeUri(checkedDocumentPath, treeUri.toString())
val takeFlags = Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION
applicationContext.contentResolver.takePersistableUriPermission(treeUri!!, takeFlags)
funAfterSAFPermission?.invoke(true)
funAfterSAFPermission = null
} else {
toast(getString(R.string.wrong_folder_selected, createAndroidDataOrObbPath(checkedDocumentPath)))
Intent(Intent.ACTION_OPEN_DOCUMENT_TREE).apply {
if (isRPlus()) {
putExtra(DocumentsContract.EXTRA_INITIAL_URI, createAndroidDataOrObbUri(checkedDocumentPath))
}
try {
startActivityForResult(this, requestCode)
} catch (e: Exception) {
showErrorToast(e)
}
}
}
} else {
funAfterSAFPermission?.invoke(false)
}
} else if (requestCode == OPEN_DOCUMENT_TREE_SD) {
if (resultCode == Activity.RESULT_OK && resultData != null && resultData.data != null) {
val isProperPartition = partition.isEmpty() || !sdOtgPattern.matcher(partition).matches() || (sdOtgPattern.matcher(partition)
.matches() && resultData.dataString!!.contains(partition))
if (isProperSDRootFolder(resultData.data!!) && isProperPartition) {
if (resultData.dataString == baseConfig.OTGTreeUri) {
toast(R.string.sd_card_usb_same)
return
}
saveTreeUri(resultData)
funAfterSAFPermission?.invoke(true)
funAfterSAFPermission = null
} else {
toast(R.string.wrong_root_selected)
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT_TREE)
try {
startActivityForResult(intent, requestCode)
} catch (e: Exception) {
showErrorToast(e)
}
}
} else {
funAfterSAFPermission?.invoke(false)
}
} else if (requestCode == OPEN_DOCUMENT_TREE_OTG) {
if (resultCode == Activity.RESULT_OK && resultData != null && resultData.data != null) {
val isProperPartition = partition.isEmpty() || !sdOtgPattern.matcher(partition).matches() || (sdOtgPattern.matcher(partition)
.matches() && resultData.dataString!!.contains(partition))
if (isProperOTGRootFolder(resultData.data!!) && isProperPartition) {
if (resultData.dataString == baseConfig.sdTreeUri) {
funAfterSAFPermission?.invoke(false)
toast(R.string.sd_card_usb_same)
return
}
baseConfig.OTGTreeUri = resultData.dataString!!
baseConfig.OTGPartition = baseConfig.OTGTreeUri.removeSuffix("%3A").substringAfterLast('/').trimEnd('/')
updateOTGPathFromPartition()
val takeFlags = Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION
applicationContext.contentResolver.takePersistableUriPermission(resultData.data!!, takeFlags)
funAfterSAFPermission?.invoke(true)
funAfterSAFPermission = null
} else {
toast(R.string.wrong_root_selected_usb)
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT_TREE)
try {
startActivityForResult(intent, requestCode)
} catch (e: Exception) {
showErrorToast(e)
}
}
} else {
funAfterSAFPermission?.invoke(false)
}
} else if (requestCode == SELECT_EXPORT_SETTINGS_FILE_INTENT && resultCode == Activity.RESULT_OK && resultData != null && resultData.data != null) {
val outputStream = contentResolver.openOutputStream(resultData.data!!)
exportSettingsTo(outputStream, configItemsToExport)
} else if (requestCode == DELETE_FILE_SDK_30_HANDLER) {
funAfterSdk30Action?.invoke(resultCode == Activity.RESULT_OK)
} else if (requestCode == RECOVERABLE_SECURITY_HANDLER) {
funRecoverableSecurity?.invoke(resultCode == Activity.RESULT_OK)
funRecoverableSecurity = null
} else if (requestCode == UPDATE_FILE_SDK_30_HANDLER) {
funAfterUpdate30File?.invoke(resultCode == Activity.RESULT_OK)
} else if (requestCode == MANAGE_MEDIA_RC) {
funAfterManageMediaPermission?.invoke()
} else if (requestCode == TRASH_FILE_SDK_30_HANDLER) {
funAfterTrash30File?.invoke(resultCode == Activity.RESULT_OK)
}
}
private fun saveTreeUri(resultData: Intent) {
val treeUri = resultData.data
baseConfig.sdTreeUri = treeUri.toString()
val takeFlags = Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION
applicationContext.contentResolver.takePersistableUriPermission(treeUri!!, takeFlags)
}
private fun isProperSDRootFolder(uri: Uri) = isExternalStorageDocument(uri) && isRootUri(uri) && !isInternalStorage(uri)
private fun isProperSDFolder(uri: Uri) = isExternalStorageDocument(uri) && !isInternalStorage(uri)
private fun isProperOTGRootFolder(uri: Uri) = isExternalStorageDocument(uri) && isRootUri(uri) && !isInternalStorage(uri)
private fun isProperOTGFolder(uri: Uri) = isExternalStorageDocument(uri) && !isInternalStorage(uri)
private fun isRootUri(uri: Uri) = uri.lastPathSegment?.endsWith(":") ?: false
private fun isInternalStorage(uri: Uri) = isExternalStorageDocument(uri) && DocumentsContract.getTreeDocumentId(uri).contains("primary")
private fun isAndroidDir(uri: Uri) = isExternalStorageDocument(uri) && DocumentsContract.getTreeDocumentId(uri).contains(":Android")
private fun isInternalStorageAndroidDir(uri: Uri) = isInternalStorage(uri) && isAndroidDir(uri)
private fun isOTGAndroidDir(uri: Uri) = isProperOTGFolder(uri) && isAndroidDir(uri)
private fun isSDAndroidDir(uri: Uri) = isProperSDFolder(uri) && isAndroidDir(uri)
private fun isExternalStorageDocument(uri: Uri) = EXTERNAL_STORAGE_PROVIDER_AUTHORITY == uri.authority
private fun isProperAndroidRoot(path: String, uri: Uri): Boolean {
return when {
isPathOnOTG(path) -> isOTGAndroidDir(uri)
isPathOnSD(path) -> isSDAndroidDir(uri)
else -> isInternalStorageAndroidDir(uri)
}
}
fun startAboutActivity(appNameId: Int, licenseMask: Long, versionName: String, faqItems: ArrayList<FAQItem>, showFAQBeforeMail: Boolean) {
hideKeyboard()
Intent(applicationContext, AboutActivity::class.java).apply {
putExtra(APP_ICON_IDS, getAppIconIDs())
putExtra(APP_LAUNCHER_NAME, getAppLauncherName())
putExtra(APP_NAME, getString(appNameId))
putExtra(APP_LICENSES, licenseMask)
putExtra(APP_VERSION_NAME, versionName)
putExtra(APP_FAQ, faqItems)
putExtra(SHOW_FAQ_BEFORE_MAIL, showFAQBeforeMail)
startActivity(this)
}
}
fun startCustomizationActivity() {
if (!packageName.contains("slootelibomelpmis".reversed(), true)) {
if (baseConfig.appRunCount > 100) {
val label = "You are using a fake version of the app. For your own safety download the original one from www.simplemobiletools.com. Thanks"
ConfirmationDialog(this, label, positive = R.string.ok, negative = 0) {
launchViewIntent(DEVELOPER_PLAY_STORE_URL)
}
return
}
}
Intent(applicationContext, CustomizationActivity::class.java).apply {
putExtra(APP_ICON_IDS, getAppIconIDs())
putExtra(APP_LAUNCHER_NAME, getAppLauncherName())
startActivity(this)
}
}
fun handleCustomizeColorsClick() {
if (isOrWasThankYouInstalled()) {
startCustomizationActivity()
} else {
FeatureLockedDialog(this) {}
}
}
@RequiresApi(Build.VERSION_CODES.O)
fun launchCustomizeNotificationsIntent() {
Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS).apply {
putExtra(Settings.EXTRA_APP_PACKAGE, packageName)
startActivity(this)
}
}
@RequiresApi(Build.VERSION_CODES.TIRAMISU)
fun launchChangeAppLanguageIntent() {
try {
Intent(Settings.ACTION_APP_LOCALE_SETTINGS).apply {
data = Uri.fromParts("package", packageName, null)
startActivity(this)
}
} catch (e: Exception) {
openDeviceSettings()
}
}
// synchronous return value determines only if we are showing the SAF dialog, callback result tells if the SD or OTG permission has been granted
fun handleSAFDialog(path: String, callback: (success: Boolean) -> Unit): Boolean {
hideKeyboard()
return if (!packageName.startsWith("com.simplemobiletools")) {
callback(true)
false
} else if (isShowingSAFDialog(path) || isShowingOTGDialog(path)) {
funAfterSAFPermission = callback
true
} else {
callback(true)
false
}
}
fun handleSAFDialogSdk30(path: String, callback: (success: Boolean) -> Unit): Boolean {
hideKeyboard()
return if (!packageName.startsWith("com.simplemobiletools")) {
callback(true)
false
} else if (isShowingSAFDialogSdk30(path)) {
funAfterSdk30Action = callback
true
} else {
callback(true)
false
}
}
fun checkManageMediaOrHandleSAFDialogSdk30(path: String, callback: (success: Boolean) -> Unit): Boolean {
hideKeyboard()
return if (canManageMedia()) {
callback(true)
false
} else {
handleSAFDialogSdk30(path, callback)
}
}
fun handleSAFCreateDocumentDialogSdk30(path: String, callback: (success: Boolean) -> Unit): Boolean {
hideKeyboard()
return if (!packageName.startsWith("com.simplemobiletools")) {
callback(true)
false
} else if (isShowingSAFCreateDocumentDialogSdk30(path)) {
funAfterSdk30Action = callback
true
} else {
callback(true)
false
}
}
fun handleAndroidSAFDialog(path: String, callback: (success: Boolean) -> Unit): Boolean {
hideKeyboard()
return if (!packageName.startsWith("com.simplemobiletools")) {
callback(true)
false
} else if (isShowingAndroidSAFDialog(path)) {
funAfterSAFPermission = callback
true
} else {
callback(true)
false
}
}
fun handleOTGPermission(callback: (success: Boolean) -> Unit) {
hideKeyboard()
if (baseConfig.OTGTreeUri.isNotEmpty()) {
callback(true)
return
}
funAfterSAFPermission = callback
WritePermissionDialog(this, WritePermissionDialogMode.Otg) {
Intent(Intent.ACTION_OPEN_DOCUMENT_TREE).apply {
try {
startActivityForResult(this, OPEN_DOCUMENT_TREE_OTG)
return@apply
} catch (e: Exception) {
type = "*/*"
}
try {
startActivityForResult(this, OPEN_DOCUMENT_TREE_OTG)
} catch (e: ActivityNotFoundException) {
toast(R.string.system_service_disabled, Toast.LENGTH_LONG)
} catch (e: Exception) {
toast(R.string.unknown_error_occurred)
}
}
}
}
@SuppressLint("NewApi")
fun deleteSDK30Uris(uris: List<Uri>, callback: (success: Boolean) -> Unit) {
hideKeyboard()
if (isRPlus()) {
funAfterSdk30Action = callback
try {
val deleteRequest = MediaStore.createDeleteRequest(contentResolver, uris).intentSender
startIntentSenderForResult(deleteRequest, DELETE_FILE_SDK_30_HANDLER, null, 0, 0, 0)
} catch (e: Exception) {
showErrorToast(e)
}
} else {
callback(false)
}
}
@SuppressLint("NewApi")
fun trashSDK30Uris(uris: List<Uri>, toTrash: Boolean, callback: (success: Boolean) -> Unit) {
hideKeyboard()
if (isRPlus()) {
funAfterTrash30File = callback
try {
val trashRequest = MediaStore.createTrashRequest(contentResolver, uris, toTrash).intentSender
startIntentSenderForResult(trashRequest, TRASH_FILE_SDK_30_HANDLER, null, 0, 0, 0)
} catch (e: Exception) {
showErrorToast(e)
}
} else {
callback(false)
}
}
@SuppressLint("NewApi")
fun updateSDK30Uris(uris: List<Uri>, callback: (success: Boolean) -> Unit) {
hideKeyboard()
if (isRPlus()) {
funAfterUpdate30File = callback
try {
val writeRequest = MediaStore.createWriteRequest(contentResolver, uris).intentSender
startIntentSenderForResult(writeRequest, UPDATE_FILE_SDK_30_HANDLER, null, 0, 0, 0)
} catch (e: Exception) {
showErrorToast(e)
}
} else {
callback(false)
}
}
@SuppressLint("NewApi")
fun handleRecoverableSecurityException(callback: (success: Boolean) -> Unit) {
try {
callback.invoke(true)
} catch (securityException: SecurityException) {
if (isQPlus()) {
funRecoverableSecurity = callback
val recoverableSecurityException = securityException as? RecoverableSecurityException ?: throw securityException
val intentSender = recoverableSecurityException.userAction.actionIntent.intentSender
startIntentSenderForResult(intentSender, RECOVERABLE_SECURITY_HANDLER, null, 0, 0, 0)
} else {
callback(false)
}
}
}
@RequiresApi(Build.VERSION_CODES.S)
fun launchMediaManagementIntent(callback: () -> Unit) {
Intent(Settings.ACTION_REQUEST_MANAGE_MEDIA).apply {
data = Uri.parse("package:$packageName")
try {
startActivityForResult(this, MANAGE_MEDIA_RC)
} catch (e: Exception) {
showErrorToast(e)
}
}
funAfterManageMediaPermission = callback
}
fun copyMoveFilesTo(
fileDirItems: ArrayList<FileDirItem>, source: String, destination: String, isCopyOperation: Boolean, copyPhotoVideoOnly: Boolean,
copyHidden: Boolean, callback: (destinationPath: String) -> Unit
) {
if (source == destination) {
toast(R.string.source_and_destination_same)
return
}
if (!getDoesFilePathExist(destination)) {
toast(R.string.invalid_destination)
return
}
handleSAFDialog(destination) {
if (!it) {
copyMoveListener.copyFailed()
return@handleSAFDialog
}
handleSAFDialogSdk30(destination) {
if (!it) {
copyMoveListener.copyFailed()
return@handleSAFDialogSdk30
}
copyMoveCallback = callback
var fileCountToCopy = fileDirItems.size
if (isCopyOperation) {
val recycleBinPath = fileDirItems.first().isRecycleBinPath(this)
if (canManageMedia() && !recycleBinPath) {
val fileUris = getFileUrisFromFileDirItems(fileDirItems)
updateSDK30Uris(fileUris) { sdk30UriSuccess ->
if (sdk30UriSuccess) {
startCopyMove(fileDirItems, destination, isCopyOperation, copyPhotoVideoOnly, copyHidden)
}
}
} else {
startCopyMove(fileDirItems, destination, isCopyOperation, copyPhotoVideoOnly, copyHidden)
}
} else {
if (isPathOnOTG(source) || isPathOnOTG(destination) || isPathOnSD(source) || isPathOnSD(destination) ||
isRestrictedSAFOnlyRoot(source) || isRestrictedSAFOnlyRoot(destination) ||
isAccessibleWithSAFSdk30(source) || isAccessibleWithSAFSdk30(destination) ||
fileDirItems.first().isDirectory
) {
handleSAFDialog(source) { safSuccess ->
if (safSuccess) {
val recycleBinPath = fileDirItems.first().isRecycleBinPath(this)
if (canManageMedia() && !recycleBinPath) {
val fileUris = getFileUrisFromFileDirItems(fileDirItems)
updateSDK30Uris(fileUris) { sdk30UriSuccess ->
if (sdk30UriSuccess) {
startCopyMove(fileDirItems, destination, isCopyOperation, copyPhotoVideoOnly, copyHidden)
}
}
} else {
startCopyMove(fileDirItems, destination, isCopyOperation, copyPhotoVideoOnly, copyHidden)
}
}
}
} else {
try {
checkConflicts(fileDirItems, destination, 0, LinkedHashMap()) {
toast(R.string.moving)
ensureBackgroundThread {
val updatedPaths = ArrayList<String>(fileDirItems.size)
val destinationFolder = File(destination)
for (oldFileDirItem in fileDirItems) {
var newFile = File(destinationFolder, oldFileDirItem.name)
if (newFile.exists()) {
when {
getConflictResolution(it, newFile.absolutePath) == CONFLICT_SKIP -> fileCountToCopy--
getConflictResolution(it, newFile.absolutePath) == CONFLICT_KEEP_BOTH -> newFile = getAlternativeFile(newFile)
else ->
// this file is guaranteed to be on the internal storage, so just delete it this way
newFile.delete()
}
}
if (!newFile.exists() && File(oldFileDirItem.path).renameTo(newFile)) {
if (!baseConfig.keepLastModified) {
newFile.setLastModified(System.currentTimeMillis())
}
updatedPaths.add(newFile.absolutePath)
deleteFromMediaStore(oldFileDirItem.path)
}
}
runOnUiThread {
if (updatedPaths.isEmpty()) {
copyMoveListener.copySucceeded(false, fileCountToCopy == 0, destination, false)
} else {
copyMoveListener.copySucceeded(false, fileCountToCopy <= updatedPaths.size, destination, updatedPaths.size == 1)
}
}
}
}
} catch (e: Exception) {
showErrorToast(e)
}
}
}
}
}
}
fun getAlternativeFile(file: File): File {
var fileIndex = 1
var newFile: File?
do {
val newName = String.format("%s(%d).%s", file.nameWithoutExtension, fileIndex, file.extension)
newFile = File(file.parent, newName)
fileIndex++
} while (getDoesFilePathExist(newFile!!.absolutePath))
return newFile
}
private fun startCopyMove(
files: ArrayList<FileDirItem>,
destinationPath: String,
isCopyOperation: Boolean,
copyPhotoVideoOnly: Boolean,
copyHidden: Boolean
) {
val availableSpace = destinationPath.getAvailableStorageB()
val sumToCopy = files.sumByLong { it.getProperSize(applicationContext, copyHidden) }
if (availableSpace == -1L || sumToCopy < availableSpace) {
checkConflicts(files, destinationPath, 0, LinkedHashMap()) {
toast(if (isCopyOperation) R.string.copying else R.string.moving)
val pair = Pair(files, destinationPath)
handleNotificationPermission { granted ->
if (granted) {
CopyMoveTask(this, isCopyOperation, copyPhotoVideoOnly, it, copyMoveListener, copyHidden).execute(pair)
} else {
PermissionRequiredDialog(this, R.string.allow_notifications_files, { openNotificationSettings() })
}
}
}
} else {
val text = String.format(getString(R.string.no_space), sumToCopy.formatSize(), availableSpace.formatSize())
toast(text, Toast.LENGTH_LONG)
}
}
fun checkConflicts(
files: ArrayList<FileDirItem>, destinationPath: String, index: Int, conflictResolutions: LinkedHashMap<String, Int>,
callback: (resolutions: LinkedHashMap<String, Int>) -> Unit
) {
if (index == files.size) {
callback(conflictResolutions)
return
}
val file = files[index]
val newFileDirItem = FileDirItem("$destinationPath/${file.name}", file.name, file.isDirectory)
ensureBackgroundThread {
if (getDoesFilePathExist(newFileDirItem.path)) {
runOnUiThread {
FileConflictDialog(this, newFileDirItem, files.size > 1) { resolution, applyForAll ->
if (applyForAll) {
conflictResolutions.clear()
conflictResolutions[""] = resolution
checkConflicts(files, destinationPath, files.size, conflictResolutions, callback)
} else {
conflictResolutions[newFileDirItem.path] = resolution
checkConflicts(files, destinationPath, index + 1, conflictResolutions, callback)
}
}
}
} else {
runOnUiThread {
checkConflicts(files, destinationPath, index + 1, conflictResolutions, callback)
}
}
}
}
fun handlePermission(permissionId: Int, callback: (granted: Boolean) -> Unit) {
actionOnPermission = null
if (hasPermission(permissionId)) {
callback(true)
} else {
isAskingPermissions = true
actionOnPermission = callback
ActivityCompat.requestPermissions(this, arrayOf(getPermissionString(permissionId)), GENERIC_PERM_HANDLER)
}
}
fun handlePartialMediaPermissions(permissionIds: Collection<Int>, force: Boolean = false, callback: (granted: Boolean) -> Unit) {
actionOnPermission = null
if (isUpsideDownCakePlus()) {
if (hasPermission(PERMISSION_READ_MEDIA_VISUAL_USER_SELECTED) && !force) {
callback(true)
} else {
isAskingPermissions = true
actionOnPermission = callback
ActivityCompat.requestPermissions(this, permissionIds.map { getPermissionString(it) }.toTypedArray(), GENERIC_PERM_HANDLER)
}
} else {
if (hasAllPermissions(permissionIds)) {
callback(true)
} else {
isAskingPermissions = true
actionOnPermission = callback
ActivityCompat.requestPermissions(this, permissionIds.map { getPermissionString(it) }.toTypedArray(), GENERIC_PERM_HANDLER)
}
}
}
fun handleNotificationPermission(callback: (granted: Boolean) -> Unit) {
if (!isTiramisuPlus()) {
callback(true)
} else {
handlePermission(PERMISSION_POST_NOTIFICATIONS) { granted ->
callback(granted)
}
}
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
isAskingPermissions = false
if (requestCode == GENERIC_PERM_HANDLER && grantResults.isNotEmpty()) {
actionOnPermission?.invoke(grantResults[0] == 0)
}
}
val copyMoveListener = object : CopyMoveListener {
override fun copySucceeded(copyOnly: Boolean, copiedAll: Boolean, destinationPath: String, wasCopyingOneFileOnly: Boolean) {
if (copyOnly) {
toast(
if (copiedAll) {
if (wasCopyingOneFileOnly) {
R.string.copying_success_one
} else {
R.string.copying_success
}
} else {
R.string.copying_success_partial
}
)
} else {
toast(
if (copiedAll) {
if (wasCopyingOneFileOnly) {
R.string.moving_success_one
} else {
R.string.moving_success
}
} else {
R.string.moving_success_partial
}
)
}
copyMoveCallback?.invoke(destinationPath)
copyMoveCallback = null
}
override fun copyFailed() {
toast(R.string.copy_move_failed)
copyMoveCallback = null
}
}
fun checkAppOnSDCard() {
if (!baseConfig.wasAppOnSDShown && isAppInstalledOnSDCard()) {
baseConfig.wasAppOnSDShown = true
ConfirmationDialog(this, "", R.string.app_on_sd_card, R.string.ok, 0) {}
}
}
fun exportSettings(configItems: LinkedHashMap<String, Any>) {
if (isQPlus()) {
configItemsToExport = configItems
ExportSettingsDialog(this, getExportSettingsFilename(), true) { path, filename ->
Intent(Intent.ACTION_CREATE_DOCUMENT).apply {
type = "text/plain"
putExtra(Intent.EXTRA_TITLE, filename)
addCategory(Intent.CATEGORY_OPENABLE)
try {
startActivityForResult(this, SELECT_EXPORT_SETTINGS_FILE_INTENT)
} catch (e: ActivityNotFoundException) {
toast(R.string.system_service_disabled, Toast.LENGTH_LONG)
} catch (e: Exception) {
showErrorToast(e)
}
}
}
} else {
handlePermission(PERMISSION_WRITE_STORAGE) {
if (it) {
ExportSettingsDialog(this, getExportSettingsFilename(), false) { path, filename ->
val file = File(path)
getFileOutputStream(file.toFileDirItem(this), true) {
exportSettingsTo(it, configItems)
}
}
}
}
}
}
private fun exportSettingsTo(outputStream: OutputStream?, configItems: LinkedHashMap<String, Any>) {
if (outputStream == null) {
toast(R.string.unknown_error_occurred)
return
}
ensureBackgroundThread {
outputStream.bufferedWriter().use { out ->
for ((key, value) in configItems) {
out.writeLn("$key=$value")
}
}
toast(R.string.settings_exported_successfully)
}
}
private fun getExportSettingsFilename(): String {
val appName = baseConfig.appId.removeSuffix(".debug").removeSuffix(".pro").removePrefix("com.simplemobiletools.")
return "$appName-settings_${getCurrentFormattedDateTime()}"
}
@SuppressLint("InlinedApi")
protected fun launchSetDefaultDialerIntent() {
if (isQPlus()) {
val roleManager = getSystemService(RoleManager::class.java)
if (roleManager!!.isRoleAvailable(RoleManager.ROLE_DIALER) && !roleManager.isRoleHeld(RoleManager.ROLE_DIALER)) {
val intent = roleManager.createRequestRoleIntent(RoleManager.ROLE_DIALER)
startActivityForResult(intent, REQUEST_CODE_SET_DEFAULT_DIALER)
}
} else {
Intent(TelecomManager.ACTION_CHANGE_DEFAULT_DIALER).putExtra(TelecomManager.EXTRA_CHANGE_DEFAULT_DIALER_PACKAGE_NAME, packageName).apply {
try {
startActivityForResult(this, REQUEST_CODE_SET_DEFAULT_DIALER)
} catch (e: ActivityNotFoundException) {
toast(R.string.no_app_found)
} catch (e: Exception) {
showErrorToast(e)
}
}
}
}
@RequiresApi(Build.VERSION_CODES.Q)
fun setDefaultCallerIdApp() {
val roleManager = getSystemService(RoleManager::class.java)
if (roleManager.isRoleAvailable(RoleManager.ROLE_CALL_SCREENING) && !roleManager.isRoleHeld(RoleManager.ROLE_CALL_SCREENING)) {
val intent = roleManager.createRequestRoleIntent(RoleManager.ROLE_CALL_SCREENING)
startActivityForResult(intent, REQUEST_CODE_SET_DEFAULT_CALLER_ID)
}
}
}
|
CT/commons/src/main/kotlin/com/simplemobiletools/commons/activities/ManageBlockedNumbersActivity.kt | 3596387979 | package com.simplemobiletools.commons.activities
import android.app.Activity
import android.app.Application
import android.content.ActivityNotFoundException
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.widget.Toast
import androidx.activity.compose.setContent
import androidx.activity.viewModels
import androidx.compose.runtime.*
import androidx.compose.ui.platform.LocalContext
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewModelScope
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.compose.alert_dialog.rememberAlertDialogState
import com.simplemobiletools.commons.compose.extensions.enableEdgeToEdgeSimple
import com.simplemobiletools.commons.compose.extensions.onEventValue
import com.simplemobiletools.commons.compose.screens.ManageBlockedNumbersScreen
import com.simplemobiletools.commons.compose.theme.AppThemeSurface
import com.simplemobiletools.commons.dialogs.AddOrEditBlockedNumberAlertDialog
import com.simplemobiletools.commons.dialogs.ExportBlockedNumbersDialog
import com.simplemobiletools.commons.dialogs.FilePickerDialog
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.*
import com.simplemobiletools.commons.models.BlockedNumber
import java.io.FileOutputStream
import java.io.OutputStream
import kotlinx.collections.immutable.ImmutableList
import kotlinx.collections.immutable.toImmutableList
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
class ManageBlockedNumbersActivity : BaseSimpleActivity() {
private val config by lazy {
baseConfig
}
private companion object {
private const val PICK_IMPORT_SOURCE_INTENT = 11
private const val PICK_EXPORT_FILE_INTENT = 21
}
override fun getAppIconIDs() = intent.getIntegerArrayListExtra(APP_ICON_IDS) ?: ArrayList()
override fun getAppLauncherName() = intent.getStringExtra(APP_LAUNCHER_NAME) ?: ""
private val manageBlockedNumbersViewModel by viewModels<ManageBlockedNumbersViewModel>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdgeSimple()
setContent {
val context = LocalContext.current
val blockedNumbers by manageBlockedNumbersViewModel.blockedNumbers.collectAsStateWithLifecycle()
LaunchedEffect(blockedNumbers) {
if (blockedNumbers?.any { blockedNumber -> blockedNumber.number.isBlockedNumberPattern() } == true) {
maybeSetDefaultCallerIdApp()
}
}
val isBlockingHiddenNumbers by config.isBlockingHiddenNumbers.collectAsStateWithLifecycle(initialValue = config.blockHiddenNumbers)
val isBlockingUnknownNumbers by config.isBlockingUnknownNumbers.collectAsStateWithLifecycle(initialValue = config.blockUnknownNumbers)
val isDialer = remember {
config.appId.startsWith("com.simplemobiletools.dialer")
}
val isDefaultDialer: Boolean = onEventValue {
context.isDefaultDialer()
}
AppThemeSurface {
var clickedBlockedNumber by remember { mutableStateOf<BlockedNumber?>(null) }
val addBlockedNumberDialogState = rememberAlertDialogState()
addBlockedNumberDialogState.DialogMember {
AddOrEditBlockedNumberAlertDialog(
alertDialogState = addBlockedNumberDialogState,
blockedNumber = clickedBlockedNumber,
deleteBlockedNumber = { blockedNumber ->
deleteBlockedNumber(blockedNumber)
updateBlockedNumbers()
}
) { blockedNumber ->
addBlockedNumber(blockedNumber)
clickedBlockedNumber = null
updateBlockedNumbers()
}
}
ManageBlockedNumbersScreen(
goBack = ::finish,
onAdd = {
clickedBlockedNumber = null
addBlockedNumberDialogState.show()
},
onImportBlockedNumbers = ::tryImportBlockedNumbers,
onExportBlockedNumbers = ::tryExportBlockedNumbers,
setAsDefault = ::maybeSetDefaultCallerIdApp,
isDialer = isDialer,
hasGivenPermissionToBlock = isDefaultDialer,
isBlockUnknownSelected = isBlockingUnknownNumbers,
onBlockUnknownSelectedChange = { isChecked ->
config.blockUnknownNumbers = isChecked
onCheckedSetCallerIdAsDefault(isChecked)
},
isHiddenSelected = isBlockingHiddenNumbers,
onHiddenSelectedChange = { isChecked ->
config.blockHiddenNumbers = isChecked
onCheckedSetCallerIdAsDefault(isChecked)
},
blockedNumbers = blockedNumbers,
onDelete = { selectedKeys ->
deleteBlockedNumbers(blockedNumbers, selectedKeys)
},
onEdit = { blockedNumber ->
clickedBlockedNumber = blockedNumber
addBlockedNumberDialogState.show()
},
onCopy = { blockedNumber ->
copyToClipboard(blockedNumber.number)
}
)
}
}
}
private fun deleteBlockedNumbers(
blockedNumbers: ImmutableList<BlockedNumber>?,
selectedKeys: Set<Long>
) {
if (blockedNumbers.isNullOrEmpty()) return
blockedNumbers.filter { blockedNumber -> selectedKeys.contains(blockedNumber.id) }
.forEach { blockedNumber ->
deleteBlockedNumber(blockedNumber.number)
}
manageBlockedNumbersViewModel.updateBlockedNumbers()
}
private fun tryImportBlockedNumbers() {
if (isQPlus()) {
Intent(Intent.ACTION_GET_CONTENT).apply {
addCategory(Intent.CATEGORY_OPENABLE)
type = "text/plain"
try {
startActivityForResult(this, PICK_IMPORT_SOURCE_INTENT)
} catch (e: ActivityNotFoundException) {
toast(R.string.system_service_disabled, Toast.LENGTH_LONG)
} catch (e: Exception) {
showErrorToast(e)
}
}
} else {
handlePermission(PERMISSION_READ_STORAGE) { isAllowed ->
if (isAllowed) {
pickFileToImportBlockedNumbers()
}
}
}
}
private fun pickFileToImportBlockedNumbers() {
FilePickerDialog(this) {
importBlockedNumbers(it)
}
}
private fun tryImportBlockedNumbersFromFile(uri: Uri) {
when (uri.scheme) {
"file" -> importBlockedNumbers(uri.path!!)
"content" -> {
val tempFile = getTempFile("blocked", "blocked_numbers.txt")
if (tempFile == null) {
toast(R.string.unknown_error_occurred)
return
}
try {
val inputStream = contentResolver.openInputStream(uri)
val out = FileOutputStream(tempFile)
inputStream!!.copyTo(out)
importBlockedNumbers(tempFile.absolutePath)
} catch (e: Exception) {
showErrorToast(e)
}
}
else -> toast(R.string.invalid_file_format)
}
}
private fun importBlockedNumbers(path: String) {
ensureBackgroundThread {
val result = BlockedNumbersImporter(this).importBlockedNumbers(path)
toast(
when (result) {
BlockedNumbersImporter.ImportResult.IMPORT_OK -> R.string.importing_successful
BlockedNumbersImporter.ImportResult.IMPORT_FAIL -> R.string.no_items_found
}
)
updateBlockedNumbers()
}
}
private fun updateBlockedNumbers() {
manageBlockedNumbersViewModel.updateBlockedNumbers()
}
private fun onCheckedSetCallerIdAsDefault(isChecked: Boolean) {
if (isChecked) {
maybeSetDefaultCallerIdApp()
}
}
private fun maybeSetDefaultCallerIdApp() {
if (isQPlus() && baseConfig.appId.startsWith("com.simplemobiletools.dialer")) {
setDefaultCallerIdApp()
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, resultData: Intent?) {
super.onActivityResult(requestCode, resultCode, resultData)
when {
requestCode == REQUEST_CODE_SET_DEFAULT_DIALER && isDefaultDialer() -> {
updateBlockedNumbers()
}
requestCode == PICK_IMPORT_SOURCE_INTENT && resultCode == Activity.RESULT_OK && resultData != null && resultData.data != null -> {
tryImportBlockedNumbersFromFile(resultData.data!!)
}
requestCode == PICK_EXPORT_FILE_INTENT && resultCode == Activity.RESULT_OK && resultData != null && resultData.data != null -> {
val outputStream = contentResolver.openOutputStream(resultData.data!!)
exportBlockedNumbersTo(outputStream)
}
requestCode == REQUEST_CODE_SET_DEFAULT_CALLER_ID && resultCode != Activity.RESULT_OK -> {
toast(R.string.must_make_default_caller_id_app, length = Toast.LENGTH_LONG)
baseConfig.blockUnknownNumbers = false
baseConfig.blockHiddenNumbers = false
}
}
}
private fun exportBlockedNumbersTo(outputStream: OutputStream?) {
ensureBackgroundThread {
val blockedNumbers = getBlockedNumbers()
if (blockedNumbers.isEmpty()) {
toast(R.string.no_entries_for_exporting)
} else {
BlockedNumbersExporter.exportBlockedNumbers(blockedNumbers, outputStream) {
toast(
when (it) {
ExportResult.EXPORT_OK -> R.string.exporting_successful
else -> R.string.exporting_failed
}
)
}
}
}
}
private fun tryExportBlockedNumbers() {
if (isQPlus()) {
ExportBlockedNumbersDialog(this, baseConfig.lastBlockedNumbersExportPath, true) { file ->
Intent(Intent.ACTION_CREATE_DOCUMENT).apply {
type = "text/plain"
putExtra(Intent.EXTRA_TITLE, file.name)
addCategory(Intent.CATEGORY_OPENABLE)
try {
startActivityForResult(this, PICK_EXPORT_FILE_INTENT)
} catch (e: ActivityNotFoundException) {
toast(R.string.system_service_disabled, Toast.LENGTH_LONG)
} catch (e: Exception) {
showErrorToast(e)
}
}
}
} else {
handlePermission(PERMISSION_WRITE_STORAGE) { isAllowed ->
if (isAllowed) {
ExportBlockedNumbersDialog(this, baseConfig.lastBlockedNumbersExportPath, false) { file ->
getFileOutputStream(file.toFileDirItem(this), true) { out ->
exportBlockedNumbersTo(out)
}
}
}
}
}
}
internal class ManageBlockedNumbersViewModel(
private val application: Application
) : AndroidViewModel(application) {
private val _blockedNumbers: MutableStateFlow<ImmutableList<BlockedNumber>?> = MutableStateFlow(null)
val blockedNumbers = _blockedNumbers.asStateFlow()
init {
updateBlockedNumbers()
}
fun updateBlockedNumbers() {
viewModelScope.launch {
withContext(Dispatchers.IO) {
application.getBlockedNumbersWithContact { list ->
_blockedNumbers.update { list.toImmutableList() }
}
}
}
}
}
}
|
CT/commons/src/main/kotlin/com/simplemobiletools/commons/activities/ContributorsActivity.kt | 412356904 | package com.simplemobiletools.commons.activities
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.runtime.remember
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.compose.extensions.enableEdgeToEdgeSimple
import com.simplemobiletools.commons.compose.screens.ContributorsScreen
import com.simplemobiletools.commons.compose.theme.AppThemeSurface
import com.simplemobiletools.commons.models.LanguageContributor
import kotlinx.collections.immutable.toImmutableList
class ContributorsActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdgeSimple()
setContent {
AppThemeSurface {
val contributors = remember {
languageContributors()
}
val showContributorsLabel = remember {
!resources.getBoolean(R.bool.hide_all_external_links)
}
ContributorsScreen(
goBack = ::finish,
showContributorsLabel = showContributorsLabel,
contributors = contributors,
)
}
}
}
private fun languageContributors() = listOf(
LanguageContributor(R.drawable.ic_flag_arabic_vector, R.string.translation_arabic, R.string.translators_arabic),
LanguageContributor(R.drawable.ic_flag_azerbaijani_vector, R.string.translation_azerbaijani, R.string.translators_azerbaijani),
LanguageContributor(R.drawable.ic_flag_bengali_vector, R.string.translation_bengali, R.string.translators_bengali),
LanguageContributor(R.drawable.ic_flag_catalan_vector, R.string.translation_catalan, R.string.translators_catalan),
LanguageContributor(R.drawable.ic_flag_czech_vector, R.string.translation_czech, R.string.translators_czech),
LanguageContributor(R.drawable.ic_flag_welsh_vector, R.string.translation_welsh, R.string.translators_welsh),
LanguageContributor(R.drawable.ic_flag_danish_vector, R.string.translation_danish, R.string.translators_danish),
LanguageContributor(R.drawable.ic_flag_german_vector, R.string.translation_german, R.string.translators_german),
LanguageContributor(R.drawable.ic_flag_greek_vector, R.string.translation_greek, R.string.translators_greek),
LanguageContributor(R.drawable.ic_flag_spanish_vector, R.string.translation_spanish, R.string.translators_spanish),
LanguageContributor(R.drawable.ic_flag_basque_vector, R.string.translation_basque, R.string.translators_basque),
LanguageContributor(R.drawable.ic_flag_persian_vector, R.string.translation_persian, R.string.translators_persian),
LanguageContributor(R.drawable.ic_flag_finnish_vector, R.string.translation_finnish, R.string.translators_finnish),
LanguageContributor(R.drawable.ic_flag_french_vector, R.string.translation_french, R.string.translators_french),
LanguageContributor(R.drawable.ic_flag_galician_vector, R.string.translation_galician, R.string.translators_galician),
LanguageContributor(R.drawable.ic_flag_hindi_vector, R.string.translation_hindi, R.string.translators_hindi),
LanguageContributor(R.drawable.ic_flag_croatian_vector, R.string.translation_croatian, R.string.translators_croatian),
LanguageContributor(R.drawable.ic_flag_hungarian_vector, R.string.translation_hungarian, R.string.translators_hungarian),
LanguageContributor(R.drawable.ic_flag_indonesian_vector, R.string.translation_indonesian, R.string.translators_indonesian),
LanguageContributor(R.drawable.ic_flag_italian_vector, R.string.translation_italian, R.string.translators_italian),
LanguageContributor(R.drawable.ic_flag_hebrew_vector, R.string.translation_hebrew, R.string.translators_hebrew),
LanguageContributor(R.drawable.ic_flag_japanese_vector, R.string.translation_japanese, R.string.translators_japanese),
LanguageContributor(R.drawable.ic_flag_korean_vector, R.string.translation_korean, R.string.translators_korean),
LanguageContributor(R.drawable.ic_flag_lithuanian_vector, R.string.translation_lithuanian, R.string.translators_lithuanian),
LanguageContributor(R.drawable.ic_flag_nepali_vector, R.string.translation_nepali, R.string.translators_nepali),
LanguageContributor(R.drawable.ic_flag_norwegian_vector, R.string.translation_norwegian, R.string.translators_norwegian),
LanguageContributor(R.drawable.ic_flag_dutch_vector, R.string.translation_dutch, R.string.translators_dutch),
LanguageContributor(R.drawable.ic_flag_polish_vector, R.string.translation_polish, R.string.translators_polish),
LanguageContributor(R.drawable.ic_flag_portuguese_vector, R.string.translation_portuguese, R.string.translators_portuguese),
LanguageContributor(R.drawable.ic_flag_romanian_vector, R.string.translation_romanian, R.string.translators_romanian),
LanguageContributor(R.drawable.ic_flag_russian_vector, R.string.translation_russian, R.string.translators_russian),
LanguageContributor(R.drawable.ic_flag_slovak_vector, R.string.translation_slovak, R.string.translators_slovak),
LanguageContributor(R.drawable.ic_flag_slovenian_vector, R.string.translation_slovenian, R.string.translators_slovenian),
LanguageContributor(R.drawable.ic_flag_swedish_vector, R.string.translation_swedish, R.string.translators_swedish),
LanguageContributor(R.drawable.ic_flag_tamil_vector, R.string.translation_tamil, R.string.translators_tamil),
LanguageContributor(R.drawable.ic_flag_turkish_vector, R.string.translation_turkish, R.string.translators_turkish),
LanguageContributor(R.drawable.ic_flag_ukrainian_vector, R.string.translation_ukrainian, R.string.translators_ukrainian),
LanguageContributor(R.drawable.ic_flag_chinese_hk_vector, R.string.translation_chinese_hk, R.string.translators_chinese_hk),
LanguageContributor(R.drawable.ic_flag_chinese_cn_vector, R.string.translation_chinese_cn, R.string.translators_chinese_cn),
LanguageContributor(R.drawable.ic_flag_chinese_tw_vector, R.string.translation_chinese_tw, R.string.translators_chinese_tw)
).toImmutableList()
}
|
CT/commons/src/main/kotlin/com/simplemobiletools/commons/activities/AboutActivity.kt | 344756980 | package com.simplemobiletools.commons.activities
import android.content.ActivityNotFoundException
import android.content.Intent
import android.content.Intent.*
import android.content.res.Resources
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.platform.LocalContext
import androidx.core.net.toUri
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.compose.alert_dialog.rememberAlertDialogState
import com.simplemobiletools.commons.compose.extensions.enableEdgeToEdgeSimple
import com.simplemobiletools.commons.compose.extensions.rateStarsRedirectAndThankYou
import com.simplemobiletools.commons.compose.screens.*
import com.simplemobiletools.commons.compose.theme.AppThemeSurface
import com.simplemobiletools.commons.dialogs.ConfirmationAdvancedAlertDialog
import com.simplemobiletools.commons.dialogs.RateStarsAlertDialog
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.*
import com.simplemobiletools.commons.models.FAQItem
class AboutActivity : ComponentActivity() {
private val appName get() = intent.getStringExtra(APP_NAME) ?: ""
private var firstVersionClickTS = 0L
private var clicksSinceFirstClick = 0
companion object {
private const val EASTER_EGG_TIME_LIMIT = 3000L
private const val EASTER_EGG_REQUIRED_CLICKS = 7
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdgeSimple()
setContent {
val context = LocalContext.current
val resources = context.resources
AppThemeSurface {
val showExternalLinks = remember { !resources.getBoolean(R.bool.hide_all_external_links) }
val showGoogleRelations = remember { !resources.getBoolean(R.bool.hide_google_relations) }
val onEmailClickAlertDialogState = getOnEmailClickAlertDialogState()
val rateStarsAlertDialogState = getRateStarsAlertDialogState()
val onRateUsClickAlertDialogState = getOnRateUsClickAlertDialogState(rateStarsAlertDialogState::show)
AboutScreen(
goBack = ::finish,
helpUsSection = {
val showHelpUsSection =
remember { showGoogleRelations || !showExternalLinks }
HelpUsSection(
onRateUsClick = {
onRateUsClick(
showConfirmationAdvancedDialog = onRateUsClickAlertDialogState::show,
showRateStarsDialog = rateStarsAlertDialogState::show
)
},
onInviteClick = ::onInviteClick,
onContributorsClick = ::onContributorsClick,
showDonate = resources.getBoolean(R.bool.show_donate_in_about) && showExternalLinks,
onDonateClick = ::onDonateClick,
showInvite = showHelpUsSection,
showRateUs = showHelpUsSection
)
},
aboutSection = {
val setupFAQ = rememberFAQ()
if (!showExternalLinks || setupFAQ) {
AboutSection(setupFAQ = setupFAQ, onFAQClick = ::launchFAQActivity, onEmailClick = {
onEmailClick(onEmailClickAlertDialogState::show)
})
}
},
socialSection = {
if (showExternalLinks) {
SocialSection(
onFacebookClick = ::onFacebookClick,
onGithubClick = ::onGithubClick,
onRedditClick = ::onRedditClick,
onTelegramClick = ::onTelegramClick
)
}
}
) {
val (showWebsite, fullVersion) = showWebsiteAndFullVersion(resources, showExternalLinks)
OtherSection(
showMoreApps = showGoogleRelations,
onMoreAppsClick = ::launchMoreAppsFromUsIntent,
showWebsite = showWebsite,
onWebsiteClick = ::onWebsiteClick,
showPrivacyPolicy = showExternalLinks,
onPrivacyPolicyClick = ::onPrivacyPolicyClick,
onLicenseClick = ::onLicenseClick,
version = fullVersion,
onVersionClick = ::onVersionClick
)
}
}
}
}
@Composable
private fun rememberFAQ() = remember { !(intent.getSerializableExtra(APP_FAQ) as? ArrayList<FAQItem>).isNullOrEmpty() }
@Composable
private fun showWebsiteAndFullVersion(
resources: Resources,
showExternalLinks: Boolean
): Pair<Boolean, String> {
val showWebsite = remember { resources.getBoolean(R.bool.show_donate_in_about) && !showExternalLinks }
var version = intent.getStringExtra(APP_VERSION_NAME) ?: ""
if (baseConfig.appId.removeSuffix(".debug").endsWith(".pro")) {
version += " ${getString(R.string.pro)}"
}
val fullVersion = remember { String.format(getString(R.string.version_placeholder, version)) }
return Pair(showWebsite, fullVersion)
}
@Composable
private fun getRateStarsAlertDialogState() =
rememberAlertDialogState().apply {
DialogMember {
RateStarsAlertDialog(alertDialogState = this, onRating = ::rateStarsRedirectAndThankYou)
}
}
@Composable
private fun getOnEmailClickAlertDialogState() =
rememberAlertDialogState().apply {
DialogMember {
ConfirmationAdvancedAlertDialog(
alertDialogState = this,
message = "${getString(R.string.before_asking_question_read_faq)}\n\n${getString(R.string.make_sure_latest)}",
messageId = null,
positive = R.string.read_faq,
negative = R.string.skip
) { success ->
if (success) {
launchFAQActivity()
} else {
launchEmailIntent()
}
}
}
}
@Composable
private fun getOnRateUsClickAlertDialogState(showRateStarsDialog: () -> Unit) =
rememberAlertDialogState().apply {
DialogMember {
ConfirmationAdvancedAlertDialog(
alertDialogState = this,
message = "${getString(R.string.before_asking_question_read_faq)}\n\n${getString(R.string.make_sure_latest)}",
messageId = null,
positive = R.string.read_faq,
negative = R.string.skip
) { success ->
if (success) {
launchFAQActivity()
} else {
launchRateUsPrompt(showRateStarsDialog)
}
}
}
}
private fun onEmailClick(
showConfirmationAdvancedDialog: () -> Unit
) {
if (intent.getBooleanExtra(SHOW_FAQ_BEFORE_MAIL, false) && !baseConfig.wasBeforeAskingShown) {
baseConfig.wasBeforeAskingShown = true
showConfirmationAdvancedDialog()
} else {
launchEmailIntent()
}
}
private fun launchFAQActivity() {
val faqItems = intent.getSerializableExtra(APP_FAQ) as ArrayList<FAQItem>
Intent(applicationContext, FAQActivity::class.java).apply {
putExtra(APP_ICON_IDS, intent.getIntegerArrayListExtra(APP_ICON_IDS) ?: ArrayList<String>())
putExtra(APP_LAUNCHER_NAME, intent.getStringExtra(APP_LAUNCHER_NAME) ?: "")
putExtra(APP_FAQ, faqItems)
startActivity(this)
}
}
private fun launchEmailIntent() {
val appVersion = String.format(getString(R.string.app_version, intent.getStringExtra(APP_VERSION_NAME)))
val deviceOS = String.format(getString(R.string.device_os), Build.VERSION.RELEASE)
val newline = "\n"
val separator = "------------------------------"
val body = "$appVersion$newline$deviceOS$newline$separator$newline$newline"
val address = if (packageName.startsWith("com.simplemobiletools")) {
getString(R.string.my_email)
} else {
getString(R.string.my_fake_email)
}
val selectorIntent = Intent(ACTION_SENDTO)
.setData("mailto:$address".toUri())
val emailIntent = Intent(ACTION_SEND).apply {
putExtra(EXTRA_EMAIL, arrayOf(address))
putExtra(EXTRA_SUBJECT, appName)
putExtra(EXTRA_TEXT, body)
selector = selectorIntent
}
try {
startActivity(emailIntent)
} catch (e: ActivityNotFoundException) {
val chooser = createChooser(emailIntent, getString(R.string.send_email))
try {
startActivity(chooser)
} catch (e: Exception) {
toast(R.string.no_email_client_found)
}
} catch (e: Exception) {
showErrorToast(e)
}
}
private fun onRateUsClick(
showConfirmationAdvancedDialog: () -> Unit,
showRateStarsDialog: () -> Unit
) {
if (baseConfig.wasBeforeRateShown) {
launchRateUsPrompt(showRateStarsDialog)
} else {
baseConfig.wasBeforeRateShown = true
showConfirmationAdvancedDialog()
}
}
private fun launchRateUsPrompt(
showRateStarsDialog: () -> Unit
) {
if (baseConfig.wasAppRated) {
redirectToRateUs()
} else {
showRateStarsDialog()
}
}
private fun onInviteClick() {
val text = String.format(getString(R.string.share_text), appName, getStoreUrl())
Intent().apply {
action = ACTION_SEND
putExtra(EXTRA_SUBJECT, appName)
putExtra(EXTRA_TEXT, text)
type = "text/plain"
startActivity(createChooser(this, getString(R.string.invite_via)))
}
}
private fun onContributorsClick() {
val intent = Intent(applicationContext, ContributorsActivity::class.java)
startActivity(intent)
}
private fun onDonateClick() {
launchViewIntent(getString(R.string.donate_url))
}
private fun onFacebookClick() {
var link = "https://www.facebook.com/simplemobiletools"
try {
packageManager.getPackageInfo("com.facebook.katana", 0)
link = "fb://page/150270895341774"
} catch (ignored: Exception) {
}
launchViewIntent(link)
}
private fun onGithubClick() {
launchViewIntent("https://github.com/SimpleMobileTools")
}
private fun onRedditClick() {
launchViewIntent("https://www.reddit.com/r/SimpleMobileTools")
}
private fun onTelegramClick() {
launchViewIntent("https://t.me/SimpleMobileTools")
}
private fun onWebsiteClick() {
launchViewIntent("https://simplemobiletools.com/")
}
private fun onPrivacyPolicyClick() {
val appId = baseConfig.appId.removeSuffix(".debug").removeSuffix(".pro").removePrefix("com.simplemobiletools.")
val url = "https://simplemobiletools.com/privacy/$appId.txt"
launchViewIntent(url)
}
private fun onLicenseClick() {
Intent(applicationContext, LicenseActivity::class.java).apply {
putExtra(APP_ICON_IDS, intent.getIntegerArrayListExtra(APP_ICON_IDS) ?: ArrayList<String>())
putExtra(APP_LAUNCHER_NAME, intent.getStringExtra(APP_LAUNCHER_NAME) ?: "")
putExtra(APP_LICENSES, intent.getLongExtra(APP_LICENSES, 0))
startActivity(this)
}
}
private fun onVersionClick() {
if (firstVersionClickTS == 0L) {
firstVersionClickTS = System.currentTimeMillis()
Handler(Looper.getMainLooper()).postDelayed({
firstVersionClickTS = 0L
clicksSinceFirstClick = 0
}, EASTER_EGG_TIME_LIMIT)
}
clicksSinceFirstClick++
if (clicksSinceFirstClick >= EASTER_EGG_REQUIRED_CLICKS) {
toast(R.string.hello)
firstVersionClickTS = 0L
clicksSinceFirstClick = 0
}
}
}
|
CT/commons/src/main/kotlin/com/simplemobiletools/commons/activities/LicenseActivity.kt | 4132677898 | package com.simplemobiletools.commons.activities
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.compose.extensions.enableEdgeToEdgeSimple
import com.simplemobiletools.commons.compose.screens.LicenseScreen
import com.simplemobiletools.commons.compose.theme.AppThemeSurface
import com.simplemobiletools.commons.extensions.launchViewIntent
import com.simplemobiletools.commons.helpers.*
import com.simplemobiletools.commons.models.License
import kotlinx.collections.immutable.toImmutableList
class LicenseActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdgeSimple()
setContent {
val licenseMask = remember { intent.getLongExtra(APP_LICENSES, 0) or LICENSE_KOTLIN }
val thirdPartyLicenses by remember { derivedStateOf { initLicenses().filter { licenseMask and it.id != 0L }.toImmutableList() } }
AppThemeSurface {
LicenseScreen(
goBack = ::finish,
thirdPartyLicenses = thirdPartyLicenses,
onLicenseClick = ::launchViewIntent
)
}
}
}
private fun initLicenses() = listOf(
License(LICENSE_KOTLIN, R.string.kotlin_title, R.string.kotlin_text, R.string.kotlin_url),
License(LICENSE_SUBSAMPLING, R.string.subsampling_title, R.string.subsampling_text, R.string.subsampling_url),
License(LICENSE_GLIDE, R.string.glide_title, R.string.glide_text, R.string.glide_url),
License(LICENSE_CROPPER, R.string.cropper_title, R.string.cropper_text, R.string.cropper_url),
License(LICENSE_RTL, R.string.rtl_viewpager_title, R.string.rtl_viewpager_text, R.string.rtl_viewpager_url),
License(LICENSE_JODA, R.string.joda_title, R.string.joda_text, R.string.joda_url),
License(LICENSE_STETHO, R.string.stetho_title, R.string.stetho_text, R.string.stetho_url),
License(LICENSE_OTTO, R.string.otto_title, R.string.otto_text, R.string.otto_url),
License(LICENSE_PHOTOVIEW, R.string.photoview_title, R.string.photoview_text, R.string.photoview_url),
License(LICENSE_PICASSO, R.string.picasso_title, R.string.picasso_text, R.string.picasso_url),
License(LICENSE_PATTERN, R.string.pattern_title, R.string.pattern_text, R.string.pattern_url),
License(LICENSE_REPRINT, R.string.reprint_title, R.string.reprint_text, R.string.reprint_url),
License(LICENSE_GIF_DRAWABLE, R.string.gif_drawable_title, R.string.gif_drawable_text, R.string.gif_drawable_url),
License(LICENSE_AUTOFITTEXTVIEW, R.string.autofittextview_title, R.string.autofittextview_text, R.string.autofittextview_url),
License(LICENSE_ROBOLECTRIC, R.string.robolectric_title, R.string.robolectric_text, R.string.robolectric_url),
License(LICENSE_ESPRESSO, R.string.espresso_title, R.string.espresso_text, R.string.espresso_url),
License(LICENSE_GSON, R.string.gson_title, R.string.gson_text, R.string.gson_url),
License(LICENSE_LEAK_CANARY, R.string.leak_canary_title, R.string.leakcanary_text, R.string.leakcanary_url),
License(LICENSE_NUMBER_PICKER, R.string.number_picker_title, R.string.number_picker_text, R.string.number_picker_url),
License(LICENSE_EXOPLAYER, R.string.exoplayer_title, R.string.exoplayer_text, R.string.exoplayer_url),
License(LICENSE_PANORAMA_VIEW, R.string.panorama_view_title, R.string.panorama_view_text, R.string.panorama_view_url),
License(LICENSE_SANSELAN, R.string.sanselan_title, R.string.sanselan_text, R.string.sanselan_url),
License(LICENSE_FILTERS, R.string.filters_title, R.string.filters_text, R.string.filters_url),
License(LICENSE_GESTURE_VIEWS, R.string.gesture_views_title, R.string.gesture_views_text, R.string.gesture_views_url),
License(LICENSE_INDICATOR_FAST_SCROLL, R.string.indicator_fast_scroll_title, R.string.indicator_fast_scroll_text, R.string.indicator_fast_scroll_url),
License(LICENSE_EVENT_BUS, R.string.event_bus_title, R.string.event_bus_text, R.string.event_bus_url),
License(LICENSE_AUDIO_RECORD_VIEW, R.string.audio_record_view_title, R.string.audio_record_view_text, R.string.audio_record_view_url),
License(LICENSE_SMS_MMS, R.string.sms_mms_title, R.string.sms_mms_text, R.string.sms_mms_url),
License(LICENSE_APNG, R.string.apng_title, R.string.apng_text, R.string.apng_url),
License(LICENSE_PDF_VIEW_PAGER, R.string.pdf_view_pager_title, R.string.pdf_view_pager_text, R.string.pdf_view_pager_url),
License(LICENSE_M3U_PARSER, R.string.m3u_parser_title, R.string.m3u_parser_text, R.string.m3u_parser_url),
License(LICENSE_ANDROID_LAME, R.string.android_lame_title, R.string.android_lame_text, R.string.android_lame_url),
License(LICENSE_PDF_VIEWER, R.string.pdf_viewer_title, R.string.pdf_viewer_text, R.string.pdf_viewer_url),
License(LICENSE_ZIP4J, R.string.zip4j_title, R.string.zip4j_text, R.string.zip4j_url)
)
}
|
CT/commons/src/main/kotlin/com/simplemobiletools/commons/activities/FAQActivity.kt | 805932126 | package com.simplemobiletools.commons.activities
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.runtime.remember
import com.simplemobiletools.commons.compose.extensions.enableEdgeToEdgeSimple
import com.simplemobiletools.commons.compose.screens.FAQScreen
import com.simplemobiletools.commons.compose.theme.AppThemeSurface
import com.simplemobiletools.commons.helpers.APP_FAQ
import com.simplemobiletools.commons.models.FAQItem
import kotlinx.collections.immutable.toImmutableList
class FAQActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdgeSimple()
setContent {
AppThemeSurface {
val faqItems = remember { intent.getSerializableExtra(APP_FAQ) as ArrayList<FAQItem> }
FAQScreen(
goBack = ::finish,
faqItems = faqItems.toImmutableList()
)
}
}
}
}
|
CT/commons/src/main/kotlin/com/simplemobiletools/commons/activities/BaseSplashActivity.kt | 1941986764 | package com.simplemobiletools.commons.activities
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.SIDELOADING_TRUE
import com.simplemobiletools.commons.helpers.SIDELOADING_UNCHECKED
abstract class BaseSplashActivity : AppCompatActivity() {
abstract fun initActivity()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (baseConfig.appSideloadingStatus == SIDELOADING_UNCHECKED) {
if (checkAppSideloading()) {
return
}
} else if (baseConfig.appSideloadingStatus == SIDELOADING_TRUE) {
showSideloadingDialog()
return
}
baseConfig.apply {
if (isUsingAutoTheme) {
val isUsingSystemDarkTheme = isUsingSystemDarkTheme()
isUsingSharedTheme = false
textColor = resources.getColor(if (isUsingSystemDarkTheme) R.color.theme_dark_text_color else R.color.theme_light_text_color)
backgroundColor = resources.getColor(if (isUsingSystemDarkTheme) R.color.theme_dark_background_color else R.color.theme_light_background_color)
}
}
if (!baseConfig.isUsingAutoTheme && !baseConfig.isUsingSystemTheme && isThankYouInstalled()) {
getSharedTheme {
if (it != null) {
baseConfig.apply {
wasSharedThemeForced = true
isUsingSharedTheme = true
wasSharedThemeEverActivated = true
textColor = it.textColor
backgroundColor = it.backgroundColor
primaryColor = it.primaryColor
accentColor = it.accentColor
}
if (baseConfig.appIconColor != it.appIconColor) {
baseConfig.appIconColor = it.appIconColor
checkAppIconColor()
}
}
initActivity()
}
} else {
initActivity()
}
}
}
|
CT/commons/src/main/kotlin/com/simplemobiletools/commons/activities/CustomizationActivity.kt | 596158304 | package com.simplemobiletools.commons.activities
import android.content.Intent
import android.graphics.Color
import android.graphics.drawable.LayerDrawable
import android.graphics.drawable.RippleDrawable
import android.os.Bundle
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.databinding.ActivityCustomizationBinding
import com.simplemobiletools.commons.dialogs.*
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.*
import com.simplemobiletools.commons.models.MyTheme
import com.simplemobiletools.commons.models.RadioItem
import com.simplemobiletools.commons.models.SharedTheme
class CustomizationActivity : BaseSimpleActivity() {
private val THEME_LIGHT = 0
private val THEME_DARK = 1
private val THEME_SOLARIZED = 2
private val THEME_DARK_RED = 3
private val THEME_BLACK_WHITE = 4
private val THEME_CUSTOM = 5
private val THEME_SHARED = 6
private val THEME_WHITE = 7
private val THEME_AUTO = 8
private val THEME_SYSTEM = 9 // Material You
private var curTextColor = 0
private var curBackgroundColor = 0
private var curPrimaryColor = 0
private var curAccentColor = 0
private var curAppIconColor = 0
private var curSelectedThemeId = 0
private var originalAppIconColor = 0
private var lastSavePromptTS = 0L
private var hasUnsavedChanges = false
private var isThankYou = false // show "Apply colors to all Simple apps" in Simple Thank You itself even with "Hide Google relations" enabled
private var predefinedThemes = LinkedHashMap<Int, MyTheme>()
private var curPrimaryLineColorPicker: LineColorPickerDialog? = null
private var storedSharedTheme: SharedTheme? = null
override fun getAppIconIDs() = intent.getIntegerArrayListExtra(APP_ICON_IDS) ?: ArrayList()
override fun getAppLauncherName() = intent.getStringExtra(APP_LAUNCHER_NAME) ?: ""
private val binding by viewBinding(ActivityCustomizationBinding::inflate)
override fun onCreate(savedInstanceState: Bundle?) {
isMaterialActivity = true
super.onCreate(savedInstanceState)
setContentView(binding.root)
setupOptionsMenu()
refreshMenuItems()
updateMaterialActivityViews(binding.customizationCoordinator, binding.customizationHolder, useTransparentNavigation = true, useTopSearchMenu = false)
isThankYou = packageName.removeSuffix(".debug") == "com.simplemobiletools.thankyou"
initColorVariables()
if (isThankYouInstalled()) {
val cursorLoader = getMyContentProviderCursorLoader()
ensureBackgroundThread {
try {
storedSharedTheme = getSharedThemeSync(cursorLoader)
if (storedSharedTheme == null) {
baseConfig.isUsingSharedTheme = false
} else {
baseConfig.wasSharedThemeEverActivated = true
}
runOnUiThread {
setupThemes()
val hideGoogleRelations = resources.getBoolean(R.bool.hide_google_relations) && !isThankYou
binding.applyToAllHolder.beVisibleIf(
storedSharedTheme == null && curSelectedThemeId != THEME_AUTO && curSelectedThemeId != THEME_SYSTEM && !hideGoogleRelations
)
}
} catch (e: Exception) {
toast(R.string.update_thank_you)
finish()
}
}
} else {
setupThemes()
baseConfig.isUsingSharedTheme = false
}
val textColor = if (baseConfig.isUsingSystemTheme) {
getProperTextColor()
} else {
baseConfig.textColor
}
updateLabelColors(textColor)
originalAppIconColor = baseConfig.appIconColor
if (resources.getBoolean(R.bool.hide_google_relations) && !isThankYou) {
binding.applyToAllHolder.beGone()
}
}
override fun onResume() {
super.onResume()
setTheme(getThemeId(getCurrentPrimaryColor()))
if (!baseConfig.isUsingSystemTheme) {
updateBackgroundColor(getCurrentBackgroundColor())
updateActionbarColor(getCurrentStatusBarColor())
}
curPrimaryLineColorPicker?.getSpecificColor()?.apply {
updateActionbarColor(this)
setTheme(getThemeId(this))
}
setupToolbar(binding.customizationToolbar, NavigationIcon.Cross, getColoredMaterialStatusBarColor())
}
private fun refreshMenuItems() {
binding.customizationToolbar.menu.findItem(R.id.save).isVisible = hasUnsavedChanges
}
private fun setupOptionsMenu() {
binding.customizationToolbar.setOnMenuItemClickListener { menuItem ->
when (menuItem.itemId) {
R.id.save -> {
saveChanges(true)
true
}
else -> false
}
}
}
override fun onBackPressed() {
if (hasUnsavedChanges && System.currentTimeMillis() - lastSavePromptTS > SAVE_DISCARD_PROMPT_INTERVAL) {
promptSaveDiscard()
} else {
super.onBackPressed()
}
}
private fun setupThemes() {
predefinedThemes.apply {
if (isSPlus()) {
put(THEME_SYSTEM, getSystemThemeColors())
}
put(THEME_AUTO, getAutoThemeColors())
put(
THEME_LIGHT,
MyTheme(
getString(R.string.light_theme),
R.color.theme_light_text_color,
R.color.theme_light_background_color,
R.color.color_primary,
R.color.color_primary
)
)
put(
THEME_DARK,
MyTheme(
getString(R.string.dark_theme),
R.color.theme_dark_text_color,
R.color.theme_dark_background_color,
R.color.color_primary,
R.color.color_primary
)
)
put(
THEME_DARK_RED,
MyTheme(
getString(R.string.dark_red),
R.color.theme_dark_text_color,
R.color.theme_dark_background_color,
R.color.theme_dark_red_primary_color,
R.color.md_red_700
)
)
put(THEME_WHITE, MyTheme(getString(R.string.white), R.color.dark_grey, android.R.color.white, android.R.color.white, R.color.color_primary))
put(
THEME_BLACK_WHITE,
MyTheme(getString(R.string.black_white), android.R.color.white, android.R.color.black, android.R.color.black, R.color.md_grey_black)
)
put(THEME_CUSTOM, MyTheme(getString(R.string.custom), 0, 0, 0, 0))
if (storedSharedTheme != null) {
put(THEME_SHARED, MyTheme(getString(R.string.shared), 0, 0, 0, 0))
}
}
setupThemePicker()
setupColorsPickers()
}
private fun setupThemePicker() {
curSelectedThemeId = getCurrentThemeId()
binding.customizationTheme.text = getThemeText()
updateAutoThemeFields()
handleAccentColorLayout()
binding.customizationThemeHolder.setOnClickListener {
if (baseConfig.wasAppIconCustomizationWarningShown) {
themePickerClicked()
} else {
ConfirmationDialog(this, "", R.string.app_icon_color_warning, R.string.ok, 0) {
baseConfig.wasAppIconCustomizationWarningShown = true
themePickerClicked()
}
}
}
if (binding.customizationTheme.value == getMaterialYouString()) {
binding.applyToAllHolder.beGone()
}
}
private fun themePickerClicked() {
val items = arrayListOf<RadioItem>()
for ((key, value) in predefinedThemes) {
items.add(RadioItem(key, value.label))
}
RadioGroupDialog(this@CustomizationActivity, items, curSelectedThemeId) {
if (it == THEME_SHARED && !isThankYouInstalled()) {
PurchaseThankYouDialog(this)
return@RadioGroupDialog
}
updateColorTheme(it as Int, true)
if (it != THEME_CUSTOM && it != THEME_SHARED && it != THEME_AUTO && it != THEME_SYSTEM && !baseConfig.wasCustomThemeSwitchDescriptionShown) {
baseConfig.wasCustomThemeSwitchDescriptionShown = true
toast(R.string.changing_color_description)
}
val hideGoogleRelations = resources.getBoolean(R.bool.hide_google_relations) && !isThankYou
binding.applyToAllHolder.beVisibleIf(
curSelectedThemeId != THEME_AUTO && curSelectedThemeId != THEME_SYSTEM && curSelectedThemeId != THEME_SHARED && !hideGoogleRelations
)
updateMenuItemColors(binding.customizationToolbar.menu, getCurrentStatusBarColor())
setupToolbar(binding.customizationToolbar, NavigationIcon.Cross, getCurrentStatusBarColor())
}
}
private fun updateColorTheme(themeId: Int, useStored: Boolean = false) {
curSelectedThemeId = themeId
binding.customizationTheme.text = getThemeText()
resources.apply {
if (curSelectedThemeId == THEME_CUSTOM) {
if (useStored) {
curTextColor = baseConfig.customTextColor
curBackgroundColor = baseConfig.customBackgroundColor
curPrimaryColor = baseConfig.customPrimaryColor
curAccentColor = baseConfig.customAccentColor
curAppIconColor = baseConfig.customAppIconColor
setTheme(getThemeId(curPrimaryColor))
updateMenuItemColors(binding.customizationToolbar.menu, curPrimaryColor)
setupToolbar(binding.customizationToolbar, NavigationIcon.Cross, curPrimaryColor)
setupColorsPickers()
} else {
baseConfig.customPrimaryColor = curPrimaryColor
baseConfig.customAccentColor = curAccentColor
baseConfig.customBackgroundColor = curBackgroundColor
baseConfig.customTextColor = curTextColor
baseConfig.customAppIconColor = curAppIconColor
}
} else if (curSelectedThemeId == THEME_SHARED) {
if (useStored) {
storedSharedTheme?.apply {
curTextColor = textColor
curBackgroundColor = backgroundColor
curPrimaryColor = primaryColor
curAccentColor = accentColor
curAppIconColor = appIconColor
}
setTheme(getThemeId(curPrimaryColor))
setupColorsPickers()
updateMenuItemColors(binding.customizationToolbar.menu, curPrimaryColor)
setupToolbar(binding.customizationToolbar, NavigationIcon.Cross, curPrimaryColor)
}
} else {
val theme = predefinedThemes[curSelectedThemeId]!!
curTextColor = getColor(theme.textColorId)
curBackgroundColor = getColor(theme.backgroundColorId)
if (curSelectedThemeId != THEME_AUTO && curSelectedThemeId != THEME_SYSTEM) {
curPrimaryColor = getColor(theme.primaryColorId)
curAccentColor = getColor(R.color.color_primary)
curAppIconColor = getColor(theme.appIconColorId)
}
setTheme(getThemeId(getCurrentPrimaryColor()))
colorChanged()
updateMenuItemColors(binding.customizationToolbar.menu, getCurrentStatusBarColor())
setupToolbar(binding.customizationToolbar, NavigationIcon.Cross, getCurrentStatusBarColor())
}
}
hasUnsavedChanges = true
refreshMenuItems()
updateLabelColors(getCurrentTextColor())
updateBackgroundColor(getCurrentBackgroundColor())
updateActionbarColor(getCurrentStatusBarColor())
updateAutoThemeFields()
updateApplyToAllColors(getCurrentPrimaryColor())
handleAccentColorLayout()
}
private fun getAutoThemeColors(): MyTheme {
val isUsingSystemDarkTheme = isUsingSystemDarkTheme()
val textColor = if (isUsingSystemDarkTheme) R.color.theme_dark_text_color else R.color.theme_light_text_color
val backgroundColor = if (isUsingSystemDarkTheme) R.color.theme_dark_background_color else R.color.theme_light_background_color
return MyTheme(getString(R.string.auto_light_dark_theme), textColor, backgroundColor, R.color.color_primary, R.color.color_primary)
}
// doesn't really matter what colors we use here, everything will be taken from the system. Use the default dark theme values here.
private fun getSystemThemeColors(): MyTheme {
return MyTheme(
getMaterialYouString(),
R.color.theme_dark_text_color,
R.color.theme_dark_background_color,
R.color.color_primary,
R.color.color_primary
)
}
private fun getCurrentThemeId(): Int {
if (baseConfig.isUsingSharedTheme) {
return THEME_SHARED
} else if ((baseConfig.isUsingSystemTheme && !hasUnsavedChanges) || curSelectedThemeId == THEME_SYSTEM) {
return THEME_SYSTEM
} else if (baseConfig.isUsingAutoTheme || curSelectedThemeId == THEME_AUTO) {
return THEME_AUTO
}
var themeId = THEME_CUSTOM
resources.apply {
for ((key, value) in predefinedThemes.filter { it.key != THEME_CUSTOM && it.key != THEME_SHARED && it.key != THEME_AUTO && it.key != THEME_SYSTEM }) {
if (curTextColor == getColor(value.textColorId) &&
curBackgroundColor == getColor(value.backgroundColorId) &&
curPrimaryColor == getColor(value.primaryColorId) &&
curAppIconColor == getColor(value.appIconColorId)
) {
themeId = key
}
}
}
return themeId
}
private fun getThemeText(): String {
var label = getString(R.string.custom)
for ((key, value) in predefinedThemes) {
if (key == curSelectedThemeId) {
label = value.label
}
}
return label
}
private fun updateAutoThemeFields() {
arrayOf(binding.customizationTextColorHolder, binding.customizationBackgroundColorHolder).forEach {
it.beVisibleIf(curSelectedThemeId != THEME_AUTO && curSelectedThemeId != THEME_SYSTEM)
}
binding.customizationPrimaryColorHolder.beVisibleIf(curSelectedThemeId != THEME_SYSTEM)
}
private fun promptSaveDiscard() {
lastSavePromptTS = System.currentTimeMillis()
ConfirmationAdvancedDialog(this, "", R.string.save_before_closing, R.string.save, R.string.discard) {
if (it) {
saveChanges(true)
} else {
resetColors()
finish()
}
}
}
private fun saveChanges(finishAfterSave: Boolean) {
val didAppIconColorChange = curAppIconColor != originalAppIconColor
baseConfig.apply {
textColor = curTextColor
backgroundColor = curBackgroundColor
primaryColor = curPrimaryColor
accentColor = curAccentColor
appIconColor = curAppIconColor
}
if (didAppIconColorChange) {
checkAppIconColor()
}
if (curSelectedThemeId == THEME_SHARED) {
val newSharedTheme = SharedTheme(curTextColor, curBackgroundColor, curPrimaryColor, curAppIconColor, 0, curAccentColor)
updateSharedTheme(newSharedTheme)
Intent().apply {
action = MyContentProvider.SHARED_THEME_UPDATED
sendBroadcast(this)
}
}
baseConfig.isUsingSharedTheme = curSelectedThemeId == THEME_SHARED
baseConfig.shouldUseSharedTheme = curSelectedThemeId == THEME_SHARED
baseConfig.isUsingAutoTheme = curSelectedThemeId == THEME_AUTO
baseConfig.isUsingSystemTheme = curSelectedThemeId == THEME_SYSTEM
hasUnsavedChanges = false
if (finishAfterSave) {
finish()
} else {
refreshMenuItems()
}
}
private fun resetColors() {
hasUnsavedChanges = false
initColorVariables()
setupColorsPickers()
updateBackgroundColor()
updateActionbarColor()
refreshMenuItems()
updateLabelColors(getCurrentTextColor())
}
private fun initColorVariables() {
curTextColor = baseConfig.textColor
curBackgroundColor = baseConfig.backgroundColor
curPrimaryColor = baseConfig.primaryColor
curAccentColor = baseConfig.accentColor
curAppIconColor = baseConfig.appIconColor
}
private fun setupColorsPickers() {
val textColor = getCurrentTextColor()
val backgroundColor = getCurrentBackgroundColor()
val primaryColor = getCurrentPrimaryColor()
binding.customizationTextColor.setFillWithStroke(textColor, backgroundColor)
binding.customizationPrimaryColor.setFillWithStroke(primaryColor, backgroundColor)
binding.customizationAccentColor.setFillWithStroke(curAccentColor, backgroundColor)
binding.customizationBackgroundColor.setFillWithStroke(backgroundColor, backgroundColor)
binding.customizationAppIconColor.setFillWithStroke(curAppIconColor, backgroundColor)
binding.applyToAll.setTextColor(primaryColor.getContrastColor())
binding.customizationTextColorHolder.setOnClickListener { pickTextColor() }
binding.customizationBackgroundColorHolder.setOnClickListener { pickBackgroundColor() }
binding.customizationPrimaryColorHolder.setOnClickListener { pickPrimaryColor() }
binding.customizationAccentColorHolder.setOnClickListener { pickAccentColor() }
handleAccentColorLayout()
binding.applyToAll.setOnClickListener {
applyToAll()
}
binding.customizationAppIconColorHolder.setOnClickListener {
if (baseConfig.wasAppIconCustomizationWarningShown) {
pickAppIconColor()
} else {
ConfirmationDialog(this, "", R.string.app_icon_color_warning, R.string.ok, 0) {
baseConfig.wasAppIconCustomizationWarningShown = true
pickAppIconColor()
}
}
}
}
private fun hasColorChanged(old: Int, new: Int) = Math.abs(old - new) > 1
private fun colorChanged() {
hasUnsavedChanges = true
setupColorsPickers()
refreshMenuItems()
}
private fun setCurrentTextColor(color: Int) {
curTextColor = color
updateLabelColors(color)
}
private fun setCurrentBackgroundColor(color: Int) {
curBackgroundColor = color
updateBackgroundColor(color)
}
private fun setCurrentPrimaryColor(color: Int) {
curPrimaryColor = color
updateActionbarColor(color)
updateApplyToAllColors(color)
}
private fun updateApplyToAllColors(newColor: Int) {
if (newColor == baseConfig.primaryColor && !baseConfig.isUsingSystemTheme) {
binding.applyToAll.setBackgroundResource(R.drawable.button_background_rounded)
} else {
val applyBackground = resources.getDrawable(R.drawable.button_background_rounded, theme) as RippleDrawable
(applyBackground as LayerDrawable).findDrawableByLayerId(R.id.button_background_holder).applyColorFilter(newColor)
binding.applyToAll.background = applyBackground
}
}
private fun handleAccentColorLayout() {
binding.customizationAccentColorHolder.beVisibleIf(curSelectedThemeId == THEME_WHITE || isCurrentWhiteTheme() || curSelectedThemeId == THEME_BLACK_WHITE || isCurrentBlackAndWhiteTheme())
binding.customizationAccentColorLabel.text = getString(
if (curSelectedThemeId == THEME_WHITE || isCurrentWhiteTheme()) {
R.string.accent_color_white
} else {
R.string.accent_color_black_and_white
}
)
}
private fun isCurrentWhiteTheme() = curTextColor == DARK_GREY && curPrimaryColor == Color.WHITE && curBackgroundColor == Color.WHITE
private fun isCurrentBlackAndWhiteTheme() = curTextColor == Color.WHITE && curPrimaryColor == Color.BLACK && curBackgroundColor == Color.BLACK
private fun pickTextColor() {
ColorPickerDialog(this, curTextColor) { wasPositivePressed, color ->
if (wasPositivePressed) {
if (hasColorChanged(curTextColor, color)) {
setCurrentTextColor(color)
colorChanged()
updateColorTheme(getUpdatedTheme())
}
}
}
}
private fun pickBackgroundColor() {
ColorPickerDialog(this, curBackgroundColor) { wasPositivePressed, color ->
if (wasPositivePressed) {
if (hasColorChanged(curBackgroundColor, color)) {
setCurrentBackgroundColor(color)
colorChanged()
updateColorTheme(getUpdatedTheme())
}
}
}
}
private fun pickPrimaryColor() {
if (!packageName.startsWith("com.simplemobiletools.", true) && baseConfig.appRunCount > 50) {
finish()
return
}
curPrimaryLineColorPicker = LineColorPickerDialog(this, curPrimaryColor, true, toolbar = binding.customizationToolbar) { wasPositivePressed, color ->
curPrimaryLineColorPicker = null
if (wasPositivePressed) {
if (hasColorChanged(curPrimaryColor, color)) {
setCurrentPrimaryColor(color)
colorChanged()
updateColorTheme(getUpdatedTheme())
setTheme(getThemeId(color))
}
updateMenuItemColors(binding.customizationToolbar.menu, color)
setupToolbar(binding.customizationToolbar, NavigationIcon.Cross, color)
} else {
updateActionbarColor(curPrimaryColor)
setTheme(getThemeId(curPrimaryColor))
updateMenuItemColors(binding.customizationToolbar.menu, curPrimaryColor)
setupToolbar(binding.customizationToolbar, NavigationIcon.Cross, curPrimaryColor)
updateTopBarColors(binding.customizationToolbar, curPrimaryColor)
}
}
}
private fun pickAccentColor() {
ColorPickerDialog(this, curAccentColor) { wasPositivePressed, color ->
if (wasPositivePressed) {
if (hasColorChanged(curAccentColor, color)) {
curAccentColor = color
colorChanged()
if (isCurrentWhiteTheme() || isCurrentBlackAndWhiteTheme()) {
updateActionbarColor(getCurrentStatusBarColor())
}
}
}
}
}
private fun pickAppIconColor() {
LineColorPickerDialog(this, curAppIconColor, false, R.array.md_app_icon_colors, getAppIconIDs()) { wasPositivePressed, color ->
if (wasPositivePressed) {
if (hasColorChanged(curAppIconColor, color)) {
curAppIconColor = color
colorChanged()
updateColorTheme(getUpdatedTheme())
}
}
}
}
private fun getUpdatedTheme() = if (curSelectedThemeId == THEME_SHARED) THEME_SHARED else getCurrentThemeId()
private fun applyToAll() {
if (isThankYouInstalled()) {
ConfirmationDialog(this, "", R.string.share_colors_success, R.string.ok, 0) {
Intent().apply {
action = MyContentProvider.SHARED_THEME_ACTIVATED
sendBroadcast(this)
}
if (!predefinedThemes.containsKey(THEME_SHARED)) {
predefinedThemes[THEME_SHARED] = MyTheme(getString(R.string.shared), 0, 0, 0, 0)
}
baseConfig.wasSharedThemeEverActivated = true
binding.applyToAllHolder.beGone()
updateColorTheme(THEME_SHARED)
saveChanges(false)
}
} else {
PurchaseThankYouDialog(this)
}
}
private fun updateLabelColors(textColor: Int) {
arrayListOf(
binding.customizationThemeLabel,
binding.customizationTheme,
binding.customizationTextColorLabel,
binding.customizationBackgroundColorLabel,
binding.customizationPrimaryColorLabel,
binding.customizationAccentColorLabel,
binding.customizationAppIconColorLabel
).forEach {
it.setTextColor(textColor)
}
val primaryColor = getCurrentPrimaryColor()
binding.applyToAll.setTextColor(primaryColor.getContrastColor())
updateApplyToAllColors(primaryColor)
}
private fun getCurrentTextColor() = if (binding.customizationTheme.value == getMaterialYouString()) {
resources.getColor(R.color.you_neutral_text_color)
} else {
curTextColor
}
private fun getCurrentBackgroundColor() = if (binding.customizationTheme.value == getMaterialYouString()) {
resources.getColor(R.color.you_background_color)
} else {
curBackgroundColor
}
private fun getCurrentPrimaryColor() = if (binding.customizationTheme.value == getMaterialYouString()) {
resources.getColor(R.color.you_primary_color)
} else {
curPrimaryColor
}
private fun getCurrentStatusBarColor() = if (binding.customizationTheme.value == getMaterialYouString()) {
resources.getColor(R.color.you_status_bar_color)
} else {
curPrimaryColor
}
private fun getMaterialYouString() = "${getString(R.string.system_default)} (${getString(R.string.material_you)})"
}
|
CT/commons/src/main/kotlin/com/simplemobiletools/commons/views/RenameSimpleTab.kt | 1010832445 | package com.simplemobiletools.commons.views
import android.content.ContentValues
import android.content.Context
import android.provider.MediaStore
import android.util.AttributeSet
import android.widget.RelativeLayout
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.activities.BaseSimpleActivity
import com.simplemobiletools.commons.databinding.TabRenameSimpleBinding
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.interfaces.RenameTab
import com.simplemobiletools.commons.models.Android30RenameFormat
import com.simplemobiletools.commons.models.FileDirItem
import java.io.File
class RenameSimpleTab(context: Context, attrs: AttributeSet) : RelativeLayout(context, attrs), RenameTab {
var ignoreClicks = false
var stopLooping = false // we should request the permission on Android 30+ for all uris at once, not one by one
var activity: BaseSimpleActivity? = null
var paths = ArrayList<String>()
private lateinit var binding: TabRenameSimpleBinding
override fun onFinishInflate() {
super.onFinishInflate()
binding = TabRenameSimpleBinding.bind(this)
context.updateTextColors(binding.renameSimpleHolder)
}
override fun initTab(activity: BaseSimpleActivity, paths: ArrayList<String>) {
this.activity = activity
this.paths = paths
}
override fun dialogConfirmed(useMediaFileExtension: Boolean, callback: (success: Boolean) -> Unit) {
stopLooping = false
val valueToAdd = binding.renameSimpleValue.text.toString()
val append = binding.renameSimpleRadioGroup.checkedRadioButtonId == binding.renameSimpleRadioAppend.id
if (valueToAdd.isEmpty()) {
callback(false)
return
}
if (!valueToAdd.isAValidFilename()) {
activity?.toast(R.string.invalid_name)
return
}
val validPaths = paths.filter { activity?.getDoesFilePathExist(it) == true }
val firstPath = validPaths.firstOrNull()
val sdFilePath = validPaths.firstOrNull { activity?.isPathOnSD(it) == true } ?: firstPath
if (firstPath == null || sdFilePath == null) {
activity?.toast(R.string.unknown_error_occurred)
return
}
activity?.handleSAFDialog(sdFilePath) {
if (!it) {
return@handleSAFDialog
}
activity?.checkManageMediaOrHandleSAFDialogSdk30(firstPath) {
if (!it) {
return@checkManageMediaOrHandleSAFDialogSdk30
}
ignoreClicks = true
var pathsCnt = validPaths.size
for (path in validPaths) {
if (stopLooping) {
return@checkManageMediaOrHandleSAFDialogSdk30
}
val fullName = path.getFilenameFromPath()
var dotAt = fullName.lastIndexOf(".")
if (dotAt == -1) {
dotAt = fullName.length
}
val name = fullName.substring(0, dotAt)
val extension = if (fullName.contains(".")) ".${fullName.getFilenameExtension()}" else ""
val newName = if (append) {
"$name$valueToAdd$extension"
} else {
"$valueToAdd$fullName"
}
val newPath = "${path.getParentPath()}/$newName"
if (activity?.getDoesFilePathExist(newPath) == true) {
continue
}
activity?.renameFile(path, newPath, true) { success, android30Format ->
if (success) {
pathsCnt--
if (pathsCnt == 0) {
callback(true)
}
} else {
ignoreClicks = false
if (android30Format != Android30RenameFormat.NONE) {
stopLooping = true
renameAllFiles(validPaths, append, valueToAdd, android30Format, callback)
}
}
}
}
stopLooping = false
}
}
}
private fun renameAllFiles(
paths: List<String>,
appendString: Boolean,
stringToAdd: String,
android30Format: Android30RenameFormat,
callback: (success: Boolean) -> Unit
) {
val fileDirItems = paths.map { File(it).toFileDirItem(context) }
val uriPairs = context.getUrisPathsFromFileDirItems(fileDirItems)
val validPaths = uriPairs.first
val uris = uriPairs.second
val activity = activity
activity?.updateSDK30Uris(uris) { success ->
if (success) {
try {
uris.forEachIndexed { index, uri ->
val path = validPaths[index]
val fullName = path.getFilenameFromPath()
var dotAt = fullName.lastIndexOf(".")
if (dotAt == -1) {
dotAt = fullName.length
}
val name = fullName.substring(0, dotAt)
val extension = if (fullName.contains(".")) ".${fullName.getFilenameExtension()}" else ""
val newName = if (appendString) {
"$name$stringToAdd$extension"
} else {
"$stringToAdd$fullName"
}
when (android30Format) {
Android30RenameFormat.SAF -> {
val sourceFile = File(path).toFileDirItem(activity)
val newPath = "${path.getParentPath()}/$newName"
val destinationFile = FileDirItem(
newPath,
newName,
sourceFile.isDirectory,
sourceFile.children,
sourceFile.size,
sourceFile.modified
)
if (activity.copySingleFileSdk30(sourceFile, destinationFile)) {
if (!activity.baseConfig.keepLastModified) {
File(newPath).setLastModified(System.currentTimeMillis())
}
activity.contentResolver.delete(uri, null)
activity.updateInMediaStore(path, newPath)
activity.scanPathsRecursively(arrayListOf(newPath))
}
}
Android30RenameFormat.CONTENT_RESOLVER -> {
val values = ContentValues().apply {
put(MediaStore.Images.Media.DISPLAY_NAME, newName)
}
context.contentResolver.update(uri, values, null, null)
}
Android30RenameFormat.NONE -> {
activity.runOnUiThread {
callback(true)
}
return@forEachIndexed
}
}
}
activity.runOnUiThread {
callback(true)
}
} catch (e: Exception) {
activity.runOnUiThread {
activity.showErrorToast(e)
callback(false)
}
}
}
}
}
}
|
CT/commons/src/main/kotlin/com/simplemobiletools/commons/views/AutoGridLayoutManager.kt | 2513065133 | package com.simplemobiletools.commons.views
import android.content.Context
import androidx.recyclerview.widget.RecyclerView
import kotlin.math.max
/**
* RecyclerView GridLayoutManager but with automatic spanCount calculation.
*
* @param context The initiating view's context.
* @param itemWidth: Grid item width in pixels. Will be used to calculate span count.
*/
class AutoGridLayoutManager(
context: Context,
private var itemWidth: Int
) : MyGridLayoutManager(context, 1) {
init {
require(itemWidth >= 0) {
"itemWidth must be >= 0"
}
}
override fun onLayoutChildren(recycler: RecyclerView.Recycler?, state: RecyclerView.State?) {
val width = width
val height = height
if (itemWidth > 0 && width > 0 && height > 0) {
val totalSpace = if (orientation == VERTICAL) {
width - paddingRight - paddingLeft
} else {
height - paddingTop - paddingBottom
}
spanCount = max(1, totalSpace / itemWidth)
}
super.onLayoutChildren(recycler, state)
}
}
|
CT/commons/src/main/kotlin/com/simplemobiletools/commons/views/MyAppCompatCheckbox.kt | 1120862615 | package com.simplemobiletools.commons.views
import android.content.Context
import android.content.res.ColorStateList
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatCheckBox
import com.simplemobiletools.commons.extensions.adjustAlpha
class MyAppCompatCheckbox : AppCompatCheckBox {
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle)
fun setColors(textColor: Int, accentColor: Int, backgroundColor: Int) {
setTextColor(textColor)
val colorStateList = ColorStateList(
arrayOf(
intArrayOf(-android.R.attr.state_checked),
intArrayOf(android.R.attr.state_checked)
),
intArrayOf(textColor.adjustAlpha(0.6f), accentColor)
)
supportButtonTintList = colorStateList
}
}
|
CT/commons/src/main/kotlin/com/simplemobiletools/commons/views/MySeekBar.kt | 3436164887 | package com.simplemobiletools.commons.views
import android.content.Context
import android.util.AttributeSet
import android.widget.SeekBar
import com.simplemobiletools.commons.extensions.applyColorFilter
class MySeekBar : SeekBar {
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle)
fun setColors(textColor: Int, accentColor: Int, backgroundColor: Int) {
progressDrawable.applyColorFilter(accentColor)
thumb?.applyColorFilter(accentColor)
}
}
|
CT/commons/src/main/kotlin/com/simplemobiletools/commons/views/MyScrollView.kt | 1012441472 | package com.simplemobiletools.commons.views
import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.widget.ScrollView
class MyScrollView : ScrollView {
var isScrollable = true
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle)
override fun onTouchEvent(ev: MotionEvent): Boolean {
return when (ev.action) {
MotionEvent.ACTION_DOWN -> {
if (isScrollable) {
super.onTouchEvent(ev)
} else {
isScrollable
}
}
else -> super.onTouchEvent(ev)
}
}
override fun onInterceptTouchEvent(ev: MotionEvent?): Boolean {
return if (!isScrollable) {
false
} else {
super.onInterceptTouchEvent(ev)
}
}
}
|
CT/commons/src/main/kotlin/com/simplemobiletools/commons/views/MyTextView.kt | 4121130571 | package com.simplemobiletools.commons.views
import android.content.Context
import android.util.AttributeSet
import android.widget.TextView
class MyTextView : TextView {
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle)
fun setColors(textColor: Int, accentColor: Int, backgroundColor: Int) {
setTextColor(textColor)
setLinkTextColor(accentColor)
}
}
|
CT/commons/src/main/kotlin/com/simplemobiletools/commons/views/MyViewPager.kt | 3292664024 | package com.simplemobiletools.commons.views
import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import com.duolingo.open.rtlviewpager.RtlViewPager
class MyViewPager : RtlViewPager {
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
override fun onInterceptTouchEvent(ev: MotionEvent): Boolean {
return try {
super.onInterceptTouchEvent(ev)
} catch (ignored: Exception) {
false
}
}
override fun onTouchEvent(ev: MotionEvent): Boolean {
return try {
super.onTouchEvent(ev)
} catch (ignored: Exception) {
false
}
}
}
|
CT/commons/src/main/kotlin/com/simplemobiletools/commons/views/MyEditText.kt | 2992936106 | package com.simplemobiletools.commons.views
import android.content.Context
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatEditText
import com.simplemobiletools.commons.extensions.adjustAlpha
import com.simplemobiletools.commons.extensions.applyColorFilter
import com.simplemobiletools.commons.helpers.MEDIUM_ALPHA
class MyEditText : AppCompatEditText {
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle)
fun setColors(textColor: Int, accentColor: Int, backgroundColor: Int) {
background?.mutate()?.applyColorFilter(accentColor)
// requires android:textCursorDrawable="@null" in xml to color the cursor too
setTextColor(textColor)
setHintTextColor(textColor.adjustAlpha(MEDIUM_ALPHA))
setLinkTextColor(accentColor)
}
}
|
CT/commons/src/main/kotlin/com/simplemobiletools/commons/views/MyButton.kt | 3281460876 | package com.simplemobiletools.commons.views
import android.content.Context
import android.util.AttributeSet
import android.widget.Button
class MyButton : Button {
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle)
fun setColors(textColor: Int, accentColor: Int, backgroundColor: Int) {
setTextColor(textColor)
}
}
|
CT/commons/src/main/kotlin/com/simplemobiletools/commons/views/MyRecyclerView.kt | 3595264010 | package com.simplemobiletools.commons.views
import android.content.Context
import android.os.Handler
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.ScaleGestureDetector
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.interfaces.RecyclerScrollCallback
// drag selection is based on https://github.com/afollestad/drag-select-recyclerview
open class MyRecyclerView : RecyclerView {
private val AUTO_SCROLL_DELAY = 25L
private var isZoomEnabled = false
private var isDragSelectionEnabled = false
private var zoomListener: MyZoomListener? = null
private var dragListener: MyDragListener? = null
private var autoScrollHandler = Handler()
private var scaleDetector: ScaleGestureDetector
private var dragSelectActive = false
private var lastDraggedIndex = -1
private var minReached = 0
private var maxReached = 0
private var initialSelection = 0
private var hotspotHeight = 0
private var hotspotOffsetTop = 0
private var hotspotOffsetBottom = 0
private var hotspotTopBoundStart = 0
private var hotspotTopBoundEnd = 0
private var hotspotBottomBoundStart = 0
private var hotspotBottomBoundEnd = 0
private var autoScrollVelocity = 0
private var inTopHotspot = false
private var inBottomHotspot = false
private var currScaleFactor = 1.0f
private var lastUp = 0L // allow only pinch zoom, not double tap
// things related to parallax scrolling (for now only in the music player)
// cut from https://github.com/ksoichiro/Android-ObservableScrollView
var recyclerScrollCallback: RecyclerScrollCallback? = null
private var mPrevFirstVisiblePosition = 0
private var mPrevScrolledChildrenHeight = 0
private var mPrevFirstVisibleChildHeight = -1
private var mScrollY = 0
// variables used for fetching additional items at scrolling to the bottom/top
var endlessScrollListener: EndlessScrollListener? = null
private var totalItemCount = 0
private var lastMaxItemIndex = 0
private var linearLayoutManager: LinearLayoutManager? = null
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
init {
hotspotHeight = context.resources.getDimensionPixelSize(R.dimen.dragselect_hotspot_height)
if (layoutManager is LinearLayoutManager) {
linearLayoutManager = layoutManager as LinearLayoutManager
}
val gestureListener = object : MyGestureListener {
override fun getLastUp() = lastUp
override fun getScaleFactor() = currScaleFactor
override fun setScaleFactor(value: Float) {
currScaleFactor = value
}
override fun getZoomListener() = zoomListener
}
scaleDetector = ScaleGestureDetector(context, GestureListener(gestureListener))
}
override fun onMeasure(widthSpec: Int, heightSpec: Int) {
super.onMeasure(widthSpec, heightSpec)
if (hotspotHeight > -1) {
hotspotTopBoundStart = hotspotOffsetTop
hotspotTopBoundEnd = hotspotOffsetTop + hotspotHeight
hotspotBottomBoundStart = measuredHeight - hotspotHeight - hotspotOffsetBottom
hotspotBottomBoundEnd = measuredHeight - hotspotOffsetBottom
}
}
private val autoScrollRunnable = object : Runnable {
override fun run() {
if (inTopHotspot) {
scrollBy(0, -autoScrollVelocity)
autoScrollHandler.postDelayed(this, AUTO_SCROLL_DELAY)
} else if (inBottomHotspot) {
scrollBy(0, autoScrollVelocity)
autoScrollHandler.postDelayed(this, AUTO_SCROLL_DELAY)
}
}
}
fun resetItemCount() {
totalItemCount = 0
}
override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
if (!dragSelectActive) {
try {
super.dispatchTouchEvent(ev)
} catch (ignored: Exception) {
}
}
when (ev.action) {
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
dragSelectActive = false
inTopHotspot = false
inBottomHotspot = false
autoScrollHandler.removeCallbacks(autoScrollRunnable)
currScaleFactor = 1.0f
lastUp = System.currentTimeMillis()
return true
}
MotionEvent.ACTION_MOVE -> {
if (dragSelectActive) {
val itemPosition = getItemPosition(ev)
if (hotspotHeight > -1) {
if (ev.y in hotspotTopBoundStart.toFloat()..hotspotTopBoundEnd.toFloat()) {
inBottomHotspot = false
if (!inTopHotspot) {
inTopHotspot = true
autoScrollHandler.removeCallbacks(autoScrollRunnable)
autoScrollHandler.postDelayed(autoScrollRunnable, AUTO_SCROLL_DELAY)
}
val simulatedFactor = (hotspotTopBoundEnd - hotspotTopBoundStart).toFloat()
val simulatedY = ev.y - hotspotTopBoundStart
autoScrollVelocity = (simulatedFactor - simulatedY).toInt() / 2
} else if (ev.y in hotspotBottomBoundStart.toFloat()..hotspotBottomBoundEnd.toFloat()) {
inTopHotspot = false
if (!inBottomHotspot) {
inBottomHotspot = true
autoScrollHandler.removeCallbacks(autoScrollRunnable)
autoScrollHandler.postDelayed(autoScrollRunnable, AUTO_SCROLL_DELAY)
}
val simulatedY = ev.y + hotspotBottomBoundEnd
val simulatedFactor = (hotspotBottomBoundStart + hotspotBottomBoundEnd).toFloat()
autoScrollVelocity = (simulatedY - simulatedFactor).toInt() / 2
} else if (inTopHotspot || inBottomHotspot) {
autoScrollHandler.removeCallbacks(autoScrollRunnable)
inTopHotspot = false
inBottomHotspot = false
}
}
if (itemPosition != RecyclerView.NO_POSITION && lastDraggedIndex != itemPosition) {
lastDraggedIndex = itemPosition
if (minReached == -1) {
minReached = lastDraggedIndex
}
if (maxReached == -1) {
maxReached = lastDraggedIndex
}
if (lastDraggedIndex > maxReached) {
maxReached = lastDraggedIndex
}
if (lastDraggedIndex < minReached) {
minReached = lastDraggedIndex
}
dragListener?.selectRange(initialSelection, lastDraggedIndex, minReached, maxReached)
if (initialSelection == lastDraggedIndex) {
minReached = lastDraggedIndex
maxReached = lastDraggedIndex
}
}
return true
}
}
}
return if (isZoomEnabled) {
scaleDetector.onTouchEvent(ev)
} else {
true
}
}
fun setupDragListener(dragListener: MyDragListener?) {
isDragSelectionEnabled = dragListener != null
this.dragListener = dragListener
}
fun setupZoomListener(zoomListener: MyZoomListener?) {
isZoomEnabled = zoomListener != null
this.zoomListener = zoomListener
}
fun setDragSelectActive(initialSelection: Int) {
if (dragSelectActive || !isDragSelectionEnabled)
return
lastDraggedIndex = -1
minReached = -1
maxReached = -1
this.initialSelection = initialSelection
dragSelectActive = true
dragListener?.selectItem(initialSelection)
}
private fun getItemPosition(e: MotionEvent): Int {
val v = findChildViewUnder(e.x, e.y) ?: return RecyclerView.NO_POSITION
if (v.tag == null || v.tag !is RecyclerView.ViewHolder) {
throw IllegalStateException("Make sure your adapter makes a call to super.onBindViewHolder(), and doesn't override itemView tags.")
}
val holder = v.tag as RecyclerView.ViewHolder
return holder.adapterPosition
}
override fun onScrollStateChanged(state: Int) {
super.onScrollStateChanged(state)
if (endlessScrollListener != null) {
if (totalItemCount == 0) {
totalItemCount = adapter?.itemCount ?: return
}
if (state == SCROLL_STATE_IDLE) {
val lastVisiblePosition = linearLayoutManager?.findLastVisibleItemPosition() ?: 0
if (lastVisiblePosition != lastMaxItemIndex && lastVisiblePosition == totalItemCount - 1) {
lastMaxItemIndex = lastVisiblePosition
endlessScrollListener!!.updateBottom()
}
val firstVisiblePosition = linearLayoutManager?.findFirstVisibleItemPosition() ?: -1
if (firstVisiblePosition == 0) {
endlessScrollListener!!.updateTop()
}
}
}
}
override fun onScrollChanged(l: Int, t: Int, oldl: Int, oldt: Int) {
super.onScrollChanged(l, t, oldl, oldt)
if (recyclerScrollCallback != null) {
if (childCount > 0) {
val firstVisiblePosition = getChildAdapterPosition(getChildAt(0))
val firstVisibleChild = getChildAt(0)
if (firstVisibleChild != null) {
if (mPrevFirstVisiblePosition < firstVisiblePosition) {
mPrevScrolledChildrenHeight += mPrevFirstVisibleChildHeight
}
if (firstVisiblePosition == 0) {
mPrevFirstVisibleChildHeight = firstVisibleChild.height
mPrevScrolledChildrenHeight = 0
}
if (mPrevFirstVisibleChildHeight < 0) {
mPrevFirstVisibleChildHeight = 0
}
mScrollY = mPrevScrolledChildrenHeight - firstVisibleChild.top
recyclerScrollCallback?.onScrolled(mScrollY)
}
}
}
}
class GestureListener(val gestureListener: MyGestureListener) : ScaleGestureDetector.SimpleOnScaleGestureListener() {
private val ZOOM_IN_THRESHOLD = -0.4f
private val ZOOM_OUT_THRESHOLD = 0.15f
override fun onScale(detector: ScaleGestureDetector): Boolean {
gestureListener.apply {
if (System.currentTimeMillis() - getLastUp() < 1000)
return false
val diff = getScaleFactor() - detector.scaleFactor
if (diff < ZOOM_IN_THRESHOLD && getScaleFactor() == 1.0f) {
getZoomListener()?.zoomIn()
setScaleFactor(detector.scaleFactor)
} else if (diff > ZOOM_OUT_THRESHOLD && getScaleFactor() == 1.0f) {
getZoomListener()?.zoomOut()
setScaleFactor(detector.scaleFactor)
}
}
return false
}
}
interface MyZoomListener {
fun zoomOut()
fun zoomIn()
}
interface MyDragListener {
fun selectItem(position: Int)
fun selectRange(initialSelection: Int, lastDraggedIndex: Int, minReached: Int, maxReached: Int)
}
interface MyGestureListener {
fun getLastUp(): Long
fun getScaleFactor(): Float
fun setScaleFactor(value: Float)
fun getZoomListener(): MyZoomListener?
}
interface EndlessScrollListener {
fun updateTop()
fun updateBottom()
}
}
|
CT/commons/src/main/kotlin/com/simplemobiletools/commons/views/MyGridLayoutManager.kt | 3266844232 | package com.simplemobiletools.commons.views
import android.content.Context
import android.util.AttributeSet
import androidx.recyclerview.widget.GridLayoutManager
open class MyGridLayoutManager : GridLayoutManager {
constructor(context: Context, spanCount: Int) : super(context, spanCount)
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes)
constructor(context: Context, spanCount: Int, orientation: Int, reverseLayout: Boolean) : super(context, spanCount, orientation, reverseLayout)
// fixes crash java.lang.IndexOutOfBoundsException: Inconsistency detected...
// taken from https://stackoverflow.com/a/33985508/1967672
override fun supportsPredictiveItemAnimations() = false
}
|
CT/commons/src/main/kotlin/com/simplemobiletools/commons/views/MyAutoCompleteTextView.kt | 3469922328 | package com.simplemobiletools.commons.views
import android.content.Context
import android.util.AttributeSet
import android.widget.AutoCompleteTextView
import com.simplemobiletools.commons.extensions.adjustAlpha
import com.simplemobiletools.commons.extensions.applyColorFilter
class MyAutoCompleteTextView : AutoCompleteTextView {
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle)
fun setColors(textColor: Int, accentColor: Int, backgroundColor: Int) {
background?.mutate()?.applyColorFilter(accentColor)
// requires android:textCursorDrawable="@null" in xml to color the cursor too
setTextColor(textColor)
setHintTextColor(textColor.adjustAlpha(0.5f))
setLinkTextColor(accentColor)
}
}
|
CT/commons/src/main/kotlin/com/simplemobiletools/commons/views/Breadcrumbs.kt | 1718087207 | package com.simplemobiletools.commons.views
import android.content.Context
import android.content.res.ColorStateList
import android.graphics.drawable.ColorDrawable
import android.util.AttributeSet
import android.util.TypedValue
import android.view.LayoutInflater
import android.view.View
import android.widget.HorizontalScrollView
import android.widget.LinearLayout
import androidx.core.content.ContextCompat
import androidx.core.view.ViewCompat
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.databinding.ItemBreadcrumbBinding
import com.simplemobiletools.commons.databinding.ItemBreadcrumbFirstBinding
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.models.FileDirItem
class Breadcrumbs(context: Context, attrs: AttributeSet) : HorizontalScrollView(context, attrs) {
private val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
private val itemsLayout: LinearLayout
private var textColor = context.getProperTextColor()
private var fontSize = resources.getDimension(R.dimen.bigger_text_size)
private var lastPath = ""
private var isLayoutDirty = true
private var isScrollToSelectedItemPending = false
private var isFirstScroll = true
private var stickyRootInitialLeft = 0
private var rootStartPadding = 0
private val textColorStateList: ColorStateList
get() = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_activated), intArrayOf()),
intArrayOf(
textColor,
textColor.adjustAlpha(0.6f)
)
)
var listener: BreadcrumbsListener? = null
var isShownInDialog = false
init {
isHorizontalScrollBarEnabled = false
itemsLayout = LinearLayout(context)
itemsLayout.orientation = LinearLayout.HORIZONTAL
rootStartPadding = paddingStart
itemsLayout.setPaddingRelative(0, paddingTop, paddingEnd, paddingBottom)
setPaddingRelative(0, 0, 0, 0)
addView(itemsLayout, LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT))
onGlobalLayout {
stickyRootInitialLeft = if (itemsLayout.childCount > 0) {
itemsLayout.getChildAt(0).left
} else {
0
}
}
}
private fun recomputeStickyRootLocation(left: Int) {
stickyRootInitialLeft = left
handleRootStickiness(scrollX)
}
private fun handleRootStickiness(scrollX: Int) {
if (scrollX > stickyRootInitialLeft) {
stickRoot(scrollX - stickyRootInitialLeft)
} else {
freeRoot()
}
}
private fun freeRoot() {
if (itemsLayout.childCount > 0) {
itemsLayout.getChildAt(0).translationX = 0f
}
}
private fun stickRoot(translationX: Int) {
if (itemsLayout.childCount > 0) {
val root = itemsLayout.getChildAt(0)
root.translationX = translationX.toFloat()
ViewCompat.setTranslationZ(root, translationZ)
}
}
override fun onScrollChanged(scrollX: Int, scrollY: Int, oldScrollX: Int, oldScrollY: Int) {
super.onScrollChanged(scrollX, scrollY, oldScrollX, oldScrollY)
handleRootStickiness(scrollX)
}
override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
super.onLayout(changed, left, top, right, bottom)
isLayoutDirty = false
if (isScrollToSelectedItemPending) {
scrollToSelectedItem()
isScrollToSelectedItemPending = false
}
recomputeStickyRootLocation(left)
}
private fun scrollToSelectedItem() {
if (isLayoutDirty) {
isScrollToSelectedItemPending = true
return
}
var selectedIndex = itemsLayout.childCount - 1
val cnt = itemsLayout.childCount
for (i in 0 until cnt) {
val child = itemsLayout.getChildAt(i)
if ((child.tag as? FileDirItem)?.path?.trimEnd('/') == lastPath.trimEnd('/')) {
selectedIndex = i
break
}
}
val selectedItemView = itemsLayout.getChildAt(selectedIndex)
val scrollX = if (layoutDirection == View.LAYOUT_DIRECTION_LTR) {
selectedItemView.left - itemsLayout.paddingStart
} else {
selectedItemView.right - width + itemsLayout.paddingStart
}
if (!isFirstScroll && isShown) {
smoothScrollTo(scrollX, 0)
} else {
scrollTo(scrollX, 0)
}
isFirstScroll = false
}
override fun requestLayout() {
isLayoutDirty = true
super.requestLayout()
}
fun setBreadcrumb(fullPath: String) {
lastPath = fullPath
val basePath = fullPath.getBasePath(context)
var currPath = basePath
val tempPath = context.humanizePath(fullPath)
itemsLayout.removeAllViews()
val dirs = tempPath.split("/").dropLastWhile(String::isEmpty)
for (i in dirs.indices) {
val dir = dirs[i]
if (i > 0) {
currPath += dir + "/"
}
if (dir.isEmpty()) {
continue
}
currPath = "${currPath.trimEnd('/')}/"
val item = FileDirItem(currPath, dir, true, 0, 0, 0)
addBreadcrumb(item, i, i > 0)
scrollToSelectedItem()
}
}
private fun addBreadcrumb(item: FileDirItem, index: Int, addPrefix: Boolean) {
if (itemsLayout.childCount == 0) {
val firstItemBgColor = if (isShownInDialog && context.baseConfig.isUsingSystemTheme) {
resources.getColor(R.color.you_dialog_background_color, context.theme)
} else {
context.getProperBackgroundColor()
}
ItemBreadcrumbFirstBinding.inflate(inflater, itemsLayout, false).apply {
resources.apply {
breadcrumbText.background = ContextCompat.getDrawable(context, R.drawable.button_background)
breadcrumbText.background.applyColorFilter(textColor)
elevation = 1f
background = ColorDrawable(firstItemBgColor)
val medium = getDimension(R.dimen.medium_margin).toInt()
breadcrumbText.setPadding(medium, medium, medium, medium)
setPadding(rootStartPadding, 0, 0, 0)
}
isActivated = item.path.trimEnd('/') == lastPath.trimEnd('/')
breadcrumbText.text = item.name
breadcrumbText.setTextColor(textColorStateList)
breadcrumbText.setTextSize(TypedValue.COMPLEX_UNIT_PX, fontSize)
itemsLayout.addView(this.root)
breadcrumbText.setOnClickListener {
if (itemsLayout.getChildAt(index) != null) {
listener?.breadcrumbClicked(index)
}
}
root.tag = item
}
} else {
ItemBreadcrumbBinding.inflate(inflater, itemsLayout, false).apply {
var textToAdd = item.name
if (addPrefix) {
textToAdd = "> $textToAdd"
}
isActivated = item.path.trimEnd('/') == lastPath.trimEnd('/')
breadcrumbText.text = textToAdd
breadcrumbText.setTextColor(textColorStateList)
breadcrumbText.setTextSize(TypedValue.COMPLEX_UNIT_PX, fontSize)
itemsLayout.addView(root)
breadcrumbText.setOnClickListener { v ->
if (itemsLayout.getChildAt(index) != null && itemsLayout.getChildAt(index) == v) {
if ((v.tag as? FileDirItem)?.path?.trimEnd('/') == lastPath.trimEnd('/')) {
scrollToSelectedItem()
} else {
listener?.breadcrumbClicked(index)
}
}
}
root.tag = item
}
}
}
fun updateColor(color: Int) {
textColor = color
setBreadcrumb(lastPath)
}
fun updateFontSize(size: Float, updateTexts: Boolean) {
fontSize = size
if (updateTexts) {
setBreadcrumb(lastPath)
}
}
fun removeBreadcrumb() {
itemsLayout.removeView(itemsLayout.getChildAt(itemsLayout.childCount - 1))
}
fun getItem(index: Int) = itemsLayout.getChildAt(index).tag as FileDirItem
fun getLastItem() = itemsLayout.getChildAt(itemsLayout.childCount - 1).tag as FileDirItem
fun getItemCount() = itemsLayout.childCount
interface BreadcrumbsListener {
fun breadcrumbClicked(id: Int)
}
}
|
CT/commons/src/main/kotlin/com/simplemobiletools/commons/views/MyFloatingActionButton.kt | 1399476892 | package com.simplemobiletools.commons.views
import android.content.Context
import android.content.res.ColorStateList
import android.util.AttributeSet
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.simplemobiletools.commons.extensions.applyColorFilter
import com.simplemobiletools.commons.extensions.getContrastColor
class MyFloatingActionButton : FloatingActionButton {
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle)
fun setColors(textColor: Int, accentColor: Int, backgroundColor: Int) {
backgroundTintList = ColorStateList.valueOf(accentColor)
applyColorFilter(accentColor.getContrastColor())
}
}
|
CT/commons/src/main/kotlin/com/simplemobiletools/commons/views/MyTextInputLayout.kt | 2621356058 | package com.simplemobiletools.commons.views
import android.content.Context
import android.content.res.ColorStateList
import android.util.AttributeSet
import com.google.android.material.textfield.TextInputLayout
import com.simplemobiletools.commons.extensions.adjustAlpha
import com.simplemobiletools.commons.extensions.value
import com.simplemobiletools.commons.helpers.HIGHER_ALPHA
import com.simplemobiletools.commons.helpers.MEDIUM_ALPHA
class MyTextInputLayout : TextInputLayout {
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle)
// we need to use reflection to make some colors work well
fun setColors(textColor: Int, accentColor: Int, backgroundColor: Int) {
try {
editText!!.setTextColor(textColor)
editText!!.backgroundTintList = ColorStateList.valueOf(accentColor)
val hintColor = if (editText!!.value.isEmpty()) textColor.adjustAlpha(HIGHER_ALPHA) else textColor
val defaultTextColor = TextInputLayout::class.java.getDeclaredField("defaultHintTextColor")
defaultTextColor.isAccessible = true
defaultTextColor.set(this, ColorStateList(arrayOf(intArrayOf(0)), intArrayOf(hintColor)))
val focusedTextColor = TextInputLayout::class.java.getDeclaredField("focusedTextColor")
focusedTextColor.isAccessible = true
focusedTextColor.set(this, ColorStateList(arrayOf(intArrayOf(0)), intArrayOf(accentColor)))
val defaultHintTextColor = textColor.adjustAlpha(MEDIUM_ALPHA)
val boxColorState = ColorStateList(
arrayOf(
intArrayOf(android.R.attr.state_active),
intArrayOf(android.R.attr.state_focused)
),
intArrayOf(
defaultHintTextColor,
accentColor
)
)
setEndIconTintList(ColorStateList(arrayOf(intArrayOf(0)), intArrayOf(hintColor)))
setBoxStrokeColorStateList(boxColorState)
defaultTextColor.set(this, ColorStateList(arrayOf(intArrayOf(0)), intArrayOf(defaultHintTextColor)))
setHelperTextColor(ColorStateList.valueOf(textColor))
} catch (e: Exception) {
}
}
}
|
CT/commons/src/main/kotlin/com/simplemobiletools/commons/views/BiometricIdTab.kt | 4044671693 | package com.simplemobiletools.commons.views
import android.content.Context
import android.util.AttributeSet
import androidx.biometric.auth.AuthPromptHost
import androidx.constraintlayout.widget.ConstraintLayout
import com.simplemobiletools.commons.databinding.TabBiometricIdBinding
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.DARK_GREY
import com.simplemobiletools.commons.interfaces.HashListener
import com.simplemobiletools.commons.interfaces.SecurityTab
class BiometricIdTab(context: Context, attrs: AttributeSet) : ConstraintLayout(context, attrs), SecurityTab {
private lateinit var hashListener: HashListener
private lateinit var biometricPromptHost: AuthPromptHost
private lateinit var binding: TabBiometricIdBinding
override fun onFinishInflate() {
super.onFinishInflate()
binding = TabBiometricIdBinding.bind(this)
context.updateTextColors(binding.biometricLockHolder)
val textColor = if (context.isWhiteTheme()) {
DARK_GREY
} else {
context.getProperPrimaryColor().getContrastColor()
}
binding.openBiometricDialog.setTextColor(textColor)
binding.openBiometricDialog.setOnClickListener {
biometricPromptHost.activity?.showBiometricPrompt(successCallback = hashListener::receivedHash)
}
}
override fun initTab(
requiredHash: String,
listener: HashListener,
scrollView: MyScrollView,
biometricPromptHost: AuthPromptHost,
showBiometricAuthentication: Boolean
) {
this.biometricPromptHost = biometricPromptHost
hashListener = listener
if (showBiometricAuthentication) {
binding.openBiometricDialog.performClick()
}
}
override fun visibilityChanged(isVisible: Boolean) {}
}
|
CT/commons/src/main/kotlin/com/simplemobiletools/commons/views/MyAppCompatSpinner.kt | 403900057 | package com.simplemobiletools.commons.views
import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.widget.AdapterView
import android.widget.TextView
import androidx.appcompat.widget.AppCompatSpinner
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.adapters.MyArrayAdapter
import com.simplemobiletools.commons.extensions.applyColorFilter
class MyAppCompatSpinner : AppCompatSpinner {
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle)
fun setColors(textColor: Int, accentColor: Int, backgroundColor: Int) {
if (adapter == null)
return
val cnt = adapter.count
val items = kotlin.arrayOfNulls<Any>(cnt)
for (i in 0 until cnt)
items[i] = adapter.getItem(i)
val position = selectedItemPosition
val padding = resources.getDimension(R.dimen.activity_margin).toInt()
adapter = MyArrayAdapter(context, android.R.layout.simple_spinner_item, items, textColor, backgroundColor, padding)
setSelection(position)
val superListener = onItemSelectedListener
onItemSelectedListener = object : OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
if (view != null) {
(view as TextView).setTextColor(textColor)
}
superListener?.onItemSelected(parent, view, position, id)
}
override fun onNothingSelected(parent: AdapterView<*>?) {
}
}
background.applyColorFilter(textColor)
}
}
|
CT/commons/src/main/kotlin/com/simplemobiletools/commons/views/ColorPickerSquare.kt | 3920195898 | package com.simplemobiletools.commons.views
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.*
import android.graphics.Shader.TileMode
import android.util.AttributeSet
import android.view.View
class ColorPickerSquare(context: Context, attrs: AttributeSet) : View(context, attrs) {
var paint: Paint? = null
var luar: Shader = LinearGradient(0f, 0f, 0f, measuredHeight.toFloat(), Color.WHITE, Color.BLACK, Shader.TileMode.CLAMP)
val color = floatArrayOf(1f, 1f, 1f)
@SuppressLint("DrawAllocation")
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
if (paint == null) {
paint = Paint()
luar = LinearGradient(0f, 0f, 0f, measuredHeight.toFloat(), Color.WHITE, Color.BLACK, TileMode.CLAMP)
}
val rgb = Color.HSVToColor(color)
val dalam = LinearGradient(0f, 0f, measuredWidth.toFloat(), 0f, Color.WHITE, rgb, TileMode.CLAMP)
val shader = ComposeShader(luar, dalam, PorterDuff.Mode.MULTIPLY)
paint!!.shader = shader
canvas.drawRect(0f, 0f, measuredWidth.toFloat(), measuredHeight.toFloat(), paint!!)
}
fun setHue(hue: Float) {
color[0] = hue
invalidate()
}
}
|
CT/commons/src/main/kotlin/com/simplemobiletools/commons/views/bottomactionmenu/BottomActionMenuItemPopup.kt | 595354859 | package com.simplemobiletools.commons.views.bottomactionmenu
import android.content.Context
import android.graphics.Color
import android.graphics.Rect
import android.view.*
import android.view.View.MeasureSpec
import android.widget.ArrayAdapter
import android.widget.FrameLayout
import android.widget.ListView
import android.widget.PopupWindow
import androidx.core.content.ContextCompat
import androidx.core.widget.PopupWindowCompat
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.databinding.ItemActionModePopupBinding
import com.simplemobiletools.commons.extensions.applyColorFilter
import com.simplemobiletools.commons.extensions.windowManager
import com.simplemobiletools.commons.helpers.isRPlus
class BottomActionMenuItemPopup(
private val context: Context,
private val items: List<BottomActionMenuItem>,
private val onSelect: (BottomActionMenuItem) -> Unit,
) {
private val popup = PopupWindow(context, null, android.R.attr.popupMenuStyle)
private var anchorView: View? = null
private var dropDownWidth = ViewGroup.LayoutParams.WRAP_CONTENT
private var dropDownHeight = ViewGroup.LayoutParams.WRAP_CONTENT
private val tempRect = Rect()
private val popupMinWidth: Int
private val popupPaddingBottom: Int
private val popupPaddingStart: Int
private val popupPaddingEnd: Int
private val popupPaddingTop: Int
val isShowing: Boolean
get() = popup.isShowing
private val popupListAdapter = object : ArrayAdapter<BottomActionMenuItem>(context, R.layout.item_action_mode_popup, items) {
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
var view: ItemActionModePopupBinding? = null
if (view == null) {
view = ItemActionModePopupBinding.inflate(LayoutInflater.from(context), parent, false)
}
val item = items[position]
view.cabItem.text = item.title
if (item.icon != View.NO_ID) {
val icon = ContextCompat.getDrawable(context, item.icon)
icon?.applyColorFilter(Color.WHITE)
view.cabItem.setCompoundDrawablesWithIntrinsicBounds(icon, null, null, null)
}
view.root.setOnClickListener {
onSelect.invoke(item)
popup.dismiss()
}
return view.root
}
}
init {
popup.isFocusable = true
popupMinWidth = context.resources.getDimensionPixelSize(R.dimen.cab_popup_menu_min_width)
popupPaddingStart = context.resources.getDimensionPixelSize(R.dimen.smaller_margin)
popupPaddingEnd = context.resources.getDimensionPixelSize(R.dimen.smaller_margin)
popupPaddingTop = context.resources.getDimensionPixelSize(R.dimen.smaller_margin)
popupPaddingBottom = context.resources.getDimensionPixelSize(R.dimen.smaller_margin)
}
fun show(anchorView: View) {
this.anchorView = anchorView
buildDropDown()
PopupWindowCompat.setWindowLayoutType(popup, WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL)
popup.isOutsideTouchable = true
popup.width = dropDownWidth
popup.height = dropDownHeight
var x = 0
var y = 0
val contentView: View = popup.contentView
val windowRect = Rect()
contentView.getWindowVisibleDisplayFrame(windowRect)
val windowW = windowRect.width()
val windowH = windowRect.height()
contentView.measure(
makeDropDownMeasureSpec(dropDownWidth, windowW),
makeDropDownMeasureSpec(dropDownHeight, windowH)
)
val anchorLocation = IntArray(2)
anchorView.getLocationInWindow(anchorLocation)
x += anchorLocation[0]
y += anchorView.height * 2
x -= dropDownWidth - anchorView.width
popup.showAtLocation(contentView, Gravity.BOTTOM, x, y)
}
internal fun dismiss() {
popup.dismiss()
popup.contentView = null
}
private fun buildDropDown() {
var otherHeights = 0
val dropDownList = ListView(context).apply {
adapter = popupListAdapter
isFocusable = true
divider = null
isFocusableInTouchMode = true
clipToPadding = false
isVerticalScrollBarEnabled = true
isHorizontalScrollBarEnabled = false
clipToOutline = true
elevation = 3f
setPaddingRelative(popupPaddingStart, popupPaddingTop, popupPaddingEnd, popupPaddingBottom)
}
val screenWidth = if (isRPlus()) {
context.windowManager.currentWindowMetrics.bounds.width()
} else {
context.windowManager.defaultDisplay.width
}
val width = measureMenuSizeAndGetWidth((0.8 * screenWidth).toInt())
updateContentWidth(width)
popup.contentView = dropDownList
// getMaxAvailableHeight() subtracts the padding, so we put it back
// to get the available height for the whole window.
val padding: Int
val popupBackground = popup.background
padding = if (popupBackground != null) {
popupBackground.getPadding(tempRect)
tempRect.top + tempRect.bottom
} else {
tempRect.setEmpty()
0
}
val maxHeight = popup.getMaxAvailableHeight(anchorView!!, 0)
val listContent = measureHeightOfChildrenCompat(maxHeight - otherHeights)
if (listContent > 0) {
val listPadding = dropDownList.paddingTop + dropDownList.paddingBottom
otherHeights += padding + listPadding
}
dropDownHeight = listContent + otherHeights
dropDownList.layoutParams = ViewGroup.LayoutParams(dropDownWidth, dropDownHeight)
}
private fun updateContentWidth(width: Int) {
val popupBackground = popup.background
dropDownWidth = if (popupBackground != null) {
popupBackground.getPadding(tempRect)
tempRect.left + tempRect.right + width
} else {
width
}
}
/**
* @see androidx.appcompat.widget.DropDownListView.measureHeightOfChildrenCompat
*/
private fun measureHeightOfChildrenCompat(maxHeight: Int): Int {
val parent = FrameLayout(context)
val widthMeasureSpec = MeasureSpec.makeMeasureSpec(dropDownWidth, MeasureSpec.EXACTLY)
// Include the padding of the list
var returnedHeight = 0
val count = popupListAdapter.count
var child: View? = null
var viewType = 0
for (i in 0 until count) {
val positionType = popupListAdapter.getItemViewType(i)
if (positionType != viewType) {
child = null
viewType = positionType
}
child = popupListAdapter.getView(i, child, parent)
// Compute child height spec
val heightMeasureSpec: Int
var childLayoutParams: ViewGroup.LayoutParams? = child.layoutParams
if (childLayoutParams == null) {
childLayoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
child.layoutParams = childLayoutParams
}
heightMeasureSpec = if (childLayoutParams.height > 0) {
MeasureSpec.makeMeasureSpec(
childLayoutParams.height,
MeasureSpec.EXACTLY
)
} else {
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)
}
child.measure(widthMeasureSpec, heightMeasureSpec)
// Since this view was measured directly against the parent measure
// spec, we must measure it again before reuse.
child.forceLayout()
val marginLayoutParams = childLayoutParams as? ViewGroup.MarginLayoutParams
val topMargin = marginLayoutParams?.topMargin ?: 0
val bottomMargin = marginLayoutParams?.bottomMargin ?: 0
val verticalMargin = topMargin + bottomMargin
returnedHeight += child.measuredHeight + verticalMargin
if (returnedHeight >= maxHeight) {
// We went over, figure out which height to return. If returnedHeight >
// maxHeight, then the i'th position did not fit completely.
return maxHeight
}
}
// At this point, we went through the range of children, and they each
// completely fit, so return the returnedHeight
return returnedHeight
}
/**
* @see androidx.appcompat.view.menu.MenuPopup.measureIndividualMenuWidth
*/
private fun measureMenuSizeAndGetWidth(maxAllowedWidth: Int): Int {
val parent = FrameLayout(context)
var maxWidth = popupMinWidth
var itemView: View? = null
var itemType = 0
val widthMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)
val heightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)
for (i in 0 until popupListAdapter.count) {
val positionType: Int = popupListAdapter.getItemViewType(i)
if (positionType != itemType) {
itemType = positionType
itemView = null
}
itemView = popupListAdapter.getView(i, itemView, parent)
itemView.measure(widthMeasureSpec, heightMeasureSpec)
val itemWidth = itemView.measuredWidth
if (itemWidth >= maxAllowedWidth) {
return maxAllowedWidth
} else if (itemWidth > maxWidth) {
maxWidth = itemWidth
}
}
return maxWidth
}
private fun makeDropDownMeasureSpec(measureSpec: Int, maxSize: Int): Int {
return MeasureSpec.makeMeasureSpec(
getDropDownMeasureSpecSize(measureSpec, maxSize),
getDropDownMeasureSpecMode(measureSpec)
)
}
private fun getDropDownMeasureSpecSize(measureSpec: Int, maxSize: Int): Int {
return when (measureSpec) {
ViewGroup.LayoutParams.MATCH_PARENT -> maxSize
else -> MeasureSpec.getSize(measureSpec)
}
}
private fun getDropDownMeasureSpecMode(measureSpec: Int): Int {
return when (measureSpec) {
ViewGroup.LayoutParams.WRAP_CONTENT -> MeasureSpec.UNSPECIFIED
else -> MeasureSpec.EXACTLY
}
}
}
|
CT/commons/src/main/kotlin/com/simplemobiletools/commons/views/bottomactionmenu/BottomActionMenuPopup.kt | 1258688736 | package com.simplemobiletools.commons.views.bottomactionmenu
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.view.accessibility.AccessibilityEvent
import android.widget.PopupWindow
import androidx.annotation.MenuRes
import androidx.core.view.doOnLayout
import androidx.core.view.updateLayoutParams
import androidx.core.widget.PopupWindowCompat
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.simplemobiletools.commons.activities.BaseSimpleActivity
class BottomActionMenuPopup(private val activity: BaseSimpleActivity, items: List<BottomActionMenuItem>) {
private val bottomActionMenuView = BottomActionMenuView(activity)
private val popup = PopupWindow(activity, null, android.R.attr.popupMenuStyle)
private var floatingActionButton: FloatingActionButton? = null
private var underlayView: View? = null
private var callback: BottomActionMenuCallback? = null
constructor(activity: BaseSimpleActivity, @MenuRes menuResId: Int) : this(activity, BottomActionMenuParser(activity).inflate(menuResId))
init {
popup.contentView = bottomActionMenuView
popup.width = ViewGroup.LayoutParams.MATCH_PARENT
popup.height = ViewGroup.LayoutParams.WRAP_CONTENT
popup.isOutsideTouchable = false
popup.setOnDismissListener {
callback?.onViewDestroyed()
floatingActionButton?.show()
}
PopupWindowCompat.setWindowLayoutType(popup, WindowManager.LayoutParams.TYPE_APPLICATION)
bottomActionMenuView.setup(items)
}
fun show(callback: BottomActionMenuCallback? = null, underlayView: View? = null, hideFab: Boolean = true) {
this.callback = callback
callback?.onViewCreated(bottomActionMenuView)
if (hideFab) {
floatingActionButton?.hide() ?: findFABAndHide()
}
bottomActionMenuView.setCallback(callback)
bottomActionMenuView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED)
popup.showAtLocation(bottomActionMenuView, Gravity.BOTTOM or Gravity.FILL_HORIZONTAL, 0, 0)
bottomActionMenuView.show()
underlayView?.let {
this.underlayView = it
adjustUnderlayViewBottomMargin(it, true)
}
}
fun dismiss() {
popup.dismiss()
underlayView?.let {
adjustUnderlayViewBottomMargin(it, false)
}
}
private fun findFABAndHide() {
val parent = activity.findViewById<ViewGroup>(android.R.id.content)
findFab(parent)
floatingActionButton?.hide()
}
private fun findFab(parent: ViewGroup) {
val count = parent.childCount
for (i in 0 until count) {
val child = parent.getChildAt(i)
if (child is FloatingActionButton) {
floatingActionButton = child
break
} else if (child is ViewGroup) {
findFab(child)
}
}
}
private fun adjustUnderlayViewBottomMargin(view: View, showing: Boolean) {
bottomActionMenuView.doOnLayout {
view.updateLayoutParams {
if (this is ViewGroup.MarginLayoutParams) {
val newMargin = if (showing) {
bottomMargin + bottomActionMenuView.height
} else {
bottomMargin - bottomActionMenuView.height
}
if (newMargin >= 0) {
bottomMargin = newMargin
}
}
}
}
}
fun invalidate() {
callback?.onViewCreated(bottomActionMenuView)
}
}
|
CT/commons/src/main/kotlin/com/simplemobiletools/commons/views/bottomactionmenu/BottomActionMenuParser.kt | 3412814764 | package com.simplemobiletools.commons.views.bottomactionmenu
import android.content.Context
import android.util.AttributeSet
import android.util.Xml
import android.view.MenuItem
import android.view.View
import com.simplemobiletools.commons.R
import org.xmlpull.v1.XmlPullParser
internal class BottomActionMenuParser(private val context: Context) {
companion object {
private const val NO_TEXT = ""
private const val MENU_TAG = "menu"
private const val MENU_ITEM_TAG = "item"
}
fun inflate(menuId: Int): List<BottomActionMenuItem> {
val parser = context.resources.getLayout(menuId)
parser.use {
val attrs = Xml.asAttributeSet(parser)
return readContextItems(parser, attrs)
}
}
private fun readContextItems(parser: XmlPullParser, attrs: AttributeSet): List<BottomActionMenuItem> {
val items = mutableListOf<BottomActionMenuItem>()
var eventType = parser.eventType
var tagName: String
// This loop will skip to the menu start tag
do {
if (eventType == XmlPullParser.START_TAG) {
tagName = parser.name
if (tagName == MENU_TAG) {
// Go to next tag
eventType = parser.next()
break
}
throw RuntimeException("Expecting menu, got $tagName")
}
eventType = parser.next()
} while (eventType != XmlPullParser.END_DOCUMENT)
var reachedEndOfMenu = false
while (!reachedEndOfMenu) {
tagName = parser.name
if (eventType == XmlPullParser.END_TAG) {
if (tagName == MENU_TAG) {
reachedEndOfMenu = true
}
}
if (eventType == XmlPullParser.START_TAG) {
when (tagName) {
MENU_ITEM_TAG -> items.add(readBottomActionMenuItem(parser, attrs))
}
}
eventType = parser.next()
}
return items
}
private fun readBottomActionMenuItem(parser: XmlPullParser, attrs: AttributeSet): BottomActionMenuItem {
val typedArray = context.obtainStyledAttributes(attrs, R.styleable.BottomActionMenuItem)
val id = typedArray.getResourceId(R.styleable.BottomActionMenuItem_android_id, View.NO_ID)
val text = typedArray.getString(R.styleable.BottomActionMenuItem_android_title) ?: NO_TEXT
val iconId = typedArray.getResourceId(R.styleable.BottomActionMenuItem_android_icon, View.NO_ID)
val showAsAction = typedArray.getInt(R.styleable.BottomActionMenuItem_showAsAction, -1)
val visible = typedArray.getBoolean(R.styleable.BottomActionMenuItem_android_visible, true)
typedArray.recycle()
parser.require(XmlPullParser.START_TAG, null, MENU_ITEM_TAG)
return BottomActionMenuItem(
id,
text,
iconId,
showAsAction == MenuItem.SHOW_AS_ACTION_ALWAYS || showAsAction == MenuItem.SHOW_AS_ACTION_IF_ROOM,
visible
)
}
}
|
CT/commons/src/main/kotlin/com/simplemobiletools/commons/views/bottomactionmenu/BottomActionMenuView.kt | 2646923329 | package com.simplemobiletools.commons.views.bottomactionmenu
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.TimeInterpolator
import android.content.Context
import android.graphics.Color
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.ViewPropertyAnimator
import android.widget.ImageView
import android.widget.LinearLayout
import androidx.annotation.IdRes
import com.google.android.material.animation.AnimationUtils
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.extensions.applyColorFilter
import com.simplemobiletools.commons.extensions.beVisibleIf
import com.simplemobiletools.commons.extensions.toast
import com.simplemobiletools.commons.extensions.windowManager
import com.simplemobiletools.commons.helpers.isRPlus
class BottomActionMenuView : LinearLayout {
companion object {
private const val ENTER_ANIMATION_DURATION = 225
private const val EXIT_ANIMATION_DURATION = 175
}
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle)
private val inflater = LayoutInflater.from(context)
private val itemsLookup = LinkedHashMap<Int, BottomActionMenuItem>()
private val items: List<BottomActionMenuItem>
get() = itemsLookup.values.toList().sortedWith(compareByDescending<BottomActionMenuItem> {
it.showAsAction
}.thenBy {
it.icon != View.NO_ID
}).filter { it.isVisible }
private var currentAnimator: ViewPropertyAnimator? = null
private var callback: BottomActionMenuCallback? = null
private var itemPopup: BottomActionMenuItemPopup? = null
init {
orientation = HORIZONTAL
elevation = 2f
}
fun setCallback(listener: BottomActionMenuCallback?) {
this.callback = listener
}
fun hide() {
slideDownToGone()
}
fun show() {
slideUpToVisible()
}
private fun slideUpToVisible() {
currentAnimator?.also {
it.cancel()
clearAnimation()
}
animateChildTo(0, ENTER_ANIMATION_DURATION.toLong(), AnimationUtils.LINEAR_OUT_SLOW_IN_INTERPOLATOR, true)
}
private fun slideDownToGone() {
currentAnimator?.also {
currentAnimator?.cancel()
clearAnimation()
}
animateChildTo(
height + (layoutParams as MarginLayoutParams).bottomMargin,
EXIT_ANIMATION_DURATION.toLong(),
AnimationUtils.FAST_OUT_LINEAR_IN_INTERPOLATOR
)
}
private fun animateChildTo(targetY: Int, duration: Long, interpolator: TimeInterpolator, visible: Boolean = false) {
currentAnimator = animate()
.translationY(targetY.toFloat())
.setInterpolator(interpolator)
.setDuration(duration)
.setListener(
object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator) {
currentAnimator = null
beVisibleIf(visible)
}
})
}
fun setup(items: List<BottomActionMenuItem>) {
items.forEach { itemsLookup[it.id] = it }
init()
}
fun add(item: BottomActionMenuItem) {
setItem(item)
}
private fun setItem(item: BottomActionMenuItem?) {
item?.let {
val oldItem = itemsLookup[item.id]
itemsLookup[item.id] = item
if (oldItem != item) {
init()
}
}
}
fun toggleItemVisibility(@IdRes itemId: Int, show: Boolean) {
val item = itemsLookup[itemId]
setItem(item?.copy(isVisible = show))
}
private fun init() {
removeAllViews()
val maxItemsBeforeOverflow = computeMaxItemsBeforeOverflow()
val allItems = items
for (i in allItems.indices) {
if (i <= maxItemsBeforeOverflow) {
drawNormalItem(allItems[i])
} else {
drawOverflowItem(allItems.slice(i until allItems.size))
break
}
}
}
private fun computeMaxItemsBeforeOverflow(): Int {
val itemsToShowAsAction = items.filter { it.showAsAction && it.icon != View.NO_ID }
val itemMinWidth = context.resources.getDimensionPixelSize(R.dimen.cab_item_min_width)
val totalActionWidth = (itemsToShowAsAction.size + 1) * itemMinWidth
val screenWidth = if (isRPlus()) {
context.windowManager.currentWindowMetrics.bounds.width()
} else {
context.windowManager.defaultDisplay.width
}
val result = if (screenWidth > totalActionWidth) {
itemsToShowAsAction.size
} else {
screenWidth / itemMinWidth
}
return result - 1
}
private fun drawNormalItem(item: BottomActionMenuItem) {
(inflater.inflate(R.layout.item_action_mode, this, false) as ImageView).apply {
setupItem(item)
setOnClickListener {
if (itemPopup?.isShowing == true) {
itemPopup?.dismiss()
} else {
callback?.onItemClicked(item)
}
}
setOnLongClickListener {
context.toast(item.title)
true
}
addView(this)
}
}
private fun drawOverflowItem(overFlowItems: List<BottomActionMenuItem>) {
(inflater.inflate(R.layout.item_action_mode, this, false) as ImageView).apply {
setImageResource(R.drawable.ic_three_dots_vector)
val contentDesc = context.getString(R.string.more_info)
contentDescription = contentDesc
applyColorFilter(Color.WHITE)
itemPopup = getOverflowPopup(overFlowItems)
setOnClickListener {
if (itemPopup?.isShowing == true) {
itemPopup?.dismiss()
} else {
itemPopup?.show(it)
}
}
setOnLongClickListener {
context.toast(contentDesc)
true
}
addView(this)
}
}
private fun ImageView.setupItem(item: BottomActionMenuItem) {
id = item.id
contentDescription = item.title
if (item.icon != View.NO_ID) {
setImageResource(item.icon)
}
beVisibleIf(item.isVisible)
applyColorFilter(Color.WHITE)
}
private fun getOverflowPopup(overFlowItems: List<BottomActionMenuItem>): BottomActionMenuItemPopup {
return BottomActionMenuItemPopup(context, overFlowItems) {
callback?.onItemClicked(it)
}
}
}
|
CT/commons/src/main/kotlin/com/simplemobiletools/commons/views/bottomactionmenu/BottomActionMenuItem.kt | 954772467 | package com.simplemobiletools.commons.views.bottomactionmenu
import android.view.View
import androidx.annotation.DrawableRes
import androidx.annotation.IdRes
data class BottomActionMenuItem(
@IdRes val id: Int,
val title: String,
@DrawableRes val icon: Int = View.NO_ID,
val showAsAction: Boolean,
val isVisible: Boolean = true,
)
|
CT/commons/src/main/kotlin/com/simplemobiletools/commons/views/bottomactionmenu/BottomActionMenuCallback.kt | 3122509152 | package com.simplemobiletools.commons.views.bottomactionmenu
interface BottomActionMenuCallback {
fun onItemClicked(item: BottomActionMenuItem) {}
fun onViewCreated(view: BottomActionMenuView) {}
fun onViewDestroyed() {}
}
|
CT/commons/src/main/kotlin/com/simplemobiletools/commons/views/MyCompatRadioButton.kt | 1578580274 | package com.simplemobiletools.commons.views
import android.content.Context
import android.content.res.ColorStateList
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatRadioButton
import com.simplemobiletools.commons.extensions.adjustAlpha
class MyCompatRadioButton : AppCompatRadioButton {
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle)
fun setColors(textColor: Int, accentColor: Int, backgroundColor: Int) {
setTextColor(textColor)
val colorStateList = ColorStateList(
arrayOf(
intArrayOf(-android.R.attr.state_checked),
intArrayOf(android.R.attr.state_checked)
),
intArrayOf(textColor.adjustAlpha(0.6f), accentColor)
)
supportButtonTintList = colorStateList
}
}
|
CT/commons/src/main/kotlin/com/simplemobiletools/commons/views/MySearchMenu.kt | 233290568 | package com.simplemobiletools.commons.views
import android.app.Activity
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import com.google.android.material.appbar.AppBarLayout
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.activities.BaseSimpleActivity
import com.simplemobiletools.commons.databinding.MenuSearchBinding
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.LOWER_ALPHA
import com.simplemobiletools.commons.helpers.MEDIUM_ALPHA
class MySearchMenu(context: Context, attrs: AttributeSet) : AppBarLayout(context, attrs) {
var isSearchOpen = false
var useArrowIcon = false
var onSearchOpenListener: (() -> Unit)? = null
var onSearchClosedListener: (() -> Unit)? = null
var onSearchTextChangedListener: ((text: String) -> Unit)? = null
var onNavigateBackClickListener: (() -> Unit)? = null
val binding = MenuSearchBinding.inflate(LayoutInflater.from(context), this, true)
fun getToolbar() = binding.topToolbar
fun setupMenu() {
binding.topToolbarSearchIcon.setOnClickListener {
if (isSearchOpen) {
closeSearch()
} else if (useArrowIcon && onNavigateBackClickListener != null) {
onNavigateBackClickListener!!()
} else {
binding.topToolbarSearch.requestFocus()
(context as? Activity)?.showKeyboard(binding.topToolbarSearch)
}
}
post {
binding.topToolbarSearch.setOnFocusChangeListener { v, hasFocus ->
if (hasFocus) {
openSearch()
}
}
}
binding.topToolbarSearch.onTextChangeListener { text ->
onSearchTextChangedListener?.invoke(text)
}
}
fun focusView() {
binding.topToolbarSearch.requestFocus()
}
private fun openSearch() {
isSearchOpen = true
onSearchOpenListener?.invoke()
binding.topToolbarSearchIcon.setImageResource(R.drawable.ic_arrow_left_vector)
binding.topToolbarSearchIcon.contentDescription = resources.getString(R.string.back)
}
fun closeSearch() {
isSearchOpen = false
onSearchClosedListener?.invoke()
binding.topToolbarSearch.setText("")
if (!useArrowIcon) {
binding.topToolbarSearchIcon.setImageResource(R.drawable.ic_search_vector)
binding.topToolbarSearchIcon.contentDescription = resources.getString(R.string.search)
}
(context as? Activity)?.hideKeyboard()
}
fun getCurrentQuery() = binding.topToolbarSearch.text.toString()
fun updateHintText(text: String) {
binding.topToolbarSearch.hint = text
}
fun toggleHideOnScroll(hideOnScroll: Boolean) {
val params = binding.topAppBarLayout.layoutParams as LayoutParams
if (hideOnScroll) {
params.scrollFlags = LayoutParams.SCROLL_FLAG_SCROLL or LayoutParams.SCROLL_FLAG_ENTER_ALWAYS
} else {
params.scrollFlags = params.scrollFlags.removeBit(LayoutParams.SCROLL_FLAG_SCROLL or LayoutParams.SCROLL_FLAG_ENTER_ALWAYS)
}
}
fun toggleForceArrowBackIcon(useArrowBack: Boolean) {
this.useArrowIcon = useArrowBack
val (icon, accessibilityString) = if (useArrowBack) {
Pair(R.drawable.ic_arrow_left_vector, R.string.back)
} else {
Pair(R.drawable.ic_search_vector, R.string.search)
}
binding.topToolbarSearchIcon.setImageResource(icon)
binding.topToolbarSearchIcon.contentDescription = resources.getString(accessibilityString)
}
fun updateColors() {
val backgroundColor = context.getProperBackgroundColor()
val contrastColor = backgroundColor.getContrastColor()
setBackgroundColor(backgroundColor)
binding.topAppBarLayout.setBackgroundColor(backgroundColor)
binding.topToolbarSearchIcon.applyColorFilter(contrastColor)
binding.topToolbarHolder.background?.applyColorFilter(context.getProperPrimaryColor().adjustAlpha(LOWER_ALPHA))
binding.topToolbarSearch.setTextColor(contrastColor)
binding.topToolbarSearch.setHintTextColor(contrastColor.adjustAlpha(MEDIUM_ALPHA))
(context as? BaseSimpleActivity)?.updateTopBarColors(binding.topToolbar, backgroundColor)
}
}
|
CT/commons/src/main/kotlin/com/simplemobiletools/commons/views/LineColorPicker.kt | 2688837084 | package com.simplemobiletools.commons.views
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.MotionEvent
import android.widget.LinearLayout
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.extensions.isRTLLayout
import com.simplemobiletools.commons.extensions.onGlobalLayout
import com.simplemobiletools.commons.interfaces.LineColorPickerListener
class LineColorPicker @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyle: Int = 0
) : LinearLayout(context, attrs, defStyle) {
private var colorsCount = 0
private var pickerWidth = 0
private var stripeWidth = 0
private var unselectedMargin = 0
private var lastColorIndex = -1
private var wasInit = false
private var colors = ArrayList<Int>()
var listener: LineColorPickerListener? = null
init {
unselectedMargin = context.resources.getDimension(R.dimen.line_color_picker_margin).toInt()
onGlobalLayout {
if (pickerWidth == 0) {
pickerWidth = width
if (colorsCount != 0)
stripeWidth = width / colorsCount
}
if (!wasInit) {
wasInit = true
initColorPicker()
updateItemMargin(lastColorIndex, false)
}
}
orientation = LinearLayout.HORIZONTAL
setOnTouchListener { view, motionEvent ->
when (motionEvent.action) {
MotionEvent.ACTION_MOVE, MotionEvent.ACTION_UP -> {
if (pickerWidth != 0 && stripeWidth != 0) {
touchAt(motionEvent.x.toInt())
}
}
}
true
}
}
fun updateColors(colors: ArrayList<Int>, selectColorIndex: Int = -1) {
this.colors = colors
colorsCount = colors.size
if (pickerWidth != 0) {
stripeWidth = pickerWidth / colorsCount
}
if (selectColorIndex != -1) {
lastColorIndex = selectColorIndex
}
initColorPicker()
updateItemMargin(lastColorIndex, false)
}
// do not remove ": Int", it causes "NoSuchMethodError" for some reason
fun getCurrentColor(): Int = colors[lastColorIndex]
private fun initColorPicker() {
removeAllViews()
val inflater = LayoutInflater.from(context)
colors.forEach {
inflater.inflate(R.layout.empty_image_view, this, false).apply {
setBackgroundColor(it)
addView(this)
}
}
}
private fun touchAt(touchX: Int) {
var colorIndex = touchX / stripeWidth
if (context.isRTLLayout) {
colorIndex = colors.size - colorIndex - 1
}
val index = Math.max(0, Math.min(colorIndex, colorsCount - 1))
if (lastColorIndex != index) {
updateItemMargin(lastColorIndex, true)
lastColorIndex = index
updateItemMargin(index, false)
listener?.colorChanged(index, colors[index])
}
}
private fun updateItemMargin(index: Int, addMargin: Boolean) {
getChildAt(index)?.apply {
(layoutParams as LinearLayout.LayoutParams).apply {
topMargin = if (addMargin) unselectedMargin else 0
bottomMargin = if (addMargin) unselectedMargin else 0
}
requestLayout()
}
}
}
|
CT/commons/src/main/kotlin/com/simplemobiletools/commons/views/PatternTab.kt | 2644306588 | package com.simplemobiletools.commons.views
import android.annotation.SuppressLint
import android.content.Context
import android.os.Handler
import android.util.AttributeSet
import android.view.MotionEvent
import android.widget.TextView
import androidx.biometric.auth.AuthPromptHost
import androidx.core.os.postDelayed
import com.andrognito.patternlockview.PatternLockView
import com.andrognito.patternlockview.listener.PatternLockViewListener
import com.andrognito.patternlockview.utils.PatternLockUtils
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.databinding.TabPatternBinding
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.PROTECTION_PATTERN
import com.simplemobiletools.commons.interfaces.BaseSecurityTab
import com.simplemobiletools.commons.interfaces.HashListener
class PatternTab(context: Context, attrs: AttributeSet) : BaseSecurityTab(context, attrs) {
private var scrollView: MyScrollView? = null
private lateinit var binding: TabPatternBinding
override val protectionType = PROTECTION_PATTERN
override val defaultTextRes = R.string.insert_pattern
override val wrongTextRes = R.string.wrong_pattern
override val titleTextView: TextView
get() = binding.patternLockTitle
@SuppressLint("ClickableViewAccessibility")
override fun onFinishInflate() {
super.onFinishInflate()
binding = TabPatternBinding.bind(this)
val textColor = context.getProperTextColor()
context.updateTextColors(binding.patternLockHolder)
binding.patternLockView.setOnTouchListener { _, event ->
when (event.action) {
MotionEvent.ACTION_DOWN -> scrollView?.isScrollable = false
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> scrollView?.isScrollable = true
}
false
}
binding.patternLockView.correctStateColor = context.getProperPrimaryColor()
binding.patternLockView.normalStateColor = textColor
binding.patternLockView.addPatternLockListener(object : PatternLockViewListener {
override fun onComplete(pattern: MutableList<PatternLockView.Dot>?) {
receivedHash(PatternLockUtils.patternToSha1(binding.patternLockView, pattern))
}
override fun onCleared() {}
override fun onStarted() {}
override fun onProgress(progressPattern: MutableList<PatternLockView.Dot>?) {}
})
binding.patternLockIcon.applyColorFilter(textColor)
maybeShowCountdown()
}
override fun initTab(
requiredHash: String,
listener: HashListener,
scrollView: MyScrollView,
biometricPromptHost: AuthPromptHost,
showBiometricAuthentication: Boolean
) {
this.requiredHash = requiredHash
this.scrollView = scrollView
computedHash = requiredHash
hashListener = listener
}
override fun onLockedOutChange(lockedOut: Boolean) {
binding.patternLockView.isInputEnabled = !lockedOut
}
private fun receivedHash(newHash: String) {
if (isLockedOut()) {
performHapticFeedback()
return
}
when {
computedHash.isEmpty() -> {
computedHash = newHash
binding.patternLockView.clearPattern()
binding.patternLockTitle.setText(R.string.repeat_pattern)
}
computedHash == newHash -> {
binding.patternLockView.setViewMode(PatternLockView.PatternViewMode.CORRECT)
onCorrectPassword()
}
else -> {
onIncorrectPassword()
binding.patternLockView.setViewMode(PatternLockView.PatternViewMode.WRONG)
Handler().postDelayed(delayInMillis = 1000) {
binding.patternLockView.clearPattern()
if (requiredHash.isEmpty()) {
computedHash = ""
}
}
}
}
}
}
|
CT/commons/src/main/kotlin/com/simplemobiletools/commons/views/AutoStaggeredGridLayoutManager.kt | 1388238311 | package com.simplemobiletools.commons.views
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import kotlin.math.max
/**
* RecyclerView StaggeredGridLayoutManager but with automatic spanCount calculation.
*
* @param context The initiating view's context.
* @param itemSize: Grid item size (width or height, depending on orientation) in pixels. Will be used to calculate span count.
*/
class AutoStaggeredGridLayoutManager(
private var itemSize: Int,
orientation: Int,
) : StaggeredGridLayoutManager(1, orientation) {
init {
require(itemSize >= 0) {
"itemSize must be >= 0"
}
}
override fun onLayoutChildren(recycler: RecyclerView.Recycler?, state: RecyclerView.State?) {
val width = width
val height = height
if (itemSize > 0 && width > 0 && height > 0) {
val totalSpace = if (orientation == VERTICAL) {
width - paddingRight - paddingLeft
} else {
height - paddingTop - paddingBottom
}
postOnAnimation {
spanCount = max(1, totalSpace / itemSize)
}
}
super.onLayoutChildren(recycler, state)
}
// fixes crash java.lang.IndexOutOfBoundsException: Inconsistency detected...
// taken from https://stackoverflow.com/a/33985508/1967672
override fun supportsPredictiveItemAnimations() = false
}
|
CT/commons/src/main/kotlin/com/simplemobiletools/commons/views/MySquareImageView.kt | 3009276916 | package com.simplemobiletools.commons.views
import android.content.Context
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatImageView
class MySquareImageView : AppCompatImageView {
var isHorizontalScrolling = false
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle)
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
val spec = if (isHorizontalScrolling) heightMeasureSpec else widthMeasureSpec
super.onMeasure(spec, spec)
}
}
|
CT/commons/src/main/kotlin/com/simplemobiletools/commons/views/FingerprintTab.kt | 532568451 | package com.simplemobiletools.commons.views
import android.content.Context
import android.content.Intent
import android.os.Handler
import android.provider.Settings
import android.util.AttributeSet
import android.widget.RelativeLayout
import androidx.biometric.auth.AuthPromptHost
import com.github.ajalt.reprint.core.AuthenticationFailureReason
import com.github.ajalt.reprint.core.AuthenticationListener
import com.github.ajalt.reprint.core.Reprint
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.databinding.TabFingerprintBinding
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.PROTECTION_FINGERPRINT
import com.simplemobiletools.commons.interfaces.HashListener
import com.simplemobiletools.commons.interfaces.SecurityTab
class FingerprintTab(context: Context, attrs: AttributeSet) : RelativeLayout(context, attrs), SecurityTab {
private val RECHECK_PERIOD = 3000L
private val registerHandler = Handler()
lateinit var hashListener: HashListener
private lateinit var binding: TabFingerprintBinding
override fun onFinishInflate() {
super.onFinishInflate()
binding = TabFingerprintBinding.bind(this)
val textColor = context.getProperTextColor()
context.updateTextColors(binding.fingerprintLockHolder)
binding.fingerprintImage.applyColorFilter(textColor)
binding.fingerprintSettings.setOnClickListener {
context.startActivity(Intent(Settings.ACTION_SETTINGS))
}
}
override fun initTab(
requiredHash: String,
listener: HashListener,
scrollView: MyScrollView,
biometricPromptHost: AuthPromptHost,
showBiometricAuthentication: Boolean
) {
hashListener = listener
}
override fun visibilityChanged(isVisible: Boolean) {
if (isVisible) {
checkRegisteredFingerprints()
} else {
Reprint.cancelAuthentication()
}
}
private fun checkRegisteredFingerprints() {
val hasFingerprints = Reprint.hasFingerprintRegistered()
binding.fingerprintSettings.beGoneIf(hasFingerprints)
binding.fingerprintLabel.text = context.getString(if (hasFingerprints) R.string.place_finger else R.string.no_fingerprints_registered)
Reprint.authenticate(object : AuthenticationListener {
override fun onSuccess(moduleTag: Int) {
hashListener.receivedHash("", PROTECTION_FINGERPRINT)
}
override fun onFailure(failureReason: AuthenticationFailureReason?, fatal: Boolean, errorMessage: CharSequence?, moduleTag: Int, errorCode: Int) {
when (failureReason) {
AuthenticationFailureReason.AUTHENTICATION_FAILED -> context.toast(R.string.authentication_failed)
AuthenticationFailureReason.LOCKED_OUT -> context.toast(R.string.authentication_blocked)
else -> {}
}
}
})
registerHandler.postDelayed({
checkRegisteredFingerprints()
}, RECHECK_PERIOD)
}
override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
registerHandler.removeCallbacksAndMessages(null)
Reprint.cancelAuthentication()
}
}
|
CT/commons/src/main/kotlin/com/simplemobiletools/commons/views/MyDialogViewPager.kt | 576377728 | package com.simplemobiletools.commons.views
import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import androidx.viewpager.widget.ViewPager
class MyDialogViewPager : ViewPager {
var allowSwiping = true
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
// disable manual swiping of viewpager at the dialog by swiping over the pattern
override fun onInterceptTouchEvent(ev: MotionEvent) = false
override fun onTouchEvent(ev: MotionEvent): Boolean {
if (!allowSwiping)
return false
try {
return super.onTouchEvent(ev)
} catch (ignored: Exception) {
}
return false
}
// https://stackoverflow.com/a/20784791/1967672
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
var height = 0
for (i in 0 until childCount) {
val child = getChildAt(i)
child.measure(widthMeasureSpec, View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED))
val h = child.measuredHeight
if (h > height) height = h
}
val newHeightMeasureSpec = View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY)
super.onMeasure(widthMeasureSpec, newHeightMeasureSpec)
}
}
|
CT/commons/src/main/kotlin/com/simplemobiletools/commons/views/MyLinearLayoutManager.kt | 2198207665 | package com.simplemobiletools.commons.views
import android.content.Context
import android.util.AttributeSet
import androidx.recyclerview.widget.LinearLayoutManager
class MyLinearLayoutManager : LinearLayoutManager {
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes)
constructor(context: Context, orientation: Int, reverseLayout: Boolean) : super(context, orientation, reverseLayout)
// fixes crash java.lang.IndexOutOfBoundsException: Inconsistency detected...
// taken from https://stackoverflow.com/a/33985508/1967672
override fun supportsPredictiveItemAnimations() = false
}
|
CT/commons/src/main/kotlin/com/simplemobiletools/commons/views/RenamePatternTab.kt | 3184856890 | package com.simplemobiletools.commons.views
import android.content.ContentValues
import android.content.Context
import android.provider.MediaStore
import android.text.format.DateFormat
import android.util.AttributeSet
import android.widget.RelativeLayout
import androidx.exifinterface.media.ExifInterface
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.activities.BaseSimpleActivity
import com.simplemobiletools.commons.databinding.DialogRenameItemsPatternBinding
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.isNougatPlus
import com.simplemobiletools.commons.interfaces.RenameTab
import com.simplemobiletools.commons.models.Android30RenameFormat
import com.simplemobiletools.commons.models.FileDirItem
import java.io.File
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Locale
class RenamePatternTab(context: Context, attrs: AttributeSet) : RelativeLayout(context, attrs), RenameTab {
var ignoreClicks = false
var stopLooping = false // we should request the permission on Android 30+ for all uris at once, not one by one
var currentIncrementalNumber = 1
var numbersCnt = 0
var activity: BaseSimpleActivity? = null
var paths = ArrayList<String>()
private lateinit var binding: DialogRenameItemsPatternBinding
override fun onFinishInflate() {
super.onFinishInflate()
binding = DialogRenameItemsPatternBinding.bind(this)
context.updateTextColors(binding.renameItemsHolder)
}
override fun initTab(activity: BaseSimpleActivity, paths: ArrayList<String>) {
this.activity = activity
this.paths = paths
binding.renameItemsValue.setText(activity.baseConfig.lastRenamePatternUsed)
}
override fun dialogConfirmed(useMediaFileExtension: Boolean, callback: (success: Boolean) -> Unit) {
stopLooping = false
if (ignoreClicks) {
return
}
val newNameRaw = binding.renameItemsValue.value
if (newNameRaw.isEmpty()) {
callback(false)
return
}
val validPaths = paths.filter { activity?.getDoesFilePathExist(it) == true }
val firstPath = validPaths.firstOrNull()
val sdFilePath = validPaths.firstOrNull { activity?.isPathOnSD(it) == true } ?: firstPath
if (firstPath == null || sdFilePath == null) {
activity?.toast(R.string.unknown_error_occurred)
return
}
activity?.baseConfig?.lastRenamePatternUsed = binding.renameItemsValue.value
activity?.handleSAFDialog(sdFilePath) {
if (!it) {
return@handleSAFDialog
}
activity?.checkManageMediaOrHandleSAFDialogSdk30(firstPath) {
if (!it) {
return@checkManageMediaOrHandleSAFDialogSdk30
}
ignoreClicks = true
var pathsCnt = validPaths.size
numbersCnt = pathsCnt.toString().length
for (path in validPaths) {
if (stopLooping) {
return@checkManageMediaOrHandleSAFDialogSdk30
}
try {
val newPath = getNewPath(path, useMediaFileExtension) ?: continue
activity?.renameFile(path, newPath, true) { success, android30Format ->
if (success) {
pathsCnt--
if (pathsCnt == 0) {
callback(true)
}
} else {
ignoreClicks = false
if (android30Format != Android30RenameFormat.NONE) {
currentIncrementalNumber = 1
stopLooping = true
renameAllFiles(validPaths, useMediaFileExtension, android30Format, callback)
}
}
}
} catch (e: Exception) {
activity?.showErrorToast(e)
}
}
stopLooping = false
}
}
}
private fun getNewPath(path: String, useMediaFileExtension: Boolean): String? {
try {
val exif = ExifInterface(path)
var dateTime = if (isNougatPlus()) {
exif.getAttribute(ExifInterface.TAG_DATETIME_ORIGINAL) ?: exif.getAttribute(ExifInterface.TAG_DATETIME)
} else {
exif.getAttribute(ExifInterface.TAG_DATETIME)
}
if (dateTime == null) {
val calendar = Calendar.getInstance(Locale.ENGLISH)
calendar.timeInMillis = File(path).lastModified()
dateTime = DateFormat.format("yyyy:MM:dd kk:mm:ss", calendar).toString()
}
val pattern = if (dateTime.substring(4, 5) == "-") "yyyy-MM-dd kk:mm:ss" else "yyyy:MM:dd kk:mm:ss"
val simpleDateFormat = SimpleDateFormat(pattern, Locale.ENGLISH)
val dt = simpleDateFormat.parse(dateTime.replace("T", " "))
val cal = Calendar.getInstance()
cal.time = dt
val year = cal.get(Calendar.YEAR).toString()
val month = (cal.get(Calendar.MONTH) + 1).ensureTwoDigits()
val day = (cal.get(Calendar.DAY_OF_MONTH)).ensureTwoDigits()
val hours = (cal.get(Calendar.HOUR_OF_DAY)).ensureTwoDigits()
val minutes = (cal.get(Calendar.MINUTE)).ensureTwoDigits()
val seconds = (cal.get(Calendar.SECOND)).ensureTwoDigits()
var newName = binding.renameItemsValue.value
.replace("%Y", year, false)
.replace("%M", month, false)
.replace("%D", day, false)
.replace("%h", hours, false)
.replace("%m", minutes, false)
.replace("%s", seconds, false)
.replace("%i", String.format("%0${numbersCnt}d", currentIncrementalNumber))
if (newName.isEmpty()) {
return null
}
currentIncrementalNumber++
if ((!newName.contains(".") && path.contains(".")) || (useMediaFileExtension && !".${newName.substringAfterLast(".")}".isMediaFile())) {
val extension = path.substringAfterLast(".")
newName += ".$extension"
}
var newPath = "${path.getParentPath()}/$newName"
var currentIndex = 0
while (activity?.getDoesFilePathExist(newPath) == true) {
currentIndex++
var extension = ""
val name = if (newName.contains(".")) {
extension = ".${newName.substringAfterLast(".")}"
newName.substringBeforeLast(".")
} else {
newName
}
newPath = "${path.getParentPath()}/$name~$currentIndex$extension"
}
return newPath
} catch (e: Exception) {
return null
}
}
private fun renameAllFiles(
paths: List<String>,
useMediaFileExtension: Boolean,
android30Format: Android30RenameFormat,
callback: (success: Boolean) -> Unit
) {
val fileDirItems = paths.map { File(it).toFileDirItem(context) }
val uriPairs = context.getUrisPathsFromFileDirItems(fileDirItems)
val validPaths = uriPairs.first
val uris = uriPairs.second
val activity = activity
activity?.updateSDK30Uris(uris) { success ->
if (success) {
try {
uris.forEachIndexed { index, uri ->
val path = validPaths[index]
val newFileName = getNewPath(path, useMediaFileExtension)?.getFilenameFromPath() ?: return@forEachIndexed
when (android30Format) {
Android30RenameFormat.SAF -> {
val sourceFile = File(path).toFileDirItem(context)
val newPath = "${path.getParentPath()}/$newFileName"
val destinationFile = FileDirItem(
newPath,
newFileName,
sourceFile.isDirectory,
sourceFile.children,
sourceFile.size,
sourceFile.modified
)
if (activity.copySingleFileSdk30(sourceFile, destinationFile)) {
if (!activity.baseConfig.keepLastModified) {
File(newPath).setLastModified(System.currentTimeMillis())
}
activity.contentResolver.delete(uri, null)
activity.updateInMediaStore(path, newPath)
activity.scanPathsRecursively(arrayListOf(newPath))
}
}
Android30RenameFormat.CONTENT_RESOLVER -> {
val values = ContentValues().apply {
put(MediaStore.Images.Media.DISPLAY_NAME, newFileName)
}
context.contentResolver.update(uri, values, null, null)
}
Android30RenameFormat.NONE -> {
activity.runOnUiThread {
callback(true)
}
return@forEachIndexed
}
}
}
activity.runOnUiThread {
callback(true)
}
} catch (e: Exception) {
activity.runOnUiThread {
activity.showErrorToast(e)
callback(false)
}
}
}
}
}
}
|
CT/commons/src/main/kotlin/com/simplemobiletools/commons/views/PinTab.kt | 3455023298 | package com.simplemobiletools.commons.views
import android.content.Context
import android.util.AttributeSet
import android.widget.TextView
import android.widget.Toast
import androidx.biometric.auth.AuthPromptHost
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.databinding.TabPinBinding
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.MINIMUM_PIN_LENGTH
import com.simplemobiletools.commons.helpers.PROTECTION_PIN
import com.simplemobiletools.commons.interfaces.BaseSecurityTab
import com.simplemobiletools.commons.interfaces.HashListener
import java.math.BigInteger
import java.security.MessageDigest
import java.util.Locale
class PinTab(context: Context, attrs: AttributeSet) : BaseSecurityTab(context, attrs) {
private var pin = ""
private lateinit var binding: TabPinBinding
override val protectionType = PROTECTION_PIN
override val defaultTextRes = R.string.enter_pin
override val wrongTextRes = R.string.wrong_pin
override val titleTextView: TextView
get() = binding.pinLockTitle
override fun onFinishInflate() {
super.onFinishInflate()
binding = TabPinBinding.bind(this)
val textColor = context.getProperTextColor()
context.updateTextColors(binding.pinLockHolder)
binding.pin0.setOnClickListener { addNumber("0") }
binding.pin1.setOnClickListener { addNumber("1") }
binding.pin2.setOnClickListener { addNumber("2") }
binding.pin3.setOnClickListener { addNumber("3") }
binding.pin4.setOnClickListener { addNumber("4") }
binding.pin5.setOnClickListener { addNumber("5") }
binding.pin6.setOnClickListener { addNumber("6") }
binding.pin7.setOnClickListener { addNumber("7") }
binding.pin8.setOnClickListener { addNumber("8") }
binding.pin9.setOnClickListener { addNumber("9") }
binding.pinC.setOnClickListener { clear() }
binding.pinOk.setOnClickListener { confirmPIN() }
binding.pinOk.applyColorFilter(textColor)
binding.pinLockIcon.applyColorFilter(textColor)
maybeShowCountdown()
}
override fun initTab(
requiredHash: String,
listener: HashListener,
scrollView: MyScrollView,
biometricPromptHost: AuthPromptHost,
showBiometricAuthentication: Boolean
) {
this.requiredHash = requiredHash
computedHash = requiredHash
hashListener = listener
}
private fun addNumber(number: String) {
if (!isLockedOut()) {
if (pin.length < 10) {
pin += number
updatePinCode()
}
}
performHapticFeedback()
}
private fun clear() {
if (pin.isNotEmpty()) {
pin = pin.substring(0, pin.length - 1)
updatePinCode()
}
performHapticFeedback()
}
private fun confirmPIN() {
if (!isLockedOut()) {
val newHash = getHashedPin()
when {
pin.isEmpty() -> {
context.toast(id = R.string.please_enter_pin, length = Toast.LENGTH_LONG)
}
computedHash.isEmpty() && pin.length < MINIMUM_PIN_LENGTH -> {
resetPin()
context.toast(id = R.string.pin_must_be_4_digits_long, length = Toast.LENGTH_LONG)
}
computedHash.isEmpty() -> {
computedHash = newHash
resetPin()
binding.pinLockTitle.setText(R.string.repeat_pin)
}
computedHash == newHash -> {
onCorrectPassword()
}
else -> {
resetPin()
onIncorrectPassword()
if (requiredHash.isEmpty()) {
computedHash = ""
}
}
}
}
performHapticFeedback()
}
private fun resetPin() {
pin = ""
binding.pinLockCurrentPin.text = ""
}
private fun updatePinCode() {
binding.pinLockCurrentPin.text = "*".repeat(pin.length)
}
private fun getHashedPin(): String {
val messageDigest = MessageDigest.getInstance("SHA-1")
messageDigest.update(pin.toByteArray(charset("UTF-8")))
val digest = messageDigest.digest()
val bigInteger = BigInteger(1, digest)
return String.format(Locale.getDefault(), "%0${digest.size * 2}x", bigInteger).lowercase(Locale.getDefault())
}
}
|
CT/commons/src/main/kotlin/com/simplemobiletools/commons/helpers/BaseConfig.kt | 547304164 | package com.simplemobiletools.commons.helpers
import android.content.Context
import android.content.res.Configuration
import android.os.Environment
import android.text.format.DateFormat
import androidx.core.content.ContextCompat
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.extensions.getInternalStoragePath
import com.simplemobiletools.commons.extensions.getSDCardPath
import com.simplemobiletools.commons.extensions.getSharedPrefs
import com.simplemobiletools.commons.extensions.sharedPreferencesCallback
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.LinkedList
import java.util.Locale
import kotlin.reflect.KProperty0
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.filterNotNull
open class BaseConfig(val context: Context) {
protected val prefs = context.getSharedPrefs()
companion object {
fun newInstance(context: Context) = BaseConfig(context)
}
var appRunCount: Int
get() = prefs.getInt(APP_RUN_COUNT, 0)
set(appRunCount) = prefs.edit().putInt(APP_RUN_COUNT, appRunCount).apply()
var lastVersion: Int
get() = prefs.getInt(LAST_VERSION, 0)
set(lastVersion) = prefs.edit().putInt(LAST_VERSION, lastVersion).apply()
var primaryAndroidDataTreeUri: String
get() = prefs.getString(PRIMARY_ANDROID_DATA_TREE_URI, "")!!
set(uri) = prefs.edit().putString(PRIMARY_ANDROID_DATA_TREE_URI, uri).apply()
var sdAndroidDataTreeUri: String
get() = prefs.getString(SD_ANDROID_DATA_TREE_URI, "")!!
set(uri) = prefs.edit().putString(SD_ANDROID_DATA_TREE_URI, uri).apply()
var otgAndroidDataTreeUri: String
get() = prefs.getString(OTG_ANDROID_DATA_TREE_URI, "")!!
set(uri) = prefs.edit().putString(OTG_ANDROID_DATA_TREE_URI, uri).apply()
var primaryAndroidObbTreeUri: String
get() = prefs.getString(PRIMARY_ANDROID_OBB_TREE_URI, "")!!
set(uri) = prefs.edit().putString(PRIMARY_ANDROID_OBB_TREE_URI, uri).apply()
var sdAndroidObbTreeUri: String
get() = prefs.getString(SD_ANDROID_OBB_TREE_URI, "")!!
set(uri) = prefs.edit().putString(SD_ANDROID_OBB_TREE_URI, uri).apply()
var otgAndroidObbTreeUri: String
get() = prefs.getString(OTG_ANDROID_OBB_TREE_URI, "")!!
set(uri) = prefs.edit().putString(OTG_ANDROID_OBB_TREE_URI, uri).apply()
var sdTreeUri: String
get() = prefs.getString(SD_TREE_URI, "")!!
set(uri) = prefs.edit().putString(SD_TREE_URI, uri).apply()
var OTGTreeUri: String
get() = prefs.getString(OTG_TREE_URI, "")!!
set(OTGTreeUri) = prefs.edit().putString(OTG_TREE_URI, OTGTreeUri).apply()
var OTGPartition: String
get() = prefs.getString(OTG_PARTITION, "")!!
set(OTGPartition) = prefs.edit().putString(OTG_PARTITION, OTGPartition).apply()
var OTGPath: String
get() = prefs.getString(OTG_REAL_PATH, "")!!
set(OTGPath) = prefs.edit().putString(OTG_REAL_PATH, OTGPath).apply()
var sdCardPath: String
get() = prefs.getString(SD_CARD_PATH, getDefaultSDCardPath())!!
set(sdCardPath) = prefs.edit().putString(SD_CARD_PATH, sdCardPath).apply()
private fun getDefaultSDCardPath() = if (prefs.contains(SD_CARD_PATH)) "" else context.getSDCardPath()
var internalStoragePath: String
get() = prefs.getString(INTERNAL_STORAGE_PATH, getDefaultInternalPath())!!
set(internalStoragePath) = prefs.edit().putString(INTERNAL_STORAGE_PATH, internalStoragePath).apply()
private fun getDefaultInternalPath() = if (prefs.contains(INTERNAL_STORAGE_PATH)) "" else context.getInternalStoragePath()
var textColor: Int
get() = prefs.getInt(TEXT_COLOR, ContextCompat.getColor(context, R.color.default_text_color))
set(textColor) = prefs.edit().putInt(TEXT_COLOR, textColor).apply()
var backgroundColor: Int
get() = prefs.getInt(BACKGROUND_COLOR, ContextCompat.getColor(context, R.color.default_background_color))
set(backgroundColor) = prefs.edit().putInt(BACKGROUND_COLOR, backgroundColor).apply()
var primaryColor: Int
get() = prefs.getInt(PRIMARY_COLOR, ContextCompat.getColor(context, R.color.default_primary_color))
set(primaryColor) = prefs.edit().putInt(PRIMARY_COLOR, primaryColor).apply()
var accentColor: Int
get() = prefs.getInt(ACCENT_COLOR, ContextCompat.getColor(context, R.color.default_accent_color))
set(accentColor) = prefs.edit().putInt(ACCENT_COLOR, accentColor).apply()
var lastHandledShortcutColor: Int
get() = prefs.getInt(LAST_HANDLED_SHORTCUT_COLOR, 1)
set(lastHandledShortcutColor) = prefs.edit().putInt(LAST_HANDLED_SHORTCUT_COLOR, lastHandledShortcutColor).apply()
var appIconColor: Int
get() = prefs.getInt(APP_ICON_COLOR, ContextCompat.getColor(context, R.color.default_app_icon_color))
set(appIconColor) {
isUsingModifiedAppIcon = appIconColor != ContextCompat.getColor(context, R.color.color_primary)
prefs.edit().putInt(APP_ICON_COLOR, appIconColor).apply()
}
var lastIconColor: Int
get() = prefs.getInt(LAST_ICON_COLOR, ContextCompat.getColor(context, R.color.color_primary))
set(lastIconColor) = prefs.edit().putInt(LAST_ICON_COLOR, lastIconColor).apply()
var customTextColor: Int
get() = prefs.getInt(CUSTOM_TEXT_COLOR, textColor)
set(customTextColor) = prefs.edit().putInt(CUSTOM_TEXT_COLOR, customTextColor).apply()
var customBackgroundColor: Int
get() = prefs.getInt(CUSTOM_BACKGROUND_COLOR, backgroundColor)
set(customBackgroundColor) = prefs.edit().putInt(CUSTOM_BACKGROUND_COLOR, customBackgroundColor).apply()
var customPrimaryColor: Int
get() = prefs.getInt(CUSTOM_PRIMARY_COLOR, primaryColor)
set(customPrimaryColor) = prefs.edit().putInt(CUSTOM_PRIMARY_COLOR, customPrimaryColor).apply()
var customAccentColor: Int
get() = prefs.getInt(CUSTOM_ACCENT_COLOR, accentColor)
set(customAccentColor) = prefs.edit().putInt(CUSTOM_ACCENT_COLOR, customAccentColor).apply()
var customAppIconColor: Int
get() = prefs.getInt(CUSTOM_APP_ICON_COLOR, appIconColor)
set(customAppIconColor) = prefs.edit().putInt(CUSTOM_APP_ICON_COLOR, customAppIconColor).apply()
var widgetBgColor: Int
get() = prefs.getInt(WIDGET_BG_COLOR, ContextCompat.getColor(context, R.color.default_widget_bg_color))
set(widgetBgColor) = prefs.edit().putInt(WIDGET_BG_COLOR, widgetBgColor).apply()
var widgetTextColor: Int
get() = prefs.getInt(WIDGET_TEXT_COLOR, ContextCompat.getColor(context, R.color.default_widget_text_color))
set(widgetTextColor) = prefs.edit().putInt(WIDGET_TEXT_COLOR, widgetTextColor).apply()
// hidden folder visibility protection
var isHiddenPasswordProtectionOn: Boolean
get() = prefs.getBoolean(PASSWORD_PROTECTION, false)
set(isHiddenPasswordProtectionOn) = prefs.edit().putBoolean(PASSWORD_PROTECTION, isHiddenPasswordProtectionOn).apply()
var hiddenPasswordHash: String
get() = prefs.getString(PASSWORD_HASH, "")!!
set(hiddenPasswordHash) = prefs.edit().putString(PASSWORD_HASH, hiddenPasswordHash).apply()
var hiddenProtectionType: Int
get() = prefs.getInt(PROTECTION_TYPE, PROTECTION_PATTERN)
set(hiddenProtectionType) = prefs.edit().putInt(PROTECTION_TYPE, hiddenProtectionType).apply()
// whole app launch protection
var isAppPasswordProtectionOn: Boolean
get() = prefs.getBoolean(APP_PASSWORD_PROTECTION, false)
set(isAppPasswordProtectionOn) = prefs.edit().putBoolean(APP_PASSWORD_PROTECTION, isAppPasswordProtectionOn).apply()
var appPasswordHash: String
get() = prefs.getString(APP_PASSWORD_HASH, "")!!
set(appPasswordHash) = prefs.edit().putString(APP_PASSWORD_HASH, appPasswordHash).apply()
var appProtectionType: Int
get() = prefs.getInt(APP_PROTECTION_TYPE, PROTECTION_PATTERN)
set(appProtectionType) = prefs.edit().putInt(APP_PROTECTION_TYPE, appProtectionType).apply()
// file delete and move protection
var isDeletePasswordProtectionOn: Boolean
get() = prefs.getBoolean(DELETE_PASSWORD_PROTECTION, false)
set(isDeletePasswordProtectionOn) = prefs.edit().putBoolean(DELETE_PASSWORD_PROTECTION, isDeletePasswordProtectionOn).apply()
var deletePasswordHash: String
get() = prefs.getString(DELETE_PASSWORD_HASH, "")!!
set(deletePasswordHash) = prefs.edit().putString(DELETE_PASSWORD_HASH, deletePasswordHash).apply()
var deleteProtectionType: Int
get() = prefs.getInt(DELETE_PROTECTION_TYPE, PROTECTION_PATTERN)
set(deleteProtectionType) = prefs.edit().putInt(DELETE_PROTECTION_TYPE, deleteProtectionType).apply()
// folder locking
fun addFolderProtection(path: String, hash: String, type: Int) {
prefs.edit()
.putString("$PROTECTED_FOLDER_HASH$path", hash)
.putInt("$PROTECTED_FOLDER_TYPE$path", type)
.apply()
}
fun removeFolderProtection(path: String) {
prefs.edit()
.remove("$PROTECTED_FOLDER_HASH$path")
.remove("$PROTECTED_FOLDER_TYPE$path")
.apply()
}
fun isFolderProtected(path: String) = getFolderProtectionType(path) != PROTECTION_NONE
fun getFolderProtectionHash(path: String) = prefs.getString("$PROTECTED_FOLDER_HASH$path", "") ?: ""
fun getFolderProtectionType(path: String) = prefs.getInt("$PROTECTED_FOLDER_TYPE$path", PROTECTION_NONE)
var lastCopyPath: String
get() = prefs.getString(LAST_COPY_PATH, "")!!
set(lastCopyPath) = prefs.edit().putString(LAST_COPY_PATH, lastCopyPath).apply()
var keepLastModified: Boolean
get() = prefs.getBoolean(KEEP_LAST_MODIFIED, true)
set(keepLastModified) = prefs.edit().putBoolean(KEEP_LAST_MODIFIED, keepLastModified).apply()
var useEnglish: Boolean
get() = prefs.getBoolean(USE_ENGLISH, false)
set(useEnglish) {
wasUseEnglishToggled = true
prefs.edit().putBoolean(USE_ENGLISH, useEnglish).commit()
}
val useEnglishFlow = ::useEnglish.asFlowNonNull()
var wasUseEnglishToggled: Boolean
get() = prefs.getBoolean(WAS_USE_ENGLISH_TOGGLED, false)
set(wasUseEnglishToggled) = prefs.edit().putBoolean(WAS_USE_ENGLISH_TOGGLED, wasUseEnglishToggled).apply()
val wasUseEnglishToggledFlow = ::wasUseEnglishToggled.asFlowNonNull()
var wasSharedThemeEverActivated: Boolean
get() = prefs.getBoolean(WAS_SHARED_THEME_EVER_ACTIVATED, false)
set(wasSharedThemeEverActivated) = prefs.edit().putBoolean(WAS_SHARED_THEME_EVER_ACTIVATED, wasSharedThemeEverActivated).apply()
var isUsingSharedTheme: Boolean
get() = prefs.getBoolean(IS_USING_SHARED_THEME, false)
set(isUsingSharedTheme) = prefs.edit().putBoolean(IS_USING_SHARED_THEME, isUsingSharedTheme).apply()
// used by Simple Thank You, stop using shared Shared Theme if it has been changed in it
var shouldUseSharedTheme: Boolean
get() = prefs.getBoolean(SHOULD_USE_SHARED_THEME, false)
set(shouldUseSharedTheme) = prefs.edit().putBoolean(SHOULD_USE_SHARED_THEME, shouldUseSharedTheme).apply()
var isUsingAutoTheme: Boolean
get() = prefs.getBoolean(IS_USING_AUTO_THEME, false)
set(isUsingAutoTheme) = prefs.edit().putBoolean(IS_USING_AUTO_THEME, isUsingAutoTheme).apply()
var isUsingSystemTheme: Boolean
get() = prefs.getBoolean(IS_USING_SYSTEM_THEME, isSPlus())
set(isUsingSystemTheme) = prefs.edit().putBoolean(IS_USING_SYSTEM_THEME, isUsingSystemTheme).apply()
var wasCustomThemeSwitchDescriptionShown: Boolean
get() = prefs.getBoolean(WAS_CUSTOM_THEME_SWITCH_DESCRIPTION_SHOWN, false)
set(wasCustomThemeSwitchDescriptionShown) = prefs.edit().putBoolean(WAS_CUSTOM_THEME_SWITCH_DESCRIPTION_SHOWN, wasCustomThemeSwitchDescriptionShown)
.apply()
var wasSharedThemeForced: Boolean
get() = prefs.getBoolean(WAS_SHARED_THEME_FORCED, false)
set(wasSharedThemeForced) = prefs.edit().putBoolean(WAS_SHARED_THEME_FORCED, wasSharedThemeForced).apply()
var showInfoBubble: Boolean
get() = prefs.getBoolean(SHOW_INFO_BUBBLE, true)
set(showInfoBubble) = prefs.edit().putBoolean(SHOW_INFO_BUBBLE, showInfoBubble).apply()
var lastConflictApplyToAll: Boolean
get() = prefs.getBoolean(LAST_CONFLICT_APPLY_TO_ALL, true)
set(lastConflictApplyToAll) = prefs.edit().putBoolean(LAST_CONFLICT_APPLY_TO_ALL, lastConflictApplyToAll).apply()
var lastConflictResolution: Int
get() = prefs.getInt(LAST_CONFLICT_RESOLUTION, CONFLICT_SKIP)
set(lastConflictResolution) = prefs.edit().putInt(LAST_CONFLICT_RESOLUTION, lastConflictResolution).apply()
var sorting: Int
get() = prefs.getInt(SORT_ORDER, context.resources.getInteger(R.integer.default_sorting))
set(sorting) = prefs.edit().putInt(SORT_ORDER, sorting).apply()
fun saveCustomSorting(path: String, value: Int) {
if (path.isEmpty()) {
sorting = value
} else {
prefs.edit().putInt(SORT_FOLDER_PREFIX + path.toLowerCase(), value).apply()
}
}
fun getFolderSorting(path: String) = prefs.getInt(SORT_FOLDER_PREFIX + path.toLowerCase(), sorting)
fun removeCustomSorting(path: String) {
prefs.edit().remove(SORT_FOLDER_PREFIX + path.toLowerCase()).apply()
}
fun hasCustomSorting(path: String) = prefs.contains(SORT_FOLDER_PREFIX + path.toLowerCase())
var hadThankYouInstalled: Boolean
get() = prefs.getBoolean(HAD_THANK_YOU_INSTALLED, false)
set(hadThankYouInstalled) = prefs.edit().putBoolean(HAD_THANK_YOU_INSTALLED, hadThankYouInstalled).apply()
var skipDeleteConfirmation: Boolean
get() = prefs.getBoolean(SKIP_DELETE_CONFIRMATION, false)
set(skipDeleteConfirmation) = prefs.edit().putBoolean(SKIP_DELETE_CONFIRMATION, skipDeleteConfirmation).apply()
var enablePullToRefresh: Boolean
get() = prefs.getBoolean(ENABLE_PULL_TO_REFRESH, true)
set(enablePullToRefresh) = prefs.edit().putBoolean(ENABLE_PULL_TO_REFRESH, enablePullToRefresh).apply()
var scrollHorizontally: Boolean
get() = prefs.getBoolean(SCROLL_HORIZONTALLY, false)
set(scrollHorizontally) = prefs.edit().putBoolean(SCROLL_HORIZONTALLY, scrollHorizontally).apply()
var preventPhoneFromSleeping: Boolean
get() = prefs.getBoolean(PREVENT_PHONE_FROM_SLEEPING, true)
set(preventPhoneFromSleeping) = prefs.edit().putBoolean(PREVENT_PHONE_FROM_SLEEPING, preventPhoneFromSleeping).apply()
var lastUsedViewPagerPage: Int
get() = prefs.getInt(LAST_USED_VIEW_PAGER_PAGE, context.resources.getInteger(R.integer.default_viewpager_page))
set(lastUsedViewPagerPage) = prefs.edit().putInt(LAST_USED_VIEW_PAGER_PAGE, lastUsedViewPagerPage).apply()
var use24HourFormat: Boolean
get() = prefs.getBoolean(USE_24_HOUR_FORMAT, DateFormat.is24HourFormat(context))
set(use24HourFormat) = prefs.edit().putBoolean(USE_24_HOUR_FORMAT, use24HourFormat).apply()
var isSundayFirst: Boolean
get() {
val isSundayFirst = Calendar.getInstance(Locale.getDefault()).firstDayOfWeek == Calendar.SUNDAY
return prefs.getBoolean(SUNDAY_FIRST, isSundayFirst)
}
set(sundayFirst) = prefs.edit().putBoolean(SUNDAY_FIRST, sundayFirst).apply()
var wasAlarmWarningShown: Boolean
get() = prefs.getBoolean(WAS_ALARM_WARNING_SHOWN, false)
set(wasAlarmWarningShown) = prefs.edit().putBoolean(WAS_ALARM_WARNING_SHOWN, wasAlarmWarningShown).apply()
var wasReminderWarningShown: Boolean
get() = prefs.getBoolean(WAS_REMINDER_WARNING_SHOWN, false)
set(wasReminderWarningShown) = prefs.edit().putBoolean(WAS_REMINDER_WARNING_SHOWN, wasReminderWarningShown).apply()
var useSameSnooze: Boolean
get() = prefs.getBoolean(USE_SAME_SNOOZE, true)
set(useSameSnooze) = prefs.edit().putBoolean(USE_SAME_SNOOZE, useSameSnooze).apply()
var snoozeTime: Int
get() = prefs.getInt(SNOOZE_TIME, 10)
set(snoozeDelay) = prefs.edit().putInt(SNOOZE_TIME, snoozeDelay).apply()
var vibrateOnButtonPress: Boolean
get() = prefs.getBoolean(VIBRATE_ON_BUTTON_PRESS, context.resources.getBoolean(R.bool.default_vibrate_on_press))
set(vibrateOnButton) = prefs.edit().putBoolean(VIBRATE_ON_BUTTON_PRESS, vibrateOnButton).apply()
var yourAlarmSounds: String
get() = prefs.getString(YOUR_ALARM_SOUNDS, "")!!
set(yourAlarmSounds) = prefs.edit().putString(YOUR_ALARM_SOUNDS, yourAlarmSounds).apply()
var isUsingModifiedAppIcon: Boolean
get() = prefs.getBoolean(IS_USING_MODIFIED_APP_ICON, false)
set(isUsingModifiedAppIcon) = prefs.edit().putBoolean(IS_USING_MODIFIED_APP_ICON, isUsingModifiedAppIcon).apply()
var appId: String
get() = prefs.getString(APP_ID, "")!!
set(appId) = prefs.edit().putString(APP_ID, appId).apply()
var initialWidgetHeight: Int
get() = prefs.getInt(INITIAL_WIDGET_HEIGHT, 0)
set(initialWidgetHeight) = prefs.edit().putInt(INITIAL_WIDGET_HEIGHT, initialWidgetHeight).apply()
var widgetIdToMeasure: Int
get() = prefs.getInt(WIDGET_ID_TO_MEASURE, 0)
set(widgetIdToMeasure) = prefs.edit().putInt(WIDGET_ID_TO_MEASURE, widgetIdToMeasure).apply()
var wasOrangeIconChecked: Boolean
get() = prefs.getBoolean(WAS_ORANGE_ICON_CHECKED, false)
set(wasOrangeIconChecked) = prefs.edit().putBoolean(WAS_ORANGE_ICON_CHECKED, wasOrangeIconChecked).apply()
var wasAppOnSDShown: Boolean
get() = prefs.getBoolean(WAS_APP_ON_SD_SHOWN, false)
set(wasAppOnSDShown) = prefs.edit().putBoolean(WAS_APP_ON_SD_SHOWN, wasAppOnSDShown).apply()
var wasBeforeAskingShown: Boolean
get() = prefs.getBoolean(WAS_BEFORE_ASKING_SHOWN, false)
set(wasBeforeAskingShown) = prefs.edit().putBoolean(WAS_BEFORE_ASKING_SHOWN, wasBeforeAskingShown).apply()
var wasBeforeRateShown: Boolean
get() = prefs.getBoolean(WAS_BEFORE_RATE_SHOWN, false)
set(wasBeforeRateShown) = prefs.edit().putBoolean(WAS_BEFORE_RATE_SHOWN, wasBeforeRateShown).apply()
var wasInitialUpgradeToProShown: Boolean
get() = prefs.getBoolean(WAS_INITIAL_UPGRADE_TO_PRO_SHOWN, false)
set(wasInitialUpgradeToProShown) = prefs.edit().putBoolean(WAS_INITIAL_UPGRADE_TO_PRO_SHOWN, wasInitialUpgradeToProShown).apply()
var wasAppIconCustomizationWarningShown: Boolean
get() = prefs.getBoolean(WAS_APP_ICON_CUSTOMIZATION_WARNING_SHOWN, false)
set(wasAppIconCustomizationWarningShown) = prefs.edit().putBoolean(WAS_APP_ICON_CUSTOMIZATION_WARNING_SHOWN, wasAppIconCustomizationWarningShown)
.apply()
var appSideloadingStatus: Int
get() = prefs.getInt(APP_SIDELOADING_STATUS, SIDELOADING_UNCHECKED)
set(appSideloadingStatus) = prefs.edit().putInt(APP_SIDELOADING_STATUS, appSideloadingStatus).apply()
var dateFormat: String
get() = prefs.getString(DATE_FORMAT, getDefaultDateFormat())!!
set(dateFormat) = prefs.edit().putString(DATE_FORMAT, dateFormat).apply()
private fun getDefaultDateFormat(): String {
val format = DateFormat.getDateFormat(context)
val pattern = (format as SimpleDateFormat).toLocalizedPattern()
return when (pattern.lowercase().replace(" ", "")) {
"d.M.y" -> DATE_FORMAT_ONE
"dd/mm/y" -> DATE_FORMAT_TWO
"mm/dd/y" -> DATE_FORMAT_THREE
"y-mm-dd" -> DATE_FORMAT_FOUR
"dmmmmy" -> DATE_FORMAT_FIVE
"mmmmdy" -> DATE_FORMAT_SIX
"mm-dd-y" -> DATE_FORMAT_SEVEN
"dd-mm-y" -> DATE_FORMAT_EIGHT
else -> DATE_FORMAT_ONE
}
}
var wasOTGHandled: Boolean
get() = prefs.getBoolean(WAS_OTG_HANDLED, false)
set(wasOTGHandled) = prefs.edit().putBoolean(WAS_OTG_HANDLED, wasOTGHandled).apply()
var wasUpgradedFromFreeShown: Boolean
get() = prefs.getBoolean(WAS_UPGRADED_FROM_FREE_SHOWN, false)
set(wasUpgradedFromFreeShown) = prefs.edit().putBoolean(WAS_UPGRADED_FROM_FREE_SHOWN, wasUpgradedFromFreeShown).apply()
var wasRateUsPromptShown: Boolean
get() = prefs.getBoolean(WAS_RATE_US_PROMPT_SHOWN, false)
set(wasRateUsPromptShown) = prefs.edit().putBoolean(WAS_RATE_US_PROMPT_SHOWN, wasRateUsPromptShown).apply()
var wasAppRated: Boolean
get() = prefs.getBoolean(WAS_APP_RATED, false)
set(wasAppRated) = prefs.edit().putBoolean(WAS_APP_RATED, wasAppRated).apply()
var wasSortingByNumericValueAdded: Boolean
get() = prefs.getBoolean(WAS_SORTING_BY_NUMERIC_VALUE_ADDED, false)
set(wasSortingByNumericValueAdded) = prefs.edit().putBoolean(WAS_SORTING_BY_NUMERIC_VALUE_ADDED, wasSortingByNumericValueAdded).apply()
var wasFolderLockingNoticeShown: Boolean
get() = prefs.getBoolean(WAS_FOLDER_LOCKING_NOTICE_SHOWN, false)
set(wasFolderLockingNoticeShown) = prefs.edit().putBoolean(WAS_FOLDER_LOCKING_NOTICE_SHOWN, wasFolderLockingNoticeShown).apply()
var lastRenameUsed: Int
get() = prefs.getInt(LAST_RENAME_USED, RENAME_SIMPLE)
set(lastRenameUsed) = prefs.edit().putInt(LAST_RENAME_USED, lastRenameUsed).apply()
var lastRenamePatternUsed: String
get() = prefs.getString(LAST_RENAME_PATTERN_USED, "")!!
set(lastRenamePatternUsed) = prefs.edit().putString(LAST_RENAME_PATTERN_USED, lastRenamePatternUsed).apply()
var lastExportedSettingsFolder: String
get() = prefs.getString(LAST_EXPORTED_SETTINGS_FOLDER, "")!!
set(lastExportedSettingsFolder) = prefs.edit().putString(LAST_EXPORTED_SETTINGS_FOLDER, lastExportedSettingsFolder).apply()
var lastBlockedNumbersExportPath: String
get() = prefs.getString(LAST_BLOCKED_NUMBERS_EXPORT_PATH, "")!!
set(lastBlockedNumbersExportPath) = prefs.edit().putString(LAST_BLOCKED_NUMBERS_EXPORT_PATH, lastBlockedNumbersExportPath).apply()
var blockUnknownNumbers: Boolean
get() = prefs.getBoolean(BLOCK_UNKNOWN_NUMBERS, false)
set(blockUnknownNumbers) = prefs.edit().putBoolean(BLOCK_UNKNOWN_NUMBERS, blockUnknownNumbers).apply()
val isBlockingUnknownNumbers: Flow<Boolean> = ::blockUnknownNumbers.asFlowNonNull()
var blockHiddenNumbers: Boolean
get() = prefs.getBoolean(BLOCK_HIDDEN_NUMBERS, false)
set(blockHiddenNumbers) = prefs.edit().putBoolean(BLOCK_HIDDEN_NUMBERS, blockHiddenNumbers).apply()
val isBlockingHiddenNumbers: Flow<Boolean> = ::blockHiddenNumbers.asFlowNonNull()
var fontSize: Int
get() = prefs.getInt(FONT_SIZE, context.resources.getInteger(R.integer.default_font_size))
set(size) = prefs.edit().putInt(FONT_SIZE, size).apply()
// notify the users about new SMS Messenger and Voice Recorder released
var wasMessengerRecorderShown: Boolean
get() = prefs.getBoolean(WAS_MESSENGER_RECORDER_SHOWN, false)
set(wasMessengerRecorderShown) = prefs.edit().putBoolean(WAS_MESSENGER_RECORDER_SHOWN, wasMessengerRecorderShown).apply()
var defaultTab: Int
get() = prefs.getInt(DEFAULT_TAB, TAB_LAST_USED)
set(defaultTab) = prefs.edit().putInt(DEFAULT_TAB, defaultTab).apply()
var startNameWithSurname: Boolean
get() = prefs.getBoolean(START_NAME_WITH_SURNAME, false)
set(startNameWithSurname) = prefs.edit().putBoolean(START_NAME_WITH_SURNAME, startNameWithSurname).apply()
var favorites: MutableSet<String>
get() = prefs.getStringSet(FAVORITES, HashSet())!!
set(favorites) = prefs.edit().remove(FAVORITES).putStringSet(FAVORITES, favorites).apply()
var showCallConfirmation: Boolean
get() = prefs.getBoolean(SHOW_CALL_CONFIRMATION, false)
set(showCallConfirmation) = prefs.edit().putBoolean(SHOW_CALL_CONFIRMATION, showCallConfirmation).apply()
// color picker last used colors
var colorPickerRecentColors: LinkedList<Int>
get(): LinkedList<Int> {
val defaultList = arrayListOf(
ContextCompat.getColor(context, R.color.md_red_700),
ContextCompat.getColor(context, R.color.md_blue_700),
ContextCompat.getColor(context, R.color.md_green_700),
ContextCompat.getColor(context, R.color.md_yellow_700),
ContextCompat.getColor(context, R.color.md_orange_700)
)
return LinkedList(prefs.getString(COLOR_PICKER_RECENT_COLORS, null)?.lines()?.map { it.toInt() } ?: defaultList)
}
set(recentColors) = prefs.edit().putString(COLOR_PICKER_RECENT_COLORS, recentColors.joinToString(separator = "\n")).apply()
val colorPickerRecentColorsFlow = ::colorPickerRecentColors.asFlowNonNull()
var ignoredContactSources: HashSet<String>
get() = prefs.getStringSet(IGNORED_CONTACT_SOURCES, hashSetOf(".")) as HashSet
set(ignoreContactSources) = prefs.edit().remove(IGNORED_CONTACT_SOURCES).putStringSet(IGNORED_CONTACT_SOURCES, ignoreContactSources).apply()
var showContactThumbnails: Boolean
get() = prefs.getBoolean(SHOW_CONTACT_THUMBNAILS, true)
set(showContactThumbnails) = prefs.edit().putBoolean(SHOW_CONTACT_THUMBNAILS, showContactThumbnails).apply()
var showPhoneNumbers: Boolean
get() = prefs.getBoolean(SHOW_PHONE_NUMBERS, false)
set(showPhoneNumbers) = prefs.edit().putBoolean(SHOW_PHONE_NUMBERS, showPhoneNumbers).apply()
var showOnlyContactsWithNumbers: Boolean
get() = prefs.getBoolean(SHOW_ONLY_CONTACTS_WITH_NUMBERS, false)
set(showOnlyContactsWithNumbers) = prefs.edit().putBoolean(SHOW_ONLY_CONTACTS_WITH_NUMBERS, showOnlyContactsWithNumbers).apply()
var lastUsedContactSource: String
get() = prefs.getString(LAST_USED_CONTACT_SOURCE, "")!!
set(lastUsedContactSource) = prefs.edit().putString(LAST_USED_CONTACT_SOURCE, lastUsedContactSource).apply()
var onContactClick: Int
get() = prefs.getInt(ON_CONTACT_CLICK, ON_CLICK_VIEW_CONTACT)
set(onContactClick) = prefs.edit().putInt(ON_CONTACT_CLICK, onContactClick).apply()
var showContactFields: Int
get() = prefs.getInt(
SHOW_CONTACT_FIELDS,
SHOW_FIRST_NAME_FIELD or SHOW_SURNAME_FIELD or SHOW_PHONE_NUMBERS_FIELD or SHOW_EMAILS_FIELD or
SHOW_ADDRESSES_FIELD or SHOW_EVENTS_FIELD or SHOW_NOTES_FIELD or SHOW_GROUPS_FIELD or SHOW_CONTACT_SOURCE_FIELD
)
set(showContactFields) = prefs.edit().putInt(SHOW_CONTACT_FIELDS, showContactFields).apply()
var showDialpadButton: Boolean
get() = prefs.getBoolean(SHOW_DIALPAD_BUTTON, true)
set(showDialpadButton) = prefs.edit().putBoolean(SHOW_DIALPAD_BUTTON, showDialpadButton).apply()
var wasLocalAccountInitialized: Boolean
get() = prefs.getBoolean(WAS_LOCAL_ACCOUNT_INITIALIZED, false)
set(wasLocalAccountInitialized) = prefs.edit().putBoolean(WAS_LOCAL_ACCOUNT_INITIALIZED, wasLocalAccountInitialized).apply()
var lastExportPath: String
get() = prefs.getString(LAST_EXPORT_PATH, "")!!
set(lastExportPath) = prefs.edit().putString(LAST_EXPORT_PATH, lastExportPath).apply()
var speedDial: String
get() = prefs.getString(SPEED_DIAL, "")!!
set(speedDial) = prefs.edit().putString(SPEED_DIAL, speedDial).apply()
var showPrivateContacts: Boolean
get() = prefs.getBoolean(SHOW_PRIVATE_CONTACTS, true)
set(showPrivateContacts) = prefs.edit().putBoolean(SHOW_PRIVATE_CONTACTS, showPrivateContacts).apply()
var mergeDuplicateContacts: Boolean
get() = prefs.getBoolean(MERGE_DUPLICATE_CONTACTS, true)
set(mergeDuplicateContacts) = prefs.edit().putBoolean(MERGE_DUPLICATE_CONTACTS, mergeDuplicateContacts).apply()
var favoritesContactsOrder: String
get() = prefs.getString(FAVORITES_CONTACTS_ORDER, "")!!
set(order) = prefs.edit().putString(FAVORITES_CONTACTS_ORDER, order).apply()
var isCustomOrderSelected: Boolean
get() = prefs.getBoolean(FAVORITES_CUSTOM_ORDER_SELECTED, false)
set(selected) = prefs.edit().putBoolean(FAVORITES_CUSTOM_ORDER_SELECTED, selected).apply()
var viewType: Int
get() = prefs.getInt(VIEW_TYPE, VIEW_TYPE_LIST)
set(viewType) = prefs.edit().putInt(VIEW_TYPE, viewType).apply()
var contactsGridColumnCount: Int
get() = prefs.getInt(CONTACTS_GRID_COLUMN_COUNT, getDefaultContactColumnsCount())
set(contactsGridColumnCount) = prefs.edit().putInt(CONTACTS_GRID_COLUMN_COUNT, contactsGridColumnCount).apply()
private fun getDefaultContactColumnsCount(): Int {
val isPortrait = context.resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT
return if (isPortrait) {
context.resources.getInteger(R.integer.contacts_grid_columns_count_portrait)
} else {
context.resources.getInteger(R.integer.contacts_grid_columns_count_landscape)
}
}
var autoBackup: Boolean
get() = prefs.getBoolean(AUTO_BACKUP, false)
set(autoBackup) = prefs.edit().putBoolean(AUTO_BACKUP, autoBackup).apply()
var autoBackupFolder: String
get() = prefs.getString(AUTO_BACKUP_FOLDER, Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).absolutePath)!!
set(autoBackupFolder) = prefs.edit().putString(AUTO_BACKUP_FOLDER, autoBackupFolder).apply()
var autoBackupFilename: String
get() = prefs.getString(AUTO_BACKUP_FILENAME, "")!!
set(autoBackupFilename) = prefs.edit().putString(AUTO_BACKUP_FILENAME, autoBackupFilename).apply()
var lastAutoBackupTime: Long
get() = prefs.getLong(LAST_AUTO_BACKUP_TIME, 0L)
set(lastAutoBackupTime) = prefs.edit().putLong(LAST_AUTO_BACKUP_TIME, lastAutoBackupTime).apply()
var passwordRetryCount: Int
get() = prefs.getInt(PASSWORD_RETRY_COUNT, 0)
set(passwordRetryCount) = prefs.edit().putInt(PASSWORD_RETRY_COUNT, passwordRetryCount).apply()
var passwordCountdownStartMs: Long
get() = prefs.getLong(PASSWORD_COUNTDOWN_START_MS, 0L)
set(passwordCountdownStartMs) = prefs.edit().putLong(PASSWORD_COUNTDOWN_START_MS, passwordCountdownStartMs).apply()
protected fun <T> KProperty0<T>.asFlow(emitOnCollect: Boolean = false): Flow<T?> = prefs.run { sharedPreferencesCallback(sendOnCollect = emitOnCollect) { [email protected]() } }
protected fun <T> KProperty0<T>.asFlowNonNull(emitOnCollect: Boolean = false): Flow<T> = asFlow(emitOnCollect).filterNotNull()
}
|
CT/commons/src/main/kotlin/com/simplemobiletools/commons/helpers/VcfExporter.kt | 1543350366 | package com.simplemobiletools.commons.helpers
import android.net.Uri
import android.provider.ContactsContract.CommonDataKinds
import android.provider.ContactsContract.CommonDataKinds.Event
import android.provider.ContactsContract.CommonDataKinds.Im
import android.provider.ContactsContract.CommonDataKinds.Phone
import android.provider.ContactsContract.CommonDataKinds.StructuredPostal
import android.provider.MediaStore
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.activities.BaseSimpleActivity
import com.simplemobiletools.commons.extensions.getByteArray
import com.simplemobiletools.commons.extensions.getDateTimeFromDateString
import com.simplemobiletools.commons.extensions.showErrorToast
import com.simplemobiletools.commons.extensions.toast
import com.simplemobiletools.commons.models.contacts.Contact
import ezvcard.Ezvcard
import ezvcard.VCard
import ezvcard.VCardVersion
import ezvcard.parameter.ImageType
import ezvcard.property.*
import java.io.OutputStream
import java.util.*
class VcfExporter {
private var contactsExported = 0
private var contactsFailed = 0
fun exportContacts(
activity: BaseSimpleActivity,
outputStream: OutputStream?,
contacts: ArrayList<Contact>,
showExportingToast: Boolean,
callback: (result: ExportResult) -> Unit
) {
try {
if (outputStream == null) {
callback(ExportResult.EXPORT_FAIL)
return
}
if (showExportingToast) {
activity.toast(R.string.exporting)
}
val cards = ArrayList<VCard>()
for (contact in contacts) {
val card = VCard()
val formattedName = arrayOf(contact.prefix, contact.firstName, contact.middleName, contact.surname, contact.suffix)
.filter { it.isNotEmpty() }
.joinToString(separator = " ")
card.formattedName = FormattedName(formattedName)
StructuredName().apply {
prefixes.add(contact.prefix)
given = contact.firstName
additionalNames.add(contact.middleName)
family = contact.surname
suffixes.add(contact.suffix)
card.structuredName = this
}
if (contact.nickname.isNotEmpty()) {
card.setNickname(contact.nickname)
}
contact.phoneNumbers.forEach {
val phoneNumber = Telephone(it.value)
phoneNumber.parameters.addType(getPhoneNumberTypeLabel(it.type, it.label))
card.addTelephoneNumber(phoneNumber)
}
contact.emails.forEach {
val email = Email(it.value)
email.parameters.addType(getEmailTypeLabel(it.type, it.label))
card.addEmail(email)
}
contact.events.forEach { event ->
if (event.type == Event.TYPE_ANNIVERSARY || event.type == Event.TYPE_BIRTHDAY) {
val dateTime = event.value.getDateTimeFromDateString(false)
Calendar.getInstance().apply {
clear()
if (event.value.startsWith("--")) {
set(Calendar.YEAR, 1900)
} else {
set(Calendar.YEAR, dateTime.year)
}
set(Calendar.MONTH, dateTime.monthOfYear - 1)
set(Calendar.DAY_OF_MONTH, dateTime.dayOfMonth)
if (event.type == Event.TYPE_BIRTHDAY) {
card.birthdays.add(Birthday(time))
} else {
card.anniversaries.add(Anniversary(time))
}
}
}
}
contact.addresses.forEach {
val address = Address()
address.streetAddress = it.value
address.parameters.addType(getAddressTypeLabel(it.type, it.label))
card.addAddress(address)
}
contact.IMs.forEach {
val impp = when (it.type) {
Im.PROTOCOL_AIM -> Impp.aim(it.value)
Im.PROTOCOL_YAHOO -> Impp.yahoo(it.value)
Im.PROTOCOL_MSN -> Impp.msn(it.value)
Im.PROTOCOL_ICQ -> Impp.icq(it.value)
Im.PROTOCOL_SKYPE -> Impp.skype(it.value)
Im.PROTOCOL_GOOGLE_TALK -> Impp(HANGOUTS, it.value)
Im.PROTOCOL_QQ -> Impp(QQ, it.value)
Im.PROTOCOL_JABBER -> Impp(JABBER, it.value)
else -> Impp(it.label, it.value)
}
card.addImpp(impp)
}
if (contact.notes.isNotEmpty()) {
card.addNote(contact.notes)
}
if (contact.organization.isNotEmpty()) {
val organization = Organization()
organization.values.add(contact.organization.company)
card.organization = organization
card.titles.add(Title(contact.organization.jobPosition))
}
contact.websites.forEach {
card.addUrl(it)
}
if (contact.thumbnailUri.isNotEmpty()) {
val photoByteArray = MediaStore.Images.Media.getBitmap(activity.contentResolver, Uri.parse(contact.thumbnailUri)).getByteArray()
val photo = Photo(photoByteArray, ImageType.JPEG)
card.addPhoto(photo)
}
if (contact.groups.isNotEmpty()) {
val groupList = Categories()
contact.groups.forEach {
groupList.values.add(it.title)
}
card.categories = groupList
}
cards.add(card)
contactsExported++
}
Ezvcard.write(cards).version(VCardVersion.V4_0).go(outputStream)
} catch (e: Exception) {
activity.showErrorToast(e)
}
callback(
when {
contactsExported == 0 -> ExportResult.EXPORT_FAIL
contactsFailed > 0 -> ExportResult.EXPORT_PARTIAL
else -> ExportResult.EXPORT_OK
}
)
}
private fun getPhoneNumberTypeLabel(type: Int, label: String) = when (type) {
Phone.TYPE_MOBILE -> CELL
Phone.TYPE_HOME -> HOME
Phone.TYPE_WORK -> WORK
Phone.TYPE_MAIN -> PREF
Phone.TYPE_FAX_WORK -> WORK_FAX
Phone.TYPE_FAX_HOME -> HOME_FAX
Phone.TYPE_PAGER -> PAGER
Phone.TYPE_OTHER -> OTHER
else -> label
}
private fun getEmailTypeLabel(type: Int, label: String) = when (type) {
CommonDataKinds.Email.TYPE_HOME -> HOME
CommonDataKinds.Email.TYPE_WORK -> WORK
CommonDataKinds.Email.TYPE_MOBILE -> MOBILE
CommonDataKinds.Email.TYPE_OTHER -> OTHER
else -> label
}
private fun getAddressTypeLabel(type: Int, label: String) = when (type) {
StructuredPostal.TYPE_HOME -> HOME
StructuredPostal.TYPE_WORK -> WORK
StructuredPostal.TYPE_OTHER -> OTHER
else -> label
}
}
|
CT/commons/src/main/kotlin/com/simplemobiletools/commons/helpers/MyContextWrapper.kt | 1008980092 | package com.simplemobiletools.commons.helpers
import android.annotation.TargetApi
import android.content.Context
import android.content.ContextWrapper
import android.content.res.Configuration
import android.os.Build
import java.util.*
// language forcing used at "Use english language", taken from https://stackoverflow.com/a/40704077/1967672
class MyContextWrapper(context: Context) : ContextWrapper(context) {
fun wrap(context: Context, language: String): ContextWrapper {
var newContext = context
val config = newContext.resources.configuration
val sysLocale: Locale?
sysLocale = if (isNougatPlus()) {
getSystemLocale(config)
} else {
getSystemLocaleLegacy(config)
}
if (language != "" && sysLocale!!.language != language) {
val locale = Locale(language)
Locale.setDefault(locale)
if (isNougatPlus()) {
setSystemLocale(config, locale)
} else {
setSystemLocaleLegacy(config, locale)
}
}
newContext = newContext.createConfigurationContext(config)
return MyContextWrapper(newContext)
}
private fun getSystemLocaleLegacy(config: Configuration) = config.locale
@TargetApi(Build.VERSION_CODES.N)
private fun getSystemLocale(config: Configuration) = config.locales.get(0)
private fun setSystemLocaleLegacy(config: Configuration, locale: Locale) {
config.locale = locale
}
@TargetApi(Build.VERSION_CODES.N)
private fun setSystemLocale(config: Configuration, locale: Locale) {
config.setLocale(locale)
}
}
|
CT/commons/src/main/kotlin/com/simplemobiletools/commons/helpers/MyContentProvider.kt | 1410019572 | package com.simplemobiletools.commons.helpers
import android.content.ContentValues
import android.net.Uri
import com.simplemobiletools.commons.models.SharedTheme
class MyContentProvider {
companion object {
private const val AUTHORITY = "com.simplemobiletools.commons.provider"
const val SHARED_THEME_ACTIVATED = "com.simplemobiletools.commons.SHARED_THEME_ACTIVATED"
const val SHARED_THEME_UPDATED = "com.simplemobiletools.commons.SHARED_THEME_UPDATED"
val MY_CONTENT_URI = Uri.parse("content://$AUTHORITY/themes")
const val COL_ID = "_id" // used in Simple Thank You
const val COL_TEXT_COLOR = "text_color"
const val COL_BACKGROUND_COLOR = "background_color"
const val COL_PRIMARY_COLOR = "primary_color"
const val COL_ACCENT_COLOR = "accent_color"
const val COL_APP_ICON_COLOR = "app_icon_color"
const val COL_LAST_UPDATED_TS = "last_updated_ts"
fun fillThemeContentValues(sharedTheme: SharedTheme) = ContentValues().apply {
put(COL_TEXT_COLOR, sharedTheme.textColor)
put(COL_BACKGROUND_COLOR, sharedTheme.backgroundColor)
put(COL_PRIMARY_COLOR, sharedTheme.primaryColor)
put(COL_ACCENT_COLOR, sharedTheme.accentColor)
put(COL_APP_ICON_COLOR, sharedTheme.appIconColor)
put(COL_LAST_UPDATED_TS, System.currentTimeMillis() / 1000)
}
}
}
|
CT/commons/src/main/kotlin/com/simplemobiletools/commons/helpers/Inlines.kt | 1165859052 | package com.simplemobiletools.commons.helpers
inline fun <T> Iterable<T>.sumByLong(selector: (T) -> Long) = this.map { selector(it) }.sum()
inline fun <T> Iterable<T>.sumByInt(selector: (T) -> Int) = this.map { selector(it) }.sum()
|
CT/commons/src/main/kotlin/com/simplemobiletools/commons/helpers/Converters.kt | 2960516353 | package com.simplemobiletools.commons.helpers
import androidx.room.TypeConverter
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.simplemobiletools.commons.models.PhoneNumber
import com.simplemobiletools.commons.models.contacts.*
import java.util.ArrayList
class Converters {
private val gson = Gson()
private val longType = object : TypeToken<List<Long>>() {}.type
private val stringType = object : TypeToken<List<String>>() {}.type
private val numberType = object : TypeToken<List<PhoneNumber>>() {}.type
private val numberConverterType = object : TypeToken<List<PhoneNumberConverter>>() {}.type
private val emailType = object : TypeToken<List<Email>>() {}.type
private val addressType = object : TypeToken<List<Address>>() {}.type
private val eventType = object : TypeToken<List<Event>>() {}.type
private val imType = object : TypeToken<List<IM>>() {}.type
@TypeConverter
fun jsonToStringList(value: String): ArrayList<String> = gson.fromJson(value, stringType)
@TypeConverter
fun stringListToJson(list: ArrayList<String>): String = gson.toJson(list)
@TypeConverter
fun jsonToLongList(value: String): ArrayList<Long> = gson.fromJson(value, longType)
@TypeConverter
fun longListToJson(list: ArrayList<Long>): String = gson.toJson(list)
// some hacky converting is needed since PhoneNumber model has been added to proguard rules, but obfuscated json was stored in database
// convert [{"a":"678910","b":2,"c":"","d":"678910","e":false}] to PhoneNumber(value=678910, type=2, label=, normalizedNumber=678910, isPrimary=false)
@TypeConverter
fun jsonToPhoneNumberList(value: String): ArrayList<PhoneNumber> {
val numbers = gson.fromJson<ArrayList<PhoneNumber>>(value, numberType)
return if (numbers.any { it.value == null }) {
val phoneNumbers = ArrayList<PhoneNumber>()
val numberConverters = gson.fromJson<ArrayList<PhoneNumberConverter>>(value, numberConverterType)
numberConverters.forEach { converter ->
val phoneNumber = PhoneNumber(converter.a, converter.b, converter.c, converter.d, converter.e)
phoneNumbers.add(phoneNumber)
}
phoneNumbers
} else {
numbers
}
}
@TypeConverter
fun phoneNumberListToJson(list: ArrayList<PhoneNumber>): String = gson.toJson(list)
@TypeConverter
fun jsonToEmailList(value: String): ArrayList<Email> = gson.fromJson(value, emailType)
@TypeConverter
fun emailListToJson(list: ArrayList<Email>): String = gson.toJson(list)
@TypeConverter
fun jsonToAddressList(value: String): ArrayList<Address> = gson.fromJson(value, addressType)
@TypeConverter
fun addressListToJson(list: ArrayList<Address>): String = gson.toJson(list)
@TypeConverter
fun jsonToEventList(value: String): ArrayList<Event> = gson.fromJson(value, eventType)
@TypeConverter
fun eventListToJson(list: ArrayList<Event>): String = gson.toJson(list)
@TypeConverter
fun jsonToIMsList(value: String): ArrayList<IM> = gson.fromJson(value, imType)
@TypeConverter
fun iMsListToJson(list: ArrayList<IM>): String = gson.toJson(list)
}
|
CT/commons/src/main/kotlin/com/simplemobiletools/commons/helpers/SimpleContactsHelper.kt | 1810975077 | package com.simplemobiletools.commons.helpers
import android.content.Context
import android.database.Cursor
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.graphics.drawable.LayerDrawable
import android.net.Uri
import android.provider.ContactsContract.CommonDataKinds.Event
import android.provider.ContactsContract.CommonDataKinds.Organization
import android.provider.ContactsContract.CommonDataKinds.Phone
import android.provider.ContactsContract.CommonDataKinds.StructuredName
import android.provider.ContactsContract.Data
import android.provider.ContactsContract.PhoneLookup
import android.text.TextUtils
import android.util.SparseArray
import android.widget.ImageView
import android.widget.TextView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DecodeFormat
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.bumptech.glide.request.RequestOptions
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.models.PhoneNumber
import com.simplemobiletools.commons.models.SimpleContact
class SimpleContactsHelper(val context: Context) {
fun getAvailableContacts(favoritesOnly: Boolean, callback: (ArrayList<SimpleContact>) -> Unit) {
ensureBackgroundThread {
val names = getContactNames(favoritesOnly)
var allContacts = getContactPhoneNumbers(favoritesOnly)
allContacts.forEach {
val contactId = it.rawId
val contact = names.firstOrNull { it.rawId == contactId }
val name = contact?.name
if (name != null) {
it.name = name
}
val photoUri = contact?.photoUri
if (photoUri != null) {
it.photoUri = photoUri
}
}
allContacts = allContacts.filter { it.name.isNotEmpty() }.distinctBy {
val startIndex = Math.max(0, it.phoneNumbers.first().normalizedNumber.length - 9)
it.phoneNumbers.first().normalizedNumber.substring(startIndex)
}.distinctBy { it.rawId }.toMutableList() as ArrayList<SimpleContact>
// if there are duplicate contacts with the same name, while the first one has phone numbers 1234 and 4567, second one has only 4567,
// use just the first contact
val contactsToRemove = ArrayList<SimpleContact>()
allContacts.groupBy { it.name }.forEach {
val contacts = it.value.toMutableList() as ArrayList<SimpleContact>
if (contacts.size > 1) {
contacts.sortByDescending { it.phoneNumbers.size }
if (contacts.any { it.phoneNumbers.size == 1 } && contacts.any { it.phoneNumbers.size > 1 }) {
val multipleNumbersContact = contacts.first()
contacts.subList(1, contacts.size).forEach { contact ->
if (contact.phoneNumbers.all { multipleNumbersContact.doesContainPhoneNumber(it.normalizedNumber) }) {
val contactToRemove = allContacts.firstOrNull { it.rawId == contact.rawId }
if (contactToRemove != null) {
contactsToRemove.add(contactToRemove)
}
}
}
}
}
}
contactsToRemove.forEach {
allContacts.remove(it)
}
val birthdays = getContactEvents(true)
var size = birthdays.size()
for (i in 0 until size) {
val key = birthdays.keyAt(i)
allContacts.firstOrNull { it.rawId == key }?.birthdays = birthdays.valueAt(i)
}
val anniversaries = getContactEvents(false)
size = anniversaries.size()
for (i in 0 until size) {
val key = anniversaries.keyAt(i)
allContacts.firstOrNull { it.rawId == key }?.anniversaries = anniversaries.valueAt(i)
}
allContacts.sort()
callback(allContacts)
}
}
private fun getContactNames(favoritesOnly: Boolean): List<SimpleContact> {
val contacts = ArrayList<SimpleContact>()
val startNameWithSurname = context.baseConfig.startNameWithSurname
val uri = Data.CONTENT_URI
val projection = arrayOf(
Data.RAW_CONTACT_ID,
Data.CONTACT_ID,
StructuredName.PREFIX,
StructuredName.GIVEN_NAME,
StructuredName.MIDDLE_NAME,
StructuredName.FAMILY_NAME,
StructuredName.SUFFIX,
StructuredName.PHOTO_THUMBNAIL_URI,
Organization.COMPANY,
Organization.TITLE,
Data.MIMETYPE
)
var selection = "(${Data.MIMETYPE} = ? OR ${Data.MIMETYPE} = ?)"
if (favoritesOnly) {
selection += " AND ${Data.STARRED} = 1"
}
val selectionArgs = arrayOf(
StructuredName.CONTENT_ITEM_TYPE,
Organization.CONTENT_ITEM_TYPE
)
context.queryCursor(uri, projection, selection, selectionArgs) { cursor ->
val rawId = cursor.getIntValue(Data.RAW_CONTACT_ID)
val contactId = cursor.getIntValue(Data.CONTACT_ID)
val mimetype = cursor.getStringValue(Data.MIMETYPE)
val photoUri = cursor.getStringValue(StructuredName.PHOTO_THUMBNAIL_URI) ?: ""
val isPerson = mimetype == StructuredName.CONTENT_ITEM_TYPE
if (isPerson) {
val prefix = cursor.getStringValue(StructuredName.PREFIX) ?: ""
val firstName = cursor.getStringValue(StructuredName.GIVEN_NAME) ?: ""
val middleName = cursor.getStringValue(StructuredName.MIDDLE_NAME) ?: ""
val familyName = cursor.getStringValue(StructuredName.FAMILY_NAME) ?: ""
val suffix = cursor.getStringValue(StructuredName.SUFFIX) ?: ""
if (firstName.isNotEmpty() || middleName.isNotEmpty() || familyName.isNotEmpty()) {
val names = if (startNameWithSurname) {
arrayOf(prefix, familyName, middleName, firstName, suffix).filter { it.isNotEmpty() }
} else {
arrayOf(prefix, firstName, middleName, familyName, suffix).filter { it.isNotEmpty() }
}
val fullName = TextUtils.join(" ", names)
val contact = SimpleContact(rawId, contactId, fullName, photoUri, ArrayList(), ArrayList(), ArrayList())
contacts.add(contact)
}
}
val isOrganization = mimetype == Organization.CONTENT_ITEM_TYPE
if (isOrganization) {
val company = cursor.getStringValue(Organization.COMPANY) ?: ""
val jobTitle = cursor.getStringValue(Organization.TITLE) ?: ""
if (company.isNotEmpty() || jobTitle.isNotEmpty()) {
val fullName = "$company $jobTitle".trim()
val contact = SimpleContact(rawId, contactId, fullName, photoUri, ArrayList(), ArrayList(), ArrayList())
contacts.add(contact)
}
}
}
return contacts
}
private fun getContactPhoneNumbers(favoritesOnly: Boolean): ArrayList<SimpleContact> {
val contacts = ArrayList<SimpleContact>()
val uri = Phone.CONTENT_URI
val projection = arrayOf(
Data.RAW_CONTACT_ID,
Data.CONTACT_ID,
Phone.NORMALIZED_NUMBER,
Phone.NUMBER,
Phone.TYPE,
Phone.LABEL,
Phone.IS_PRIMARY
)
val selection = if (favoritesOnly) "${Data.STARRED} = 1" else null
context.queryCursor(uri, projection, selection) { cursor ->
val normalizedNumber = cursor.getStringValue(Phone.NORMALIZED_NUMBER)
?: cursor.getStringValue(Phone.NUMBER)?.normalizePhoneNumber() ?: return@queryCursor
val rawId = cursor.getIntValue(Data.RAW_CONTACT_ID)
val contactId = cursor.getIntValue(Data.CONTACT_ID)
val type = cursor.getIntValue(Phone.TYPE)
val label = cursor.getStringValue(Phone.LABEL) ?: ""
val isPrimary = cursor.getIntValue(Phone.IS_PRIMARY) != 0
if (contacts.firstOrNull { it.rawId == rawId } == null) {
val contact = SimpleContact(rawId, contactId, "", "", ArrayList(), ArrayList(), ArrayList())
contacts.add(contact)
}
val phoneNumber = PhoneNumber(normalizedNumber, type, label, normalizedNumber, isPrimary)
contacts.firstOrNull { it.rawId == rawId }?.phoneNumbers?.add(phoneNumber)
}
return contacts
}
private fun getContactEvents(getBirthdays: Boolean): SparseArray<ArrayList<String>> {
val eventDates = SparseArray<ArrayList<String>>()
val uri = Data.CONTENT_URI
val projection = arrayOf(
Data.RAW_CONTACT_ID,
Event.START_DATE
)
val selection = "${Event.MIMETYPE} = ? AND ${Event.TYPE} = ?"
val requiredType = if (getBirthdays) Event.TYPE_BIRTHDAY.toString() else Event.TYPE_ANNIVERSARY.toString()
val selectionArgs = arrayOf(Event.CONTENT_ITEM_TYPE, requiredType)
context.queryCursor(uri, projection, selection, selectionArgs) { cursor ->
val id = cursor.getIntValue(Data.RAW_CONTACT_ID)
val startDate = cursor.getStringValue(Event.START_DATE) ?: return@queryCursor
if (eventDates[id] == null) {
eventDates.put(id, ArrayList())
}
eventDates[id]!!.add(startDate)
}
return eventDates
}
fun getNameFromPhoneNumber(number: String): String {
if (!context.hasPermission(PERMISSION_READ_CONTACTS)) {
return number
}
val uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number))
val projection = arrayOf(
PhoneLookup.DISPLAY_NAME
)
try {
val cursor = context.contentResolver.query(uri, projection, null, null, null)
cursor.use {
if (cursor?.moveToFirst() == true) {
return cursor.getStringValue(PhoneLookup.DISPLAY_NAME)
}
}
} catch (ignored: Exception) {
}
return number
}
fun getPhotoUriFromPhoneNumber(number: String): String {
if (!context.hasPermission(PERMISSION_READ_CONTACTS)) {
return ""
}
val uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number))
val projection = arrayOf(
PhoneLookup.PHOTO_URI
)
try {
val cursor = context.contentResolver.query(uri, projection, null, null, null)
cursor.use {
if (cursor?.moveToFirst() == true) {
return cursor.getStringValue(PhoneLookup.PHOTO_URI) ?: ""
}
}
} catch (ignored: Exception) {
}
return ""
}
fun loadContactImage(path: String, imageView: ImageView, placeholderName: String, placeholderImage: Drawable? = null) {
val placeholder = placeholderImage ?: BitmapDrawable(context.resources, getContactLetterIcon(placeholderName))
val options = RequestOptions()
.diskCacheStrategy(DiskCacheStrategy.RESOURCE)
.error(placeholder)
.centerCrop()
Glide.with(context)
.load(path)
.transition(DrawableTransitionOptions.withCrossFade())
.placeholder(placeholder)
.apply(options)
.apply(RequestOptions.circleCropTransform())
.into(imageView)
}
fun getContactLetterIcon(name: String): Bitmap {
val letter = name.getNameLetter()
val size = context.resources.getDimension(R.dimen.normal_icon_size).toInt()
val bitmap = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
val view = TextView(context)
view.layout(0, 0, size, size)
val circlePaint = Paint().apply {
color = letterBackgroundColors[Math.abs(name.hashCode()) % letterBackgroundColors.size].toInt()
isAntiAlias = true
}
val wantedTextSize = size / 2f
val textPaint = Paint().apply {
color = circlePaint.color.getContrastColor()
isAntiAlias = true
textAlign = Paint.Align.CENTER
textSize = wantedTextSize
style = Paint.Style.FILL
}
canvas.drawCircle(size / 2f, size / 2f, size / 2f, circlePaint)
val xPos = canvas.width / 2f
val yPos = canvas.height / 2 - (textPaint.descent() + textPaint.ascent()) / 2
canvas.drawText(letter, xPos, yPos, textPaint)
view.draw(canvas)
return bitmap
}
fun getColoredGroupIcon(title: String): Drawable {
val icon = context.resources.getDrawable(R.drawable.ic_group_circle_bg)
val bgColor = letterBackgroundColors[Math.abs(title.hashCode()) % letterBackgroundColors.size].toInt()
(icon as LayerDrawable).findDrawableByLayerId(R.id.attendee_circular_background).applyColorFilter(bgColor)
return icon
}
fun getContactLookupKey(contactId: String): String {
val uri = Data.CONTENT_URI
val projection = arrayOf(Data.CONTACT_ID, Data.LOOKUP_KEY)
val selection = "${Data.MIMETYPE} = ? AND ${Data.RAW_CONTACT_ID} = ?"
val selectionArgs = arrayOf(StructuredName.CONTENT_ITEM_TYPE, contactId)
val cursor = context.contentResolver.query(uri, projection, selection, selectionArgs, null)
cursor?.use {
if (cursor.moveToFirst()) {
val id = cursor.getIntValue(Data.CONTACT_ID)
val lookupKey = cursor.getStringValue(Data.LOOKUP_KEY)
return "$lookupKey/$id"
}
}
return ""
}
fun deleteContactRawIDs(ids: ArrayList<Int>, callback: () -> Unit) {
ensureBackgroundThread {
val uri = Data.CONTENT_URI
ids.chunked(30).forEach { chunk ->
val selection = "${Data.RAW_CONTACT_ID} IN (${getQuestionMarks(chunk.size)})"
val selectionArgs = chunk.map { it.toString() }.toTypedArray()
context.contentResolver.delete(uri, selection, selectionArgs)
}
callback()
}
}
fun getShortcutImage(path: String, placeholderName: String, callback: (image: Bitmap) -> Unit) {
ensureBackgroundThread {
val placeholder = BitmapDrawable(context.resources, getContactLetterIcon(placeholderName))
try {
val options = RequestOptions()
.format(DecodeFormat.PREFER_ARGB_8888)
.diskCacheStrategy(DiskCacheStrategy.NONE)
.error(placeholder)
.centerCrop()
val size = context.resources.getDimension(R.dimen.shortcut_size).toInt()
val bitmap = Glide.with(context).asBitmap()
.load(path)
.placeholder(placeholder)
.apply(options)
.apply(RequestOptions.circleCropTransform())
.into(size, size)
.get()
callback(bitmap)
} catch (ignored: Exception) {
callback(placeholder.bitmap)
}
}
}
fun exists(number: String, privateCursor: Cursor?, callback: (Boolean) -> Unit) {
SimpleContactsHelper(context).getAvailableContacts(false) { contacts ->
val contact = contacts.firstOrNull { it.doesHavePhoneNumber(number) }
if (contact != null) {
callback.invoke(true)
} else {
val privateContacts = MyContactsContentProvider.getSimpleContacts(context, privateCursor)
val privateContact = privateContacts.firstOrNull { it.doesHavePhoneNumber(number) }
callback.invoke(privateContact != null)
}
}
}
}
|
CT/commons/src/main/kotlin/com/simplemobiletools/commons/helpers/MyContactsContentProvider.kt | 2431144464 | package com.simplemobiletools.commons.helpers
import android.content.Context
import android.database.Cursor
import android.net.Uri
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.simplemobiletools.commons.extensions.getIntValue
import com.simplemobiletools.commons.extensions.getStringValue
import com.simplemobiletools.commons.models.PhoneNumber
import com.simplemobiletools.commons.models.SimpleContact
import com.simplemobiletools.commons.models.contacts.Contact
// used for sharing privately stored contacts in Simple Contacts with Simple Dialer, Simple SMS Messenger and Simple Calendar Pro
class MyContactsContentProvider {
companion object {
private const val AUTHORITY = "com.simplemobiletools.commons.contactsprovider"
val CONTACTS_CONTENT_URI = Uri.parse("content://$AUTHORITY/contacts")
const val FAVORITES_ONLY = "favorites_only"
const val COL_RAW_ID = "raw_id"
const val COL_CONTACT_ID = "contact_id"
const val COL_NAME = "name"
const val COL_PHOTO_URI = "photo_uri"
const val COL_PHONE_NUMBERS = "phone_numbers"
const val COL_BIRTHDAYS = "birthdays"
const val COL_ANNIVERSARIES = "anniversaries"
fun getSimpleContacts(context: Context, cursor: Cursor?): ArrayList<SimpleContact> {
val contacts = ArrayList<SimpleContact>()
val packageName = context.packageName.removeSuffix(".debug")
if (packageName != "com.simplemobiletools.dialer" && packageName != "com.simplemobiletools.smsmessenger" && packageName != "com.simplemobiletools.calendar.pro") {
return contacts
}
try {
cursor?.use {
if (cursor.moveToFirst()) {
do {
val rawId = cursor.getIntValue(COL_RAW_ID)
val contactId = cursor.getIntValue(COL_CONTACT_ID)
val name = cursor.getStringValue(COL_NAME)
val photoUri = cursor.getStringValue(COL_PHOTO_URI)
val phoneNumbersJson = cursor.getStringValue(COL_PHONE_NUMBERS)
val birthdaysJson = cursor.getStringValue(COL_BIRTHDAYS)
val anniversariesJson = cursor.getStringValue(COL_ANNIVERSARIES)
val phoneNumbersToken = object : TypeToken<ArrayList<PhoneNumber>>() {}.type
val phoneNumbers = Gson().fromJson<ArrayList<PhoneNumber>>(phoneNumbersJson, phoneNumbersToken) ?: ArrayList()
val stringsToken = object : TypeToken<ArrayList<String>>() {}.type
val birthdays = Gson().fromJson<ArrayList<String>>(birthdaysJson, stringsToken) ?: ArrayList()
val anniversaries = Gson().fromJson<ArrayList<String>>(anniversariesJson, stringsToken) ?: ArrayList()
val contact = SimpleContact(rawId, contactId, name, photoUri, phoneNumbers, birthdays, anniversaries)
contacts.add(contact)
} while (cursor.moveToNext())
}
}
} catch (ignored: Exception) {
}
return contacts
}
fun getContacts(context: Context, cursor: Cursor?): ArrayList<Contact> {
val contacts = ArrayList<Contact>()
val packageName = context.packageName.removeSuffix(".debug")
if (packageName != "com.simplemobiletools.dialer" && packageName != "com.simplemobiletools.smsmessenger" && packageName != "com.simplemobiletools.calendar.pro") {
return contacts
}
try {
cursor?.use {
if (cursor.moveToFirst()) {
do {
val rawId = cursor.getIntValue(COL_RAW_ID)
val contactId = cursor.getIntValue(COL_CONTACT_ID)
val name = cursor.getStringValue(COL_NAME)
val photoUri = cursor.getStringValue(COL_PHOTO_URI)
val phoneNumbersJson = cursor.getStringValue(COL_PHONE_NUMBERS)
val birthdaysJson = cursor.getStringValue(COL_BIRTHDAYS)
val anniversariesJson = cursor.getStringValue(COL_ANNIVERSARIES)
val phoneNumbersToken = object : TypeToken<ArrayList<PhoneNumber>>() {}.type
val phoneNumbers = Gson().fromJson<ArrayList<PhoneNumber>>(phoneNumbersJson, phoneNumbersToken) ?: ArrayList()
val stringsToken = object : TypeToken<ArrayList<String>>() {}.type
val birthdays = Gson().fromJson<ArrayList<String>>(birthdaysJson, stringsToken) ?: ArrayList()
val anniversaries = Gson().fromJson<ArrayList<String>>(anniversariesJson, stringsToken) ?: ArrayList()
val names = if (name.contains(",")) {
name.split(",")
} else {
name.split(" ")
}
var firstName = names.firstOrNull() ?: ""
if (name.contains(",")) {
firstName += ", "
}
val middleName = if (names.size >= 3) {
names.subList(1, names.size - 1).joinToString(" ")
} else {
""
}
val surname = names.lastOrNull()?.takeIf { names.size > 1 } ?: ""
val contact = Contact(
id = rawId,
contactId = contactId,
firstName = firstName,
middleName = middleName,
surname = surname,
photoUri = photoUri,
phoneNumbers = phoneNumbers,
source = SMT_PRIVATE
).also {
it.birthdays = birthdays
it.anniversaries = anniversaries
}
contacts.add(contact)
} while (cursor.moveToNext())
}
}
} catch (ignored: Exception) {
}
return contacts
}
}
}
|
CT/commons/src/main/kotlin/com/simplemobiletools/commons/helpers/BlockedNumbersExporter.kt | 1656258369 | package com.simplemobiletools.commons.helpers
import com.simplemobiletools.commons.models.BlockedNumber
import java.io.OutputStream
object BlockedNumbersExporter {
fun exportBlockedNumbers(
blockedNumbers: ArrayList<BlockedNumber>,
outputStream: OutputStream?,
callback: (result: ExportResult) -> Unit,
) {
if (outputStream == null) {
callback.invoke(ExportResult.EXPORT_FAIL)
return
}
try {
outputStream.bufferedWriter().use { out ->
out.write(blockedNumbers.joinToString(BLOCKED_NUMBERS_EXPORT_DELIMITER) {
it.number
})
}
callback.invoke(ExportResult.EXPORT_OK)
} catch (e: Exception) {
callback.invoke(ExportResult.EXPORT_FAIL)
}
}
}
|
CT/commons/src/main/kotlin/com/simplemobiletools/commons/helpers/ContactsHelper.kt | 3033753997 | package com.simplemobiletools.commons.helpers
import android.accounts.Account
import android.accounts.AccountManager
import android.content.*
import android.graphics.Bitmap
import android.net.Uri
import android.os.Handler
import android.os.Looper
import android.provider.ContactsContract
import android.provider.ContactsContract.*
import android.provider.MediaStore
import android.text.TextUtils
import android.util.SparseArray
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.models.PhoneNumber
import com.simplemobiletools.commons.models.contacts.*
import com.simplemobiletools.commons.overloads.times
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import java.io.OutputStream
import java.util.Locale
class ContactsHelper(val context: Context) {
private val BATCH_SIZE = 50
private var displayContactSources = ArrayList<String>()
fun getContacts(
getAll: Boolean = false,
gettingDuplicates: Boolean = false,
ignoredContactSources: HashSet<String> = HashSet(),
showOnlyContactsWithNumbers: Boolean = context.baseConfig.showOnlyContactsWithNumbers,
callback: (ArrayList<Contact>) -> Unit
) {
ensureBackgroundThread {
val contacts = SparseArray<Contact>()
displayContactSources = context.getVisibleContactSources()
if (getAll) {
displayContactSources = if (ignoredContactSources.isEmpty()) {
context.getAllContactSources().map { it.name }.toMutableList() as ArrayList
} else {
context.getAllContactSources().filter {
it.getFullIdentifier().isNotEmpty() && !ignoredContactSources.contains(it.getFullIdentifier())
}.map { it.name }.toMutableList() as ArrayList
}
}
getDeviceContacts(contacts, ignoredContactSources, gettingDuplicates)
if (displayContactSources.contains(SMT_PRIVATE)) {
LocalContactsHelper(context).getAllContacts().forEach {
contacts.put(it.id, it)
}
}
val contactsSize = contacts.size()
val tempContacts = ArrayList<Contact>(contactsSize)
val resultContacts = ArrayList<Contact>(contactsSize)
(0 until contactsSize).filter {
if (ignoredContactSources.isEmpty() && showOnlyContactsWithNumbers) {
contacts.valueAt(it).phoneNumbers.isNotEmpty()
} else {
true
}
}.mapTo(tempContacts) {
contacts.valueAt(it)
}
if (context.baseConfig.mergeDuplicateContacts && ignoredContactSources.isEmpty() && !getAll) {
tempContacts.filter { displayContactSources.contains(it.source) }.groupBy { it.getNameToDisplay().toLowerCase() }.values.forEach { it ->
if (it.size == 1) {
resultContacts.add(it.first())
} else {
val sorted = it.sortedByDescending { it.getStringToCompare().length }
resultContacts.add(sorted.first())
}
}
} else {
resultContacts.addAll(tempContacts)
}
// groups are obtained with contactID, not rawID, so assign them to proper contacts like this
val groups = getContactGroups(getStoredGroupsSync())
val size = groups.size()
for (i in 0 until size) {
val key = groups.keyAt(i)
resultContacts.firstOrNull { it.contactId == key }?.groups = groups.valueAt(i)
}
Contact.sorting = context.baseConfig.sorting
Contact.startWithSurname = context.baseConfig.startNameWithSurname
resultContacts.sort()
Handler(Looper.getMainLooper()).post {
callback(resultContacts)
}
}
}
private fun getContentResolverAccounts(): HashSet<ContactSource> {
val sources = HashSet<ContactSource>()
arrayOf(Groups.CONTENT_URI, Settings.CONTENT_URI, RawContacts.CONTENT_URI).forEach {
fillSourcesFromUri(it, sources)
}
return sources
}
private fun fillSourcesFromUri(uri: Uri, sources: HashSet<ContactSource>) {
val projection = arrayOf(
RawContacts.ACCOUNT_NAME,
RawContacts.ACCOUNT_TYPE
)
context.queryCursor(uri, projection) { cursor ->
val name = cursor.getStringValue(RawContacts.ACCOUNT_NAME) ?: ""
val type = cursor.getStringValue(RawContacts.ACCOUNT_TYPE) ?: ""
var publicName = name
if (type == TELEGRAM_PACKAGE) {
publicName = context.getString(R.string.telegram)
}
val source = ContactSource(name, type, publicName)
sources.add(source)
}
}
private fun getDeviceContacts(contacts: SparseArray<Contact>, ignoredContactSources: HashSet<String>?, gettingDuplicates: Boolean) {
if (!context.hasPermission(PERMISSION_READ_CONTACTS)) {
return
}
val ignoredSources = ignoredContactSources ?: context.baseConfig.ignoredContactSources
val uri = Data.CONTENT_URI
val projection = getContactProjection()
arrayOf(CommonDataKinds.Organization.CONTENT_ITEM_TYPE, CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE).forEach { mimetype ->
val selection = "${Data.MIMETYPE} = ?"
val selectionArgs = arrayOf(mimetype)
val sortOrder = getSortString()
context.queryCursor(uri, projection, selection, selectionArgs, sortOrder, true) { cursor ->
val accountName = cursor.getStringValue(RawContacts.ACCOUNT_NAME) ?: ""
val accountType = cursor.getStringValue(RawContacts.ACCOUNT_TYPE) ?: ""
if (ignoredSources.contains("$accountName:$accountType")) {
return@queryCursor
}
val id = cursor.getIntValue(Data.RAW_CONTACT_ID)
var prefix = ""
var firstName = ""
var middleName = ""
var surname = ""
var suffix = ""
// ignore names at Organization type contacts
if (mimetype == CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE) {
prefix = cursor.getStringValue(CommonDataKinds.StructuredName.PREFIX) ?: ""
firstName = cursor.getStringValue(CommonDataKinds.StructuredName.GIVEN_NAME) ?: ""
middleName = cursor.getStringValue(CommonDataKinds.StructuredName.MIDDLE_NAME) ?: ""
surname = cursor.getStringValue(CommonDataKinds.StructuredName.FAMILY_NAME) ?: ""
suffix = cursor.getStringValue(CommonDataKinds.StructuredName.SUFFIX) ?: ""
}
var photoUri = ""
var starred = 0
var contactId = 0
var thumbnailUri = ""
var ringtone: String? = null
if (!gettingDuplicates) {
photoUri = cursor.getStringValue(CommonDataKinds.StructuredName.PHOTO_URI) ?: ""
starred = cursor.getIntValue(CommonDataKinds.StructuredName.STARRED)
contactId = cursor.getIntValue(Data.CONTACT_ID)
thumbnailUri = cursor.getStringValue(CommonDataKinds.StructuredName.PHOTO_THUMBNAIL_URI) ?: ""
ringtone = cursor.getStringValue(CommonDataKinds.StructuredName.CUSTOM_RINGTONE)
}
val nickname = ""
val numbers = ArrayList<PhoneNumber>() // proper value is obtained below
val emails = ArrayList<Email>()
val addresses = ArrayList<Address>()
val events = ArrayList<Event>()
val notes = ""
val groups = ArrayList<Group>()
val organization = Organization("", "")
val websites = ArrayList<String>()
val ims = ArrayList<IM>()
val contact = Contact(
id, prefix, firstName, middleName, surname, suffix, nickname, photoUri, numbers, emails, addresses,
events, accountName, starred, contactId, thumbnailUri, null, notes, groups, organization, websites, ims, mimetype, ringtone
)
contacts.put(id, contact)
}
}
val emails = getEmails()
var size = emails.size()
for (i in 0 until size) {
val key = emails.keyAt(i)
contacts[key]?.emails = emails.valueAt(i)
}
val organizations = getOrganizations()
size = organizations.size()
for (i in 0 until size) {
val key = organizations.keyAt(i)
contacts[key]?.organization = organizations.valueAt(i)
}
// no need to fetch some fields if we are only getting duplicates of the current contact
if (gettingDuplicates) {
return
}
val phoneNumbers = getPhoneNumbers(null)
size = phoneNumbers.size()
for (i in 0 until size) {
val key = phoneNumbers.keyAt(i)
if (contacts[key] != null) {
val numbers = phoneNumbers.valueAt(i)
contacts[key].phoneNumbers = numbers
}
}
val addresses = getAddresses()
size = addresses.size()
for (i in 0 until size) {
val key = addresses.keyAt(i)
contacts[key]?.addresses = addresses.valueAt(i)
}
val IMs = getIMs()
size = IMs.size()
for (i in 0 until size) {
val key = IMs.keyAt(i)
contacts[key]?.IMs = IMs.valueAt(i)
}
val events = getEvents()
size = events.size()
for (i in 0 until size) {
val key = events.keyAt(i)
contacts[key]?.events = events.valueAt(i)
}
val notes = getNotes()
size = notes.size()
for (i in 0 until size) {
val key = notes.keyAt(i)
contacts[key]?.notes = notes.valueAt(i)
}
val nicknames = getNicknames()
size = nicknames.size()
for (i in 0 until size) {
val key = nicknames.keyAt(i)
contacts[key]?.nickname = nicknames.valueAt(i)
}
val websites = getWebsites()
size = websites.size()
for (i in 0 until size) {
val key = websites.keyAt(i)
contacts[key]?.websites = websites.valueAt(i)
}
}
private fun getPhoneNumbers(contactId: Int? = null): SparseArray<ArrayList<PhoneNumber>> {
val phoneNumbers = SparseArray<ArrayList<PhoneNumber>>()
val uri = CommonDataKinds.Phone.CONTENT_URI
val projection = arrayOf(
Data.RAW_CONTACT_ID,
CommonDataKinds.Phone.NUMBER,
CommonDataKinds.Phone.NORMALIZED_NUMBER,
CommonDataKinds.Phone.TYPE,
CommonDataKinds.Phone.LABEL,
CommonDataKinds.Phone.IS_PRIMARY
)
val selection = if (contactId == null) getSourcesSelection() else "${Data.RAW_CONTACT_ID} = ?"
val selectionArgs = if (contactId == null) getSourcesSelectionArgs() else arrayOf(contactId.toString())
context.queryCursor(uri, projection, selection, selectionArgs, showErrors = true) { cursor ->
val id = cursor.getIntValue(Data.RAW_CONTACT_ID)
val number = cursor.getStringValue(CommonDataKinds.Phone.NUMBER) ?: return@queryCursor
val normalizedNumber = cursor.getStringValue(CommonDataKinds.Phone.NORMALIZED_NUMBER) ?: number.normalizePhoneNumber()
val type = cursor.getIntValue(CommonDataKinds.Phone.TYPE)
val label = cursor.getStringValue(CommonDataKinds.Phone.LABEL) ?: ""
val isPrimary = cursor.getIntValue(CommonDataKinds.Phone.IS_PRIMARY) != 0
if (phoneNumbers[id] == null) {
phoneNumbers.put(id, ArrayList())
}
val phoneNumber = PhoneNumber(number, type, label, normalizedNumber, isPrimary)
phoneNumbers[id].add(phoneNumber)
}
return phoneNumbers
}
private fun getNicknames(contactId: Int? = null): SparseArray<String> {
val nicknames = SparseArray<String>()
val uri = Data.CONTENT_URI
val projection = arrayOf(
Data.RAW_CONTACT_ID,
CommonDataKinds.Nickname.NAME
)
val selection = getSourcesSelection(true, contactId != null)
val selectionArgs = getSourcesSelectionArgs(CommonDataKinds.Nickname.CONTENT_ITEM_TYPE, contactId)
context.queryCursor(uri, projection, selection, selectionArgs, showErrors = true) { cursor ->
val id = cursor.getIntValue(Data.RAW_CONTACT_ID)
val nickname = cursor.getStringValue(CommonDataKinds.Nickname.NAME) ?: return@queryCursor
nicknames.put(id, nickname)
}
return nicknames
}
private fun getEmails(contactId: Int? = null): SparseArray<ArrayList<Email>> {
val emails = SparseArray<ArrayList<Email>>()
val uri = CommonDataKinds.Email.CONTENT_URI
val projection = arrayOf(
Data.RAW_CONTACT_ID,
CommonDataKinds.Email.DATA,
CommonDataKinds.Email.TYPE,
CommonDataKinds.Email.LABEL
)
val selection = if (contactId == null) getSourcesSelection() else "${Data.RAW_CONTACT_ID} = ?"
val selectionArgs = if (contactId == null) getSourcesSelectionArgs() else arrayOf(contactId.toString())
context.queryCursor(uri, projection, selection, selectionArgs, showErrors = true) { cursor ->
val id = cursor.getIntValue(Data.RAW_CONTACT_ID)
val email = cursor.getStringValue(CommonDataKinds.Email.DATA) ?: return@queryCursor
val type = cursor.getIntValue(CommonDataKinds.Email.TYPE)
val label = cursor.getStringValue(CommonDataKinds.Email.LABEL) ?: ""
if (emails[id] == null) {
emails.put(id, ArrayList())
}
emails[id]!!.add(Email(email, type, label))
}
return emails
}
private fun getAddresses(contactId: Int? = null): SparseArray<ArrayList<Address>> {
val addresses = SparseArray<ArrayList<Address>>()
val uri = CommonDataKinds.StructuredPostal.CONTENT_URI
val projection = arrayOf(
Data.RAW_CONTACT_ID,
CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS,
CommonDataKinds.StructuredPostal.TYPE,
CommonDataKinds.StructuredPostal.LABEL
)
val selection = if (contactId == null) getSourcesSelection() else "${Data.RAW_CONTACT_ID} = ?"
val selectionArgs = if (contactId == null) getSourcesSelectionArgs() else arrayOf(contactId.toString())
context.queryCursor(uri, projection, selection, selectionArgs, showErrors = true) { cursor ->
val id = cursor.getIntValue(Data.RAW_CONTACT_ID)
val address = cursor.getStringValue(CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS) ?: return@queryCursor
val type = cursor.getIntValue(CommonDataKinds.StructuredPostal.TYPE)
val label = cursor.getStringValue(CommonDataKinds.StructuredPostal.LABEL) ?: ""
if (addresses[id] == null) {
addresses.put(id, ArrayList())
}
addresses[id]!!.add(Address(address, type, label))
}
return addresses
}
private fun getIMs(contactId: Int? = null): SparseArray<ArrayList<IM>> {
val IMs = SparseArray<ArrayList<IM>>()
val uri = Data.CONTENT_URI
val projection = arrayOf(
Data.RAW_CONTACT_ID,
CommonDataKinds.Im.DATA,
CommonDataKinds.Im.PROTOCOL,
CommonDataKinds.Im.CUSTOM_PROTOCOL
)
val selection = getSourcesSelection(true, contactId != null)
val selectionArgs = getSourcesSelectionArgs(CommonDataKinds.Im.CONTENT_ITEM_TYPE, contactId)
context.queryCursor(uri, projection, selection, selectionArgs, showErrors = true) { cursor ->
val id = cursor.getIntValue(Data.RAW_CONTACT_ID)
val IM = cursor.getStringValue(CommonDataKinds.Im.DATA) ?: return@queryCursor
val type = cursor.getIntValue(CommonDataKinds.Im.PROTOCOL)
val label = cursor.getStringValue(CommonDataKinds.Im.CUSTOM_PROTOCOL) ?: ""
if (IMs[id] == null) {
IMs.put(id, ArrayList())
}
IMs[id]!!.add(IM(IM, type, label))
}
return IMs
}
private fun getEvents(contactId: Int? = null): SparseArray<ArrayList<Event>> {
val events = SparseArray<ArrayList<Event>>()
val uri = Data.CONTENT_URI
val projection = arrayOf(
Data.RAW_CONTACT_ID,
CommonDataKinds.Event.START_DATE,
CommonDataKinds.Event.TYPE
)
val selection = getSourcesSelection(true, contactId != null)
val selectionArgs = getSourcesSelectionArgs(CommonDataKinds.Event.CONTENT_ITEM_TYPE, contactId)
context.queryCursor(uri, projection, selection, selectionArgs, showErrors = true) { cursor ->
val id = cursor.getIntValue(Data.RAW_CONTACT_ID)
val startDate = cursor.getStringValue(CommonDataKinds.Event.START_DATE) ?: return@queryCursor
val type = cursor.getIntValue(CommonDataKinds.Event.TYPE)
if (events[id] == null) {
events.put(id, ArrayList())
}
events[id]!!.add(Event(startDate, type))
}
return events
}
private fun getNotes(contactId: Int? = null): SparseArray<String> {
val notes = SparseArray<String>()
val uri = Data.CONTENT_URI
val projection = arrayOf(
Data.RAW_CONTACT_ID,
CommonDataKinds.Note.NOTE
)
val selection = getSourcesSelection(true, contactId != null)
val selectionArgs = getSourcesSelectionArgs(CommonDataKinds.Note.CONTENT_ITEM_TYPE, contactId)
context.queryCursor(uri, projection, selection, selectionArgs, showErrors = true) { cursor ->
val id = cursor.getIntValue(Data.RAW_CONTACT_ID)
val note = cursor.getStringValue(CommonDataKinds.Note.NOTE) ?: return@queryCursor
notes.put(id, note)
}
return notes
}
private fun getOrganizations(contactId: Int? = null): SparseArray<Organization> {
val organizations = SparseArray<Organization>()
val uri = Data.CONTENT_URI
val projection = arrayOf(
Data.RAW_CONTACT_ID,
CommonDataKinds.Organization.COMPANY,
CommonDataKinds.Organization.TITLE
)
val selection = getSourcesSelection(true, contactId != null)
val selectionArgs = getSourcesSelectionArgs(CommonDataKinds.Organization.CONTENT_ITEM_TYPE, contactId)
context.queryCursor(uri, projection, selection, selectionArgs, showErrors = true) { cursor ->
val id = cursor.getIntValue(Data.RAW_CONTACT_ID)
val company = cursor.getStringValue(CommonDataKinds.Organization.COMPANY) ?: ""
val title = cursor.getStringValue(CommonDataKinds.Organization.TITLE) ?: ""
if (company.isEmpty() && title.isEmpty()) {
return@queryCursor
}
val organization = Organization(company, title)
organizations.put(id, organization)
}
return organizations
}
private fun getWebsites(contactId: Int? = null): SparseArray<ArrayList<String>> {
val websites = SparseArray<ArrayList<String>>()
val uri = Data.CONTENT_URI
val projection = arrayOf(
Data.RAW_CONTACT_ID,
CommonDataKinds.Website.URL
)
val selection = getSourcesSelection(true, contactId != null)
val selectionArgs = getSourcesSelectionArgs(CommonDataKinds.Website.CONTENT_ITEM_TYPE, contactId)
context.queryCursor(uri, projection, selection, selectionArgs, showErrors = true) { cursor ->
val id = cursor.getIntValue(Data.RAW_CONTACT_ID)
val url = cursor.getStringValue(CommonDataKinds.Website.URL) ?: return@queryCursor
if (websites[id] == null) {
websites.put(id, ArrayList())
}
websites[id]!!.add(url)
}
return websites
}
private fun getContactGroups(storedGroups: ArrayList<Group>, contactId: Int? = null): SparseArray<ArrayList<Group>> {
val groups = SparseArray<ArrayList<Group>>()
if (!context.hasPermission(PERMISSION_READ_CONTACTS)) {
return groups
}
val uri = Data.CONTENT_URI
val projection = arrayOf(
Data.CONTACT_ID,
Data.DATA1
)
val selection = getSourcesSelection(true, contactId != null, false)
val selectionArgs = getSourcesSelectionArgs(CommonDataKinds.GroupMembership.CONTENT_ITEM_TYPE, contactId)
context.queryCursor(uri, projection, selection, selectionArgs, showErrors = true) { cursor ->
val id = cursor.getIntValue(Data.CONTACT_ID)
val newRowId = cursor.getLongValue(Data.DATA1)
val groupTitle = storedGroups.firstOrNull { it.id == newRowId }?.title ?: return@queryCursor
val group = Group(newRowId, groupTitle)
if (groups[id] == null) {
groups.put(id, ArrayList())
}
groups[id]!!.add(group)
}
return groups
}
private fun getQuestionMarks() = ("?," * displayContactSources.filter { it.isNotEmpty() }.size).trimEnd(',')
private fun getSourcesSelection(addMimeType: Boolean = false, addContactId: Boolean = false, useRawContactId: Boolean = true): String {
val strings = ArrayList<String>()
if (addMimeType) {
strings.add("${Data.MIMETYPE} = ?")
}
if (addContactId) {
strings.add("${if (useRawContactId) Data.RAW_CONTACT_ID else Data.CONTACT_ID} = ?")
} else {
// sometimes local device storage has null account_name, handle it properly
val accountnameString = StringBuilder()
if (displayContactSources.contains("")) {
accountnameString.append("(")
}
accountnameString.append("${RawContacts.ACCOUNT_NAME} IN (${getQuestionMarks()})")
if (displayContactSources.contains("")) {
accountnameString.append(" OR ${RawContacts.ACCOUNT_NAME} IS NULL)")
}
strings.add(accountnameString.toString())
}
return TextUtils.join(" AND ", strings)
}
private fun getSourcesSelectionArgs(mimetype: String? = null, contactId: Int? = null): Array<String> {
val args = ArrayList<String>()
if (mimetype != null) {
args.add(mimetype)
}
if (contactId != null) {
args.add(contactId.toString())
} else {
args.addAll(displayContactSources.filter { it.isNotEmpty() })
}
return args.toTypedArray()
}
fun getStoredGroups(callback: (ArrayList<Group>) -> Unit) {
ensureBackgroundThread {
val groups = getStoredGroupsSync()
Handler(Looper.getMainLooper()).post {
callback(groups)
}
}
}
fun getStoredGroupsSync(): ArrayList<Group> {
val groups = getDeviceStoredGroups()
groups.addAll(context.groupsDB.getGroups())
return groups
}
private fun getDeviceStoredGroups(): ArrayList<Group> {
val groups = ArrayList<Group>()
if (!context.hasPermission(PERMISSION_READ_CONTACTS)) {
return groups
}
val uri = Groups.CONTENT_URI
val projection = arrayOf(
Groups._ID,
Groups.TITLE,
Groups.SYSTEM_ID
)
val selection = "${Groups.AUTO_ADD} = ? AND ${Groups.FAVORITES} = ?"
val selectionArgs = arrayOf("0", "0")
context.queryCursor(uri, projection, selection, selectionArgs, showErrors = true) { cursor ->
val id = cursor.getLongValue(Groups._ID)
val title = cursor.getStringValue(Groups.TITLE) ?: return@queryCursor
val systemId = cursor.getStringValue(Groups.SYSTEM_ID)
if (groups.map { it.title }.contains(title) && systemId != null) {
return@queryCursor
}
groups.add(Group(id, title))
}
return groups
}
fun createNewGroup(title: String, accountName: String, accountType: String): Group? {
if (accountType == SMT_PRIVATE) {
val newGroup = Group(null, title)
val id = context.groupsDB.insertOrUpdate(newGroup)
newGroup.id = id
return newGroup
}
val operations = ArrayList<ContentProviderOperation>()
ContentProviderOperation.newInsert(Groups.CONTENT_URI).apply {
withValue(Groups.TITLE, title)
withValue(Groups.GROUP_VISIBLE, 1)
withValue(Groups.ACCOUNT_NAME, accountName)
withValue(Groups.ACCOUNT_TYPE, accountType)
operations.add(build())
}
try {
val results = context.contentResolver.applyBatch(AUTHORITY, operations)
val rawId = ContentUris.parseId(results[0].uri!!)
return Group(rawId, title)
} catch (e: Exception) {
context.showErrorToast(e)
}
return null
}
fun renameGroup(group: Group) {
val operations = ArrayList<ContentProviderOperation>()
ContentProviderOperation.newUpdate(Groups.CONTENT_URI).apply {
val selection = "${Groups._ID} = ?"
val selectionArgs = arrayOf(group.id.toString())
withSelection(selection, selectionArgs)
withValue(Groups.TITLE, group.title)
operations.add(build())
}
try {
context.contentResolver.applyBatch(AUTHORITY, operations)
} catch (e: Exception) {
context.showErrorToast(e)
}
}
fun deleteGroup(id: Long) {
val operations = ArrayList<ContentProviderOperation>()
val uri = ContentUris.withAppendedId(Groups.CONTENT_URI, id).buildUpon()
.appendQueryParameter(CALLER_IS_SYNCADAPTER, "true")
.build()
operations.add(ContentProviderOperation.newDelete(uri).build())
try {
context.contentResolver.applyBatch(AUTHORITY, operations)
} catch (e: Exception) {
context.showErrorToast(e)
}
}
fun getContactWithId(id: Int, isLocalPrivate: Boolean): Contact? {
if (id == 0) {
return null
} else if (isLocalPrivate) {
return LocalContactsHelper(context).getContactWithId(id)
}
val selection = "(${Data.MIMETYPE} = ? OR ${Data.MIMETYPE} = ?) AND ${Data.RAW_CONTACT_ID} = ?"
val selectionArgs = arrayOf(CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE, CommonDataKinds.Organization.CONTENT_ITEM_TYPE, id.toString())
return parseContactCursor(selection, selectionArgs)
}
fun getContactFromUri(uri: Uri): Contact? {
val key = getLookupKeyFromUri(uri) ?: return null
return getContactWithLookupKey(key)
}
private fun getLookupKeyFromUri(lookupUri: Uri): String? {
val projection = arrayOf(ContactsContract.Contacts.LOOKUP_KEY)
val cursor = context.contentResolver.query(lookupUri, projection, null, null, null)
cursor?.use {
if (cursor.moveToFirst()) {
return cursor.getStringValue(ContactsContract.Contacts.LOOKUP_KEY)
}
}
return null
}
fun getContactWithLookupKey(key: String): Contact? {
val selection = "(${Data.MIMETYPE} = ? OR ${Data.MIMETYPE} = ?) AND ${Data.LOOKUP_KEY} = ?"
val selectionArgs = arrayOf(CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE, CommonDataKinds.Organization.CONTENT_ITEM_TYPE, key)
return parseContactCursor(selection, selectionArgs)
}
private fun parseContactCursor(selection: String, selectionArgs: Array<String>): Contact? {
val storedGroups = getStoredGroupsSync()
val uri = Data.CONTENT_URI
val projection = getContactProjection()
val cursor = context.contentResolver.query(uri, projection, selection, selectionArgs, null)
cursor?.use {
if (cursor.moveToFirst()) {
val id = cursor.getIntValue(Data.RAW_CONTACT_ID)
var prefix = ""
var firstName = ""
var middleName = ""
var surname = ""
var suffix = ""
var mimetype = cursor.getStringValue(Data.MIMETYPE)
// if first line is an Organization type contact, go to next line if available
if (mimetype != CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE) {
if (!cursor.isLast() && cursor.moveToNext()) {
mimetype = cursor.getStringValue(Data.MIMETYPE)
}
}
// ignore names at Organization type contacts
if (mimetype == CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE) {
prefix = cursor.getStringValue(CommonDataKinds.StructuredName.PREFIX) ?: ""
firstName = cursor.getStringValue(CommonDataKinds.StructuredName.GIVEN_NAME) ?: ""
middleName = cursor.getStringValue(CommonDataKinds.StructuredName.MIDDLE_NAME) ?: ""
surname = cursor.getStringValue(CommonDataKinds.StructuredName.FAMILY_NAME) ?: ""
suffix = cursor.getStringValue(CommonDataKinds.StructuredName.SUFFIX) ?: ""
}
val nickname = getNicknames(id)[id] ?: ""
val photoUri = cursor.getStringValueOrNull(CommonDataKinds.Phone.PHOTO_URI) ?: ""
val number = getPhoneNumbers(id)[id] ?: ArrayList()
val emails = getEmails(id)[id] ?: ArrayList()
val addresses = getAddresses(id)[id] ?: ArrayList()
val events = getEvents(id)[id] ?: ArrayList()
val notes = getNotes(id)[id] ?: ""
val accountName = cursor.getStringValue(RawContacts.ACCOUNT_NAME) ?: ""
val starred = cursor.getIntValue(CommonDataKinds.StructuredName.STARRED)
val ringtone = cursor.getStringValue(CommonDataKinds.StructuredName.CUSTOM_RINGTONE)
val contactId = cursor.getIntValue(Data.CONTACT_ID)
val groups = getContactGroups(storedGroups, contactId)[contactId] ?: ArrayList()
val thumbnailUri = cursor.getStringValue(CommonDataKinds.StructuredName.PHOTO_THUMBNAIL_URI) ?: ""
val organization = getOrganizations(id)[id] ?: Organization("", "")
val websites = getWebsites(id)[id] ?: ArrayList()
val ims = getIMs(id)[id] ?: ArrayList()
return Contact(
id, prefix, firstName, middleName, surname, suffix, nickname, photoUri, number, emails, addresses, events,
accountName, starred, contactId, thumbnailUri, null, notes, groups, organization, websites, ims, mimetype, ringtone
)
}
}
return null
}
fun getContactSources(callback: (ArrayList<ContactSource>) -> Unit) {
ensureBackgroundThread {
callback(getContactSourcesSync())
}
}
private fun getContactSourcesSync(): ArrayList<ContactSource> {
val sources = getDeviceContactSources()
sources.add(context.getPrivateContactSource())
return ArrayList(sources)
}
fun getSaveableContactSources(callback: (ArrayList<ContactSource>) -> Unit) {
ensureBackgroundThread {
val ignoredTypes = arrayListOf(
SIGNAL_PACKAGE,
TELEGRAM_PACKAGE,
WHATSAPP_PACKAGE,
THREEMA_PACKAGE
)
val contactSources = getContactSourcesSync()
val filteredSources = contactSources.filter { !ignoredTypes.contains(it.type) }.toMutableList() as ArrayList<ContactSource>
callback(filteredSources)
}
}
fun getDeviceContactSources(): LinkedHashSet<ContactSource> {
val sources = LinkedHashSet<ContactSource>()
if (!context.hasPermission(PERMISSION_READ_CONTACTS)) {
return sources
}
if (!context.baseConfig.wasLocalAccountInitialized) {
initializeLocalPhoneAccount()
context.baseConfig.wasLocalAccountInitialized = true
}
val accounts = AccountManager.get(context).accounts
if (context.hasPermission(PERMISSION_READ_SYNC_SETTINGS)) {
accounts.forEach {
if (ContentResolver.getIsSyncable(it, AUTHORITY) == 1) {
var publicName = it.name
if (it.type == TELEGRAM_PACKAGE) {
publicName = context.getString(R.string.telegram)
} else if (it.type == VIBER_PACKAGE) {
publicName = context.getString(R.string.viber)
}
val contactSource = ContactSource(it.name, it.type, publicName)
sources.add(contactSource)
}
}
}
var hadEmptyAccount = false
val allAccounts = getContentResolverAccounts()
val contentResolverAccounts = allAccounts.filter {
if (it.name.isEmpty() && it.type.isEmpty() && allAccounts.none { it.name.lowercase(Locale.getDefault()) == "phone" }) {
hadEmptyAccount = true
}
it.name.isNotEmpty() && it.type.isNotEmpty() && !accounts.contains(Account(it.name, it.type))
}
sources.addAll(contentResolverAccounts)
if (hadEmptyAccount) {
sources.add(ContactSource("", "", context.getString(R.string.phone_storage)))
}
return sources
}
// make sure the local Phone contact source is initialized and available
// https://stackoverflow.com/a/6096508/1967672
private fun initializeLocalPhoneAccount() {
try {
val operations = ArrayList<ContentProviderOperation>()
ContentProviderOperation.newInsert(RawContacts.CONTENT_URI).apply {
withValue(RawContacts.ACCOUNT_NAME, null)
withValue(RawContacts.ACCOUNT_TYPE, null)
operations.add(build())
}
val results = context.contentResolver.applyBatch(AUTHORITY, operations)
val rawContactUri = results.firstOrNull()?.uri ?: return
context.contentResolver.delete(rawContactUri, null, null)
} catch (ignored: Exception) {
}
}
private fun getContactSourceType(accountName: String) = getDeviceContactSources().firstOrNull { it.name == accountName }?.type ?: ""
private fun getContactProjection() = arrayOf(
Data.MIMETYPE,
Data.CONTACT_ID,
Data.RAW_CONTACT_ID,
CommonDataKinds.StructuredName.PREFIX,
CommonDataKinds.StructuredName.GIVEN_NAME,
CommonDataKinds.StructuredName.MIDDLE_NAME,
CommonDataKinds.StructuredName.FAMILY_NAME,
CommonDataKinds.StructuredName.SUFFIX,
CommonDataKinds.StructuredName.PHOTO_URI,
CommonDataKinds.StructuredName.PHOTO_THUMBNAIL_URI,
CommonDataKinds.StructuredName.STARRED,
CommonDataKinds.StructuredName.CUSTOM_RINGTONE,
RawContacts.ACCOUNT_NAME,
RawContacts.ACCOUNT_TYPE
)
private fun getSortString(): String {
val sorting = context.baseConfig.sorting
return when {
sorting and SORT_BY_FIRST_NAME != 0 -> "${CommonDataKinds.StructuredName.GIVEN_NAME} COLLATE NOCASE"
sorting and SORT_BY_MIDDLE_NAME != 0 -> "${CommonDataKinds.StructuredName.MIDDLE_NAME} COLLATE NOCASE"
sorting and SORT_BY_SURNAME != 0 -> "${CommonDataKinds.StructuredName.FAMILY_NAME} COLLATE NOCASE"
sorting and SORT_BY_FULL_NAME != 0 -> CommonDataKinds.StructuredName.DISPLAY_NAME
else -> Data.RAW_CONTACT_ID
}
}
private fun getRealContactId(id: Long): Int {
val uri = Data.CONTENT_URI
val projection = getContactProjection()
val selection = "(${Data.MIMETYPE} = ? OR ${Data.MIMETYPE} = ?) AND ${Data.RAW_CONTACT_ID} = ?"
val selectionArgs = arrayOf(CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE, CommonDataKinds.Organization.CONTENT_ITEM_TYPE, id.toString())
val cursor = context.contentResolver.query(uri, projection, selection, selectionArgs, null)
cursor?.use {
if (cursor.moveToFirst()) {
return cursor.getIntValue(Data.CONTACT_ID)
}
}
return 0
}
fun updateContact(contact: Contact, photoUpdateStatus: Int): Boolean {
context.toast(R.string.updating)
if (contact.isPrivate()) {
return LocalContactsHelper(context).insertOrUpdateContact(contact)
}
try {
val operations = ArrayList<ContentProviderOperation>()
ContentProviderOperation.newUpdate(Data.CONTENT_URI).apply {
val selection = "${Data.RAW_CONTACT_ID} = ? AND ${Data.MIMETYPE} = ?"
val selectionArgs = arrayOf(contact.id.toString(), contact.mimetype)
withSelection(selection, selectionArgs)
withValue(CommonDataKinds.StructuredName.PREFIX, contact.prefix)
withValue(CommonDataKinds.StructuredName.GIVEN_NAME, contact.firstName)
withValue(CommonDataKinds.StructuredName.MIDDLE_NAME, contact.middleName)
withValue(CommonDataKinds.StructuredName.FAMILY_NAME, contact.surname)
withValue(CommonDataKinds.StructuredName.SUFFIX, contact.suffix)
operations.add(build())
}
// delete nickname
ContentProviderOperation.newDelete(Data.CONTENT_URI).apply {
val selection = "${Data.RAW_CONTACT_ID} = ? AND ${Data.MIMETYPE} = ? "
val selectionArgs = arrayOf(contact.id.toString(), CommonDataKinds.Nickname.CONTENT_ITEM_TYPE)
withSelection(selection, selectionArgs)
operations.add(build())
}
// add nickname
ContentProviderOperation.newInsert(Data.CONTENT_URI).apply {
withValue(Data.RAW_CONTACT_ID, contact.id)
withValue(Data.MIMETYPE, CommonDataKinds.Nickname.CONTENT_ITEM_TYPE)
withValue(CommonDataKinds.Nickname.NAME, contact.nickname)
operations.add(build())
}
// delete phone numbers
ContentProviderOperation.newDelete(Data.CONTENT_URI).apply {
val selection = "${Data.RAW_CONTACT_ID} = ? AND ${Data.MIMETYPE} = ? "
val selectionArgs = arrayOf(contact.id.toString(), CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
withSelection(selection, selectionArgs)
operations.add(build())
}
// add phone numbers
contact.phoneNumbers.forEach {
ContentProviderOperation.newInsert(Data.CONTENT_URI).apply {
withValue(Data.RAW_CONTACT_ID, contact.id)
withValue(Data.MIMETYPE, CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
withValue(CommonDataKinds.Phone.NUMBER, it.value)
withValue(CommonDataKinds.Phone.NORMALIZED_NUMBER, it.normalizedNumber)
withValue(CommonDataKinds.Phone.TYPE, it.type)
withValue(CommonDataKinds.Phone.LABEL, it.label)
withValue(CommonDataKinds.Phone.IS_PRIMARY, it.isPrimary)
operations.add(build())
}
}
// delete emails
ContentProviderOperation.newDelete(Data.CONTENT_URI).apply {
val selection = "${Data.RAW_CONTACT_ID} = ? AND ${Data.MIMETYPE} = ? "
val selectionArgs = arrayOf(contact.id.toString(), CommonDataKinds.Email.CONTENT_ITEM_TYPE)
withSelection(selection, selectionArgs)
operations.add(build())
}
// add emails
contact.emails.forEach {
ContentProviderOperation.newInsert(Data.CONTENT_URI).apply {
withValue(Data.RAW_CONTACT_ID, contact.id)
withValue(Data.MIMETYPE, CommonDataKinds.Email.CONTENT_ITEM_TYPE)
withValue(CommonDataKinds.Email.DATA, it.value)
withValue(CommonDataKinds.Email.TYPE, it.type)
withValue(CommonDataKinds.Email.LABEL, it.label)
operations.add(build())
}
}
// delete addresses
ContentProviderOperation.newDelete(Data.CONTENT_URI).apply {
val selection = "${Data.RAW_CONTACT_ID} = ? AND ${Data.MIMETYPE} = ? "
val selectionArgs = arrayOf(contact.id.toString(), CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE)
withSelection(selection, selectionArgs)
operations.add(build())
}
// add addresses
contact.addresses.forEach {
ContentProviderOperation.newInsert(Data.CONTENT_URI).apply {
withValue(Data.RAW_CONTACT_ID, contact.id)
withValue(Data.MIMETYPE, CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE)
withValue(CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS, it.value)
withValue(CommonDataKinds.StructuredPostal.TYPE, it.type)
withValue(CommonDataKinds.StructuredPostal.LABEL, it.label)
operations.add(build())
}
}
// delete IMs
ContentProviderOperation.newDelete(Data.CONTENT_URI).apply {
val selection = "${Data.RAW_CONTACT_ID} = ? AND ${Data.MIMETYPE} = ? "
val selectionArgs = arrayOf(contact.id.toString(), CommonDataKinds.Im.CONTENT_ITEM_TYPE)
withSelection(selection, selectionArgs)
operations.add(build())
}
// add IMs
contact.IMs.forEach {
ContentProviderOperation.newInsert(Data.CONTENT_URI).apply {
withValue(Data.RAW_CONTACT_ID, contact.id)
withValue(Data.MIMETYPE, CommonDataKinds.Im.CONTENT_ITEM_TYPE)
withValue(CommonDataKinds.Im.DATA, it.value)
withValue(CommonDataKinds.Im.PROTOCOL, it.type)
withValue(CommonDataKinds.Im.CUSTOM_PROTOCOL, it.label)
operations.add(build())
}
}
// delete events
ContentProviderOperation.newDelete(Data.CONTENT_URI).apply {
val selection = "${Data.RAW_CONTACT_ID} = ? AND ${Data.MIMETYPE} = ? "
val selectionArgs = arrayOf(contact.id.toString(), CommonDataKinds.Event.CONTENT_ITEM_TYPE)
withSelection(selection, selectionArgs)
operations.add(build())
}
// add events
contact.events.forEach {
ContentProviderOperation.newInsert(Data.CONTENT_URI).apply {
withValue(Data.RAW_CONTACT_ID, contact.id)
withValue(Data.MIMETYPE, CommonDataKinds.Event.CONTENT_ITEM_TYPE)
withValue(CommonDataKinds.Event.START_DATE, it.value)
withValue(CommonDataKinds.Event.TYPE, it.type)
operations.add(build())
}
}
// delete notes
ContentProviderOperation.newDelete(Data.CONTENT_URI).apply {
val selection = "${Data.RAW_CONTACT_ID} = ? AND ${Data.MIMETYPE} = ? "
val selectionArgs = arrayOf(contact.id.toString(), CommonDataKinds.Note.CONTENT_ITEM_TYPE)
withSelection(selection, selectionArgs)
operations.add(build())
}
// add notes
ContentProviderOperation.newInsert(Data.CONTENT_URI).apply {
withValue(Data.RAW_CONTACT_ID, contact.id)
withValue(Data.MIMETYPE, CommonDataKinds.Note.CONTENT_ITEM_TYPE)
withValue(CommonDataKinds.Note.NOTE, contact.notes)
operations.add(build())
}
// delete organization
ContentProviderOperation.newDelete(Data.CONTENT_URI).apply {
val selection = "${Data.RAW_CONTACT_ID} = ? AND ${Data.MIMETYPE} = ? "
val selectionArgs = arrayOf(contact.id.toString(), CommonDataKinds.Organization.CONTENT_ITEM_TYPE)
withSelection(selection, selectionArgs)
operations.add(build())
}
// add organization
if (contact.organization.isNotEmpty()) {
ContentProviderOperation.newInsert(Data.CONTENT_URI).apply {
withValue(Data.RAW_CONTACT_ID, contact.id)
withValue(Data.MIMETYPE, CommonDataKinds.Organization.CONTENT_ITEM_TYPE)
withValue(CommonDataKinds.Organization.COMPANY, contact.organization.company)
withValue(CommonDataKinds.Organization.TYPE, DEFAULT_ORGANIZATION_TYPE)
withValue(CommonDataKinds.Organization.TITLE, contact.organization.jobPosition)
withValue(CommonDataKinds.Organization.TYPE, DEFAULT_ORGANIZATION_TYPE)
operations.add(build())
}
}
// delete websites
ContentProviderOperation.newDelete(Data.CONTENT_URI).apply {
val selection = "${Data.RAW_CONTACT_ID} = ? AND ${Data.MIMETYPE} = ? "
val selectionArgs = arrayOf(contact.id.toString(), CommonDataKinds.Website.CONTENT_ITEM_TYPE)
withSelection(selection, selectionArgs)
operations.add(build())
}
// add websites
contact.websites.forEach {
ContentProviderOperation.newInsert(Data.CONTENT_URI).apply {
withValue(Data.RAW_CONTACT_ID, contact.id)
withValue(Data.MIMETYPE, CommonDataKinds.Website.CONTENT_ITEM_TYPE)
withValue(CommonDataKinds.Website.URL, it)
withValue(CommonDataKinds.Website.TYPE, DEFAULT_WEBSITE_TYPE)
operations.add(build())
}
}
// delete groups
val relevantGroupIDs = getStoredGroupsSync().map { it.id }
if (relevantGroupIDs.isNotEmpty()) {
val IDsString = TextUtils.join(",", relevantGroupIDs)
ContentProviderOperation.newDelete(Data.CONTENT_URI).apply {
val selection = "${Data.CONTACT_ID} = ? AND ${Data.MIMETYPE} = ? AND ${Data.DATA1} IN ($IDsString)"
val selectionArgs = arrayOf(contact.contactId.toString(), CommonDataKinds.GroupMembership.CONTENT_ITEM_TYPE)
withSelection(selection, selectionArgs)
operations.add(build())
}
}
// add groups
contact.groups.forEach {
ContentProviderOperation.newInsert(Data.CONTENT_URI).apply {
withValue(Data.RAW_CONTACT_ID, contact.id)
withValue(Data.MIMETYPE, CommonDataKinds.GroupMembership.CONTENT_ITEM_TYPE)
withValue(CommonDataKinds.GroupMembership.GROUP_ROW_ID, it.id)
operations.add(build())
}
}
// favorite, ringtone
try {
val uri = Uri.withAppendedPath(Contacts.CONTENT_URI, contact.contactId.toString())
val contentValues = ContentValues(2)
contentValues.put(Contacts.STARRED, contact.starred)
contentValues.put(Contacts.CUSTOM_RINGTONE, contact.ringtone)
context.contentResolver.update(uri, contentValues, null, null)
} catch (e: Exception) {
context.showErrorToast(e)
}
// photo
when (photoUpdateStatus) {
PHOTO_ADDED, PHOTO_CHANGED -> addPhoto(contact, operations)
PHOTO_REMOVED -> removePhoto(contact, operations)
}
context.contentResolver.applyBatch(AUTHORITY, operations)
return true
} catch (e: Exception) {
context.showErrorToast(e)
return false
}
}
private fun addPhoto(contact: Contact, operations: ArrayList<ContentProviderOperation>): ArrayList<ContentProviderOperation> {
if (contact.photoUri.isNotEmpty()) {
val photoUri = Uri.parse(contact.photoUri)
val bitmap = MediaStore.Images.Media.getBitmap(context.contentResolver, photoUri)
val thumbnailSize = context.getPhotoThumbnailSize()
val scaledPhoto = Bitmap.createScaledBitmap(bitmap, thumbnailSize, thumbnailSize, false)
val scaledSizePhotoData = scaledPhoto.getByteArray()
scaledPhoto.recycle()
val fullSizePhotoData = bitmap.getByteArray()
bitmap.recycle()
ContentProviderOperation.newInsert(Data.CONTENT_URI).apply {
withValue(Data.RAW_CONTACT_ID, contact.id)
withValue(Data.MIMETYPE, CommonDataKinds.Photo.CONTENT_ITEM_TYPE)
withValue(CommonDataKinds.Photo.PHOTO, scaledSizePhotoData)
operations.add(build())
}
addFullSizePhoto(contact.id.toLong(), fullSizePhotoData)
}
return operations
}
private fun removePhoto(contact: Contact, operations: ArrayList<ContentProviderOperation>): ArrayList<ContentProviderOperation> {
ContentProviderOperation.newDelete(Data.CONTENT_URI).apply {
val selection = "${Data.RAW_CONTACT_ID} = ? AND ${Data.MIMETYPE} = ?"
val selectionArgs = arrayOf(contact.id.toString(), CommonDataKinds.Photo.CONTENT_ITEM_TYPE)
withSelection(selection, selectionArgs)
operations.add(build())
}
return operations
}
fun addContactsToGroup(contacts: ArrayList<Contact>, groupId: Long) {
try {
val operations = ArrayList<ContentProviderOperation>()
contacts.forEach {
ContentProviderOperation.newInsert(Data.CONTENT_URI).apply {
withValue(Data.RAW_CONTACT_ID, it.id)
withValue(Data.MIMETYPE, CommonDataKinds.GroupMembership.CONTENT_ITEM_TYPE)
withValue(CommonDataKinds.GroupMembership.GROUP_ROW_ID, groupId)
operations.add(build())
}
if (operations.size % BATCH_SIZE == 0) {
context.contentResolver.applyBatch(AUTHORITY, operations)
operations.clear()
}
}
context.contentResolver.applyBatch(AUTHORITY, operations)
} catch (e: Exception) {
context.showErrorToast(e)
}
}
fun removeContactsFromGroup(contacts: ArrayList<Contact>, groupId: Long) {
try {
val operations = ArrayList<ContentProviderOperation>()
contacts.forEach {
ContentProviderOperation.newDelete(Data.CONTENT_URI).apply {
val selection = "${Data.CONTACT_ID} = ? AND ${Data.MIMETYPE} = ? AND ${Data.DATA1} = ?"
val selectionArgs = arrayOf(it.contactId.toString(), CommonDataKinds.GroupMembership.CONTENT_ITEM_TYPE, groupId.toString())
withSelection(selection, selectionArgs)
operations.add(build())
}
if (operations.size % BATCH_SIZE == 0) {
context.contentResolver.applyBatch(AUTHORITY, operations)
operations.clear()
}
}
context.contentResolver.applyBatch(AUTHORITY, operations)
} catch (e: Exception) {
context.showErrorToast(e)
}
}
fun insertContact(contact: Contact): Boolean {
if (contact.isPrivate()) {
return LocalContactsHelper(context).insertOrUpdateContact(contact)
}
try {
val operations = ArrayList<ContentProviderOperation>()
ContentProviderOperation.newInsert(RawContacts.CONTENT_URI).apply {
withValue(RawContacts.ACCOUNT_NAME, contact.source)
withValue(RawContacts.ACCOUNT_TYPE, getContactSourceType(contact.source))
operations.add(build())
}
// names
ContentProviderOperation.newInsert(Data.CONTENT_URI).apply {
withValueBackReference(Data.RAW_CONTACT_ID, 0)
withValue(Data.MIMETYPE, CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
withValue(CommonDataKinds.StructuredName.PREFIX, contact.prefix)
withValue(CommonDataKinds.StructuredName.GIVEN_NAME, contact.firstName)
withValue(CommonDataKinds.StructuredName.MIDDLE_NAME, contact.middleName)
withValue(CommonDataKinds.StructuredName.FAMILY_NAME, contact.surname)
withValue(CommonDataKinds.StructuredName.SUFFIX, contact.suffix)
operations.add(build())
}
// nickname
ContentProviderOperation.newInsert(Data.CONTENT_URI).apply {
withValueBackReference(Data.RAW_CONTACT_ID, 0)
withValue(Data.MIMETYPE, CommonDataKinds.Nickname.CONTENT_ITEM_TYPE)
withValue(CommonDataKinds.Nickname.NAME, contact.nickname)
operations.add(build())
}
// phone numbers
contact.phoneNumbers.forEach {
ContentProviderOperation.newInsert(Data.CONTENT_URI).apply {
withValueBackReference(Data.RAW_CONTACT_ID, 0)
withValue(Data.MIMETYPE, CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
withValue(CommonDataKinds.Phone.NUMBER, it.value)
withValue(CommonDataKinds.Phone.NORMALIZED_NUMBER, it.normalizedNumber)
withValue(CommonDataKinds.Phone.TYPE, it.type)
withValue(CommonDataKinds.Phone.LABEL, it.label)
withValue(CommonDataKinds.Phone.IS_PRIMARY, it.isPrimary)
operations.add(build())
}
}
// emails
contact.emails.forEach {
ContentProviderOperation.newInsert(Data.CONTENT_URI).apply {
withValueBackReference(Data.RAW_CONTACT_ID, 0)
withValue(Data.MIMETYPE, CommonDataKinds.Email.CONTENT_ITEM_TYPE)
withValue(CommonDataKinds.Email.DATA, it.value)
withValue(CommonDataKinds.Email.TYPE, it.type)
withValue(CommonDataKinds.Email.LABEL, it.label)
operations.add(build())
}
}
// addresses
contact.addresses.forEach {
ContentProviderOperation.newInsert(Data.CONTENT_URI).apply {
withValueBackReference(Data.RAW_CONTACT_ID, 0)
withValue(Data.MIMETYPE, CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE)
withValue(CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS, it.value)
withValue(CommonDataKinds.StructuredPostal.TYPE, it.type)
withValue(CommonDataKinds.StructuredPostal.LABEL, it.label)
operations.add(build())
}
}
// IMs
contact.IMs.forEach {
ContentProviderOperation.newInsert(Data.CONTENT_URI).apply {
withValueBackReference(Data.RAW_CONTACT_ID, 0)
withValue(Data.MIMETYPE, CommonDataKinds.Im.CONTENT_ITEM_TYPE)
withValue(CommonDataKinds.Im.DATA, it.value)
withValue(CommonDataKinds.Im.PROTOCOL, it.type)
withValue(CommonDataKinds.Im.CUSTOM_PROTOCOL, it.label)
operations.add(build())
}
}
// events
contact.events.forEach {
ContentProviderOperation.newInsert(Data.CONTENT_URI).apply {
withValueBackReference(Data.RAW_CONTACT_ID, 0)
withValue(Data.MIMETYPE, CommonDataKinds.Event.CONTENT_ITEM_TYPE)
withValue(CommonDataKinds.Event.START_DATE, it.value)
withValue(CommonDataKinds.Event.TYPE, it.type)
operations.add(build())
}
}
// notes
ContentProviderOperation.newInsert(Data.CONTENT_URI).apply {
withValueBackReference(Data.RAW_CONTACT_ID, 0)
withValue(Data.MIMETYPE, CommonDataKinds.Note.CONTENT_ITEM_TYPE)
withValue(CommonDataKinds.Note.NOTE, contact.notes)
operations.add(build())
}
// organization
if (contact.organization.isNotEmpty()) {
ContentProviderOperation.newInsert(Data.CONTENT_URI).apply {
withValueBackReference(Data.RAW_CONTACT_ID, 0)
withValue(Data.MIMETYPE, CommonDataKinds.Organization.CONTENT_ITEM_TYPE)
withValue(CommonDataKinds.Organization.COMPANY, contact.organization.company)
withValue(CommonDataKinds.Organization.TYPE, DEFAULT_ORGANIZATION_TYPE)
withValue(CommonDataKinds.Organization.TITLE, contact.organization.jobPosition)
withValue(CommonDataKinds.Organization.TYPE, DEFAULT_ORGANIZATION_TYPE)
operations.add(build())
}
}
// websites
contact.websites.forEach {
ContentProviderOperation.newInsert(Data.CONTENT_URI).apply {
withValueBackReference(Data.RAW_CONTACT_ID, 0)
withValue(Data.MIMETYPE, CommonDataKinds.Website.CONTENT_ITEM_TYPE)
withValue(CommonDataKinds.Website.URL, it)
withValue(CommonDataKinds.Website.TYPE, DEFAULT_WEBSITE_TYPE)
operations.add(build())
}
}
// groups
contact.groups.forEach {
ContentProviderOperation.newInsert(Data.CONTENT_URI).apply {
withValueBackReference(Data.RAW_CONTACT_ID, 0)
withValue(Data.MIMETYPE, CommonDataKinds.GroupMembership.CONTENT_ITEM_TYPE)
withValue(CommonDataKinds.GroupMembership.GROUP_ROW_ID, it.id)
operations.add(build())
}
}
// photo (inspired by https://gist.github.com/slightfoot/5985900)
var fullSizePhotoData: ByteArray? = null
if (contact.photoUri.isNotEmpty()) {
val photoUri = Uri.parse(contact.photoUri)
fullSizePhotoData = context.contentResolver.openInputStream(photoUri)?.readBytes()
}
val results = context.contentResolver.applyBatch(AUTHORITY, operations)
// storing contacts on some devices seems to be messed up and they move on Phone instead, or disappear completely
// try storing a lighter contact version with this oldschool version too just so it wont disappear, future edits work well
if (getContactSourceType(contact.source).contains(".sim")) {
val simUri = Uri.parse("content://icc/adn")
ContentValues().apply {
put("number", contact.phoneNumbers.firstOrNull()?.value ?: "")
put("tag", contact.getNameToDisplay())
context.contentResolver.insert(simUri, this)
}
}
// fullsize photo
val rawId = ContentUris.parseId(results[0].uri!!)
if (contact.photoUri.isNotEmpty() && fullSizePhotoData != null) {
addFullSizePhoto(rawId, fullSizePhotoData)
}
// favorite, ringtone
val userId = getRealContactId(rawId)
if (userId != 0) {
val uri = Uri.withAppendedPath(Contacts.CONTENT_URI, userId.toString())
val contentValues = ContentValues(2)
contentValues.put(Contacts.STARRED, contact.starred)
contentValues.put(Contacts.CUSTOM_RINGTONE, contact.ringtone)
context.contentResolver.update(uri, contentValues, null, null)
}
return true
} catch (e: Exception) {
context.showErrorToast(e)
return false
}
}
private fun addFullSizePhoto(contactId: Long, fullSizePhotoData: ByteArray) {
val baseUri = ContentUris.withAppendedId(RawContacts.CONTENT_URI, contactId)
val displayPhotoUri = Uri.withAppendedPath(baseUri, RawContacts.DisplayPhoto.CONTENT_DIRECTORY)
val fileDescriptor = context.contentResolver.openAssetFileDescriptor(displayPhotoUri, "rw")
val photoStream = fileDescriptor!!.createOutputStream()
photoStream.write(fullSizePhotoData)
photoStream.close()
fileDescriptor.close()
}
fun getContactMimeTypeId(contactId: String, mimeType: String): String {
val uri = Data.CONTENT_URI
val projection = arrayOf(Data._ID, Data.RAW_CONTACT_ID, Data.MIMETYPE)
val selection = "${Data.MIMETYPE} = ? AND ${Data.RAW_CONTACT_ID} = ?"
val selectionArgs = arrayOf(mimeType, contactId)
val cursor = context.contentResolver.query(uri, projection, selection, selectionArgs, null)
cursor?.use {
if (cursor.moveToFirst()) {
return cursor.getStringValue(Data._ID)
}
}
return ""
}
fun addFavorites(contacts: ArrayList<Contact>) {
ensureBackgroundThread {
toggleLocalFavorites(contacts, true)
if (context.hasContactPermissions()) {
toggleFavorites(contacts, true)
}
}
}
fun removeFavorites(contacts: ArrayList<Contact>) {
ensureBackgroundThread {
toggleLocalFavorites(contacts, false)
if (context.hasContactPermissions()) {
toggleFavorites(contacts, false)
}
}
}
private fun toggleFavorites(contacts: ArrayList<Contact>, addToFavorites: Boolean) {
try {
val operations = ArrayList<ContentProviderOperation>()
contacts.filter { !it.isPrivate() }.map { it.contactId.toString() }.forEach {
val uri = Uri.withAppendedPath(Contacts.CONTENT_URI, it)
ContentProviderOperation.newUpdate(uri).apply {
withValue(Contacts.STARRED, if (addToFavorites) 1 else 0)
operations.add(build())
}
if (operations.size % BATCH_SIZE == 0) {
context.contentResolver.applyBatch(AUTHORITY, operations)
operations.clear()
}
}
context.contentResolver.applyBatch(AUTHORITY, operations)
} catch (e: Exception) {
context.showErrorToast(e)
}
}
private fun toggleLocalFavorites(contacts: ArrayList<Contact>, addToFavorites: Boolean) {
val localContacts = contacts.filter { it.isPrivate() }.map { it.id }.toTypedArray()
LocalContactsHelper(context).toggleFavorites(localContacts, addToFavorites)
}
fun updateRingtone(contactId: String, newUri: String) {
try {
val operations = ArrayList<ContentProviderOperation>()
val uri = Uri.withAppendedPath(Contacts.CONTENT_URI, contactId)
ContentProviderOperation.newUpdate(uri).apply {
withValue(Contacts.CUSTOM_RINGTONE, newUri)
operations.add(build())
}
context.contentResolver.applyBatch(AUTHORITY, operations)
} catch (e: Exception) {
context.showErrorToast(e)
}
}
fun deleteContact(originalContact: Contact, deleteClones: Boolean = false, callback: (success: Boolean) -> Unit) {
ensureBackgroundThread {
if (deleteClones) {
getDuplicatesOfContact(originalContact, true) { contacts ->
ensureBackgroundThread {
if (deleteContacts(contacts)) {
callback(true)
}
}
}
} else {
if (deleteContacts(arrayListOf(originalContact))) {
callback(true)
}
}
}
}
fun deleteContacts(contacts: ArrayList<Contact>): Boolean {
val localContacts = contacts.filter { it.isPrivate() }.map { it.id.toLong() }.toMutableList()
LocalContactsHelper(context).deleteContactIds(localContacts)
return try {
val operations = ArrayList<ContentProviderOperation>()
val selection = "${RawContacts._ID} = ?"
contacts.filter { !it.isPrivate() }.forEach {
ContentProviderOperation.newDelete(RawContacts.CONTENT_URI).apply {
val selectionArgs = arrayOf(it.id.toString())
withSelection(selection, selectionArgs)
operations.add(build())
}
if (operations.size % BATCH_SIZE == 0) {
context.contentResolver.applyBatch(AUTHORITY, operations)
operations.clear()
}
}
if (context.hasPermission(PERMISSION_WRITE_CONTACTS)) {
context.contentResolver.applyBatch(AUTHORITY, operations)
}
true
} catch (e: Exception) {
context.showErrorToast(e)
false
}
}
fun getDuplicatesOfContact(contact: Contact, addOriginal: Boolean, callback: (ArrayList<Contact>) -> Unit) {
ensureBackgroundThread {
getContacts(true, true) { contacts ->
val duplicates =
contacts.filter { it.id != contact.id && it.getHashToCompare() == contact.getHashToCompare() }.toMutableList() as ArrayList<Contact>
if (addOriginal) {
duplicates.add(contact)
}
callback(duplicates)
}
}
}
fun getContactsToExport(selectedContactSources: Set<String>, callback: (List<Contact>) -> Unit) {
getContacts(getAll = true) { receivedContacts ->
val contacts = receivedContacts.filter { it.source in selectedContactSources }
callback(contacts)
}
}
fun exportContacts(contacts: List<Contact>, outputStream: OutputStream): ExportResult {
return try {
val jsonString = Json.encodeToString(contacts)
outputStream.use {
it.write(jsonString.toByteArray())
}
ExportResult.EXPORT_OK
} catch (_: Error) {
ExportResult.EXPORT_FAIL
}
}
}
|
CT/commons/src/main/kotlin/com/simplemobiletools/commons/helpers/AlphanumericComparator.kt | 62872250 | package com.simplemobiletools.commons.helpers
// taken from https://gist.github.com/MichaelRocks/1b94bb44c7804e999dbf31dac86955ec
// make IMG_5.jpg come before IMG_10.jpg
class AlphanumericComparator {
fun compare(string1: String, string2: String): Int {
var thisMarker = 0
var thatMarker = 0
val s1Length = string1.length
val s2Length = string2.length
while (thisMarker < s1Length && thatMarker < s2Length) {
val thisChunk = getChunk(string1, s1Length, thisMarker)
thisMarker += thisChunk.length
val thatChunk = getChunk(string2, s2Length, thatMarker)
thatMarker += thatChunk.length
// If both chunks contain numeric characters, sort them numerically.
var result: Int
if (isDigit(thisChunk[0]) && isDigit(thatChunk[0])) {
// Simple chunk comparison by length.
val thisChunkLength = thisChunk.length
result = thisChunkLength - thatChunk.length
// If equal, the first different number counts.
if (result == 0) {
for (i in 0 until thisChunkLength) {
result = thisChunk[i] - thatChunk[i]
if (result != 0) {
return result
}
}
}
} else {
result = thisChunk.compareTo(thatChunk)
}
if (result != 0) {
return result
}
}
return s1Length - s2Length
}
private fun getChunk(string: String, length: Int, marker: Int): String {
var current = marker
val chunk = StringBuilder()
var c = string[current]
chunk.append(c)
current++
if (isDigit(c)) {
while (current < length) {
c = string[current]
if (!isDigit(c)) {
break
}
chunk.append(c)
current++
}
} else {
while (current < length) {
c = string[current]
if (isDigit(c)) {
break
}
chunk.append(c)
current++
}
}
return chunk.toString()
}
private fun isDigit(ch: Char) = ch in '0'..'9'
}
|
CT/commons/src/main/kotlin/com/simplemobiletools/commons/helpers/ExportResult.kt | 547305950 | package com.simplemobiletools.commons.helpers
enum class ExportResult {
EXPORT_FAIL, EXPORT_OK, EXPORT_PARTIAL
}
|
CT/commons/src/main/kotlin/com/simplemobiletools/commons/helpers/BlockedNumbersImporter.kt | 3939097844 | package com.simplemobiletools.commons.helpers
import android.app.Activity
import android.telephony.PhoneNumberUtils
import com.simplemobiletools.commons.extensions.addBlockedNumber
import com.simplemobiletools.commons.extensions.showErrorToast
import java.io.File
class BlockedNumbersImporter(
private val activity: Activity,
) {
enum class ImportResult {
IMPORT_FAIL, IMPORT_OK
}
fun importBlockedNumbers(path: String): ImportResult {
return try {
val inputStream = File(path).inputStream()
val numbers = inputStream.bufferedReader().use {
val content = it.readText().trimEnd().split(BLOCKED_NUMBERS_EXPORT_DELIMITER)
content.filter { text -> PhoneNumberUtils.isGlobalPhoneNumber(text) }
}
if (numbers.isNotEmpty()) {
numbers.forEach { number ->
activity.addBlockedNumber(number)
}
ImportResult.IMPORT_OK
} else {
ImportResult.IMPORT_FAIL
}
} catch (e: Exception) {
activity.showErrorToast(e)
ImportResult.IMPORT_FAIL
}
}
}
|
CT/commons/src/main/kotlin/com/simplemobiletools/commons/helpers/LocalContactsHelper.kt | 2833759484 | package com.simplemobiletools.commons.helpers
import android.content.Context
import android.graphics.BitmapFactory
import android.net.Uri
import android.provider.ContactsContract.CommonDataKinds.Event
import android.provider.MediaStore
import com.simplemobiletools.commons.extensions.contactsDB
import com.simplemobiletools.commons.extensions.getByteArray
import com.simplemobiletools.commons.extensions.getEmptyContact
import com.simplemobiletools.commons.models.SimpleContact
import com.simplemobiletools.commons.models.contacts.Contact
import com.simplemobiletools.commons.models.contacts.*
import com.simplemobiletools.commons.models.contacts.LocalContact
class LocalContactsHelper(val context: Context) {
fun getAllContacts(favoritesOnly: Boolean = false): ArrayList<Contact> {
val contacts = if (favoritesOnly) context.contactsDB.getFavoriteContacts() else context.contactsDB.getContacts()
val storedGroups = ContactsHelper(context).getStoredGroupsSync()
return (contacts.map { convertLocalContactToContact(it, storedGroups) }.toMutableList() as? ArrayList<Contact>) ?: arrayListOf()
}
fun getContactWithId(id: Int): Contact? {
val storedGroups = ContactsHelper(context).getStoredGroupsSync()
return convertLocalContactToContact(context.contactsDB.getContactWithId(id), storedGroups)
}
fun insertOrUpdateContact(contact: Contact): Boolean {
val localContact = convertContactToLocalContact(contact)
return context.contactsDB.insertOrUpdate(localContact) > 0
}
fun addContactsToGroup(contacts: ArrayList<Contact>, groupId: Long) {
contacts.forEach {
val localContact = convertContactToLocalContact(it)
val newGroups = localContact.groups
newGroups.add(groupId)
newGroups.distinct()
localContact.groups = newGroups
context.contactsDB.insertOrUpdate(localContact)
}
}
fun removeContactsFromGroup(contacts: ArrayList<Contact>, groupId: Long) {
contacts.forEach {
val localContact = convertContactToLocalContact(it)
val newGroups = localContact.groups
newGroups.remove(groupId)
localContact.groups = newGroups
context.contactsDB.insertOrUpdate(localContact)
}
}
fun deleteContactIds(ids: MutableList<Long>) {
ids.chunked(30).forEach {
context.contactsDB.deleteContactIds(it)
}
}
fun toggleFavorites(ids: Array<Int>, addToFavorites: Boolean) {
val isStarred = if (addToFavorites) 1 else 0
ids.forEach {
context.contactsDB.updateStarred(isStarred, it)
}
}
fun updateRingtone(id: Int, ringtone: String) {
context.contactsDB.updateRingtone(ringtone, id)
}
private fun getPhotoByteArray(uri: String): ByteArray {
if (uri.isEmpty()) {
return ByteArray(0)
}
val photoUri = Uri.parse(uri)
val bitmap = MediaStore.Images.Media.getBitmap(context.contentResolver, photoUri)
val fullSizePhotoData = bitmap.getByteArray()
bitmap.recycle()
return fullSizePhotoData
}
private fun convertLocalContactToContact(localContact: LocalContact?, storedGroups: ArrayList<Group>): Contact? {
if (localContact == null) {
return null
}
val contactPhoto = if (localContact.photo == null) {
null
} else {
try {
BitmapFactory.decodeByteArray(localContact.photo, 0, localContact.photo!!.size)
} catch (e: OutOfMemoryError) {
null
}
}
return context.getEmptyContact().apply {
id = localContact.id!!
prefix = localContact.prefix
firstName = localContact.firstName
middleName = localContact.middleName
surname = localContact.surname
suffix = localContact.suffix
nickname = localContact.nickname
phoneNumbers = localContact.phoneNumbers
emails = localContact.emails
addresses = localContact.addresses
events = localContact.events
source = SMT_PRIVATE
starred = localContact.starred
contactId = localContact.id!!
thumbnailUri = ""
photo = contactPhoto
photoUri = localContact.photoUri
notes = localContact.notes
groups = storedGroups.filter { localContact.groups.contains(it.id) } as ArrayList<Group>
organization = Organization(localContact.company, localContact.jobPosition)
websites = localContact.websites
IMs = localContact.IMs
ringtone = localContact.ringtone
}
}
private fun convertContactToLocalContact(contact: Contact): LocalContact {
val photoByteArray = if (contact.photoUri.isNotEmpty()) {
getPhotoByteArray(contact.photoUri)
} else {
contact.photo?.getByteArray()
}
return getEmptyLocalContact().apply {
id = if (contact.id <= FIRST_CONTACT_ID) null else contact.id
prefix = contact.prefix
firstName = contact.firstName
middleName = contact.middleName
surname = contact.surname
suffix = contact.suffix
nickname = contact.nickname
photo = photoByteArray
phoneNumbers = contact.phoneNumbers
emails = contact.emails
events = contact.events
starred = contact.starred
addresses = contact.addresses
notes = contact.notes
groups = contact.groups.map { it.id }.toMutableList() as ArrayList<Long>
company = contact.organization.company
jobPosition = contact.organization.jobPosition
websites = contact.websites
IMs = contact.IMs
ringtone = contact.ringtone
}
}
fun getPrivateSimpleContactsSync(favoritesOnly: Boolean, withPhoneNumbersOnly: Boolean) = getAllContacts(favoritesOnly).mapNotNull {
convertContactToSimpleContact(it, withPhoneNumbersOnly)
}
companion object{
fun convertContactToSimpleContact(contact: Contact?, withPhoneNumbersOnly: Boolean): SimpleContact?{
return if (contact == null || (withPhoneNumbersOnly && contact.phoneNumbers.isEmpty())) {
null
} else {
val birthdays = contact.events.filter { it.type == Event.TYPE_BIRTHDAY }.map { it.value }.toMutableList() as ArrayList<String>
val anniversaries = contact.events.filter { it.type == Event.TYPE_ANNIVERSARY }.map { it.value }.toMutableList() as ArrayList<String>
SimpleContact(contact.id, contact.id, contact.getNameToDisplay(), contact.photoUri, contact.phoneNumbers, birthdays, anniversaries)
}
}
}
}
|
CT/commons/src/main/kotlin/com/simplemobiletools/commons/helpers/ExternalStorageProviderHack.kt | 3375093559 | package com.simplemobiletools.commons.helpers
import android.database.Cursor
import android.database.MatrixCursor
import android.database.MergeCursor
import android.net.Uri
import android.provider.DocumentsContract
import com.simplemobiletools.commons.extensions.getStringValue
// On Android 11, ExternalStorageProvider no longer returns Android/data and Android/obb as children
// of the Android directory on primary storage. However, the two child directories are actually
// still accessible.
// Inspired by: https://github.com/zhanghai/MaterialFiles/blob/master/app/src/main/java/me/zhanghai/android/files/provider/document/resolver/ExternalStorageProviderPrimaryAndroidDataHack.kt
object ExternalStorageProviderHack {
private const val ANDROID_DATA_DISPLAY_NAME = "data"
private const val ANDROID_OBB_DISPLAY_NAME = "obb"
private val CHILD_DOCUMENTS_CURSOR_COLUMN_NAMES = arrayOf(
DocumentsContract.Document.COLUMN_DOCUMENT_ID,
DocumentsContract.Document.COLUMN_DISPLAY_NAME,
DocumentsContract.Document.COLUMN_MIME_TYPE,
DocumentsContract.Document.COLUMN_LAST_MODIFIED,
DocumentsContract.Document.COLUMN_SIZE,
)
private fun getAndroidDocumentId(rootDocId: String): String {
return "$rootDocId:Android"
}
private fun getAndroidDataDocumentId(rootDocId: String): String {
return "${getAndroidDocumentId(rootDocId)}/data"
}
private fun getAndroidObbDocumentId(rootDocId: String): String {
return "${getAndroidDocumentId(rootDocId)}/obb"
}
fun transformQueryResult(rootDocId: String, uri: Uri, cursor: Cursor): Cursor {
val documentId = DocumentsContract.getDocumentId(uri)
if (uri.authority == EXTERNAL_STORAGE_PROVIDER_AUTHORITY && documentId == getAndroidDocumentId(rootDocId)) {
var hasDataRow = false
var hasObbRow = false
try {
while (cursor.moveToNext()) {
when (cursor.getStringValue(DocumentsContract.Document.COLUMN_DOCUMENT_ID)) {
getAndroidDataDocumentId(rootDocId) ->
hasDataRow = true
getAndroidObbDocumentId(rootDocId) ->
hasObbRow = true
}
if (hasDataRow && hasObbRow) {
break
}
}
} finally {
cursor.moveToPosition(-1)
}
if (hasDataRow && hasObbRow) {
return cursor
}
val extraCursor = MatrixCursor(CHILD_DOCUMENTS_CURSOR_COLUMN_NAMES)
if (!hasDataRow) {
extraCursor.newRow()
.add(
DocumentsContract.Document.COLUMN_DOCUMENT_ID,
getAndroidDataDocumentId(rootDocId)
)
.add(
DocumentsContract.Document.COLUMN_DISPLAY_NAME,
ANDROID_DATA_DISPLAY_NAME
)
.add(
DocumentsContract.Document.COLUMN_MIME_TYPE,
DocumentsContract.Document.MIME_TYPE_DIR
)
.add(
DocumentsContract.Document.COLUMN_LAST_MODIFIED,
System.currentTimeMillis()
)
.add(
DocumentsContract.Document.COLUMN_SIZE,
0L
)
}
if (!hasObbRow) {
extraCursor.newRow()
.add(
DocumentsContract.Document.COLUMN_DOCUMENT_ID,
getAndroidObbDocumentId(rootDocId)
)
.add(
DocumentsContract.Document.COLUMN_DISPLAY_NAME,
ANDROID_OBB_DISPLAY_NAME
)
.add(
DocumentsContract.Document.COLUMN_MIME_TYPE,
DocumentsContract.Document.MIME_TYPE_DIR
)
.add(
DocumentsContract.Document.COLUMN_LAST_MODIFIED,
System.currentTimeMillis()
)
.add(
DocumentsContract.Document.COLUMN_SIZE,
0L
)
}
return MergeCursor(arrayOf(cursor, extraCursor))
}
return cursor
}
}
|
CT/commons/src/main/kotlin/com/simplemobiletools/commons/helpers/Constants.kt | 59083090 | package com.simplemobiletools.commons.helpers
import android.content.Context
import android.graphics.drawable.Drawable
import android.os.Build
import android.os.Looper
import android.provider.ContactsContract
import android.util.Log
import androidx.annotation.ChecksSdkIntAtLeast
import androidx.annotation.StringRes
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.extensions.normalizeString
import com.simplemobiletools.commons.models.contacts.LocalContact
import com.simplemobiletools.commons.overloads.times
const val EXTERNAL_STORAGE_PROVIDER_AUTHORITY = "com.android.externalstorage.documents"
const val EXTRA_SHOW_ADVANCED = "android.content.extra.SHOW_ADVANCED"
const val APP_NAME = "app_name"
const val APP_LICENSES = "app_licenses"
const val APP_FAQ = "app_faq"
const val APP_VERSION_NAME = "app_version_name"
const val APP_ICON_IDS = "app_icon_ids"
const val APP_ID = "app_id"
const val APP_LAUNCHER_NAME = "app_launcher_name"
const val REAL_FILE_PATH = "real_file_path_2"
const val IS_FROM_GALLERY = "is_from_gallery"
const val BROADCAST_REFRESH_MEDIA = "com.simplemobiletools.REFRESH_MEDIA"
const val REFRESH_PATH = "refresh_path"
const val IS_CUSTOMIZING_COLORS = "is_customizing_colors"
const val BLOCKED_NUMBERS_EXPORT_DELIMITER = ","
const val BLOCKED_NUMBERS_EXPORT_EXTENSION = ".txt"
const val NOMEDIA = ".nomedia"
const val YOUR_ALARM_SOUNDS_MIN_ID = 1000
const val SHOW_FAQ_BEFORE_MAIL = "show_faq_before_mail"
const val CHOPPED_LIST_DEFAULT_SIZE = 50
const val SAVE_DISCARD_PROMPT_INTERVAL = 1000L
const val SD_OTG_PATTERN = "^/storage/[A-Za-z0-9]{4}-[A-Za-z0-9]{4}$"
const val SD_OTG_SHORT = "^[A-Za-z0-9]{4}-[A-Za-z0-9]{4}$"
const val KEY_PHONE = "phone"
const val KEY_MAILTO = "mailto"
const val CONTACT_ID = "contact_id"
const val IS_PRIVATE = "is_private"
const val SMT_PRIVATE = "smt_private" // used at the contact source of local contacts hidden from other apps
const val FIRST_GROUP_ID = 10000L
const val MD5 = "MD5"
const val SHORT_ANIMATION_DURATION = 150L
val DARK_GREY = 0xFF333333.toInt()
const val LOWER_ALPHA = 0.25f
const val MEDIUM_ALPHA = 0.5f
const val HIGHER_ALPHA = 0.75f
// alpha values on a scale 0 - 255
const val LOWER_ALPHA_INT = 30
const val MEDIUM_ALPHA_INT = 90
const val HOUR_MINUTES = 60
const val DAY_MINUTES = 24 * HOUR_MINUTES
const val WEEK_MINUTES = DAY_MINUTES * 7
const val MONTH_MINUTES = DAY_MINUTES * 30
const val YEAR_MINUTES = DAY_MINUTES * 365
const val MINUTE_SECONDS = 60
const val HOUR_SECONDS = HOUR_MINUTES * 60
const val DAY_SECONDS = DAY_MINUTES * 60
const val WEEK_SECONDS = WEEK_MINUTES * 60
const val MONTH_SECONDS = MONTH_MINUTES * 60
const val YEAR_SECONDS = YEAR_MINUTES * 60
// shared preferences
const val PREFS_KEY = "Prefs"
const val APP_RUN_COUNT = "app_run_count"
const val LAST_VERSION = "last_version"
const val SD_TREE_URI = "tree_uri_2"
const val PRIMARY_ANDROID_DATA_TREE_URI = "primary_android_data_tree_uri_2"
const val OTG_ANDROID_DATA_TREE_URI = "otg_android_data_tree__uri_2"
const val SD_ANDROID_DATA_TREE_URI = "sd_android_data_tree_uri_2"
const val PRIMARY_ANDROID_OBB_TREE_URI = "primary_android_obb_tree_uri_2"
const val OTG_ANDROID_OBB_TREE_URI = "otg_android_obb_tree_uri_2"
const val SD_ANDROID_OBB_TREE_URI = "sd_android_obb_tree_uri_2"
const val OTG_TREE_URI = "otg_tree_uri_2"
const val SD_CARD_PATH = "sd_card_path_2"
const val OTG_REAL_PATH = "otg_real_path_2"
const val INTERNAL_STORAGE_PATH = "internal_storage_path"
const val TEXT_COLOR = "text_color"
const val BACKGROUND_COLOR = "background_color"
const val PRIMARY_COLOR = "primary_color_2"
const val ACCENT_COLOR = "accent_color"
const val APP_ICON_COLOR = "app_icon_color"
const val LAST_HANDLED_SHORTCUT_COLOR = "last_handled_shortcut_color"
const val LAST_ICON_COLOR = "last_icon_color"
const val CUSTOM_TEXT_COLOR = "custom_text_color"
const val CUSTOM_BACKGROUND_COLOR = "custom_background_color"
const val CUSTOM_PRIMARY_COLOR = "custom_primary_color"
const val CUSTOM_ACCENT_COLOR = "custom_accent_color"
const val CUSTOM_APP_ICON_COLOR = "custom_app_icon_color"
const val WIDGET_BG_COLOR = "widget_bg_color"
const val WIDGET_TEXT_COLOR = "widget_text_color"
const val PASSWORD_PROTECTION = "password_protection"
const val PASSWORD_HASH = "password_hash"
const val PROTECTION_TYPE = "protection_type"
const val APP_PASSWORD_PROTECTION = "app_password_protection"
const val APP_PASSWORD_HASH = "app_password_hash"
const val APP_PROTECTION_TYPE = "app_protection_type"
const val DELETE_PASSWORD_PROTECTION = "delete_password_protection"
const val DELETE_PASSWORD_HASH = "delete_password_hash"
const val DELETE_PROTECTION_TYPE = "delete_protection_type"
const val PROTECTED_FOLDER_PATH = "protected_folder_path_"
const val PROTECTED_FOLDER_HASH = "protected_folder_hash_"
const val PROTECTED_FOLDER_TYPE = "protected_folder_type_"
const val KEEP_LAST_MODIFIED = "keep_last_modified"
const val USE_ENGLISH = "use_english"
const val WAS_USE_ENGLISH_TOGGLED = "was_use_english_toggled"
const val WAS_SHARED_THEME_EVER_ACTIVATED = "was_shared_theme_ever_activated"
const val IS_USING_SHARED_THEME = "is_using_shared_theme"
const val IS_USING_AUTO_THEME = "is_using_auto_theme"
const val IS_USING_SYSTEM_THEME = "is_using_system_theme"
const val SHOULD_USE_SHARED_THEME = "should_use_shared_theme"
const val WAS_SHARED_THEME_FORCED = "was_shared_theme_forced"
const val WAS_CUSTOM_THEME_SWITCH_DESCRIPTION_SHOWN = "was_custom_theme_switch_description_shown"
const val SHOW_INFO_BUBBLE = "show_info_bubble"
const val LAST_CONFLICT_RESOLUTION = "last_conflict_resolution"
const val LAST_CONFLICT_APPLY_TO_ALL = "last_conflict_apply_to_all"
const val LAST_COPY_PATH = "last_copy_path"
const val HAD_THANK_YOU_INSTALLED = "had_thank_you_installed"
const val SKIP_DELETE_CONFIRMATION = "skip_delete_confirmation"
const val ENABLE_PULL_TO_REFRESH = "enable_pull_to_refresh"
const val SCROLL_HORIZONTALLY = "scroll_horizontally"
const val PREVENT_PHONE_FROM_SLEEPING = "prevent_phone_from_sleeping"
const val LAST_USED_VIEW_PAGER_PAGE = "last_used_view_pager_page"
const val USE_24_HOUR_FORMAT = "use_24_hour_format"
const val SUNDAY_FIRST = "sunday_first"
const val WAS_ALARM_WARNING_SHOWN = "was_alarm_warning_shown"
const val WAS_REMINDER_WARNING_SHOWN = "was_reminder_warning_shown"
const val USE_SAME_SNOOZE = "use_same_snooze"
const val SNOOZE_TIME = "snooze_delay"
const val VIBRATE_ON_BUTTON_PRESS = "vibrate_on_button_press"
const val YOUR_ALARM_SOUNDS = "your_alarm_sounds"
const val SILENT = "silent"
const val OTG_PARTITION = "otg_partition_2"
const val IS_USING_MODIFIED_APP_ICON = "is_using_modified_app_icon"
const val INITIAL_WIDGET_HEIGHT = "initial_widget_height"
const val WIDGET_ID_TO_MEASURE = "widget_id_to_measure"
const val WAS_ORANGE_ICON_CHECKED = "was_orange_icon_checked"
const val WAS_APP_ON_SD_SHOWN = "was_app_on_sd_shown"
const val WAS_BEFORE_ASKING_SHOWN = "was_before_asking_shown"
const val WAS_BEFORE_RATE_SHOWN = "was_before_rate_shown"
const val WAS_INITIAL_UPGRADE_TO_PRO_SHOWN = "was_initial_upgrade_to_pro_shown"
const val WAS_APP_ICON_CUSTOMIZATION_WARNING_SHOWN = "was_app_icon_customization_warning_shown"
const val APP_SIDELOADING_STATUS = "app_sideloading_status"
const val DATE_FORMAT = "date_format"
const val WAS_OTG_HANDLED = "was_otg_handled_2"
const val WAS_UPGRADED_FROM_FREE_SHOWN = "was_upgraded_from_free_shown"
const val WAS_RATE_US_PROMPT_SHOWN = "was_rate_us_prompt_shown"
const val WAS_APP_RATED = "was_app_rated"
const val WAS_SORTING_BY_NUMERIC_VALUE_ADDED = "was_sorting_by_numeric_value_added"
const val WAS_FOLDER_LOCKING_NOTICE_SHOWN = "was_folder_locking_notice_shown"
const val LAST_RENAME_USED = "last_rename_used"
const val LAST_RENAME_PATTERN_USED = "last_rename_pattern_used"
const val LAST_EXPORTED_SETTINGS_FOLDER = "last_exported_settings_folder"
const val LAST_EXPORTED_SETTINGS_FILE = "last_exported_settings_file"
const val LAST_BLOCKED_NUMBERS_EXPORT_PATH = "last_blocked_numbers_export_path"
const val BLOCK_UNKNOWN_NUMBERS = "block_unknown_numbers"
const val BLOCK_HIDDEN_NUMBERS = "block_hidden_numbers"
const val FONT_SIZE = "font_size"
const val WAS_MESSENGER_RECORDER_SHOWN = "was_messenger_recorder_shown"
const val DEFAULT_TAB = "default_tab"
const val START_NAME_WITH_SURNAME = "start_name_with_surname"
const val FAVORITES = "favorites"
const val SHOW_CALL_CONFIRMATION = "show_call_confirmation"
const val COLOR_PICKER_RECENT_COLORS = "color_picker_recent_colors"
const val SHOW_CONTACT_THUMBNAILS = "show_contact_thumbnails"
const val SHOW_PHONE_NUMBERS = "show_phone_numbers"
const val SHOW_ONLY_CONTACTS_WITH_NUMBERS = "show_only_contacts_with_numbers"
const val IGNORED_CONTACT_SOURCES = "ignored_contact_sources_2"
const val LAST_USED_CONTACT_SOURCE = "last_used_contact_source"
const val ON_CONTACT_CLICK = "on_contact_click"
const val SHOW_CONTACT_FIELDS = "show_contact_fields"
const val SHOW_TABS = "show_tabs"
const val SHOW_DIALPAD_BUTTON = "show_dialpad_button"
const val SPEED_DIAL = "speed_dial"
const val LAST_EXPORT_PATH = "last_export_path"
const val WAS_LOCAL_ACCOUNT_INITIALIZED = "was_local_account_initialized"
const val SHOW_PRIVATE_CONTACTS = "show_private_contacts"
const val MERGE_DUPLICATE_CONTACTS = "merge_duplicate_contacts"
const val FAVORITES_CONTACTS_ORDER = "favorites_contacts_order"
const val FAVORITES_CUSTOM_ORDER_SELECTED = "favorites_custom_order_selected"
const val VIEW_TYPE = "view_type"
const val CONTACTS_GRID_COLUMN_COUNT = "contacts_grid_column_count"
const val AUTO_BACKUP = "auto_backup"
const val AUTO_BACKUP_FOLDER = "auto_backup_folder"
const val AUTO_BACKUP_FILENAME = "auto_backup_filename"
const val LAST_AUTO_BACKUP_TIME = "last_auto_backup_time"
const val PASSWORD_RETRY_COUNT = "password_retry_count"
const val PASSWORD_COUNTDOWN_START_MS = "password_count_down_start_ms"
const val MAX_PASSWORD_RETRY_COUNT = 3
const val DEFAULT_PASSWORD_COUNTDOWN = 5
const val MINIMUM_PIN_LENGTH = 4
// contact grid view constants
const val CONTACTS_GRID_MAX_COLUMNS_COUNT = 10
// phone number/email types
const val CELL = "CELL"
const val WORK = "WORK"
const val HOME = "HOME"
const val OTHER = "OTHER"
const val PREF = "PREF"
const val MAIN = "MAIN"
const val FAX = "FAX"
const val WORK_FAX = "WORK;FAX"
const val HOME_FAX = "HOME;FAX"
const val PAGER = "PAGER"
const val MOBILE = "MOBILE"
// IMs not supported by Ez-vcard
const val HANGOUTS = "Hangouts"
const val QQ = "QQ"
const val JABBER = "Jabber"
// licenses
internal const val LICENSE_KOTLIN = 1L
const val LICENSE_SUBSAMPLING = 2L
const val LICENSE_GLIDE = 4L
const val LICENSE_CROPPER = 8L
const val LICENSE_FILTERS = 16L
const val LICENSE_RTL = 32L
const val LICENSE_JODA = 64L
const val LICENSE_STETHO = 128L
const val LICENSE_OTTO = 256L
const val LICENSE_PHOTOVIEW = 512L
const val LICENSE_PICASSO = 1024L
const val LICENSE_PATTERN = 2048L
const val LICENSE_REPRINT = 4096L
const val LICENSE_GIF_DRAWABLE = 8192L
const val LICENSE_AUTOFITTEXTVIEW = 16384L
const val LICENSE_ROBOLECTRIC = 32768L
const val LICENSE_ESPRESSO = 65536L
const val LICENSE_GSON = 131072L
const val LICENSE_LEAK_CANARY = 262144L
const val LICENSE_NUMBER_PICKER = 524288L
const val LICENSE_EXOPLAYER = 1048576L
const val LICENSE_PANORAMA_VIEW = 2097152L
const val LICENSE_SANSELAN = 4194304L
const val LICENSE_GESTURE_VIEWS = 8388608L
const val LICENSE_INDICATOR_FAST_SCROLL = 16777216L
const val LICENSE_EVENT_BUS = 33554432L
const val LICENSE_AUDIO_RECORD_VIEW = 67108864L
const val LICENSE_SMS_MMS = 134217728L
const val LICENSE_APNG = 268435456L
const val LICENSE_PDF_VIEW_PAGER = 536870912L
const val LICENSE_M3U_PARSER = 1073741824L
const val LICENSE_ANDROID_LAME = 2147483648L
const val LICENSE_PDF_VIEWER = 4294967296L
const val LICENSE_ZIP4J = 8589934592L
// global intents
const val OPEN_DOCUMENT_TREE_FOR_ANDROID_DATA_OR_OBB = 1000
const val OPEN_DOCUMENT_TREE_OTG = 1001
const val OPEN_DOCUMENT_TREE_SD = 1002
const val OPEN_DOCUMENT_TREE_FOR_SDK_30 = 1003
const val REQUEST_SET_AS = 1004
const val REQUEST_EDIT_IMAGE = 1005
const val SELECT_EXPORT_SETTINGS_FILE_INTENT = 1006
const val REQUEST_CODE_SET_DEFAULT_DIALER = 1007
const val CREATE_DOCUMENT_SDK_30 = 1008
const val REQUEST_CODE_SET_DEFAULT_CALLER_ID = 1010
// sorting
const val SORT_ORDER = "sort_order"
const val SORT_FOLDER_PREFIX = "sort_folder_" // storing folder specific values at using "Use for this folder only"
const val SORT_BY_NAME = 1
const val SORT_BY_DATE_MODIFIED = 2
const val SORT_BY_SIZE = 4
const val SORT_BY_DATE_TAKEN = 8
const val SORT_BY_EXTENSION = 16
const val SORT_BY_PATH = 32
const val SORT_BY_NUMBER = 64
const val SORT_BY_FIRST_NAME = 128
const val SORT_BY_MIDDLE_NAME = 256
const val SORT_BY_SURNAME = 512
const val SORT_DESCENDING = 1024
const val SORT_BY_TITLE = 2048
const val SORT_BY_ARTIST = 4096
const val SORT_BY_DURATION = 8192
const val SORT_BY_RANDOM = 16384
const val SORT_USE_NUMERIC_VALUE = 32768
const val SORT_BY_FULL_NAME = 65536
const val SORT_BY_CUSTOM = 131072
const val SORT_BY_DATE_CREATED = 262144
// security
const val WAS_PROTECTION_HANDLED = "was_protection_handled"
const val PROTECTION_NONE = -1
const val PROTECTION_PATTERN = 0
const val PROTECTION_PIN = 1
const val PROTECTION_FINGERPRINT = 2
// renaming
const val RENAME_SIMPLE = 0
const val RENAME_PATTERN = 1
const val SHOW_ALL_TABS = -1
const val SHOW_PATTERN = 0
const val SHOW_PIN = 1
const val SHOW_FINGERPRINT = 2
// permissions
const val PERMISSION_READ_STORAGE = 1
const val PERMISSION_WRITE_STORAGE = 2
const val PERMISSION_CAMERA = 3
const val PERMISSION_RECORD_AUDIO = 4
const val PERMISSION_READ_CONTACTS = 5
const val PERMISSION_WRITE_CONTACTS = 6
const val PERMISSION_READ_CALENDAR = 7
const val PERMISSION_WRITE_CALENDAR = 8
const val PERMISSION_CALL_PHONE = 9
const val PERMISSION_READ_CALL_LOG = 10
const val PERMISSION_WRITE_CALL_LOG = 11
const val PERMISSION_GET_ACCOUNTS = 12
const val PERMISSION_READ_SMS = 13
const val PERMISSION_SEND_SMS = 14
const val PERMISSION_READ_PHONE_STATE = 15
const val PERMISSION_MEDIA_LOCATION = 16
const val PERMISSION_POST_NOTIFICATIONS = 17
const val PERMISSION_READ_MEDIA_IMAGES = 18
const val PERMISSION_READ_MEDIA_VIDEO = 19
const val PERMISSION_READ_MEDIA_AUDIO = 20
const val PERMISSION_ACCESS_COARSE_LOCATION = 21
const val PERMISSION_ACCESS_FINE_LOCATION = 22
const val PERMISSION_READ_MEDIA_VISUAL_USER_SELECTED = 23
const val PERMISSION_READ_SYNC_SETTINGS = 24
// conflict resolving
const val CONFLICT_SKIP = 1
const val CONFLICT_OVERWRITE = 2
const val CONFLICT_MERGE = 3
const val CONFLICT_KEEP_BOTH = 4
// font sizes
const val FONT_SIZE_SMALL = 0
const val FONT_SIZE_MEDIUM = 1
const val FONT_SIZE_LARGE = 2
const val FONT_SIZE_EXTRA_LARGE = 3
const val MONDAY_BIT = 1
const val TUESDAY_BIT = 2
const val WEDNESDAY_BIT = 4
const val THURSDAY_BIT = 8
const val FRIDAY_BIT = 16
const val SATURDAY_BIT = 32
const val SUNDAY_BIT = 64
const val EVERY_DAY_BIT = MONDAY_BIT or TUESDAY_BIT or WEDNESDAY_BIT or THURSDAY_BIT or FRIDAY_BIT or SATURDAY_BIT or SUNDAY_BIT
const val WEEK_DAYS_BIT = MONDAY_BIT or TUESDAY_BIT or WEDNESDAY_BIT or THURSDAY_BIT or FRIDAY_BIT
const val WEEKENDS_BIT = SATURDAY_BIT or SUNDAY_BIT
const val SIDELOADING_UNCHECKED = 0
const val SIDELOADING_TRUE = 1
const val SIDELOADING_FALSE = 2
// default tabs
const val TAB_LAST_USED = 0
const val TAB_CONTACTS = 1
const val TAB_FAVORITES = 2
const val TAB_CALL_HISTORY = 4
const val TAB_GROUPS = 8
const val TAB_FILES = 16
const val TAB_RECENT_FILES = 32
const val TAB_STORAGE_ANALYSIS = 64
val photoExtensions: Array<String> get() = arrayOf(".jpg", ".png", ".jpeg", ".bmp", ".webp", ".heic", ".heif", ".apng", ".avif")
val videoExtensions: Array<String> get() = arrayOf(".mp4", ".mkv", ".webm", ".avi", ".3gp", ".mov", ".m4v", ".3gpp")
val audioExtensions: Array<String> get() = arrayOf(".mp3", ".wav", ".wma", ".ogg", ".m4a", ".opus", ".flac", ".aac", ".m4b")
val rawExtensions: Array<String> get() = arrayOf(".dng", ".orf", ".nef", ".arw", ".rw2", ".cr2", ".cr3")
val extensionsSupportingEXIF: Array<String> get() = arrayOf(".jpg", ".jpeg", ".png", ".webp", ".dng")
const val DATE_FORMAT_ONE = "dd.MM.yyyy"
const val DATE_FORMAT_TWO = "dd/MM/yyyy"
const val DATE_FORMAT_THREE = "MM/dd/yyyy"
const val DATE_FORMAT_FOUR = "yyyy-MM-dd"
const val DATE_FORMAT_FIVE = "d MMMM yyyy"
const val DATE_FORMAT_SIX = "MMMM d yyyy"
const val DATE_FORMAT_SEVEN = "MM-dd-yyyy"
const val DATE_FORMAT_EIGHT = "dd-MM-yyyy"
const val DATE_FORMAT_NINE = "yyyyMMdd"
const val DATE_FORMAT_TEN = "yyyy.MM.dd"
const val DATE_FORMAT_ELEVEN = "yy-MM-dd"
const val DATE_FORMAT_TWELVE = "yyMMdd"
const val DATE_FORMAT_THIRTEEN = "yy.MM.dd"
const val DATE_FORMAT_FOURTEEN = "yy/MM/dd"
const val TIME_FORMAT_12 = "hh:mm a"
const val TIME_FORMAT_24 = "HH:mm"
// possible icons at the top left corner
enum class NavigationIcon(@StringRes val accessibilityResId: Int) {
Cross(R.string.close),
Arrow(R.string.back),
None(0)
}
val appIconColorStrings = arrayListOf(
".Red",
".Pink",
".Purple",
".Deep_purple",
".Indigo",
".Blue",
".Light_blue",
".Cyan",
".Teal",
".Green",
".Light_green",
".Lime",
".Yellow",
".Amber",
".Orange",
".Deep_orange",
".Brown",
".Blue_grey",
".Grey_black"
)
// most app icon colors from md_app_icon_colors with reduced alpha
// used at showing contact placeholders without image
val letterBackgroundColors = arrayListOf(
0xCCD32F2F,
0xCCC2185B,
0xCC1976D2,
0xCC0288D1,
0xCC0097A7,
0xCC00796B,
0xCC388E3C,
0xCC689F38,
0xCCF57C00,
0xCCE64A19
)
// view types
const val VIEW_TYPE_GRID = 1
const val VIEW_TYPE_LIST = 2
const val VIEW_TYPE_UNEVEN_GRID = 3
fun isOnMainThread() = Looper.myLooper() == Looper.getMainLooper()
fun ensureBackgroundThread(callback: () -> Unit) {
if (isOnMainThread()) {
Thread {
callback()
}.start()
} else {
callback()
}
}
@ChecksSdkIntAtLeast(api = Build.VERSION_CODES.N)
fun isNougatPlus() = Build.VERSION.SDK_INT >= Build.VERSION_CODES.N
@ChecksSdkIntAtLeast(api = Build.VERSION_CODES.N_MR1)
fun isNougatMR1Plus() = Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1
@ChecksSdkIntAtLeast(api = Build.VERSION_CODES.O)
fun isOreoPlus() = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
@ChecksSdkIntAtLeast(api = Build.VERSION_CODES.O_MR1)
fun isOreoMr1Plus() = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1
@ChecksSdkIntAtLeast(api = Build.VERSION_CODES.P)
fun isPiePlus() = Build.VERSION.SDK_INT >= Build.VERSION_CODES.P
@ChecksSdkIntAtLeast(api = Build.VERSION_CODES.Q)
fun isQPlus() = Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q
@ChecksSdkIntAtLeast(api = Build.VERSION_CODES.R)
fun isRPlus() = Build.VERSION.SDK_INT >= Build.VERSION_CODES.R
@ChecksSdkIntAtLeast(api = Build.VERSION_CODES.S)
fun isSPlus() = Build.VERSION.SDK_INT >= Build.VERSION_CODES.S
@ChecksSdkIntAtLeast(api = Build.VERSION_CODES.TIRAMISU)
fun isTiramisuPlus() = Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU
@ChecksSdkIntAtLeast(api = Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
fun isUpsideDownCakePlus() = Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE
fun getDateFormats() = arrayListOf(
"--MM-dd",
"yyyy-MM-dd",
"yyyyMMdd",
"yyyy.MM.dd",
"yy-MM-dd",
"yyMMdd",
"yy.MM.dd",
"yy/MM/dd",
"MM-dd",
"MMdd",
"MM/dd",
"MM.dd"
)
fun getDateFormatsWithYear() = arrayListOf(
DATE_FORMAT_FOUR,
DATE_FORMAT_NINE,
DATE_FORMAT_TEN,
DATE_FORMAT_ELEVEN,
DATE_FORMAT_TWELVE,
DATE_FORMAT_THIRTEEN,
DATE_FORMAT_FOURTEEN,
)
val normalizeRegex = "\\p{InCombiningDiacriticalMarks}+".toRegex()
fun getConflictResolution(resolutions: LinkedHashMap<String, Int>, path: String): Int {
return if (resolutions.size == 1 && resolutions.containsKey("")) {
resolutions[""]!!
} else if (resolutions.containsKey(path)) {
resolutions[path]!!
} else {
CONFLICT_SKIP
}
}
val proPackages = arrayListOf("draw", "gallery", "filemanager", "contacts", "notes", "calendar")
fun mydebug(message: String) = Log.e("DEBUG", message)
fun getQuestionMarks(size: Int) = ("?," * size).trimEnd(',')
fun getFilePlaceholderDrawables(context: Context): HashMap<String, Drawable> {
val fileDrawables = HashMap<String, Drawable>()
hashMapOf<String, Int>().apply {
put("aep", R.drawable.ic_file_aep)
put("ai", R.drawable.ic_file_ai)
put("avi", R.drawable.ic_file_avi)
put("css", R.drawable.ic_file_css)
put("csv", R.drawable.ic_file_csv)
put("dbf", R.drawable.ic_file_dbf)
put("doc", R.drawable.ic_file_doc)
put("docx", R.drawable.ic_file_doc)
put("dwg", R.drawable.ic_file_dwg)
put("exe", R.drawable.ic_file_exe)
put("fla", R.drawable.ic_file_fla)
put("flv", R.drawable.ic_file_flv)
put("htm", R.drawable.ic_file_html)
put("html", R.drawable.ic_file_html)
put("ics", R.drawable.ic_file_ics)
put("indd", R.drawable.ic_file_indd)
put("iso", R.drawable.ic_file_iso)
put("jpg", R.drawable.ic_file_jpg)
put("jpeg", R.drawable.ic_file_jpg)
put("js", R.drawable.ic_file_js)
put("json", R.drawable.ic_file_json)
put("m4a", R.drawable.ic_file_m4a)
put("mp3", R.drawable.ic_file_mp3)
put("mp4", R.drawable.ic_file_mp4)
put("ogg", R.drawable.ic_file_ogg)
put("pdf", R.drawable.ic_file_pdf)
put("plproj", R.drawable.ic_file_plproj)
put("ppt", R.drawable.ic_file_ppt)
put("pptx", R.drawable.ic_file_ppt)
put("prproj", R.drawable.ic_file_prproj)
put("psd", R.drawable.ic_file_psd)
put("rtf", R.drawable.ic_file_rtf)
put("sesx", R.drawable.ic_file_sesx)
put("sql", R.drawable.ic_file_sql)
put("svg", R.drawable.ic_file_svg)
put("txt", R.drawable.ic_file_txt)
put("vcf", R.drawable.ic_file_vcf)
put("wav", R.drawable.ic_file_wav)
put("wmv", R.drawable.ic_file_wmv)
put("xls", R.drawable.ic_file_xls)
put("xlsx", R.drawable.ic_file_xls)
put("xml", R.drawable.ic_file_xml)
put("zip", R.drawable.ic_file_zip)
}.forEach { (key, value) ->
fileDrawables[key] = context.resources.getDrawable(value)
}
return fileDrawables
}
const val FIRST_CONTACT_ID = 1000000
const val DEFAULT_FILE_NAME = "contacts.vcf"
// visible fields filtering
const val SHOW_PREFIX_FIELD = 1
const val SHOW_FIRST_NAME_FIELD = 2
const val SHOW_MIDDLE_NAME_FIELD = 4
const val SHOW_SURNAME_FIELD = 8
const val SHOW_SUFFIX_FIELD = 16
const val SHOW_PHONE_NUMBERS_FIELD = 32
const val SHOW_EMAILS_FIELD = 64
const val SHOW_ADDRESSES_FIELD = 128
const val SHOW_EVENTS_FIELD = 256
const val SHOW_NOTES_FIELD = 512
const val SHOW_ORGANIZATION_FIELD = 1024
const val SHOW_GROUPS_FIELD = 2048
const val SHOW_CONTACT_SOURCE_FIELD = 4096
const val SHOW_WEBSITES_FIELD = 8192
const val SHOW_NICKNAME_FIELD = 16384
const val SHOW_IMS_FIELD = 32768
const val SHOW_RINGTONE_FIELD = 65536
const val DEFAULT_EMAIL_TYPE = ContactsContract.CommonDataKinds.Email.TYPE_HOME
const val DEFAULT_PHONE_NUMBER_TYPE = ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE
const val DEFAULT_ADDRESS_TYPE = ContactsContract.CommonDataKinds.StructuredPostal.TYPE_HOME
const val DEFAULT_EVENT_TYPE = ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY
const val DEFAULT_ORGANIZATION_TYPE = ContactsContract.CommonDataKinds.Organization.TYPE_WORK
const val DEFAULT_WEBSITE_TYPE = ContactsContract.CommonDataKinds.Website.TYPE_HOMEPAGE
const val DEFAULT_IM_TYPE = ContactsContract.CommonDataKinds.Im.PROTOCOL_SKYPE
const val DEFAULT_MIMETYPE = ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE
// contact photo changes
const val PHOTO_ADDED = 1
const val PHOTO_REMOVED = 2
const val PHOTO_CHANGED = 3
const val PHOTO_UNCHANGED = 4
const val ON_CLICK_CALL_CONTACT = 1
const val ON_CLICK_VIEW_CONTACT = 2
const val ON_CLICK_EDIT_CONTACT = 3
// apps with special handling
const val TELEGRAM_PACKAGE = "org.telegram.messenger"
const val SIGNAL_PACKAGE = "org.thoughtcrime.securesms"
const val WHATSAPP_PACKAGE = "com.whatsapp"
const val VIBER_PACKAGE = "com.viber.voip"
const val THREEMA_PACKAGE = "ch.threema.app"
const val SOCIAL_VOICE_CALL = 0
const val SOCIAL_VIDEO_CALL = 1
const val SOCIAL_MESSAGE = 2
fun getEmptyLocalContact() = LocalContact(
0,
"",
"",
"",
"",
"",
"",
null,
"",
ArrayList(),
ArrayList(),
ArrayList(),
0,
ArrayList(),
"",
ArrayList(),
"",
"",
ArrayList(),
ArrayList(),
null
)
fun getProperText(text: String, shouldNormalize: Boolean) = if (shouldNormalize) text.normalizeString() else text
|
CT/commons/src/main/kotlin/com/simplemobiletools/commons/interfaces/SecurityTab.kt | 1633737762 | package com.simplemobiletools.commons.interfaces
import androidx.biometric.auth.AuthPromptHost
import com.simplemobiletools.commons.views.MyScrollView
interface SecurityTab {
fun initTab(
requiredHash: String,
listener: HashListener,
scrollView: MyScrollView,
biometricPromptHost: AuthPromptHost,
showBiometricAuthentication: Boolean
)
fun visibilityChanged(isVisible: Boolean)
}
|
CT/commons/src/main/kotlin/com/simplemobiletools/commons/interfaces/ItemMoveCallback.kt | 2578461425 | package com.simplemobiletools.commons.interfaces
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.RecyclerView
import com.simplemobiletools.commons.adapters.MyRecyclerViewAdapter
open class ItemMoveCallback(private val mAdapter: ItemTouchHelperContract, private val allowHorizontalDrag: Boolean = false) : ItemTouchHelper.Callback() {
override fun isLongPressDragEnabled() = false
override fun isItemViewSwipeEnabled() = false
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, i: Int) {}
override fun getMovementFlags(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder): Int {
var dragFlags = ItemTouchHelper.UP or ItemTouchHelper.DOWN
if (allowHorizontalDrag) {
dragFlags = dragFlags or ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT
}
return makeMovementFlags(dragFlags, 0)
}
override fun onMove(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder): Boolean {
mAdapter.onRowMoved(viewHolder.adapterPosition, target.adapterPosition)
return true
}
override fun onSelectedChanged(viewHolder: RecyclerView.ViewHolder?, actionState: Int) {
if (actionState != ItemTouchHelper.ACTION_STATE_IDLE) {
if (viewHolder is MyRecyclerViewAdapter.ViewHolder) {
mAdapter.onRowSelected(viewHolder)
}
}
super.onSelectedChanged(viewHolder, actionState)
}
override fun clearView(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder) {
super.clearView(recyclerView, viewHolder)
if (viewHolder is MyRecyclerViewAdapter.ViewHolder) {
mAdapter.onRowClear(viewHolder)
}
}
}
|
CT/commons/src/main/kotlin/com/simplemobiletools/commons/interfaces/ItemTouchHelperContract.kt | 3721496169 | package com.simplemobiletools.commons.interfaces
import com.simplemobiletools.commons.adapters.MyRecyclerViewAdapter
interface ItemTouchHelperContract {
fun onRowMoved(fromPosition: Int, toPosition: Int)
fun onRowSelected(myViewHolder: MyRecyclerViewAdapter.ViewHolder?)
fun onRowClear(myViewHolder: MyRecyclerViewAdapter.ViewHolder?)
}
|
CT/commons/src/main/kotlin/com/simplemobiletools/commons/interfaces/ContactsDao.kt | 3305964679 | package com.simplemobiletools.commons.interfaces
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import com.simplemobiletools.commons.models.contacts.LocalContact
@Dao
interface ContactsDao {
@Query("SELECT * FROM contacts")
fun getContacts(): List<LocalContact>
@Query("SELECT * FROM contacts WHERE starred = 1")
fun getFavoriteContacts(): List<LocalContact>
@Query("SELECT * FROM contacts WHERE id = :id")
fun getContactWithId(id: Int): LocalContact?
@Query("SELECT * FROM contacts WHERE phone_numbers LIKE :number")
fun getContactWithNumber(number: String): LocalContact?
@Query("UPDATE contacts SET starred = :isStarred WHERE id = :id")
fun updateStarred(isStarred: Int, id: Int)
@Query("UPDATE contacts SET ringtone = :ringtone WHERE id = :id")
fun updateRingtone(ringtone: String, id: Int)
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertOrUpdate(contact: LocalContact): Long
@Query("DELETE FROM contacts WHERE id = :id")
fun deleteContactId(id: Int)
@Query("DELETE FROM contacts WHERE id IN (:ids)")
fun deleteContactIds(ids: List<Long>)
}
|
CT/commons/src/main/kotlin/com/simplemobiletools/commons/interfaces/GroupsDao.kt | 1698260027 | package com.simplemobiletools.commons.interfaces
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import com.simplemobiletools.commons.models.contacts.Group
@Dao
interface GroupsDao {
@Query("SELECT * FROM groups")
fun getGroups(): List<Group>
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertOrUpdate(group: Group): Long
@Query("DELETE FROM groups WHERE id = :id")
fun deleteGroupId(id: Long)
}
|
CT/commons/src/main/kotlin/com/simplemobiletools/commons/interfaces/MyActionModeCallback.kt | 4085280082 | package com.simplemobiletools.commons.interfaces
import android.view.ActionMode
abstract class MyActionModeCallback : ActionMode.Callback {
var isSelectable = false
}
|
CT/commons/src/main/kotlin/com/simplemobiletools/commons/interfaces/RenameTab.kt | 1441124640 | package com.simplemobiletools.commons.interfaces
import com.simplemobiletools.commons.activities.BaseSimpleActivity
interface RenameTab {
fun initTab(activity: BaseSimpleActivity, paths: ArrayList<String>)
fun dialogConfirmed(useMediaFileExtension: Boolean, callback: (success: Boolean) -> Unit)
}
|
CT/commons/src/main/kotlin/com/simplemobiletools/commons/interfaces/BaseSecurityTab.kt | 3817595374 | package com.simplemobiletools.commons.interfaces
import android.content.Context
import android.os.Handler
import android.os.Looper
import android.util.AttributeSet
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.annotation.ColorInt
import androidx.core.os.postDelayed
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.extensions.baseConfig
import com.simplemobiletools.commons.extensions.countdown
import com.simplemobiletools.commons.extensions.getProperTextColor
import com.simplemobiletools.commons.helpers.DEFAULT_PASSWORD_COUNTDOWN
import com.simplemobiletools.commons.helpers.MAX_PASSWORD_RETRY_COUNT
abstract class BaseSecurityTab(context: Context, attrs: AttributeSet) : RelativeLayout(context, attrs), SecurityTab {
abstract val protectionType: Int
abstract val defaultTextRes: Int
abstract val wrongTextRes: Int
abstract val titleTextView: TextView
lateinit var computedHash: String
lateinit var requiredHash: String
lateinit var hashListener: HashListener
private val config = context.baseConfig
private val handler = Handler(Looper.getMainLooper())
open fun onLockedOutChange(lockedOut: Boolean) {}
fun isLockedOut() = requiredHash.isNotEmpty() && getCountdown() > 0
fun onCorrectPassword() {
resetCountdown()
handler.postDelayed(delayInMillis = 300) {
hashListener.receivedHash(computedHash, protectionType)
}
}
fun onIncorrectPassword() {
config.passwordRetryCount += 1
if (requiredHash.isNotEmpty() && shouldStartCountdown()) {
onLockedOutChange(lockedOut = true)
startCountdown()
} else {
updateTitle(context.getString(wrongTextRes), context.getColor(R.color.md_red))
handler.postDelayed(delayInMillis = 1000) {
updateTitle(context.getString(defaultTextRes), context.getProperTextColor())
}
}
}
fun maybeShowCountdown() {
if (shouldStartCountdown()) {
startCountdown()
} else {
updateCountdownText(0)
}
}
private fun shouldStartCountdown() = config.passwordRetryCount >= MAX_PASSWORD_RETRY_COUNT
private fun resetCountdown() {
config.passwordRetryCount = 0
config.passwordCountdownStartMs = 0
}
private fun getCountdown(): Int {
val retryCount = config.passwordRetryCount
if (retryCount >= MAX_PASSWORD_RETRY_COUNT) {
val currentTimeMs = System.currentTimeMillis()
val countdownStartMs = config.passwordCountdownStartMs
if (countdownStartMs == 0L) {
config.passwordCountdownStartMs = currentTimeMs
return DEFAULT_PASSWORD_COUNTDOWN
}
val countdownWaitMs = DEFAULT_PASSWORD_COUNTDOWN * 1000L
val elapsedMs = currentTimeMs - countdownStartMs
return if (elapsedMs < countdownWaitMs) {
val remainingMs = countdownWaitMs - elapsedMs
val remainingSeconds = remainingMs / 1000L
remainingSeconds.toInt()
} else {
0
}
}
return 0
}
private fun startCountdown() {
getCountdown().countdown(intervalMillis = 1000L) { count ->
updateCountdownText(count)
if (count == 0) {
resetCountdown()
onLockedOutChange(lockedOut = false)
}
}
}
private fun updateCountdownText(count: Int) {
removeCallbacks()
if (count > 0) {
updateTitle(context.getString(R.string.too_many_incorrect_attempts, count), context.getColor(R.color.md_red))
} else {
updateTitle(context.getString(defaultTextRes), context.getProperTextColor())
}
}
private fun removeCallbacks() = handler.removeCallbacksAndMessages(null)
private fun updateTitle(text: String, @ColorInt color: Int) {
titleTextView.text = text
titleTextView.setTextColor(color)
}
override fun visibilityChanged(isVisible: Boolean) {}
}
|
CT/commons/src/main/kotlin/com/simplemobiletools/commons/interfaces/LineColorPickerListener.kt | 383153319 | package com.simplemobiletools.commons.interfaces
fun interface LineColorPickerListener {
fun colorChanged(index: Int, color: Int)
}
|
CT/commons/src/main/kotlin/com/simplemobiletools/commons/interfaces/RecyclerScrollCallback.kt | 2896236529 | package com.simplemobiletools.commons.interfaces
interface RecyclerScrollCallback {
fun onScrolled(scrollY: Int)
}
|
CT/commons/src/main/kotlin/com/simplemobiletools/commons/interfaces/HashListener.kt | 2459153698 | package com.simplemobiletools.commons.interfaces
interface HashListener {
fun receivedHash(hash: String, type: Int)
}
|
CT/commons/src/main/kotlin/com/simplemobiletools/commons/interfaces/RefreshRecyclerViewListener.kt | 3068105451 | package com.simplemobiletools.commons.interfaces
interface RefreshRecyclerViewListener {
fun refreshItems()
}
|
CT/commons/src/main/kotlin/com/simplemobiletools/commons/interfaces/StartReorderDragListener.kt | 706306918 | package com.simplemobiletools.commons.interfaces
import androidx.recyclerview.widget.RecyclerView
interface StartReorderDragListener {
fun requestDrag(viewHolder: RecyclerView.ViewHolder)
}
|
CT/commons/src/main/kotlin/com/simplemobiletools/commons/interfaces/CopyMoveListener.kt | 4023623062 | package com.simplemobiletools.commons.interfaces
interface CopyMoveListener {
fun copySucceeded(copyOnly: Boolean, copiedAll: Boolean, destinationPath: String, wasCopyingOneFileOnly: Boolean)
fun copyFailed()
}
|
TaskProximityKotlin/app/src/androidTest/java/com/example/taskproximity/ExampleInstrumentedTest.kt | 931554655 | package com.example.taskproximity
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.taskproximity", appContext.packageName)
}
} |
TaskProximityKotlin/app/src/test/java/com/example/taskproximity/ExampleUnitTest.kt | 3631725841 | package com.example.taskproximity
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
} |
TaskProximityKotlin/app/src/main/java/com/example/taskproximity/locationTrack.kt | 808132045 | package com.example.taskproximity
import android.Manifest
import android.app.Service
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Bundle
import android.os.IBinder
import androidx.core.app.ActivityCompat
import androidx.localbroadcastmanager.content.LocalBroadcastManager
class locationTrack : Service() {
private lateinit var locationManager: LocationManager
private lateinit var locationListener: LocationListener
override fun onCreate() {
super.onCreate()
// Initialize LocationManager and LocationListener
locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
locationListener = object : LocationListener {
override fun onLocationChanged(location: Location) {
// Broadcast the updated location to the activity
val intent = Intent("location_updated")
intent.putExtra("latitude", location.latitude)
intent.putExtra("longitude", location.longitude)
LocalBroadcastManager.getInstance(applicationContext).sendBroadcast(intent)
}
override fun onStatusChanged(provider: String?, status: Int, extras: Bundle?) {}
override fun onProviderEnabled(provider: String) {}
override fun onProviderDisabled(provider: String) {}
}
// Request location updates
if (ActivityCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_FINE_LOCATION
) == PackageManager.PERMISSION_GRANTED
) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
1000, // Update interval in milliseconds (1 second)
0f, // Minimum distance between updates in meters
locationListener
)
}
}
override fun onBind(intent: Intent): IBinder? {
return null
}
override fun onDestroy() {
super.onDestroy()
// Remove location updates when the service is destroyed
locationManager.removeUpdates(locationListener)
}
} |
TaskProximityKotlin/app/src/main/java/com/example/taskproximity/editTask.kt | 1764598929 | package com.example.taskproximity
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.LinearLayout
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.google.firebase.firestore.FirebaseFirestore
class editTask : AppCompatActivity() {
private lateinit var editTaskLayout: LinearLayout
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_edit_task)
editTaskLayout = findViewById(R.id.editTaskLayout)
// Retrieve data from Firestore and populate the LinearLayout with buttons for each document
val db = FirebaseFirestore.getInstance()
val collectionRef = db.collection("tasks")
collectionRef.get()
.addOnSuccessListener { documents ->
for (document in documents) {
val description = document.getString("description")
val latitude = document.getDouble("latitude")
val longitude = document.getDouble("longitude")
val status = document.getString("status")
val taskId = document.id // Use document ID instead of getString("taskId")
// Create a new button for each document and set the field values
val editTaskButton = Button(this)
editTaskButton.text = "Description: $description\n" +
"Latitude: $latitude\n" +
"Longitude: $longitude\n" +
"Status: $status\n" +
"Task ID: $taskId\n"
// Set button layout parameters
val layoutParams = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT
)
layoutParams.setMargins(0, 0, 0, 16) // Optional: Add some margin between each button
editTaskButton.layoutParams = layoutParams
// Add a click listener to the button
editTaskButton.setOnClickListener {
val intent = Intent(this, TaskEditDescActivity::class.java)
intent.putExtra("taskId", taskId)
intent.putExtra("description", description)
intent.putExtra("latitude", latitude)
intent.putExtra("longitude", longitude)
intent.putExtra("status", status)
startActivity(intent)
}
// Add the new button to the tasksLayout LinearLayout
editTaskLayout.addView(editTaskButton)
}
}
.addOnFailureListener { exception ->
// Handle any errors
Toast.makeText(this, "Error: ${exception.message}", Toast.LENGTH_SHORT).show()
}
}
} |
TaskProximityKotlin/app/src/main/java/com/example/taskproximity/MainActivity.kt | 4265089429 | package com.example.taskproximity
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val button1 = findViewById<Button>(R.id.loginButton)
val button2 = findViewById<Button>(R.id.signupButton)
button1.setOnClickListener{
val intent = Intent(this, Login::class.java)
startActivity(intent)
}
button2.setOnClickListener{
val intent2 = Intent(this, SignUp::class.java)
startActivity(intent2)
}
}
} |
TaskProximityKotlin/app/src/main/java/com/example/taskproximity/adminAddTask.kt | 2157834771 | package com.example.taskproximity
import android.Manifest
import android.annotation.SuppressLint
import android.content.pm.PackageManager
import android.location.Location
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.google.android.gms.location.FusedLocationProviderClient
import com.google.android.gms.location.LocationServices
import com.google.firebase.firestore.FirebaseFirestore
class adminAddTask : AppCompatActivity() {
private lateinit var tvLatitude: TextView
private lateinit var tvLongitude: TextView
private lateinit var etDescription: EditText
private lateinit var btnLocation: Button
private lateinit var fusedLocationClient: FusedLocationProviderClient
private var latitudeString: String = ""
private var longitudeString: String = ""
private var statusString: String = "active"
private var descriptionString: String = ""
private var taskId: String = ""
private val firestore: FirebaseFirestore = FirebaseFirestore.getInstance()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_admin_add_task)
tvLatitude = findViewById(R.id.tv_latitude)
tvLongitude = findViewById(R.id.tv_longitude)
etDescription = findViewById(R.id.etDescription)
btnLocation = findViewById(R.id.btn_location)
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
btnLocation.setOnClickListener {
checkLocationPermission()
saveDescription()
generateRandomTaskId()
//createTask()
}
}
private fun checkLocationPermission() {
if (ContextCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_FINE_LOCATION
) != PackageManager.PERMISSION_GRANTED
) {
ActivityCompat.requestPermissions(
this,
arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION
)
} else {
getLastKnownLocation()
}
}
@SuppressLint("MissingPermission")
private fun getLastKnownLocation() {
fusedLocationClient.lastLocation
.addOnSuccessListener { location: Location? ->
location?.let {
val latitude = location.latitude
val longitude = location.longitude
latitudeString = latitude.toString()
longitudeString = longitude.toString()
tvLatitude.text = latitudeString
tvLongitude.text = longitudeString
createTask(latitude, longitude)
}
}
}
private fun saveDescription() {
descriptionString = etDescription.text.toString()
}
private fun generateRandomTaskId() {
val charPool: List<Char> = ('a'..'z') + ('A'..'Z') + ('0'..'9')
taskId = (1..10)
.map { kotlin.random.Random.nextInt(0, charPool.size) }
.map(charPool::get)
.joinToString("")
println("Random Task ID: $taskId")
}
private fun createTask(latitude: Double, longitude: Double) {
val task = Task(taskId, latitude, longitude, statusString, descriptionString)
saveTaskToFirestore(task)
}
private fun saveTaskToFirestore(task: Task) {
firestore.collection("tasks")
.add(task)
.addOnSuccessListener { documentReference ->
// Task saved successfully
Toast.makeText(this, "Task added successfully", Toast.LENGTH_SHORT).show()
finish()
}
.addOnFailureListener { e ->
// Error occurred while saving the task
Toast.makeText(this, "Error adding task: $e", Toast.LENGTH_SHORT).show()
}
}
companion object {
private const val PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 100
}
}
data class Task(
val taskId: String,
val latitude: Double,
val longitude: Double,
val status: String,
val description: String
) |
TaskProximityKotlin/app/src/main/java/com/example/taskproximity/Login.kt | 938089063 | package com.example.taskproximity
import android.Manifest
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import com.example.taskproximity.AdminHome
import com.example.taskproximity.R
import com.google.firebase.auth.FirebaseAuth
class Login : AppCompatActivity() {
private lateinit var emailEditText: EditText
private lateinit var passwordEditText: EditText
private lateinit var firebaseAuth: FirebaseAuth
private val notificationChannelId = "LOGIN_CHANNEL"
private val notificationId = 1
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
emailEditText = findViewById(R.id.username)
passwordEditText = findViewById(R.id.password)
firebaseAuth = FirebaseAuth.getInstance()
val loginUser = findViewById<Button>(R.id.loginUser)
val loginAdmin = findViewById<Button>(R.id.loginAdmin)
loginUser.setOnClickListener {
val email = emailEditText.text.toString()
val password = passwordEditText.text.toString()
login(email, password)
}
loginAdmin.setOnClickListener {
val email = emailEditText.text.toString()
val password = passwordEditText.text.toString()
loginAsAdmin(email, password)
}
}
private fun login(email: String, password: String) {
firebaseAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
Toast.makeText(this, "Login successful!", Toast.LENGTH_SHORT).show()
val intent = Intent(this, userHome::class.java)
startActivity(intent)
finish()
} else {
Toast.makeText(this, "Login failed! Please try again.", Toast.LENGTH_SHORT).show()
}
}
}
private fun loginAsAdmin(email: String, password: String) {
if (!email.contains("admin")) {
showLoginNotification()
return
}
firebaseAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
Toast.makeText(this, "Login successful!", Toast.LENGTH_SHORT).show()
val intent = Intent(this, AdminHome::class.java)
startActivity(intent)
finish()
} else {
Toast.makeText(this, "Login failed! Please try again.", Toast.LENGTH_SHORT).show()
}
}
}
private fun showLoginNotification() {
createNotificationChannel()
val builder = NotificationCompat.Builder(this, notificationChannelId)
.setSmallIcon(android.R.drawable.ic_dialog_info)
.setContentTitle("Login Failed")
.setContentText("Users can't log in as admin")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setAutoCancel(true)
val notificationManager = NotificationManagerCompat.from(this)
if (ActivityCompat.checkSelfPermission(
this,
Manifest.permission.POST_NOTIFICATIONS
) != PackageManager.PERMISSION_GRANTED
) {
ActivityCompat.requestPermissions(
this,
arrayOf(Manifest.permission.POST_NOTIFICATIONS),
0
)
} else {
notificationManager.notify(notificationId, builder.build())
}
}
private fun createNotificationChannel() {
// Create the NotificationChannel on devices running Android 8.0 and higher
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
val name = "Login Channel"
val descriptionText = "Channel for login notifications"
val importance = NotificationManager.IMPORTANCE_DEFAULT
val channel = NotificationChannel(notificationChannelId, name, importance).apply {
description = descriptionText
}
// Register the channel with the system
val notificationManager = getSystemService(NotificationManager::class.java)
notificationManager.createNotificationChannel(channel)
}
}
}
|
TaskProximityKotlin/app/src/main/java/com/example/taskproximity/LocationTracker.kt | 3061937971 | package com.example.taskproximity
import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Build
import android.os.Bundle
import androidx.annotation.NonNull
import androidx.annotation.RequiresPermission
class LocationTracker constructor(
val minTimeBetweenUpdates: Long = 5000.toLong(),
val minDistanceBetweenUpdates: Float = 10f,
val shouldUseGPS: Boolean = true,
val shouldUseNetwork: Boolean = true,
val shouldUsePassive: Boolean = true
) {
// Android LocationManager
private lateinit var locationManager: LocationManager
// Last known location
private var lastKnownLocation: Location? = null
// Custom Listener for the LocationManager
private val listener = object : LocationListener {
override fun onLocationChanged(p0: Location) {
Location(p0).let { currentLocation ->
lastKnownLocation = currentLocation
hasLocationFound = true
listeners.forEach { l -> l.onLocationFound(currentLocation) }
}
}
override fun onProviderDisabled(provider: String) {
behaviorListener.forEach { l -> l.onProviderDisabled(provider) }
}
override fun onProviderEnabled(provider: String) {
behaviorListener.forEach { l -> l.onProviderEnabled(provider) }
}
override fun onStatusChanged(provider: String, status: Int, extras: Bundle) {
behaviorListener.forEach { l -> l.onStatusChanged(provider, status, extras) }
}
}
// List used to register the listeners to notify
private val listeners: MutableSet<Listener> = mutableSetOf()
// List used to register the behavior listeners to notify
private val behaviorListener: MutableSet<BehaviorListener> = mutableSetOf()
var isListening = false
private set
var hasLocationFound = false
private set
fun addListener(listener: Listener): Boolean = listeners.add(listener)
fun removeListener(listener: Listener): Boolean = listeners.remove(listener)
fun addBehaviorListener(listener: BehaviorListener): Boolean = behaviorListener.add(listener)
fun removeBehaviorListener(listener: BehaviorListener): Boolean = behaviorListener.remove(listener)
@RequiresPermission(anyOf = [Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION])
fun startListening(context: Context) {
initManagerAndUpdateLastKnownLocation(context)
if (!isListening) {
// Listen for GPS Updates
if (shouldUseGPS) {
registerForLocationUpdates(LocationManager.GPS_PROVIDER)
}
// Listen for Network Updates
if (shouldUseNetwork) {
registerForLocationUpdates(LocationManager.NETWORK_PROVIDER)
}
// Listen for Passive Updates
if (shouldUseNetwork) {
registerForLocationUpdates(LocationManager.PASSIVE_PROVIDER)
}
isListening = true
}
}
fun stopListening(clearListeners: Boolean = false) {
if (isListening) {
locationManager.removeUpdates(listener)
isListening = false
if (clearListeners) {
listeners.clear()
}
}
}
@RequiresPermission(anyOf = [Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION])
fun quickFix(@NonNull context: Context) {
initManagerAndUpdateLastKnownLocation(context)
lastKnownLocation?.let { lastLocation ->
listeners.forEach { l -> l.onLocationFound(lastLocation) }
}
}
@SuppressLint("MissingPermission")
private fun initManagerAndUpdateLastKnownLocation(context: Context) {
// Init the manager
locationManager = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
context.getSystemService(LocationManager::class.java)
} else {
context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
}
// Update the lastKnownLocation
if (lastKnownLocation == null && shouldUseGPS) {
lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER)
}
if (lastKnownLocation == null && shouldUseNetwork) {
lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER)
}
if (lastKnownLocation == null && shouldUsePassive) {
lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER)
}
}
@SuppressLint("MissingPermission")
private fun registerForLocationUpdates(provider: String) {
if (locationManager.isProviderEnabled(provider)) {
locationManager.requestLocationUpdates(provider, minTimeBetweenUpdates, minDistanceBetweenUpdates, listener)
} else {
//nothing
}
}
interface Listener {
fun onLocationFound(location: Location)
//nothing fun onProviderError(providerError: ProviderError)
}
interface BehaviorListener {
fun onProviderDisabled(provider: String)
fun onProviderEnabled(provider: String)
fun onStatusChanged(provider: String, status: Int, extras: Bundle)
}
}
|
TaskProximityKotlin/app/src/main/java/com/example/taskproximity/SignUp.kt | 2831234755 | package com.example.taskproximity
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.example.taskproximity.R
import com.example.taskproximity.databinding.ActivitySignUpBinding
import com.google.firebase.FirebaseApp
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
import com.google.firebase.firestore.FirebaseFirestore
class SignUp : AppCompatActivity() {
private lateinit var firebaseAuth: FirebaseAuth
private lateinit var binding: ActivitySignUpBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivitySignUpBinding.inflate(layoutInflater)
setContentView(binding.root)
firebaseAuth = FirebaseAuth.getInstance()
val db = FirebaseFirestore.getInstance()
val usersCollection = db.collection("users")
fun signup(email: String, password: String) {
firebaseAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
val user: FirebaseUser? = firebaseAuth.currentUser
Toast.makeText(this, "Signup successful!", Toast.LENGTH_SHORT).show()
// Proceed to the next activity or perform other actions
} else {
Toast.makeText(this, "Signup failed! Please try again.", Toast.LENGTH_SHORT).show()
}
}
}
binding.button.setOnClickListener {
val username = binding.username.text.toString()
val password = binding.password.text.toString()
if (username.isNotEmpty() && password.isNotEmpty()) {
val user = hashMapOf(
"email" to username,
"password" to password
)
usersCollection.add(user)
.addOnSuccessListener {
// User data added successfully
val intent = Intent(this, Login::class.java)
startActivity(intent)
}
.addOnFailureListener { e ->
// Error adding user data
Toast.makeText(this, "Error: ${e.message}", Toast.LENGTH_SHORT).show()
}
firebaseAuth.createUserWithEmailAndPassword(username, password)
.addOnCompleteListener {
if (it.isSuccessful) {
val intent = Intent(this, Login::class.java)
startActivity(intent)
} else {
Toast.makeText(this, it.exception.toString(), Toast.LENGTH_SHORT).show()
}
}
} else {
Toast.makeText(this, "Empty Fields are not allowed", Toast.LENGTH_SHORT).show()
}
}
//button2
binding.button2.setOnClickListener {
val username = binding.username.text.toString()
val password = binding.password.text.toString()
if (username.isNotEmpty() && password.isNotEmpty()) {
val user = hashMapOf(
"email" to username,
"password" to password
)
usersCollection.add(user)
.addOnSuccessListener {
// User data added successfully
val intent = Intent(this, Login::class.java)
startActivity(intent)
}
.addOnFailureListener { e ->
// Error adding user data
Toast.makeText(this, "Error: ${e.message}", Toast.LENGTH_SHORT).show()
}
firebaseAuth.createUserWithEmailAndPassword(username, password)
.addOnCompleteListener {
if (it.isSuccessful) {
val intent = Intent(this, Login::class.java)
startActivity(intent)
} else {
Toast.makeText(this, it.exception.toString(), Toast.LENGTH_SHORT).show()
}
}
} else {
Toast.makeText(this, "Empty Fields are not allowed", Toast.LENGTH_SHORT).show()
}
}
}
} |
TaskProximityKotlin/app/src/main/java/com/example/taskproximity/AdminHome.kt | 2986808824 | package com.example.taskproximity
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
class AdminHome : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_adminhome)
val button1 = findViewById<Button>(R.id.addTask)
val button2 = findViewById<Button>(R.id.editTask)
button1.setOnClickListener{
val intent = Intent(this, adminAddTask::class.java)
startActivity(intent)
}
button2.setOnClickListener{
val intent = Intent(this, editTask::class.java)
startActivity(intent)
}
}
} |
TaskProximityKotlin/app/src/main/java/com/example/taskproximity/TaskEditDescActivity.kt | 4018217766 | package com.example.taskproximity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.google.firebase.firestore.FirebaseFirestore
class TaskEditDescActivity : AppCompatActivity() {
private lateinit var taskId: String
private lateinit var descriptionEditText: EditText
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_task_edit_desc)
taskId = intent.getStringExtra("taskId") ?: ""
val description = intent.getStringExtra("description") ?: ""
descriptionEditText = findViewById(R.id.editTextDescription)
descriptionEditText.setText(description)
val confirmButton: Button = findViewById(R.id.buttonConfirm)
confirmButton.setOnClickListener {
val updatedDescription = descriptionEditText.text.toString()
val db = FirebaseFirestore.getInstance()
val taskRef = db.collection("tasks").document(taskId)
taskRef.update("description", updatedDescription)
.addOnSuccessListener {
Toast.makeText(this, "Description updated successfully", Toast.LENGTH_SHORT).show()
finish()
}
.addOnFailureListener { exception ->
Toast.makeText(this, "Error: ${exception.message}", Toast.LENGTH_SHORT).show()
}
}
}
} |
TaskProximityKotlin/app/src/main/java/com/example/taskproximity/OGC.kt | 2129217051 | package com.example.taskproximity
import android.Manifest
import android.annotation.SuppressLint
import android.content.pm.PackageManager
import android.location.Location
import android.os.Bundle
import android.widget.ArrayAdapter
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import kotlin.math.atan2
import kotlin.math.cos
import kotlin.math.sin
import kotlin.math.sqrt
class OGC : AppCompatActivity() {
private lateinit var latitudeTv: TextView
private lateinit var longitudeTv: TextView
private lateinit var startStopBtn: Button
lateinit var listViewAdapter: ArrayAdapter<String>
private var latLngStrings = ArrayList<String>()
private var tracker: LocationTracker = LocationTracker(
minTimeBetweenUpdates = 500L, // 0.5 second
minDistanceBetweenUpdates = 1F, // one meter
shouldUseGPS = true,
shouldUseNetwork = true,
shouldUsePassive = true
).also {
it.addListener(object : LocationTracker.Listener {
@SuppressLint("SetTextI18n")
override fun onLocationFound(location: Location) {
val latT = location.latitude.toString()
val lngT = location.longitude.toString()
val lat = location.latitude
val long = location.longitude
val tLat = 31.783089
val tLong = 35.804489
val distance = calDistance(tLat, tLong, lat, long)
if(distance<=200)
{
Toast.makeText(applicationContext, "You are $distance away from the task", Toast.LENGTH_SHORT).show()
listViewAdapter.add("$latT, $lngT")
}
runOnUiThread {
latitudeTv.text = latT
longitudeTv.text = lngT
}
}
})
}
private fun calDistance(latT: Double, longT: Double, lat: Double, long: Double): Double {
// Radius of the Earth in meters
val R = 6371000.0
// Convert coordinates from degrees to radians
val lat1Rad = Math.toRadians(latT)
val lng1Rad = Math.toRadians(longT)
val lat2Rad = Math.toRadians(lat)
val lng2Rad = Math.toRadians(long)
// Calculate differences
val dlat = lat2Rad - lat1Rad
val dlng = lng2Rad - lng1Rad
// Haversine formula
val a = sin(dlat / 2) * sin(dlat / 2) +
cos(lat1Rad) * cos(lat2Rad) * sin(dlng / 2) * sin(dlng / 2)
val c = 2 * atan2(sqrt(a), sqrt(1 - a))
val distance = R * c
return distance
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_ogc)
latitudeTv = findViewById(R.id.tv_lat)
longitudeTv = findViewById(R.id.tv_long)
startStopBtn = findViewById(R.id.btn_start_stop)
listViewAdapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, latLngStrings)
// list_view.adapter = listViewAdapter
startStopBtn.setOnClickListener {
startStop()
}
}
override fun onStart() {
super.onStart()
initTracker()
}
override fun onDestroy() {
super.onDestroy()
tracker.stopListening(clearListeners = true)
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
initTracker()
}
private fun initTracker() {
val hasFineLocation =
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
val hasCoarseLocation =
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED
if (!hasFineLocation || !hasCoarseLocation) {
return ActivityCompat.requestPermissions(
this,
arrayOf(
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION
),
1337
)
}
}
@SuppressLint("MissingPermission")
private fun startStop() {
if (tracker.isListening) {
startStopBtn.text = "Start"
tracker.stopListening()
} else {
startStopBtn.text = "Stop"
tracker.startListening(context = baseContext)
}
}
}
|
TaskProximityKotlin/app/src/main/java/com/example/taskproximity/taskDetails.kt | 2737677899 | package com.example.taskproximity
import android.Manifest
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.widget.ArrayAdapter
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import java.lang.Math.atan2
import java.lang.Math.cos
import java.lang.Math.sin
import java.lang.Math.sqrt
class taskDetails : AppCompatActivity() {
private lateinit var descriptionTextView: TextView
private lateinit var latitudeTextView: TextView
private lateinit var longitudeTextView: TextView
private lateinit var statusTextView: TextView
private lateinit var taskIdTextView: TextView
lateinit var listViewAdapter: ArrayAdapter<String>
var latitude: Double = 0.0
var latitudeT: Double = 0.0
var longitude: Double = 0.0
var longitudeT: Double = 0.0
private val CHANNEL_ID = "TASK_PROXIMITY_CHANNEL"
private val locationUpdateReceiver: BroadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val latitude = intent.getDoubleExtra("latitude", 0.0)
val longitude = intent.getDoubleExtra("longitude", 0.0)
// Update the UI with the new location
latitudeTextView.text = "Latitude: $latitude"
longitudeTextView.text = "Longitude: $longitude"
//checkTaskProximity(latitude, longitude)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_task_details)
descriptionTextView = findViewById(R.id.descriptionTextView)
latitudeTextView = findViewById(R.id.latitudeTextView)
longitudeTextView = findViewById(R.id.longitudeTextView)
statusTextView = findViewById(R.id.statusTextView)
taskIdTextView = findViewById(R.id.taskIdTextView)
// Start the location tracker service
val serviceIntent = Intent(this, locationTrack::class.java)
startService(serviceIntent)
// Register the location update receiver
LocalBroadcastManager.getInstance(this)
.registerReceiver(locationUpdateReceiver, IntentFilter("location_updated"))
// Retrieve the task information from the intent extras
val description = intent.getStringExtra("description")
latitudeT = intent.getDoubleExtra("latitude", 0.0)
longitudeT = intent.getDoubleExtra("longitude", 0.0)
val status = intent.getStringExtra("status")
val taskId = intent.getStringExtra("taskId")
// Set the task information in the respective TextView elements
descriptionTextView.text = "Description: $description"
latitudeTextView.text = "Latitude: $latitudeT"
longitudeTextView.text = "longitude: $longitudeT"
statusTextView.text = "Status: $status"
taskIdTextView.text = "Task Id: $taskId"
// Create the notification channel
createNotificationChannel()
//push long and lat here
val openActivityButton = findViewById<Button>(R.id.openActivityButton)
openActivityButton.setOnClickListener {
val intent = Intent(this, OGC::class.java)
startActivity(intent)
}
}
override fun onDestroy() {
super.onDestroy()
// Stop the location tracker service
val serviceIntent = Intent(this, locationTrack::class.java)
stopService(serviceIntent)
// Unregister the location update receiver
LocalBroadcastManager.getInstance(this).unregisterReceiver(locationUpdateReceiver)
}
private fun createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val name = "Task Proximity Channel"
val descriptionText = "Channel for Task Proximity Notifications"
val importance = NotificationManager.IMPORTANCE_DEFAULT
val channel = NotificationChannel(CHANNEL_ID, name, importance).apply {
description = descriptionText
}
val notificationManager: NotificationManager =
getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(channel)
}
}
}
|
TaskProximityKotlin/app/src/main/java/com/example/taskproximity/userHome.kt | 2700782541 | package com.example.taskproximity
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.media.MediaPlayer
import android.view.ViewGroup.LayoutParams
import android.widget.LinearLayout
import com.google.firebase.firestore.FirebaseFirestore
import android.Manifest
import android.annotation.SuppressLint
import android.content.pm.PackageManager
import android.location.Location
import android.os.Bundle
import android.util.Log
import android.widget.ArrayAdapter
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import com.google.android.material.textfield.TextInputEditText
import kotlin.math.atan2
import kotlin.math.cos
import kotlin.math.sin
import kotlin.math.sqrt
class userHome : AppCompatActivity() {
val dataMap = mutableMapOf<String?, MutableSet<Pair<Double?, Double?>>>()
var NotifyDist = 200.0
private lateinit var tasksLayout: LinearLayout
@SuppressLint("SetTextI18n")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_user_home)
tasksLayout = findViewById(R.id.tasksLayout)
latitudeTv = findViewById(R.id.tv_lat)
longitudeTv = findViewById(R.id.tv_long)
startStopBtn = findViewById(R.id.btn_start_stop)
startStopBtn.setOnClickListener {
startStop()
}
// Retrieve data from Firestore and populate the LinearLayout with buttons for each document
val db = FirebaseFirestore.getInstance()
val collectionRef = db.collection("tasks")
val distBtn = findViewById<Button>(R.id.distanceConfitmBtn)
distBtn.setOnClickListener{
val Edit = findViewById<EditText>(R.id.editTextNumberDecimal)
val inputText = Edit.text.toString()
NotifyDist = inputText.toDouble()
}
collectionRef.get()
.addOnSuccessListener { documents ->
for (document in documents) {
val description = document.getString("description")
val latitude = document.getDouble("latitude")
val longitude = document.getDouble("longitude")
val status = document.getString("status")
val taskId = document.getString("taskId")
val coordinatePair = Pair(latitude, longitude)
val coordinateSet = dataMap.getOrDefault(taskId, mutableSetOf())
coordinateSet.add(coordinatePair)
dataMap[taskId] = coordinateSet
// Create a new button for each document and set the field values
val taskButton = Button(this)
taskButton.text = "Description: $description\n" +
"Latitude: $latitude\n" +
"Longitude: $longitude\n" +
"Status: $status\n" +
"Task ID: $taskId\n"
// Set button layout parameters
val layoutParams = LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT
)
layoutParams.setMargins(0, 0, 0, 16) // Optional: Add some margin between each button
taskButton.layoutParams = layoutParams
// Add a click listener to the button takes you to details of task
taskButton.setOnClickListener { //for now it copies to clip board, where u can use the long lat in google maps
// Copy latitude and longitude to clipboard
val clipboard = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
val clip = ClipData.newPlainText("Coordinates", "Latitude: $latitude\nLongitude: $longitude")
clipboard.setPrimaryClip(clip)
//
// // Start the TaskDetailsActivity and pass the description as an extra
// val intent = Intent(this, taskDetails::class.java)
// intent.putExtra("description", description)
// intent.putExtra("latitude", latitude)
// intent.putExtra("longitude", longitude)
// intent.putExtra("status", status)
// intent.putExtra("taskId", taskId)
// startActivity(intent)
//
// // Show a toast indicating that the latitude and longitude are copied to the clipboard
// Toast.makeText(this, "Latitude and Longitude copied to clipboard", Toast.LENGTH_SHORT).show()
}
// Add the new button to the tasksLayout LinearLayout
tasksLayout.addView(taskButton)
}
}
.addOnFailureListener { exception ->
// Handle any errors
Toast.makeText(this, "Error: ${exception.message}", Toast.LENGTH_SHORT).show()
}
}
private lateinit var latitudeTv: TextView
private lateinit var longitudeTv: TextView
private lateinit var startStopBtn: Button
private var tracker: LocationTracker = LocationTracker(
minTimeBetweenUpdates = 500L, // 0.5 second
minDistanceBetweenUpdates = 1F, // one meter
shouldUseGPS = true,
shouldUseNetwork = true,
shouldUsePassive = true
).also {
it.addListener(object : LocationTracker.Listener {
@SuppressLint("SetTextI18n", "SuspiciousIndentation")
override fun onLocationFound(location: Location) {
val latT = location.latitude.toString()
val lngT = location.longitude.toString()
val lat = location.latitude
val long = location.longitude
val tLat = 4.0
val tLong = 3.0
dataMap.entries.forEach { entry ->
val taskId: String? = entry.key
val coordinateSet: Set<Pair<Double?, Double?>>? = entry.value
if (taskId != null && coordinateSet != null) {
coordinateSet.forEach { coordinatePair ->
val latitude: Double? = coordinatePair.first
val longitude: Double? = coordinatePair.second
if (latitude != null && longitude != null) {
// Perform operations with the taskId, latitude, and longitude
// For example, you can log or process the values here
val distance = calDistance(latitude,longitude,lat,long)
if(distance<=NotifyDist)
{
runOnUiThread {
//when you make toast, take description and id of task, add finish button under start/stop
//when pressed -> changes status of task, and makes it done in db and in task in xml- Saleh
Toast.makeText(applicationContext, "You are $distance away from the task", Toast.LENGTH_SHORT).show()
// Play the sound file
val mediaPlayer = MediaPlayer.create(applicationContext, R.raw.my_sound) // Replace "your_sound_file" with the actual name of your sound file
mediaPlayer.start()
}
}
}
}
}
}
//commented because they affect the correct distance that is displayed
//val distance = calDistance(tLat, tLong, lat, long)
// if(distance<=NotifyDist)
// {
// Toast.makeText(applicationContext, "You are $distance away from the task", Toast.LENGTH_SHORT).show()
//
// // Play the sound file
// val mediaPlayer = MediaPlayer.create(applicationContext, R.raw.my_sound) // Replace "your_sound_file" with the actual name of your sound file
// mediaPlayer.start()
// }
runOnUiThread {
latitudeTv.text = "Latitude: $latT"
longitudeTv.text = "Longitude: $lngT"
}
}
})
}
private fun calDistance(latT: Double, longT: Double, lat: Double, long: Double): Double {
// Radius of the Earth in meters
val R = 6371000.0
// Convert coordinates from degrees to radians
val lat1Rad = Math.toRadians(latT)
val lng1Rad = Math.toRadians(longT)
val lat2Rad = Math.toRadians(lat)
val lng2Rad = Math.toRadians(long)
// Calculate differences
val dlat = lat2Rad - lat1Rad
val dlng = lng2Rad - lng1Rad
// Haversine formula
val a = sin(dlat / 2) * sin(dlat / 2) +
cos(lat1Rad) * cos(lat2Rad) * sin(dlng / 2) * sin(dlng / 2)
val c = 2 * atan2(sqrt(a), sqrt(1 - a))
val distance = R * c
return distance
}
override fun onStart() {
super.onStart()
initTracker()
}
override fun onDestroy() {
super.onDestroy()
tracker.stopListening(clearListeners = true)
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
initTracker()
}
private fun initTracker() {
val hasFineLocation =
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
val hasCoarseLocation =
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED
if (!hasFineLocation || !hasCoarseLocation) {
return ActivityCompat.requestPermissions(
this,
arrayOf(
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION
),
1337
)
}
}
@SuppressLint("MissingPermission")
private fun startStop() {
if (tracker.isListening) {
startStopBtn.text = "Start"
tracker.stopListening()
} else {
startStopBtn.text = "Stop"
tracker.startListening(context = baseContext)
}
}
}
|
test1/app/src/main/java/com/ubaya/anmp_week1/MainActivity.kt | 1979688132 | package com.ubaya.anmp_week1
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.navigation.NavController
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.ui.NavigationUI
import androidx.navigation.ui.setupWithNavController
import com.ubaya.anmp_week1.databinding.ActivityMainBinding
import java.security.AccessController
class MainActivity : AppCompatActivity() {
private lateinit var navController:NavController
private lateinit var binding:ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//setup binding di activity
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
navController = (supportFragmentManager.findFragmentById(R.id.navHost) as NavHostFragment).navController
NavigationUI.setupActionBarWithNavController(this,navController,binding.drawerLayout)
//setupActionBarWithNavController yg diatas. paramenter ke3 drawer klo ada
//menyuruh agar nav vontroler menghanlde navview(ygsembunyi)
NavigationUI.setupWithNavController(binding.navView,navController)
//handle navigation
binding.bottomNav.setupWithNavController(navController)
}
override fun onSupportNavigateUp(): Boolean {
//automaticly pindah ke back stack yang diatasnya
return NavigationUI.navigateUp(navController,binding.drawerLayout) || super.onSupportNavigateUp()
}
} |
test1/app/src/main/java/com/ubaya/anmp_week1/OptionFragment.kt | 3608266124 | package com.ubaya.anmp_week1
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import com.ubaya.anmp_week1.databinding.FragmentOptionBinding
class OptionFragment : BottomSheetDialogFragment() {
private val level = arrayOf("Easy","Medium","Hard")
private lateinit var binding:FragmentOptionBinding
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentOptionBinding.inflate(inflater,container,false)
// Inflate the layout for this fragment
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val adapter = ArrayAdapter<String>(requireContext(),
android.R.layout.simple_dropdown_item_1line,level
)
binding.txtLevel.setAdapter(adapter)
}
} |
test1/app/src/main/java/com/ubaya/anmp_week1/HistoryFragment.kt | 1230530680 | package com.ubaya.anmp_week1
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"
/**
* A simple [Fragment] subclass.
* Use the [HistoryFragment.newInstance] factory method to
* create an instance of this fragment.
*/
class HistoryFragment : Fragment() {
// TODO: Rename and change types of parameters
private var param1: String? = null
private var param2: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
param1 = it.getString(ARG_PARAM1)
param2 = it.getString(ARG_PARAM2)
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_history, container, false)
}
companion object {
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment HistoryFragment.
*/
// TODO: Rename and change types and number of parameters
@JvmStatic
fun newInstance(param1: String, param2: String) =
HistoryFragment().apply {
arguments = Bundle().apply {
putString(ARG_PARAM1, param1)
putString(ARG_PARAM2, param2)
}
}
}
} |
test1/app/src/main/java/com/ubaya/anmp_week1/LoginAtivity.kt | 3515892022 | package com.ubaya.anmp_week1
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
class LoginAtivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login_ativity)
}
} |
test1/app/src/main/java/com/ubaya/anmp_week1/ResultFragment.kt | 1790748864 | package com.ubaya.anmp_week1
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.navigation.Navigation
import com.ubaya.anmp_week1.databinding.FragmentMainBinding
import com.ubaya.anmp_week1.databinding.FragmentResultBinding
class ResultFragment : Fragment() {
private lateinit var binding:FragmentResultBinding
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
binding = FragmentResultBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
if(arguments != null){
val score = ResultFragmentArgs.fromBundle(requireArguments()).resultScore
binding.txtScore.text = "Your Score is $score"
}
binding.btnBackMain.setOnClickListener{
val action = ResultFragmentDirections.actionBackMainFragment()
Navigation.findNavController(it).navigate(action)
}
}
} |
test1/app/src/main/java/com/ubaya/anmp_week1/MainFragment.kt | 760618645 | package com.ubaya.anmp_week1
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import androidx.navigation.Navigation
import com.ubaya.anmp_week1.databinding.FragmentMainBinding
import java.util.logging.Level
import kotlin.random.Random
class MainFragment : Fragment() {
private lateinit var binding: FragmentMainBinding
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
binding = FragmentMainBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
var num1 = Random.nextInt(1,1000)
var num2 = Random.nextInt(1,1000)
var answer = num1 + num2
binding.txtQuestion.text = "$num1 + $num2"
var score = 0
binding.btnSubmit.setOnClickListener{
if(binding.txtAnswer.text.toString() == answer.toString()){
score = score + 1
num1 = Random.nextInt(1,1000)
num2 = Random.nextInt(1,1000)
answer = num1 + num2
binding.txtQuestion.text = "$num1 + $num2"
binding.txtAnswer.text = null
}
else{
//val name = binding.txtName.text.toString()
val action = MainFragmentDirections.actionResultFragment(score)
//memintakan contorler untuk mencari controler yg ada di
//bernavigasi ke action yg dipilih
Navigation.findNavController(it).navigate(action)
}
}
binding.btnSetting.setOnClickListener{
val action = MainFragmentDirections.actionOptionFagment()
Navigation.findNavController(it).navigate(action)
}
}
} |
test1/app/src/main/java/com/ubaya/anmp_week1/SignUpActivity.kt | 357153827 | package com.ubaya.anmp_week1
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
class SignUpActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
//signup for user
//1.check existing account
//2.check password
//3.implement
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_sign_up)
}
} |
test1/app/src/main/java/com/ubaya/anmp_week1/GameFragment.kt | 1995561012 | package com.ubaya.anmp_week1
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.navigation.Navigation
import com.ubaya.anmp_week1.databinding.FragmentGameBinding
class GameFragment : Fragment() {
private lateinit var binding:FragmentGameBinding
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentGameBinding.inflate(inflater,container,false)
// Inflate the layout for this fragment
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
if(arguments != null){
val name = GameFragmentArgs.fromBundle(requireArguments()).playerName
binding.txtTurn.text = "$name 's turn"
}
binding.btnBack.setOnClickListener{
val action = GameFragmentDirections.actionMainFragment()
Navigation.findNavController(it).navigate(action)
}
}
} |
test1/app/src/main/java/com/ubaya/anmp_week1/ProfileFragment.kt | 129123690 | package com.ubaya.anmp_week1
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"
/**
* A simple [Fragment] subclass.
* Use the [ProfileFragment.newInstance] factory method to
* create an instance of this fragment.
*/
class ProfileFragment : Fragment() {
// TODO: Rename and change types of parameters
private var param1: String? = null
private var param2: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
param1 = it.getString(ARG_PARAM1)
param2 = it.getString(ARG_PARAM2)
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_profile, container, false)
}
companion object {
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment ProfileFragment.
*/
// TODO: Rename and change types and number of parameters
@JvmStatic
fun newInstance(param1: String, param2: String) =
ProfileFragment().apply {
arguments = Bundle().apply {
putString(ARG_PARAM1, param1)
putString(ARG_PARAM2, param2)
}
}
}
} |
test1/Works/W4App/app/src/main/java/com/ubaya/studentapp/viewmodel/DetailViewModel.kt | 2923771696 | package com.ubaya.studentapp.viewmodel
import android.app.Application
import android.util.Log
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.android.volley.Request
import com.android.volley.RequestQueue
import com.android.volley.toolbox.StringRequest
import com.android.volley.toolbox.Volley
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.ubaya.studentapp.model.Student
class DetailViewModel(application: Application): AndroidViewModel(application) {
private val listStudent = MutableLiveData<ArrayList<Student>>()
val studentLD = MutableLiveData<Student>()
val TAG = "volleyTag"
private var queue: RequestQueue? = null
fun fetch(idStudent:String?) {
queue = Volley.newRequestQueue(getApplication())
val url = "http://adv.jitusolution.com/student.php?id="+idStudent
val stringRequest = StringRequest(
Request.Method.GET, url,
{
val sType = object: TypeToken<Student>(){}.type
val result = Gson().fromJson<Student>(it, sType)
studentLD.value = result as Student
Log.d("showvoleyid", studentLD.value.toString())
},
{
Log.d("showvoley", it.toString())
})
stringRequest.tag = TAG
queue?.add(stringRequest)
}
}
|
test1/Works/W4App/app/src/main/java/com/ubaya/studentapp/viewmodel/ListViewModel.kt | 3536791165 | package com.ubaya.studentapp.viewmodel
import android.app.Application
import android.util.Log
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.android.volley.RequestQueue
import com.android.volley.toolbox.StringRequest
import com.android.volley.toolbox.Volley
import com.ubaya.studentapp.model.Student
import com.android.volley.Request
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
class ListViewModel(application: Application): AndroidViewModel(application) {
val studentsLD = MutableLiveData<ArrayList<Student>>()
//buat liat loding ato gk
val loadingLD = MutableLiveData<Boolean>()
val studentLoadErrorLD = MutableLiveData<Boolean>()
val TAG = "volleyTag"
private var queue: RequestQueue?= null
fun refresh(){
//karna dummy jdi gk mungkin salah
//studentLoadErrorLD.value = false
//loadingLD.value = false
studentLoadErrorLD.value = false
loadingLD.value = true
queue = Volley.newRequestQueue(getApplication())
val url = "http://adv.jitusolution.com/student.php"
val stringRequest = StringRequest(
Request.Method.GET,
url,
{//callback jk voley succes
loadingLD.value =false
Log.d("show_volley",it)
val sType = object: TypeToken<List<Student>>(){}.type
//gson berusaha mengubah json sesuai dengan list student
val result = Gson().fromJson<List<Student>>(it,sType)
studentsLD.value = result as ArrayList<Student>
},
{
loadingLD.value =false
Log.e("show_volley",it.toString())
}
)
stringRequest.tag = TAG
queue?.add(stringRequest)
}
//klo viewmodel g dipake
override fun onCleared() {
super.onCleared()
queue?.cancelAll(TAG)
}
} |
test1/Works/W4App/app/src/main/java/com/ubaya/studentapp/viewmodel/SongListViewModel.kt | 2790330287 | package com.ubaya.studentapp.viewmodel
import android.app.Application
import android.util.Log
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import com.android.volley.Request
import com.android.volley.RequestQueue
import com.android.volley.toolbox.StringRequest
import com.android.volley.toolbox.Volley
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.ubaya.studentapp.model.Song
import com.ubaya.studentapp.model.Student
class SongListViewModel(application: Application):AndroidViewModel(application) {
val songsLD = MutableLiveData<ArrayList<Song>>()
//buat liat loding ato gk
val loadingLD = MutableLiveData<Boolean>()
val songLoadErrorLD = MutableLiveData<Boolean>()
val TAG = "volleyTag"
private var queue: RequestQueue?= null
fun refresh(){
songLoadErrorLD.value = false
loadingLD.value = true
queue = Volley.newRequestQueue(getApplication())
val url = "http://192.168.152.27/songs.json"
val stringRequest = StringRequest(
Request.Method.GET,
url,
{//callback jk voley succes
loadingLD.value =false
Log.d("show_volley",it)
val sType = object: TypeToken<List<Song>>(){}.type
//gson berusaha mengubah json sesuai dengan list student
val result = Gson().fromJson<List<Song>>(it,sType)
songsLD.value = result as ArrayList<Song>
},
{
loadingLD.value =false
Log.e("show_volley",it.toString())
}
)
stringRequest.tag = TAG
queue?.add(stringRequest)
}
override fun onCleared() {
super.onCleared()
queue?.cancelAll(TAG)
}
} |
test1/Works/W4App/app/src/main/java/com/ubaya/studentapp/util/util.kt | 1022604207 | package com.ubaya.studentapp.util
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.os.Build
import android.view.View
import android.widget.ImageView
import android.widget.ProgressBar
import com.squareup.picasso.Callback
import com.squareup.picasso.Picasso
import com.ubaya.studentapp.R
fun createNotificationChannel(context: Context, importance:Int, showBadge:Boolean, name:String, description:String)
{
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
val channelId = "${context.packageName}-$name"
val channel = NotificationChannel(channelId, name, importance)
channel.description = description
channel.setShowBadge(showBadge)
val notificationManager = context.getSystemService(NotificationManager::class.java)
notificationManager.createNotificationChannel(channel)
}
}
fun ImageView.loadImage(url: String?, progressBar: ProgressBar) {
Picasso.get()
.load(url)
.resize(400, 400)
.centerCrop()
.error(R.drawable.ic_launcher_background)
.into(this, object: Callback {
override fun onSuccess() {
progressBar.visibility = View.GONE
}
override fun onError(e: Exception?) {
}
})
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.