content
stringlengths
0
13M
path
stringlengths
4
263
contentHash
stringlengths
1
10
package com.funny.translation.kmp import android.app.Activity import android.content.Context import android.content.ContextWrapper import android.os.Build import android.view.View import android.view.Window import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalView import androidx.compose.ui.window.DialogWindowProvider import androidx.core.view.ViewCompat import androidx.core.view.WindowCompat import androidx.core.view.WindowInsetsCompat class AndroidSystemUiController( private val view: View, private val window: Window? ) : SystemUiController { private val windowInsetsController = window?.let { WindowCompat.getInsetsController(it, view) } override fun setStatusBarColor( color: Color, darkIcons: Boolean, transformColorForLightContent: (Color) -> Color ) { statusBarDarkContentEnabled = darkIcons window?.statusBarColor = when { darkIcons && windowInsetsController?.isAppearanceLightStatusBars != true -> { // If we're set to use dark icons, but our windowInsetsController call didn't // succeed (usually due to API level), we instead transform the color to maintain // contrast transformColorForLightContent(color) } else -> color }.toArgb() } override fun setNavigationBarColor( color: Color, darkIcons: Boolean, navigationBarContrastEnforced: Boolean, transformColorForLightContent: (Color) -> Color ) { navigationBarDarkContentEnabled = darkIcons isNavigationBarContrastEnforced = navigationBarContrastEnforced window?.navigationBarColor = when { darkIcons && windowInsetsController?.isAppearanceLightNavigationBars != true -> { // If we're set to use dark icons, but our windowInsetsController call didn't // succeed (usually due to API level), we instead transform the color to maintain // contrast transformColorForLightContent(color) } else -> color }.toArgb() } override var systemBarsBehavior: Int get() = windowInsetsController?.systemBarsBehavior ?: 0 set(value) { windowInsetsController?.systemBarsBehavior = value } override var isStatusBarVisible: Boolean get() { return ViewCompat.getRootWindowInsets(view) ?.isVisible(WindowInsetsCompat.Type.statusBars()) == true } set(value) { if (value) { windowInsetsController?.show(WindowInsetsCompat.Type.statusBars()) } else { windowInsetsController?.hide(WindowInsetsCompat.Type.statusBars()) } } override var isNavigationBarVisible: Boolean get() { return ViewCompat.getRootWindowInsets(view) ?.isVisible(WindowInsetsCompat.Type.navigationBars()) == true } set(value) { if (value) { windowInsetsController?.show(WindowInsetsCompat.Type.navigationBars()) } else { windowInsetsController?.hide(WindowInsetsCompat.Type.navigationBars()) } } override var statusBarDarkContentEnabled: Boolean get() = windowInsetsController?.isAppearanceLightStatusBars == true set(value) { windowInsetsController?.isAppearanceLightStatusBars = value } override var navigationBarDarkContentEnabled: Boolean get() = windowInsetsController?.isAppearanceLightNavigationBars == true set(value) { windowInsetsController?.isAppearanceLightNavigationBars = value } override var isNavigationBarContrastEnforced: Boolean get() = Build.VERSION.SDK_INT >= 29 && window?.isNavigationBarContrastEnforced == true set(value) { if (Build.VERSION.SDK_INT >= 29) { window?.isNavigationBarContrastEnforced = value } } } @Composable actual fun rememberSystemUiController(): SystemUiController { return rememberSystemUiController(window = findWindow()) } /** * Remembers a [SystemUiController] for the given [window]. * * If no [window] is provided, an attempt to find the correct [Window] is made. * * First, if the [LocalView]'s parent is a [DialogWindowProvider], then that dialog's [Window] will * be used. * * Second, we attempt to find [Window] for the [Activity] containing the [LocalView]. * * If none of these are found (such as may happen in a preview), then the functionality of the * returned [SystemUiController] will be degraded, but won't throw an exception. */ @Composable public fun rememberSystemUiController( window: Window? = findWindow(), ): SystemUiController { val view = LocalView.current return remember(view, window) { AndroidSystemUiController(view, window) } } @Composable private fun findWindow(): Window? = (LocalView.current.parent as? DialogWindowProvider)?.window ?: LocalView.current.context.findWindow() private tailrec fun Context.findWindow(): Window? = when (this) { is Activity -> window is ContextWrapper -> baseContext.findWindow() else -> null }
Transtation-KMP/base-kmp/src/androidMain/kotlin/com/funny/translation/kmp/SystemUiController.android.kt
1577404197
package com.funny.translation.kmp import android.content.Intent import androidx.activity.result.ActivityResultLauncher import com.funny.translation.BaseActivity import com.funny.translation.helper.Log import moe.tlaster.precompose.navigation.NavOptions import java.util.LinkedList actual object ActivityManager { private const val TAG = "ActivityManager" actual val activityStack: MutableList<BaseActivity> = LinkedList<BaseActivity>() private val activityResultLaunchers = mutableMapOf<BaseActivity, ActivityResultLauncher<Intent>>() actual fun addActivity(activity: BaseActivity) { activityStack.add(activity) Log.d(TAG, "【${activity::class.java.simpleName}】 Created! currentStackSize:${activityStack.size}") } actual fun removeActivity(activity: BaseActivity) { activityStack.remove(activity) Log.d(TAG, "【${activity::class.java.simpleName}】 Destroyed! currentStackSize:${activityStack.size}") } actual fun currentActivity(): BaseActivity? { return activityStack.lastOrNull() } actual fun start( targetClass: Class<out BaseActivity>, data: MutableMap<String, Any?>, options: NavOptions, onBack: (result: Map<String, Any?>?) -> Unit ) { val activity = currentActivity() ?: return val launcher = activity.activityResultLauncher launcher.launch(data.toIntent().apply { setClassName(activity, targetClass.name) }) } } fun Intent.toMap(): Map<String, Any?> { return mapOf( "action" to action, "data" to data, "extras" to extras, "flags" to flags, ) } fun Map<String, Any?>.toIntent(): Intent { return Intent().apply { action = this@toIntent["action"] as? String data = this@toIntent["data"] as? android.net.Uri val extras = this@toIntent["extras"] as? DataType extras?.entries?.forEach { entry -> val (key, value) = entry when (value) { is String -> putExtra(key, value) is Int -> putExtra(key, value) is Boolean -> putExtra(key, value) is Float -> putExtra(key, value) is Double -> putExtra(key, value) is Long -> putExtra(key, value) } } flags = this@toIntent["flags"] as? Int ?: 0 } }
Transtation-KMP/base-kmp/src/androidMain/kotlin/com/funny/translation/kmp/ActivityManager.android.kt
2238167834
package com.funny.translation.kmp import com.eygraber.uri.Uri import com.eygraber.uri.toAndroidUri import com.funny.translation.helper.readText import com.funny.translation.helper.writeText actual fun Uri.writeText(text: String) { this.toAndroidUri().writeText(appCtx, text) } actual fun Uri.readText(): String { return this.toAndroidUri().readText(appCtx) }
Transtation-KMP/base-kmp/src/androidMain/kotlin/com/funny/translation/kmp/Uri.android.kt
1479262837
package com.funny.translation.kmp.paging import android.os.Parcel import android.os.Parcelable internal actual data class PagingPlaceholderKey actual constructor(actual val index: Int) : Parcelable { override fun writeToParcel(parcel: Parcel, flags: Int) { parcel.writeInt(index) } override fun describeContents(): Int { return 0 } companion object { @Suppress("unused") @JvmField val CREATOR: Parcelable.Creator<PagingPlaceholderKey> = object : Parcelable.Creator<PagingPlaceholderKey> { override fun createFromParcel(parcel: Parcel) = PagingPlaceholderKey(parcel.readInt()) override fun newArray(size: Int) = arrayOfNulls<PagingPlaceholderKey?>(size) } } }
Transtation-KMP/base-kmp/src/androidMain/kotlin/com/funny/translation/kmp/paging/PagingPlaceHolderContentType.android.kt
2418988364
package com.funny.translation.kmp actual fun getPlatform(): Platform = Platform.Android
Transtation-KMP/base-kmp/src/androidMain/kotlin/com/funny/translation/kmp/Platform.android.kt
3503956930
package com.funny.translation.kmp import androidx.compose.foundation.layout.ExperimentalLayoutApi import androidx.compose.foundation.layout.imeNestedScroll import androidx.compose.ui.Modifier @OptIn(ExperimentalLayoutApi::class) actual fun Modifier.kmpImeNestedScroll(): Modifier = imeNestedScroll()
Transtation-KMP/base-kmp/src/androidMain/kotlin/com/funny/translation/kmp/Modifiers.android.kt
269555747
package com.funny.translation.helper.handler import android.os.Build.VERSION.SDK_INT import android.os.Handler import android.os.Looper import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers.IO import kotlinx.coroutines.launch /** This main looper cache avoids synchronization overhead when accessed repeatedly. */ @JvmField val mainLooper: Looper = Looper.getMainLooper()!! @JvmField val mainThread: Thread = mainLooper.thread val isMainThread: Boolean inline get() = mainThread === Thread.currentThread() @PublishedApi internal val currentThread: Any? inline get() = Thread.currentThread() @JvmField val mainHandler: Handler = if (SDK_INT >= 28) Handler.createAsync(mainLooper) else try { Handler::class.java.getDeclaredConstructor( Looper::class.java, Handler.Callback::class.java, Boolean::class.javaPrimitiveType // async ).newInstance(mainLooper, null, true) } catch (ignored: NoSuchMethodException) { Handler(mainLooper) // Hidden constructor absent. Fall back to non-async constructor. } inline fun runOnUI(crossinline function: () -> Unit) { if (isMainThread) { function() } else { mainHandler.post { function() } } } fun CoroutineScope.runOnIO(function: () -> Unit) { if (isMainThread) { launch(IO) { function() } } else { function() } }
Transtation-KMP/base-kmp/src/androidMain/kotlin/com/funny/translation/helper/handler/HandlerUtil.kt
3377203237
package com.funny.translation.helper import android.app.AlertDialog import android.content.Context import com.funny.translation.helper.handler.runOnUI import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.suspendCancellableCoroutine @OptIn(ExperimentalCoroutinesApi::class) suspend fun awaitDialog( context: Context, title: String, message: String, positiveButton: String, negativeButton: String, ) = suspendCancellableCoroutine { continuation -> runOnUI { AlertDialog.Builder(context).setTitle(title).setMessage(message) .setPositiveButton(positiveButton) { _, _ -> continuation.resume(true, {}) } .setNegativeButton(negativeButton) { _, _ -> continuation.resume(false, {}) } .show() } }
Transtation-KMP/base-kmp/src/androidMain/kotlin/com/funny/translation/helper/DialogEx.kt
182011226
package com.funny.translation.helper import androidx.compose.runtime.Composable import androidx.compose.runtime.ReadOnlyComposable import androidx.compose.ui.platform.LocalConfiguration import androidx.compose.ui.platform.LocalContext private const val TAG = "ResourcesEx" /** * 带 i18n 的 assetsString,文件名应当形如 xxx_zh.json * 如果找不到带语言的文件,则使用默认的文件 * @param name String * @return String */ @ReadOnlyComposable @Composable actual fun assetsStringLocalized(name: String): String { val context = LocalContext.current val locale = LocalConfiguration.current.locale val localedAssetsName = name.addBeforeFileEx("_" + locale.language) Log.d(TAG, "assetsStringLocalized: try to find $localedAssetsName") return if (context.assets.list("")?.contains(localedAssetsName) == true) { assetsString(localedAssetsName) } else { assetsString(name) } }
Transtation-KMP/base-kmp/src/androidMain/kotlin/com/funny/translation/helper/ResourcesEx.android.kt
3533763602
package com.funny.translation.helper import android.content.Context import android.content.res.Resources import android.graphics.Bitmap import android.graphics.BitmapFactory import android.graphics.Matrix import com.eygraber.uri.Uri import com.eygraber.uri.toAndroidUri import java.io.ByteArrayOutputStream import java.io.File import java.io.FileOutputStream import java.io.IOException import java.nio.ByteBuffer private const val TAG = "BitmapUtil" actual object BitmapUtil { actual fun compressImage(bytes: ByteArray?, width: Int, height: Int, maxSize: Long): ByteArray { bytes ?: return byteArrayOf() val image = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888) val buffer = ByteBuffer.wrap(bytes) buffer.position(0) image.copyPixelsFromBuffer(buffer) return compressImage(image, maxSize) } actual fun getBitmapFromUri(ctx: Context, targetWidth: Int, targetHeight: Int, maxSize: Long, uri: Uri): ByteArray? { val (originalWidth, originalHeight) = getImageSizeFromUri(ctx, uri) if (originalWidth == -1 || originalHeight == -1) return null //缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可 var be = 1 // be=1表示不缩放 if (originalWidth > originalHeight && originalWidth > targetWidth) { //如果宽度大的话根据宽度固定大小缩放 be = (originalWidth / targetWidth) } else if (originalWidth < originalHeight && originalHeight > targetHeight) { //如果高度高的话根据宽度固定大小缩放 be = (originalHeight / targetHeight) } if (be <= 0) be = 1 //比例压缩 val bitmapOptions = BitmapFactory.Options() bitmapOptions.inSampleSize = be //设置缩放比例 bitmapOptions.inDither = true //optional bitmapOptions.inPreferredConfig = Bitmap.Config.ARGB_8888 //optional ctx.contentResolver.openInputStream(uri.toAndroidUri())?.use { return compressImage(BitmapFactory.decodeStream(it, null, bitmapOptions), maxSize) //再进行质量压缩 } return null } // 获取图片的宽高,如果获取失败则返回 -1, -1 actual fun getImageSizeFromUri(ctx: Context, uri: Uri): Pair<Int, Int> { Log.d(TAG, "getImageSizeFromUri: $uri, toAndroidUri: ${uri.toAndroidUri()}") val input = ctx.contentResolver.openInputStream(uri.toAndroidUri()) input?.use { val onlyBoundsOptions = BitmapFactory.Options() onlyBoundsOptions.inJustDecodeBounds = true onlyBoundsOptions.inDither = true //optional onlyBoundsOptions.inPreferredConfig = Bitmap.Config.ARGB_8888 //optional BitmapFactory.decodeStream(input, null, onlyBoundsOptions) val originalWidth = onlyBoundsOptions.outWidth val originalHeight = onlyBoundsOptions.outHeight return Pair(originalWidth, originalHeight) } return Pair(-1, -1) } actual fun saveBitmap(bytes: ByteArray, imagePath: String) { val file = File(imagePath) if (file.exists()) { file.delete() } try { file.createNewFile() val fos = FileOutputStream(file) fos.write(bytes) fos.flush() fos.close() } catch (e: IOException) { e.printStackTrace() } } fun getBitmapFromResources( re: Resources?, id: Int ): Bitmap { return BitmapFactory.decodeResource(re, id) } @JvmStatic fun getBitmapFromResources( re: Resources?, id: Int, targetWidth: Int, targetHeight: Int ): Bitmap { return getScaledBitmap(BitmapFactory.decodeResource(re, id), targetWidth, targetHeight) } fun getScaledBitmap( bitmap: Bitmap, targetWidth: Int, targetHeight: Int ): Bitmap { val width = bitmap.width val height = bitmap.height val scaleWidth = targetWidth.toFloat() / width val scaleHeight = targetHeight.toFloat() / height val matrix = Matrix() matrix.postScale(scaleWidth, scaleHeight) return Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true) } fun getBigBitmapFromResources( re: Resources?, id: Int, targetWidth: Int, targetHeight: Int ): Bitmap { val options = BitmapFactory.Options() options.inJustDecodeBounds = true BitmapFactory.decodeResource(re, id, options) //现在原始宽高以存储在了options对象的outWidth和outHeight实例域中 val rawWidth = options.outWidth val rawHeight = options.outHeight var inSampleSize = 1 if (rawWidth > targetWidth || rawHeight > targetHeight) { val ratioHeight = rawHeight.toFloat() / targetHeight val ratioWidth = rawWidth.toFloat() / targetWidth inSampleSize = Math.min(ratioWidth, ratioHeight).toInt() } options.inSampleSize = inSampleSize options.inJustDecodeBounds = false return BitmapFactory.decodeResource(re, id, options) } /** * 质量压缩方法 * * @param image * @return */ fun compressImage(image: Bitmap?, maxSize: Long): ByteArray { val baos = ByteArrayOutputStream() image!!.compress(Bitmap.CompressFormat.JPEG, 100, baos) //质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中 var options = 100 var bytes: ByteArray while (baos.toByteArray() .also { bytes = it }.size > maxSize ) { //循环判断如果压缩后图片是否大于100kb,大于继续压缩 baos.reset() //重置baos即清空baos options -= 10 //每次都减少10 //第一个参数 :图片格式 ,第二个参数: 图片质量,100为最高,0为最差 ,第三个参数:保存压缩后的数据的流 image.compress(Bitmap.CompressFormat.JPEG, options, baos) //这里压缩options%,把压缩后的数据存放到baos中 } image.recycle() return bytes } }
Transtation-KMP/base-kmp/src/androidMain/kotlin/com/funny/translation/helper/BitmapUtil.android.kt
3591601243
// androidMain/src/com/funny/translation/helper/ClipBoardUtilAndroid.kt package com.funny.translation.helper import android.content.ClipData import android.content.ClipDescription import android.content.ClipboardManager import android.content.Context import com.funny.translation.kmp.appCtx actual object ClipBoardUtil { private const val CLIPBOARD_LABEL = "ClipBoardLabel" private fun getClipboardManager(context: Context): ClipboardManager { return context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager } actual fun read(): String { return try { val clipboardManager = getClipboardManager(appCtx) if (clipboardManager.hasPrimaryClip() && clipboardManager.primaryClipDescription?.hasMimeType( ClipDescription.MIMETYPE_TEXT_PLAIN) == true) { val clip = clipboardManager.primaryClip val item = clip?.getItemAt(0) item?.text?.toString() ?: "" } else { "" } } catch (e: Exception) { "" } } actual fun copy(content: CharSequence?) { val clipboardManager = getClipboardManager(appCtx) val clip = ClipData.newPlainText(CLIPBOARD_LABEL, content) clipboardManager.setPrimaryClip(clip) } actual fun clear() { val clipboardManager = getClipboardManager(appCtx) clipboardManager.setPrimaryClip(ClipData.newPlainText("", "")) } }
Transtation-KMP/base-kmp/src/androidMain/kotlin/com/funny/translation/helper/ClipBoardUtil.android.kt
2461126881
package com.funny.translation.helper import android.content.Context import android.content.Context.VIBRATOR_SERVICE import android.os.Build import android.os.VibrationEffect import android.os.Vibrator import android.os.VibratorManager import com.funny.translation.kmp.appCtx actual object VibratorUtils { private val vibrator by lazy{ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { val vibratorManager = appCtx.getSystemService(Context.VIBRATOR_MANAGER_SERVICE) as VibratorManager vibratorManager.defaultVibrator } else { @Suppress("DEPRECATION") appCtx.getSystemService(VIBRATOR_SERVICE) as Vibrator } } actual fun vibrate(time: Long) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { vibrator.vibrate(VibrationEffect.createOneShot(time, VibrationEffect.DEFAULT_AMPLITUDE)) } else vibrator.vibrate(time) } actual fun cancel() { vibrator.cancel() } }
Transtation-KMP/base-kmp/src/androidMain/kotlin/com/funny/translation/helper/VibratorUtils.android.kt
2347009679
package com.funny.translation.helper import android.content.Context import android.media.AudioManager import android.os.Build import com.funny.translation.kmp.appCtx actual object DeviceUtils { actual fun is64Bit(): Boolean { return Build.SUPPORTED_64_BIT_ABIS.isNotEmpty() } // 获取系统当前音量 actual fun getSystemVolume(): Int { val audioManager = appCtx.getSystemService(Context.AUDIO_SERVICE) as AudioManager return audioManager.getStreamVolume(AudioManager.STREAM_MUSIC) } // 判断是否静音 actual fun isMute() = getSystemVolume() == 0 }
Transtation-KMP/base-kmp/src/androidMain/kotlin/com/funny/translation/helper/DeviceUtils.android.kt
3594825824
package com.funny.translation.helper import android.graphics.Bitmap import androidx.compose.ui.graphics.asImageBitmap import com.kyant.monet.getKeyColors private const val TAG = "BitmapEx" fun Bitmap.getKeyColors(count: Int) = this.asImageBitmap().getKeyColors(count)
Transtation-KMP/base-kmp/src/androidMain/kotlin/com/funny/translation/helper/BitmapEx.kt
2663675201
package com.funny.translation.helper import com.funny.data_saver.core.DataSaverInterface import com.funny.data_saver.mmkv.DefaultDataSaverMMKV actual val DataSaverUtils: DataSaverInterface = DefaultDataSaverMMKV
Transtation-KMP/base-kmp/src/androidMain/kotlin/com/funny/translation/helper/DataSaverUtils.android.kt
907134433
package com.funny.translation.helper import android.content.SharedPreferences import com.funny.translation.Consts import com.funny.translation.bean.AppLanguage import java.util.Locale actual object LocaleUtils { private lateinit var sharedPreferences: SharedPreferences private lateinit var appLanguage: AppLanguage actual fun init(context: Context) { sharedPreferences = context.getSharedPreferences("shared_pref", android.content.Context.MODE_PRIVATE) } actual fun getWarpedContext(context: Context, locale: Locale): Context { val configuration = context.resources.configuration configuration.setLocale(locale) Locale.setDefault(locale) Log.d("LocaleUtils", "getWarpedContext: ${locale.language}") return context.createConfigurationContext(configuration) } actual fun saveAppLanguage(appLanguage: AppLanguage) { this.appLanguage = appLanguage sharedPreferences.edit().putInt(Consts.KEY_APP_LANGUAGE, appLanguage.ordinal).apply() Log.d("LocaleUtils", "saveAppLanguage: ${appLanguage.description}") } actual fun getAppLanguage(): AppLanguage { if (!this::appLanguage.isInitialized) { appLanguage = kotlin.runCatching { AppLanguage.values()[sharedPreferences.getInt(Consts.KEY_APP_LANGUAGE, 0)] }.onFailure { it.printStackTrace() }.getOrDefault(AppLanguage.FOLLOW_SYSTEM) } Log.d("LocaleUtils", "getAppLanguage: ${appLanguage.description}") return this.appLanguage } // 不经过获取 AppLanguage -> Locale 的过程,直接获取 Locale // 这个方法会在 attachBaseContext() 里调用,所以不能使用 AppLanguage 这个类 actual fun getLocaleDirectly(): Locale { val id = sharedPreferences.getInt(Consts.KEY_APP_LANGUAGE, 0) return when(id) { 0 -> Locale.getDefault() 1 -> Locale.ENGLISH 2 -> Locale.CHINESE else -> Locale.getDefault() } } }
Transtation-KMP/base-kmp/src/androidMain/kotlin/com/funny/translation/helper/LocaleUtils.android.kt
3391323498
package com.funny.translation.helper import android.util.Log as AndroidLog actual object Logger { private const val TAG = "DefaultLog" // i, d, w, e, v actual fun d(msg: String) { AndroidLog.d(TAG, msg) } actual fun d(tag: String, msg: String) { AndroidLog.d(tag, msg) } actual fun d(tag: String, msg: String, throwable: Throwable) { AndroidLog.d(tag, msg, throwable) } actual fun i(msg: String) { AndroidLog.i(TAG, msg) } actual fun i(tag: String, msg: String) { AndroidLog.i(tag, msg) } actual fun i(tag: String, msg: String, throwable: Throwable) { AndroidLog.i(tag, msg, throwable) } actual fun w(msg: String) { AndroidLog.w(TAG, msg) } actual fun w(tag: String, msg: String) { AndroidLog.w(tag, msg) } actual fun w(tag: String, msg: String, throwable: Throwable) { AndroidLog.w(tag, msg, throwable) } actual fun e(msg: String) { AndroidLog.e(TAG, msg) } actual fun e(tag: String, msg: String) { AndroidLog.e(tag, msg) } actual fun e(tag: String, msg: String, throwable: Throwable) { AndroidLog.e(tag, msg, throwable) } actual fun v(msg: String) { AndroidLog.v(TAG, msg) } actual fun v(tag: String, msg: String) { AndroidLog.v(tag, msg) } actual fun v(tag: String, msg: String, throwable: Throwable) { AndroidLog.v(tag, msg, throwable) } // wtf actual fun wtf(msg: String) { AndroidLog.wtf(TAG, msg) } actual fun wtf(tag: String, msg: String) { AndroidLog.wtf(tag, msg) } actual fun wtf(tag: String, msg: String, throwable: Throwable) { AndroidLog.wtf(tag, msg, throwable) } }
Transtation-KMP/base-kmp/src/androidMain/kotlin/com/funny/translation/helper/Logger.android.kt
1244498795
package com.funny.translation.helper import android.content.Intent import com.funny.translation.kmp.appCtx actual object ApplicationUtil { actual fun restartApp() { val context = appCtx val intent = context.packageManager.getLaunchIntentForPackage(context.packageName) intent!!.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) context.startActivity(intent) android.os.Process.killProcess(android.os.Process.myPid()) } }
Transtation-KMP/base-kmp/src/androidMain/kotlin/com/funny/translation/helper/ApplicationUtil.android.kt
2626399945
package com.funny.translation.helper import android.content.Context import android.content.res.AssetFileDescriptor import android.net.Uri import com.funny.translation.kmp.base.strings.ResStrings import java.io.* private const val TAG = "UriExtensions" @Throws(IOException::class) fun Uri.readText(ctx: Context): String { val stringBuilder = StringBuilder() ctx.contentResolver.openInputStream(this).use { inputStream -> BufferedReader( InputStreamReader(inputStream) ).use { reader -> var line: String? while (reader.readLine().also { line = it } != null) { stringBuilder.append(line) stringBuilder.append("\n") } } } return stringBuilder.toString() } @Throws(IOException::class) fun Uri.readByteArray(ctx: Context): ByteArray { var byteArray: ByteArray ctx.contentResolver.openInputStream(this).use { inputStream -> byteArray = inputStream?.readBytes() ?: byteArrayOf() } return byteArray } @Throws(IOException::class) fun Uri.writeText(context: Context, text: String) { val pfd: AssetFileDescriptor? = context.contentResolver.openAssetFileDescriptor(this, "w") if (pfd != null) { val fileWriter = FileWriter(pfd.fileDescriptor) fileWriter.write(text) try { fileWriter.close() pfd.close() }catch (e:Exception) { context.toastOnUi(ResStrings.err_write_text) e.printStackTrace() } } }
Transtation-KMP/base-kmp/src/androidMain/kotlin/com/funny/translation/helper/UriExtentions.kt
2237080534
package com.funny.translation.helper.biomertic import android.os.Build import android.security.keystore.KeyGenParameterSpec import android.security.keystore.KeyPermanentlyInvalidatedException import android.security.keystore.KeyProperties import androidx.annotation.RequiresApi import com.funny.translation.helper.Context import com.funny.translation.helper.JsonX import com.funny.translation.helper.Log import java.nio.charset.Charset import java.security.KeyStore import javax.crypto.Cipher import javax.crypto.KeyGenerator import javax.crypto.SecretKey import javax.crypto.spec.GCMParameterSpec @RequiresApi(Build.VERSION_CODES.M) actual fun CryptographyManager(): CryptographyManager = CryptographyManagerImpl() /** * To get an instance of this private CryptographyManagerImpl class, use the top-level function * fun CryptographyManager(): CryptographyManager = CryptographyManagerImpl() */ @RequiresApi(Build.VERSION_CODES.M) private class CryptographyManagerImpl : CryptographyManager { private val keyStore by lazy { KeyStore.getInstance(ANDROID_KEYSTORE).apply { load(null) // Keystore must be loaded before it can be accessed } } companion object { private const val TAG = "CryptographyManagerImpl" private const val KEY_SIZE = 256 private const val ANDROID_KEYSTORE = "AndroidKeyStore" private const val ENCRYPTION_BLOCK_MODE = KeyProperties.BLOCK_MODE_GCM private const val ENCRYPTION_PADDING = KeyProperties.ENCRYPTION_PADDING_NONE private const val ENCRYPTION_ALGORITHM = KeyProperties.KEY_ALGORITHM_AES } override fun getInitializedCipherForEncryption(keyName: String, shouldRetry: Boolean): Cipher { val cipher = getCipher() val secretKey = getOrCreateSecretKey(keyName) try { cipher.init(Cipher.ENCRYPT_MODE, secretKey) }catch (e: KeyPermanentlyInvalidatedException){ Log.d(TAG, "key 过期了,删除重建 ") keyStore.deleteEntry(keyName) if (shouldRetry) return getInitializedCipherForEncryption(keyName, false) else throw Exception("getInitializedCipherForEncryption Key过期了,且无法重建") } return cipher } override fun getInitializedCipherForDecryption( keyName: String, initializationVector: ByteArray, shouldRetry: Boolean ): Cipher { val cipher = getCipher() val secretKey = getOrCreateSecretKey(keyName) try { cipher.init(Cipher.DECRYPT_MODE, secretKey, GCMParameterSpec(128, initializationVector)) }catch (e: KeyPermanentlyInvalidatedException){ Log.d(TAG, "key 过期了,删除重建 ") keyStore.deleteEntry(keyName) if (shouldRetry) return getInitializedCipherForDecryption(keyName, initializationVector, false) else throw Exception("getInitializedCipherForDecryption Key过期了,且无法重建") } return cipher } override fun encryptData(plaintext: String, cipher: Cipher): CiphertextWrapper { val ciphertext = cipher.doFinal(plaintext.toByteArray(Charset.forName("UTF-8"))) return CiphertextWrapper(ciphertext, cipher.iv) } override fun decryptData(ciphertext: ByteArray, cipher: Cipher): String { val plaintext = cipher.doFinal(ciphertext) return String(plaintext, Charset.forName("UTF-8")) } private fun getCipher(): Cipher { val transformation = "$ENCRYPTION_ALGORITHM/$ENCRYPTION_BLOCK_MODE/$ENCRYPTION_PADDING" return Cipher.getInstance(transformation) } private fun getOrCreateSecretKey(keyName: String): SecretKey { keyStore.getKey(keyName, null)?.let { return it as SecretKey } // if you reach here, then a new SecretKey must be generated for that keyName val paramsBuilder = KeyGenParameterSpec.Builder( keyName, KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT ) paramsBuilder.apply { setBlockModes(ENCRYPTION_BLOCK_MODE) setEncryptionPaddings(ENCRYPTION_PADDING) setKeySize(KEY_SIZE) setUserAuthenticationRequired(false) } val keyGenParams = paramsBuilder.build() val keyGenerator = KeyGenerator.getInstance( KeyProperties.KEY_ALGORITHM_AES, ANDROID_KEYSTORE ) keyGenerator.init(keyGenParams) return keyGenerator.generateKey() } override fun persistCiphertextWrapperToSharedPrefs( ciphertextWrapper: CiphertextWrapper, context: Context, filename: String, mode: Int, prefKey: String ) { val json = JsonX.toJson(ciphertextWrapper) context.getSharedPreferences(filename, mode).edit().putString(prefKey, json).apply() } override fun getCiphertextWrapperFromSharedPrefs( context: Context, filename: String, mode: Int, prefKey: String ): CiphertextWrapper? { var json = context.getSharedPreferences(filename, mode).getString(prefKey, null) ?: return null // 处理 kotlinx.serialization.Json 和 Gson 的差异 json = json.replace("ciphertext", "a").replace("initializationVector", "b") return JsonX.fromJson(json, CiphertextWrapper::class.java) } override fun clearCiphertextWrapperFromSharedPrefs( ctx: Context, filename: String, modePrivate: Int, username: String ) { ctx.getSharedPreferences(filename, modePrivate).edit().remove(username).apply() } }
Transtation-KMP/base-kmp/src/androidMain/kotlin/com/funny/translation/helper/biomertic/CryptographyManager.android.kt
3356122361
package com.funny.translation.helper.biomertic import android.content.Context import android.os.Build import androidx.annotation.RequiresApi import androidx.appcompat.app.AppCompatActivity import androidx.biometric.BiometricManager import androidx.biometric.BiometricPrompt import com.funny.translation.AppConfig import com.funny.translation.helper.Log import com.funny.translation.helper.UserUtils import com.funny.translation.helper.awaitDialog import com.funny.translation.helper.handler.runOnUI import com.funny.translation.kmp.KMPActivity import com.funny.translation.kmp.appCtx import com.funny.translation.kmp.base.strings.ResStrings import com.funny.translation.kmp.toastOnUi import com.funny.translation.network.ServiceCreator import com.funny.translation.network.api import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext @RequiresApi(Build.VERSION_CODES.M) actual object BiometricUtils { private const val TAG = "BiometricUtils" private const val SHARED_PREFS_FILENAME = "biometric_prefs_v2" const val CIPHERTEXT_WRAPPER = "ciphertext_wrapper" private const val SECRET_KEY = "trans_key" // 用于注册时临时保存当前的指纹数据 actual var tempSetFingerPrintInfo = FingerPrintInfo() actual var tempSetUserName = "" actual val fingerPrintService by lazy(LazyThreadSafetyMode.PUBLICATION) { ServiceCreator.create(FingerPrintService::class.java) } private val biometricManager by lazy { BiometricManager.from(appCtx) } actual val cryptographyManager = CryptographyManager() private val scope by lazy { CoroutineScope(Dispatchers.IO) } actual fun checkBiometricAvailable(): String = when (biometricManager.canAuthenticate( BiometricManager.Authenticators.BIOMETRIC_STRONG )) { BiometricManager.BIOMETRIC_SUCCESS -> "" BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE -> ResStrings.err_no_fingerprint_device BiometricManager.BIOMETRIC_ERROR_HW_UNAVAILABLE -> ResStrings.err_fingerprint_not_enabled BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED -> ResStrings.err_no_fingerprint else -> ResStrings.unknown_error } actual fun init() { } actual suspend fun uploadFingerPrint(username: String) = withContext(Dispatchers.IO){ fingerPrintService.saveFingerPrintInfo( username = username, did = AppConfig.androidId, encryptedInfo = tempSetFingerPrintInfo.encrypted_info, iv = tempSetFingerPrintInfo.iv, ) } // 设置指纹信息,相关内容会暂存,等到注册时提交 actual fun setFingerPrint( activity: KMPActivity, username: String, did: String, onNotSupport: (msg: String) -> Unit, onSuccess: (String, String) -> Unit, onUsePassword: () -> Unit, onFail: () -> Unit, onError: (errorCode: Int, errString: CharSequence) -> Unit ) { val error = checkBiometricAvailable() if (error != "") { onNotSupport(error) return } val secretKeyName = SECRET_KEY try { val cipher = cryptographyManager.getInitializedCipherForEncryption(secretKeyName) val biometricPrompt = BiometricPromptUtils.createBiometricPrompt(activity, authSuccess = { authResult -> authResult.cryptoObject?.cipher?.apply { val encryptedServerTokenWrapper = cryptographyManager.encryptData("$username@$did", this) val ei = encryptedServerTokenWrapper.ciphertext.joinToString(",") val iv = encryptedServerTokenWrapper.initializationVector.joinToString(",") cryptographyManager.persistCiphertextWrapperToSharedPrefs( encryptedServerTokenWrapper, appCtx, SHARED_PREFS_FILENAME, Context.MODE_PRIVATE, username ) tempSetFingerPrintInfo.iv = iv tempSetFingerPrintInfo.encrypted_info = ei tempSetUserName = username onSuccess(ei, iv) } }, authError = { errorCode: Int, errString: String -> if (errorCode == BiometricPrompt.ERROR_NEGATIVE_BUTTON) { onUsePassword() } else { onError(errorCode, errString) } }, onFail) ?: return val promptInfo = BiometricPromptUtils.createPromptInfo() runOnUI { biometricPrompt.authenticate(promptInfo, BiometricPrompt.CryptoObject(cipher)) } }catch (e: Exception){ e.printStackTrace() onFail() } } actual fun validateFingerPrint( activity: KMPActivity, username: String, did: String, onNotSupport: (msg: String) -> Unit, onSuccess: (String, String) -> Unit, onFail: () -> Unit, onUsePassword: () -> Unit, onError: (errorCode: Int, errString: CharSequence) -> Unit, // 新设备登录时回调 onNewFingerPrint: (email: String) -> Unit ) { val error = checkBiometricAvailable() if (error != "") { onNotSupport(error) return } val ciphertextWrapper = cryptographyManager.getCiphertextWrapperFromSharedPrefs( appCtx, SHARED_PREFS_FILENAME, Context.MODE_PRIVATE, username ) if (ciphertextWrapper == null) { scope.launch(Dispatchers.IO) { val email = api(UserUtils.userService::getUserEmail, username) if (email == null || email == ""){ activity.toastOnUi(ResStrings.not_registered) return@launch } if (activity !is AppCompatActivity) return@launch if (awaitDialog( activity, ResStrings.hint, ResStrings.tip_reset_fingerprint.format( username, UserUtils.anonymousEmail(email) ), ResStrings.confirm, ResStrings.cancel, ) ) { setFingerPrint( activity, username, did, onSuccess = { encryptedInfo, iv -> onSuccess(encryptedInfo, iv) onNewFingerPrint(email) }, onFail = { onError(-2, ResStrings.validate_fingerprint_failed) }, onError = onError, onUsePassword = onUsePassword ) } } } else { val secretKeyName = SECRET_KEY try { val cipher = cryptographyManager.getInitializedCipherForDecryption( secretKeyName, ciphertextWrapper.initializationVector ) val biometricPrompt = BiometricPromptUtils.createBiometricPrompt( activity, authSuccess = { authResult -> authResult.cryptoObject?.cipher?.let { val plaintext = cryptographyManager.decryptData(ciphertextWrapper.ciphertext, it) Log.d(TAG, "validateFingerPrint: plainText: $plaintext") // SampleAppUser.fakeToken = plaintext // Now that you have the token, you can query server for everything else // the only reason we call this fakeToken is because we didn't really get it from // the server. In your case, you will have gotten it from the server the first time // and therefore, it's a real token. onSuccess( ciphertextWrapper.ciphertext.joinToString(","), ciphertextWrapper.initializationVector.joinToString(",") ) } }, authError = { errorCode, errString -> if (errorCode == BiometricPrompt.ERROR_NEGATIVE_BUTTON) { onUsePassword() } else { onError(errorCode, errString) } }, onFail ) ?: return val promptInfo = BiometricPromptUtils.createPromptInfo() runOnUI { biometricPrompt.authenticate(promptInfo, BiometricPrompt.CryptoObject(cipher)) } }catch (e: Exception){ e.printStackTrace() onFail() } } } actual fun clearFingerPrintInfo(username: String){ tempSetFingerPrintInfo = FingerPrintInfo() tempSetUserName = "" cryptographyManager.clearCiphertextWrapperFromSharedPrefs( appCtx, SHARED_PREFS_FILENAME, android.content.Context.MODE_PRIVATE, username ) } }
Transtation-KMP/base-kmp/src/androidMain/kotlin/com/funny/translation/helper/biomertic/BiometricUtils.android.kt
1670415559
/* * Copyright (C) 2020 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.funny.translation.helper.biomertic import androidx.appcompat.app.AppCompatActivity import androidx.biometric.BiometricPrompt import androidx.core.content.ContextCompat import com.funny.translation.helper.Log import com.funny.translation.kmp.KMPActivity import com.funny.translation.kmp.base.strings.ResStrings // Since we are using the same methods in more than one Activity, better give them their own file. object BiometricPromptUtils { private const val TAG = "BiometricPromptUtils" fun createBiometricPrompt( activity: KMPActivity, authSuccess: (BiometricPrompt.AuthenticationResult) -> Unit, authError: (errCode: Int, errString: String) -> Unit, authFail: () -> Unit ): BiometricPrompt? { if (activity !is AppCompatActivity) return null val executor = ContextCompat.getMainExecutor(activity) val callback = object : BiometricPrompt.AuthenticationCallback() { override fun onAuthenticationError(errCode: Int, errString: CharSequence) { super.onAuthenticationError(errCode, errString) Log.d(TAG, "errCode is $errCode and errString is: $errString") authError(errCode, errString.toString()) } override fun onAuthenticationFailed() { super.onAuthenticationFailed() Log.d(TAG, "Biometric authentication failed for unknown reason.") authFail() } override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) { super.onAuthenticationSucceeded(result) Log.d(TAG, "Authentication was successful") authSuccess(result) } } return BiometricPrompt(activity, executor, callback) } fun createPromptInfo(): BiometricPrompt.PromptInfo = BiometricPrompt.PromptInfo.Builder() .setTitle(ResStrings.validate_fingerprint) .setSubtitle(ResStrings.please_touch_fingerprint) .setNegativeButtonText(ResStrings.use_password) .build() }
Transtation-KMP/base-kmp/src/androidMain/kotlin/com/funny/translation/helper/biomertic/BiometricPromptUtils.kt
3859280032
package com.funny.translation.helper import android.content.Context import android.content.Intent import android.net.Uri import android.widget.Toast import com.funny.translation.helper.handler.runOnUI import com.funny.translation.kmp.base.strings.ResStrings import com.funny.translation.kmp.readAssetsFile import com.hjq.toast.Toaster actual fun Context.readAssets(fileName: String): String = readAssetsFile(fileName) actual fun Context.openUrl(url: String) { openUrl(Uri.parse(url)) } fun Context.openUrl(uri: Uri) { val intent = Intent(Intent.ACTION_VIEW) intent.data = uri try { startActivity(intent) } catch (e: Exception) { try { startActivity(Intent.createChooser(intent, ResStrings.please_choose_browser)) } catch (e: Exception) { toastOnUi(e.localizedMessage ?: "open url error") } } } actual inline fun Context.toastOnUi(message: Int, length: Int) { toastOnUi(getString(message), length) } // 内联以使得框架能够获取到调用的真正位置 actual inline fun Context.toastOnUi(message: CharSequence?, length: Int) { runOnUI { if (length == Toast.LENGTH_SHORT) { Toaster.showShort(message) } else { Toaster.showLong(message) } } }
Transtation-KMP/base-kmp/src/androidMain/kotlin/com/funny/translation/helper/ContextExtentions.android.kt
3164733306
/* * Copyright (C) 2005-2017 Qihoo 360 Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed To in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.funny.translation.helper import android.content.Context import android.content.pm.PackageManager import android.content.res.AssetManager import android.os.Build import android.text.TextUtils import java.lang.reflect.Method /** * @author RePlugin Team */ // https://github.com/Qihoo360/RePlugin object WebViewResourceHelper { private var sInitialed = false fun addChromeResourceIfNeeded(context: Context): Boolean { if (sInitialed) { return true } val dir = getWebViewResourceDir(context) if (TextUtils.isEmpty(dir)) { return false } try { val m = addAssetPathMethod if (m != null) { val ret = m.invoke(context.assets, dir) as Int sInitialed = ret > 0 return sInitialed } } catch (e: Exception) { e.printStackTrace() } return false } private val addAssetPathMethod: Method? private get() { var m: Method? = null val c: Class<*> = AssetManager::class.java if (Build.VERSION.SDK_INT >= 24) { try { m = c.getDeclaredMethod("addAssetPathAsSharedLibrary", String::class.java) m.isAccessible = true } catch (e: NoSuchMethodException) { // Do Nothing e.printStackTrace() } return m } try { m = c.getDeclaredMethod("addAssetPath", String::class.java) m.isAccessible = true } catch (e: NoSuchMethodException) { // Do Nothing e.printStackTrace() } return m } private fun getWebViewResourceDir(context: Context): String? { val pkgName = webViewPackageName if (TextUtils.isEmpty(pkgName)) { return null } try { val pi = context.packageManager.getPackageInfo( webViewPackageName!!, PackageManager.GET_SHARED_LIBRARY_FILES ) return pi.applicationInfo.sourceDir } catch (e: PackageManager.NameNotFoundException) { e.printStackTrace() } catch (e: Exception) { // Do Nothing } return null } private val webViewPackageName: String? private get() { val sdk = Build.VERSION.SDK_INT return if (sdk <= 20) { null } else when (sdk) { 21, 22 -> webViewPackageName4Lollipop 23 -> webViewPackageName4M 24 -> webViewPackageName4N 25 -> webViewPackageName4More else -> webViewPackageName4More } } private val webViewPackageName4Lollipop: String? private get() { try { return ReflectUtil.invokeStaticMethod( "android.webkit.WebViewFactory", "getWebViewPackageName", null ) as String } catch (e: Throwable) { // } return "com.google.android.webview" } private val webViewPackageName4M: String? private get() = webViewPackageName4Lollipop private val webViewPackageName4N: String private get() { try { val c = ReflectUtil.invokeStaticMethod( "android.webkit.WebViewFactory", "getWebViewContextAndSetProvider", null ) as Context return c.applicationInfo.packageName } catch (e: Throwable) { // } return "com.google.android.webview" } private val webViewPackageName4More: String private get() = webViewPackageName4N }
Transtation-KMP/base-kmp/src/androidMain/kotlin/com/funny/translation/helper/WebViewResourceHelper.kt
1742451005
/* * Copyright (C) 2005-2017 Qihoo 360 Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed To in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.funny.translation.helper import java.lang.reflect.Field /** * @author RePlugin Team */ // https://github.com/Qihoo360/RePlugin object ReflectUtil { private const val TAG = "ReflectUtil" fun invokeStaticMethod( clzName: String?, methodName: String?, methodParamTypes: Array<Class<*>?>?, vararg methodParamValues: Any? ): Any? { try { val clz = Class.forName(clzName) if (clz != null && methodParamTypes != null) { val med = clz.getDeclaredMethod(methodName, *methodParamTypes) if (med != null) { med.isAccessible = true return med.invoke(null, *methodParamValues) } } } catch (e: Exception) { e.printStackTrace() } return null } fun invokeMethod( clzName: String?, methodName: String?, methodReceiver: Any?, methodParamTypes: Array<Class<*>?>, vararg methodParamValues: Any? ): Any? { try { if (methodReceiver == null) { return null } val clz = Class.forName(clzName) if (clz != null) { val med = clz.getDeclaredMethod(methodName, *methodParamTypes) if (med != null) { med.isAccessible = true return med.invoke(methodReceiver, *methodParamValues) } } } catch (e: Exception) { e.printStackTrace() } return null } fun getStaticField(clzName: String?, filedName: String?): Any? { try { var field: Field? = null val clz = Class.forName(clzName) if (clz != null) { field = clz.getField(filedName) if (field != null) { return field[""] } } } catch (e: Exception) { e.printStackTrace() } return null } fun getField(clzName: String?, obj: Any?, filedName: String?): Any? { try { if (obj == null) { return null } val clz = Class.forName(clzName) if (clz != null) { val field = clz.getField(filedName) if (field != null) { return field[obj] } } } catch (e: Exception) { e.printStackTrace() } return null } }
Transtation-KMP/base-kmp/src/androidMain/kotlin/com/funny/translation/helper/ReflectUtil.kt
1550570446
package com.funny.translation.helper import com.funny.translation.kmp.appCtx import java.io.File actual object CacheManager { private val ctx get() = appCtx actual var cacheDir: File = ctx.externalCacheDir ?: ctx.cacheDir val innerCacheDir: File = ctx.cacheDir }
Transtation-KMP/base-kmp/src/androidMain/kotlin/com/funny/translation/helper/CacheManager.android.kt
3634261069
package com.funny.translation.helper import com.eygraber.uri.Uri import com.funny.translation.kmp.KMPContext import okhttp3.MultipartBody import okhttp3.RequestBody.Companion.toRequestBody actual suspend fun UserUtils.uploadUserAvatar( context: KMPContext, imgUri: Uri, filename: String, width: Int, height: Int, uid: Int ): String { try { val data = BitmapUtil.getBitmapFromUri(context, TARGET_AVATAR_SIZE, TARGET_AVATAR_SIZE, 1024 * 100, imgUri) ?: return "" val body = MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("uid", uid.toString()) .addFormDataPart("avatar", filename, data.toRequestBody()) .build() val response = userService.uploadAvatar(body) if (response.code == 50){ return response.data ?: "" } }catch (e: Exception){ e.printStackTrace() } return "" }
Transtation-KMP/base-kmp/src/androidMain/kotlin/com/funny/translation/helper/UserUtils.android.kt
1606616116
package com.funny.translation import android.annotation.SuppressLint import android.provider.Settings import com.funny.translation.kmp.appCtx @SuppressLint("HardwareIds") internal actual fun getDid(): String { return Settings.Secure.getString(appCtx.contentResolver, Settings.Secure.ANDROID_ID) ?: "" } internal actual fun getVersionName(): String { return appCtx.packageManager.getPackageInfo(appCtx.packageName, 0).versionName } internal actual fun getVersionCode(): Int { return appCtx.packageManager.getPackageInfo(appCtx.packageName, 0).versionCode ?: 0 }
Transtation-KMP/base-kmp/src/androidMain/kotlin/com/funny/translation/AppConfig.android.kt
3435004269
package com.funny.data_saver.mmkv import android.os.Parcelable import com.funny.data_saver.core.DataSaverInterface import com.tencent.mmkv.MMKV open class DataSaverMMKV( val kv: MMKV, senseExternalDataChange: Boolean = false ) : DataSaverInterface(senseExternalDataChange) { // MMKV doesn't support listener, so we manually notify the listener private fun notifyExternalDataChanged(key: String, value: Any?) { if (senseExternalDataChange) externalDataChangedFlow?.tryEmit(key to value) } override fun <T> saveData(key: String, data: T) { if (data == null){ remove(key) notifyExternalDataChanged(key, null) return } with(kv) { when (data) { is Long -> encode(key, data) is Int -> encode(key, data) is String -> encode(key, data) is Boolean -> encode(key, data) is Float -> encode(key, data) is Double -> encode(key, data) is Parcelable -> encode(key, data) is ByteArray -> encode(key, data) else -> throwError("save", data) } notifyExternalDataChanged(key, data) } } override fun <T> readData(key: String, default: T): T = with(kv) { val res: Any = when (default) { is Long -> decodeLong(key, default) is Int -> decodeInt(key, default) is String -> decodeString(key, default)!! is Boolean -> decodeBool(key, default) is Float -> decodeFloat(key, default) is Double -> decodeDouble(key, default) is Parcelable -> decodeParcelable(key, (default as Parcelable)::class.java) ?: default is ByteArray -> decodeBytes(key, default)!! else -> throwError("read", default) } return@with res as T } override fun remove(key: String) { kv.removeValueForKey(key) notifyExternalDataChanged(key, null) } override fun contains(key: String) = kv.containsKey(key) } val DefaultDataSaverMMKV by lazy(LazyThreadSafetyMode.PUBLICATION) { DataSaverMMKV(MMKV.defaultMMKV()) }
Transtation-KMP/base-kmp/src/androidMain/kotlin/com/funny/data_saver/mmkv/DataSaverMMKV.kt
1903954547
package com.funny.trans.login.ui import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.material3.Button import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.buildAnnotatedString import androidx.compose.ui.text.withStyle import androidx.compose.ui.unit.dp import com.funny.translation.AppConfig import com.funny.translation.helper.UserUtils import com.funny.translation.kmp.NavController import com.funny.translation.login.strings.ResStrings import com.funny.translation.network.api import com.funny.translation.ui.CommonPage import kotlinx.coroutines.launch import java.util.Date @Composable fun ChangeUsernamePage(navController: NavController) { CommonPage { val user by AppConfig.userInfo var username by remember { mutableStateOf(user.username) } val canChangeUsername by remember { derivedStateOf { user.canChangeUsername() } } val nextChangeUsernameString = remember(user) { user.nextChangeUsernameTimeStr() } val scope = rememberCoroutineScope() Column( Modifier.fillMaxWidth(WIDTH_FRACTION), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center, ) { InputUsername( usernameProvider = { username }, updateUsername = { username = it }, isValidUsernameProvider = { UserUtils.isValidUsername(username) } ) Spacer(modifier = Modifier.height(8.dp)) if (canChangeUsername) { Button(onClick = { scope.launch { api(UserUtils.userService::changeUsername, user.uid, username) { addSuccess { AppConfig.userInfo.value = user.copy(username = username, lastChangeUsernameTime = Date()) navController.popBackStack() } } } }) { Text(text = ResStrings.confirm_to_modify) } } else { // 您每 30 天可以修改一次用户名 Text(text = buildAnnotatedString { append(ResStrings.change_username_tip) withStyle(SpanStyle(color = MaterialTheme.colorScheme.primary)) { append(nextChangeUsernameString) } }) } } } }
Transtation-KMP/login/src/commonMain/kotlin/com/funny/trans/login/ui/ChangeUsernamePage.kt
21352535
@file:OptIn(ExperimentalMaterial3Api::class) package com.funny.trans.login.ui import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.material3.AlertDialog import androidx.compose.material3.Button import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import com.funny.translation.AppConfig import com.funny.translation.kmp.LocalKMPContext import com.funny.translation.kmp.NavController import com.funny.translation.kmp.NavHostController import com.funny.translation.kmp.viewModel import com.funny.translation.login.strings.ResStrings import com.funny.translation.ui.CommonPage import com.funny.translation.ui.MarkdownText @Composable fun CancelAccountPage( navController: NavHostController ) { CommonPage { val vm = viewModel<LoginViewModel>() val context = LocalKMPContext.current SideEffect { AppConfig.userInfo.value.takeIf { it.isValid() }?.let { vm.email = it.email vm.username = it.username } } TipDialog(navController) Spacer(modifier = Modifier.height(60.dp)) Column(Modifier.fillMaxWidth(WIDTH_FRACTION)) { InputUsername( usernameProvider = vm::username, updateUsername = vm::updateUsername, isValidUsernameProvider = vm::isValidUsername ) Spacer(modifier = Modifier.height(8.dp)) InputEmail( modifier = Modifier.fillMaxWidth(), value = vm.email, onValueChange = { vm.email = it }, isError = vm.email != "" && !vm.isValidEmail, verifyCode = vm.verifyCode, onVerifyCodeChange = { vm.verifyCode = it }, initialSent = false, onClick = { vm.sendCancelAccountEmail(context) } ) Spacer(modifier = Modifier.height(8.dp)) val enable by remember { derivedStateOf { vm.isValidUsername && vm.isValidEmail && vm.verifyCode.length == 6 } } Button(modifier = Modifier.fillMaxWidth(), onClick = { vm.cancelAccount { AppConfig.logout() navController.popBackStack() // 账号详情 navController.popBackStack() // 主页 } }, enabled = enable) { Text(text = ResStrings.confirm_cancel) } } } } @Composable fun TipDialog(navController: NavController) { var showTipDialog by remember { mutableStateOf(true) } if (showTipDialog) { AlertDialog( onDismissRequest = { }, title = { Text(ResStrings.warning) }, text = { MarkdownText(ResStrings.cancel_account_tip) }, confirmButton = { CountDownTimeButton( modifier = Modifier, onClick = { showTipDialog = false }, text = ResStrings.confirm, initialSent = true, countDownTime = 10 ) }, dismissButton = { TextButton(onClick = { showTipDialog = false navController.popBackStack() }) { Text(ResStrings.cancel) } } ) } }
Transtation-KMP/login/src/commonMain/kotlin/com/funny/trans/login/ui/CancelAccountPage.kt
2540714350
package com.funny.trans.login.ui import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material3.Button import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.unit.dp import com.funny.translation.AppConfig import com.funny.translation.helper.UserUtils import com.funny.translation.helper.toastOnUi import com.funny.translation.kmp.LocalKMPContext import com.funny.translation.kmp.NavController import com.funny.translation.kmp.viewModel import com.funny.translation.login.strings.ResStrings import com.funny.translation.ui.CommonPage import com.funny.translation.ui.TransparentTopBar @Composable fun ResetPasswordPage( navController: NavController ) { CommonPage( topBar = { TransparentTopBar() } ) { val vm = viewModel<LoginViewModel>() val context = LocalKMPContext.current SideEffect { AppConfig.userInfo.value.takeIf { it.isValid() }?.let { vm.email = it.email vm.username = it.username } } Spacer(modifier = Modifier.height(60.dp)) Column(Modifier.fillMaxWidth(WIDTH_FRACTION)) { InputUsername( usernameProvider = vm::username, updateUsername = vm::updateUsername, isValidUsernameProvider = vm::isValidUsername ) Spacer(modifier = Modifier.height(8.dp)) InputEmail( modifier = Modifier.fillMaxWidth(), value = vm.email, onValueChange = { vm.email = it }, isError = vm.email != "" && !vm.isValidEmail, verifyCode = vm.verifyCode, onVerifyCodeChange = { vm.verifyCode = it }, initialSent = false, onClick = { vm.sendResetPasswordEmail(context) } ) Spacer(modifier = Modifier.height(8.dp)) InputPassword( passwordProvider = vm::password, updatePassword = vm::updatePassword, labelText = ResStrings.new_password ) // 重复密码 var repeatPassword by remember { mutableStateOf("") } val isRepeatPwdError by remember { derivedStateOf { vm.password != repeatPassword } } Spacer(modifier = Modifier.height(8.dp)) ConcealableTextField( value = repeatPassword, onValueChange = { repeatPassword = it }, modifier = Modifier.fillMaxWidth(), isError = isRepeatPwdError, label = { Text(ResStrings.repeat_password) }, keyboardOptions = KeyboardOptions( keyboardType = KeyboardType.Password, imeAction = ImeAction.Done ) ) Spacer(modifier = Modifier.height(8.dp)) val enable by remember { derivedStateOf { vm.isValidUsername && vm.isValidEmail && vm.verifyCode.length == 6 && UserUtils.isValidPassword( vm.password ) && vm.password == repeatPassword } } Button(modifier = Modifier.fillMaxWidth(), onClick = { vm.resetPassword(context, onSuccess = { context.toastOnUi("密码重置成功!") navController.popBackStack() }) }, enabled = enable) { Text(text = ResStrings.reset_password) } } } }
Transtation-KMP/login/src/commonMain/kotlin/com/funny/trans/login/ui/ResetPasswordPage.kt
996000375
package com.funny.trans.login.ui import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import com.funny.translation.AppConfig import com.funny.translation.bean.UserInfoBean import com.funny.translation.helper.Context import com.funny.translation.helper.SignUpException import com.funny.translation.helper.UserUtils import com.funny.translation.helper.biomertic.BiometricUtils import com.funny.translation.helper.displayMsg import com.funny.translation.helper.toastOnUi import com.funny.translation.kmp.appCtx import com.funny.translation.login.strings.ResStrings import com.funny.translation.network.api import kotlinx.coroutines.launch import moe.tlaster.precompose.viewmodel.ViewModel import moe.tlaster.precompose.viewmodel.viewModelScope const val PASSWORD_TYPE_FINGERPRINT = "1" const val PASSWORD_TYPE_PASSWORD = "2" expect val supportBiometric: Boolean class LoginViewModel : ViewModel() { var username by mutableStateOf("") var password by mutableStateOf("") var email by mutableStateOf("") // 为了保护隐私,当从远程获取到邮箱时,需要隐藏邮箱 var secureEmail by mutableStateOf(false) val displayEmail by derivedStateOf { if (secureEmail) { UserUtils.anonymousEmail(email) } else email } var verifyCode by mutableStateOf("") var inviteCode by mutableStateOf("") val isValidUsername by derivedStateOf { UserUtils.isValidUsername(username) } val isValidEmail by derivedStateOf { UserUtils.isValidEmail(email) } val isValidInviteCode by derivedStateOf { UserUtils.isValidInviteCode(inviteCode) } var finishSetFingerPrint by mutableStateOf(false) var finishValidateFingerPrint by mutableStateOf(false) // 1 -> 指纹 // 2 -> 密码 var passwordType by mutableStateOf(if(!supportBiometric) PASSWORD_TYPE_PASSWORD else PASSWORD_TYPE_FINGERPRINT) // 当在新设备登录时,需要验证邮箱 var shouldVerifyEmailWhenLogin by mutableStateOf(false) var encryptedInfo = "" var iv = "" private val userService = UserUtils.userService private fun clearData(){ email = "" verifyCode = "" finishSetFingerPrint = false finishValidateFingerPrint = false encryptedInfo = "" iv = "" } fun login( onSuccess: (UserInfoBean) -> Unit, onError: (String) -> Unit ){ viewModelScope.launch { try { val userBean = if (passwordType == PASSWORD_TYPE_FINGERPRINT){ UserUtils.login(username, "${AppConfig.androidId}#$encryptedInfo#$iv", passwordType, email, if(shouldVerifyEmailWhenLogin) verifyCode else "") } else { UserUtils.login(username, password, passwordType, email, "") } if (userBean != null) { onSuccess(userBean) }else{ onError(ResStrings.login_failed_empty_result) } } catch (e: Exception) { e.printStackTrace() onError(e.displayMsg(ResStrings.login)) } } } fun register( onSuccess: () -> Unit, onError: (String) -> Unit ){ val successAction = { onSuccess() clearData() } viewModelScope.launch { try { if (passwordType == PASSWORD_TYPE_FINGERPRINT){ if(supportBiometric && BiometricUtils.tempSetUserName != username) throw SignUpException(ResStrings.different_fingerprint) UserUtils.register(username, "${AppConfig.androidId}#$encryptedInfo#$iv", passwordType, email, verifyCode, "", inviteCode, successAction) } else { UserUtils.register(username, password, passwordType, email, verifyCode, "", inviteCode, successAction) } } catch (e: Exception) { e.printStackTrace() onError(e.displayMsg(ResStrings.register)) } } } fun sendVerifyEmail(context: Context){ viewModelScope.launch { api(userService::sendVerifyEmail, username, email) { error { context.toastOnUi(ResStrings.error_sending_email) } } } } fun sendResetPasswordEmail(context: Context){ viewModelScope.launch { api(userService::sendResetPasswordEmail, username, email) { error { context.toastOnUi(ResStrings.error_sending_email) } } } } fun sendFindUsernameEmail(context: Context){ viewModelScope.launch { api(userService::sendFindUsernameEmail, email) { error { context.toastOnUi(ResStrings.error_sending_email) } } } } fun sendCancelAccountEmail(context: Context){ viewModelScope.launch { api(userService::sendCancelAccountEmail, username, email) { error { context.toastOnUi(ResStrings.error_sending_email) } } } } fun resetPassword(context: Context, onSuccess: () -> Unit){ viewModelScope.launch { api(userService::resetPassword, username, password, verifyCode) { error { context.toastOnUi(ResStrings.reset_password_failed) } success { onSuccess() } } } } fun resetFingerprint() { finishSetFingerPrint = false finishValidateFingerPrint = false encryptedInfo = "" iv = "" if (supportBiometric) { BiometricUtils.clearFingerPrintInfo(username) } appCtx.toastOnUi(ResStrings.reset_fingerprint_success) } fun findUsername(onSuccess: (List<String>) -> Unit){ viewModelScope.launch { api(userService::findUsername, email, verifyCode) { success { onSuccess(it.data ?: emptyList()) } } } } fun cancelAccount(onSuccess: () -> Unit){ viewModelScope.launch { api(userService::cancelAccount, verifyCode) { addSuccess { onSuccess() } } } } fun updateUsername(s: String) { username = s } fun updatePassword(s: String) { password = s } }
Transtation-KMP/login/src/commonMain/kotlin/com/funny/trans/login/ui/LoginViewModel.kt
848649124
package com.funny.trans.login.ui import androidx.compose.animation.AnimatedContent import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.text.KeyboardActions import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedButton import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.input.PasswordVisualTransformation import androidx.compose.ui.text.input.VisualTransformation import androidx.compose.ui.unit.dp import com.funny.translation.helper.UserUtils import com.funny.translation.helper.rememberStateOf import com.funny.translation.kmp.painterDrawableRes import com.funny.translation.login.strings.ResStrings import com.funny.translation.ui.FixedSizeIcon import org.jetbrains.compose.resources.ExperimentalResourceApi @Composable fun InputUsername( usernameProvider: () -> String, updateUsername: (String) -> Unit, isValidUsernameProvider: () -> Boolean, imeAction: ImeAction = ImeAction.Next ) { val username = usernameProvider() val isValidUsername = isValidUsernameProvider() OutlinedTextField( modifier = Modifier.fillMaxWidth(), value = username, onValueChange = updateUsername, isError = username != "" && !isValidUsername, label = { Text(text = ResStrings.username) }, placeholder = { Text(ResStrings.username_rule) }, singleLine = true, keyboardOptions = KeyboardOptions( keyboardType = KeyboardType.Text, imeAction = imeAction ), ) } @Composable fun InputPassword( passwordProvider: () -> String, updatePassword: (String) -> Unit, labelText: String = ResStrings.password, ) { val password = passwordProvider() val isPwdError by remember(password) { derivedStateOf { password != "" && !UserUtils.isValidPassword(password) } } ConcealableTextField(modifier = Modifier.fillMaxWidth(), value = password, onValueChange = updatePassword, placeholder = { Text(text = ResStrings.password_rule) }, label = { Text(text = labelText) }, isError = isPwdError, keyboardOptions = KeyboardOptions( keyboardType = KeyboardType.Password, imeAction = ImeAction.Next ), ) } @OptIn(ExperimentalResourceApi::class) @Composable fun ConcealableTextField( modifier: Modifier = Modifier, value: String, onValueChange: (String) -> Unit, label: @Composable (() -> Unit)? = null, placeholder: @Composable (() -> Unit)? = null, leadingIcon: @Composable (() -> Unit)? = null, prefix: @Composable (() -> Unit)? = null, isError: Boolean = false, keyboardOptions: KeyboardOptions = KeyboardOptions.Default, keyboardActions: KeyboardActions = KeyboardActions.Default, ) { var hiddenInput by rememberStateOf(value = true) OutlinedTextField( modifier = modifier, value = value, onValueChange = onValueChange, enabled = true, placeholder = placeholder, leadingIcon = leadingIcon, prefix = prefix, label = label, trailingIcon = { AnimatedContent(hiddenInput, label = "hidden_input_icon") { if (it) { FixedSizeIcon( painterDrawableRes("ic_hidden_password"), contentDescription = ResStrings.click_to_show_password, modifier = Modifier .padding(end = 4.dp) .clickable { hiddenInput = false }, tint = MaterialTheme.colorScheme.primary ) } else { FixedSizeIcon( painterDrawableRes("ic_show_password"), contentDescription = ResStrings.click_to_hide_password, modifier = Modifier .padding(end = 4.dp) .clickable { hiddenInput = true }, tint = MaterialTheme.colorScheme.primary ) } } }, isError = isError, keyboardOptions = keyboardOptions, keyboardActions = keyboardActions, visualTransformation = if (hiddenInput) PasswordVisualTransformation('*') else VisualTransformation.None ) } @OptIn(ExperimentalResourceApi::class) @Composable fun CompletableButton( modifier: Modifier, enabled: Boolean, onClick: () -> Unit, completed: Boolean = false, text: @Composable () -> Unit ) { OutlinedButton(onClick = onClick, modifier = modifier, enabled = enabled) { text() if (completed) FixedSizeIcon( painterDrawableRes("ic_finish"), contentDescription = ResStrings.finished, modifier = Modifier.padding(start = 4.dp), tint = MaterialTheme.colorScheme.primary ) } }
Transtation-KMP/login/src/commonMain/kotlin/com/funny/trans/login/ui/CommonComposable.kt
3505305330
package com.funny.trans.login.ui import androidx.compose.animation.core.Animatable import androidx.compose.animation.core.Spring import androidx.compose.animation.core.spring import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.IntrinsicSize import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.imePadding import androidx.compose.foundation.layout.navigationBarsPadding import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.padding import androidx.compose.foundation.pager.HorizontalPager import androidx.compose.foundation.pager.rememberPagerState import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.foundation.verticalScroll import androidx.compose.material3.Button import androidx.compose.material3.Checkbox import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Tab import androidx.compose.material3.TabRow import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.material3.contentColorFor import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.funny.translation.AppConfig import com.funny.translation.bean.UserInfoBean import com.funny.translation.helper.SimpleAction import com.funny.translation.helper.UserUtils import com.funny.translation.helper.VibratorUtils import com.funny.translation.helper.biomertic.BiometricUtils import com.funny.translation.helper.toastOnUi import com.funny.translation.kmp.KMPActivity import com.funny.translation.kmp.LocalKMPContext import com.funny.translation.kmp.NavController import com.funny.translation.kmp.viewModel import com.funny.translation.login.strings.ResStrings import com.funny.translation.network.api import com.funny.translation.ui.MarkdownText import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlin.math.roundToInt internal const val WIDTH_FRACTION = 0.8f @OptIn(ExperimentalFoundationApi::class) @Composable fun LoginPage( navController: NavController, onLoginSuccess: (UserInfoBean) -> Unit, ) { val vm: LoginViewModel = viewModel() Column( Modifier .fillMaxHeight() .imePadding(), horizontalAlignment = Alignment.CenterHorizontally, ) { Spacer(modifier = Modifier.height(24.dp)) val pagerState = rememberPagerState(pageCount = { 2 }) val scope = rememberCoroutineScope() fun changePage(index: Int) = scope.launch { pagerState.animateScrollToPage(index) } TabRow( pagerState.currentPage, modifier = Modifier .fillMaxWidth(WIDTH_FRACTION) .clip(shape = RoundedCornerShape(12.dp)) .background(Color.Transparent), containerColor = Color.Transparent //backgroundColor = Color.Unspecified ) { Tab(pagerState.currentPage == 0, onClick = { changePage(0) }) { Text( ResStrings.login, modifier = Modifier.padding(8.dp), style = MaterialTheme.typography.labelLarge ) } Tab(pagerState.currentPage == 1, onClick = { changePage(1) }) { Text( ResStrings.register, modifier = Modifier.padding(8.dp), style = MaterialTheme.typography.labelLarge ) } } Spacer(modifier = Modifier.height(24.dp)) var privacyGranted by remember { mutableStateOf(false) } val shrinkAnim = remember { Animatable(0f) } val context = LocalKMPContext.current val remindToGrantPrivacyAction = remember { { scope.launch { intArrayOf(20, 0).forEach { shrinkAnim.animateTo(it.toFloat(), spring(Spring.DampingRatioHighBouncy)) } } VibratorUtils.vibrate(70) context.toastOnUi(ResStrings.tip_confirm_privacy_first) } } HorizontalPager( modifier = Modifier .weight(1f) .fillMaxWidth(), state = pagerState, ) { page -> Column(Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally) { when (page) { 0 -> LoginForm( navController, vm, onLoginSuccess = onLoginSuccess, privacyGranted = privacyGranted, remindToGrantPrivacyAction = remindToGrantPrivacyAction ) 1 -> RegisterForm( vm, onRegisterSuccess = { changePage(0) }, privacyGranted = privacyGranted, remindToGrantPrivacyAction = remindToGrantPrivacyAction ) } } } Row( Modifier .padding(8.dp) .offset { IntOffset(0, shrinkAnim.value.roundToInt()) }, horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically, ) { Checkbox(checked = privacyGranted, onCheckedChange = { privacyGranted = it }) MarkdownText( ResStrings.tip_agree_privacy, color = contentColorFor(backgroundColor = MaterialTheme.colorScheme.background).copy( 0.8f ), fontSize = 12.sp ) } Spacer(modifier = Modifier.navigationBarsPadding()) } } @Composable private fun LoginForm( navController: NavController, vm: LoginViewModel, privacyGranted: Boolean = false, onLoginSuccess: (UserInfoBean) -> Unit = {}, remindToGrantPrivacyAction: () -> Unit = {}, ) { val context = LocalKMPContext.current val scope = rememberCoroutineScope() Column( Modifier .fillMaxWidth(WIDTH_FRACTION) .fillMaxHeight() .verticalScroll(rememberScrollState()), horizontalAlignment = Alignment.CenterHorizontally ) { InputUsernameWrapper( vm, if (vm.passwordType == PASSWORD_TYPE_FINGERPRINT) ImeAction.Done else ImeAction.Next ) Spacer(modifier = Modifier.height(12.dp)) if (vm.shouldVerifyEmailWhenLogin) { InputEmailWrapper(modifier = Modifier.fillMaxWidth(), vm = vm, initialSent = true) Spacer(modifier = Modifier.height(12.dp)) } if (vm.passwordType == PASSWORD_TYPE_PASSWORD) { InputPasswordWrapper(vm = vm) } else CompletableButton( onClick = { if (supportBiometric) { BiometricUtils.validateFingerPrint( context as KMPActivity, username = vm.username, did = AppConfig.androidId, onNotSupport = { msg: String -> context.toastOnUi(msg) }, onFail = { context.toastOnUi(ResStrings.validate_fingerprint_failed_unknown_reason) }, onSuccess = { encryptedInfo, iv -> context.toastOnUi(ResStrings.validate_fingerprint_success) vm.finishValidateFingerPrint = true vm.encryptedInfo = encryptedInfo vm.iv = iv }, onError = { errorCode, errorMsg -> context.toastOnUi( ResStrings.validate_fingerprint_failed_with_msg. format(errorCode.toString(), errorMsg.toString()) ) }, onNewFingerPrint = { email -> if (email.isNotEmpty()) { try { scope.launch { vm.shouldVerifyEmailWhenLogin = true vm.email = email vm.secureEmail = true // BiometricUtils.uploadFingerPrint(username = vm.username) api(UserUtils.userService::sendVerifyEmail, vm.username, email) } } catch (e: Exception) { context.toastOnUi(ResStrings.error_sending_email) } } }, onUsePassword = { vm.passwordType = PASSWORD_TYPE_PASSWORD vm.password = "" } ) } else { context.toastOnUi(ResStrings.fingerprint_not_support) vm.passwordType = PASSWORD_TYPE_PASSWORD } }, modifier = Modifier.fillMaxWidth(), enabled = vm.isValidUsername, completed = vm.finishValidateFingerPrint ) { Text(ResStrings.validate_fingerprint) } ExchangePasswordType( passwordType = vm.passwordType, resetFingerprintAction = vm::resetFingerprint ) { vm.passwordType = it } Spacer(modifier = Modifier.height(12.dp)) // 因为下面的表达式变化速度快过UI的变化速度,为了减少重组次数,此处使用 derivedStateOf val enabledLogin by remember { derivedStateOf { if (vm.shouldVerifyEmailWhenLogin) { vm.isValidUsername && vm.finishValidateFingerPrint && vm.isValidEmail && vm.verifyCode.length == 6 } else { when (vm.passwordType) { PASSWORD_TYPE_FINGERPRINT -> vm.isValidUsername && vm.finishValidateFingerPrint PASSWORD_TYPE_PASSWORD -> vm.isValidUsername && UserUtils.isValidPassword(vm.password) else -> false } } } } Button( onClick = { if (!privacyGranted) { remindToGrantPrivacyAction() return@Button } vm.login( onSuccess = { onLoginSuccess(it) }, onError = { msg -> } ) }, modifier = Modifier.fillMaxWidth(), enabled = enabledLogin ) { Text(ResStrings.login) } Spacer(modifier = Modifier.height(12.dp)) Row( modifier = Modifier .fillMaxWidth() .height(IntrinsicSize.Min), horizontalArrangement = Arrangement.SpaceBetween ) { TextButton( onClick = { navController.navigate(LoginRoute.FindUsernamePage.route) } ) { Text(ResStrings.forgot_username) } TextButton( onClick = { navController.navigate(LoginRoute.ResetPasswordPage.route) } ) { Text(ResStrings.forgot_password) } } } } @Composable private fun RegisterForm( vm: LoginViewModel, privacyGranted: Boolean, onRegisterSuccess: () -> Unit = {}, remindToGrantPrivacyAction: () -> Unit, ) { val context = LocalKMPContext.current Column( Modifier .fillMaxWidth(WIDTH_FRACTION) .fillMaxHeight() .verticalScroll(rememberScrollState()), horizontalAlignment = Alignment.CenterHorizontally ) { InputUsernameWrapper(vm) Spacer(modifier = Modifier.height(8.dp)) InputEmailWrapper(modifier = Modifier.fillMaxWidth(), vm = vm) // 邀请码 Spacer(modifier = Modifier.height(8.dp)) OutlinedTextField( modifier = Modifier.fillMaxWidth(), value = vm.inviteCode, onValueChange = { vm.inviteCode = it }, isError = vm.inviteCode != "" && !vm.isValidInviteCode, label = { Text(text = ResStrings.invite_code) }, placeholder = { Text(ResStrings.please_input_invite_code) }, singleLine = true, keyboardOptions = KeyboardOptions( imeAction = ImeAction.Next ) ) Spacer(modifier = Modifier.height(12.dp)) if (vm.passwordType == PASSWORD_TYPE_PASSWORD) { InputPasswordWrapper(vm = vm) Spacer(modifier = Modifier.height(8.dp)) } else { CompletableButton( onClick = { if (supportBiometric) { BiometricUtils.setFingerPrint( context as KMPActivity, username = vm.username, did = AppConfig.androidId, onNotSupport = { msg: String -> context.toastOnUi(msg) }, onFail = { context.toastOnUi(ResStrings.validate_fingerprint_failed_unknown_reason) }, onSuccess = { encryptedInfo, iv -> context.toastOnUi(ResStrings.add_fingerprint_success) vm.finishSetFingerPrint = true vm.encryptedInfo = encryptedInfo vm.iv = iv }, onError = { errorCode, errorMsg -> context.toastOnUi( ResStrings.validate_fingerprint_failed_with_msg.format( errorCode.toString(), errorMsg.toString() ) ) }, onUsePassword = { vm.passwordType = PASSWORD_TYPE_PASSWORD vm.password = "" } ) } else { context.toastOnUi(ResStrings.fingerprint_not_support) vm.passwordType = PASSWORD_TYPE_PASSWORD } }, modifier = Modifier.fillMaxWidth(), enabled = vm.isValidUsername, completed = vm.finishSetFingerPrint ) { Text(ResStrings.add_fingerprint) } } ExchangePasswordType( passwordType = vm.passwordType ) { vm.passwordType = it } Spacer(modifier = Modifier.height(12.dp)) val enableRegister by remember { derivedStateOf { if (vm.passwordType == PASSWORD_TYPE_FINGERPRINT) vm.isValidUsername && vm.isValidEmail && vm.verifyCode.length == 6 && vm.finishSetFingerPrint else vm.isValidUsername && vm.isValidEmail && vm.verifyCode.length == 6 && UserUtils.isValidPassword(vm.password) } } Button( onClick = { if (!privacyGranted) { remindToGrantPrivacyAction() return@Button } vm.register( onSuccess = onRegisterSuccess, onError = { msg -> context.toastOnUi(ResStrings.register_failed_with_msg.format(msg)) } ) }, modifier = Modifier.fillMaxWidth(), enabled = enableRegister ) { Text(ResStrings.register) } } } @Composable private fun ExchangePasswordType( passwordType: String, resetFingerprintAction: SimpleAction? = null, updatePasswordType: (String) -> Unit, ) { if (passwordType == PASSWORD_TYPE_PASSWORD && supportBiometric) { Spacer(modifier = Modifier.height(4.dp)) Text( modifier = Modifier.clickable { updatePasswordType(PASSWORD_TYPE_FINGERPRINT) }, text = ResStrings.change_to_fingerprint, style = MaterialTheme.typography.labelSmall ) } else if (passwordType == PASSWORD_TYPE_FINGERPRINT) { Spacer(modifier = Modifier.height(4.dp)) Row(Modifier.height(IntrinsicSize.Min), verticalAlignment = Alignment.CenterVertically) { Text( modifier = Modifier.clickable { updatePasswordType(PASSWORD_TYPE_PASSWORD) }, text = ResStrings.change_to_password, style = MaterialTheme.typography.labelSmall ) if (resetFingerprintAction != null) { Text(text = " | ") // 重设指纹 Text( modifier = Modifier.clickable(onClick = resetFingerprintAction), text = ResStrings.reset_fingerprint, style = MaterialTheme.typography.labelSmall ) } } } } @Composable private fun InputUsernameWrapper( vm: LoginViewModel, imeAction: ImeAction = ImeAction.Next, ) { InputUsername( usernameProvider = vm::username, updateUsername = vm::updateUsername, isValidUsernameProvider = vm::isValidUsername, imeAction = imeAction ) } @Composable private fun InputEmailWrapper( modifier: Modifier, vm: LoginViewModel, initialSent: Boolean = false, ) { val context = LocalKMPContext.current InputEmail( modifier = modifier, value = vm.displayEmail, onValueChange = { vm.email = it }, isError = vm.email != "" && !vm.isValidEmail, verifyCode = vm.verifyCode, onVerifyCodeChange = { vm.verifyCode = it }, initialSent = initialSent, onClick = { vm.sendVerifyEmail(context) } ) } @Composable fun InputEmail( modifier: Modifier = Modifier, value: String = "", onValueChange: (String) -> Unit = {}, isError: Boolean = false, verifyCode: String, onVerifyCodeChange: (String) -> Unit = {}, initialSent: Boolean, onClick: () -> Unit ) { Column(modifier) { OutlinedTextField( modifier = Modifier.fillMaxWidth(), value = value, onValueChange = { onValueChange(it.lowercase()) }, isError = isError, label = { Text(text = ResStrings.Email) }, placeholder = { Text(ResStrings.please_input_validate_email) }, singleLine = true, keyboardOptions = KeyboardOptions( keyboardType = KeyboardType.Email, imeAction = ImeAction.Next ), trailingIcon = { CountDownTimeButton( modifier = Modifier.weight(1f), onClick = onClick, enabled = value != "" && !isError, initialSent = initialSent // 当需要 ) }, ) Spacer(modifier = Modifier.height(8.dp)) val isVerifyCodeError by remember(verifyCode) { derivedStateOf { verifyCode != "" && verifyCode.length != 6 } } OutlinedTextField( modifier = Modifier.fillMaxWidth(), value = verifyCode, onValueChange = onVerifyCodeChange, isError = isVerifyCodeError, label = { Text(text = ResStrings.verify_code) }, placeholder = { Text(ResStrings.please_input_verify_code) }, singleLine = true, keyboardOptions = KeyboardOptions( keyboardType = KeyboardType.Number, imeAction = ImeAction.Next ) ) } } @Composable private fun InputPasswordWrapper( vm: LoginViewModel ) { InputPassword( passwordProvider = vm::password, updatePassword = vm::updatePassword, ) } /** * 带倒计时的按钮 * */ @Composable fun CountDownTimeButton( modifier: Modifier, onClick: () -> Unit, countDownTime: Int = 60, text: String = ResStrings.get_verify_code, enabled: Boolean = true, initialSent: Boolean = false ) { var time by remember { mutableStateOf(countDownTime) } var isTiming by remember { mutableStateOf(initialSent) } LaunchedEffect(isTiming) { while (isTiming) { delay(1000) time-- if (time == 0) { isTiming = false time = countDownTime } } } TextButton( onClick = { if (!isTiming) { isTiming = true onClick() } }, modifier = modifier, enabled = enabled && !isTiming ) { Text(text = if (isTiming) "${time}s" else text) } }
Transtation-KMP/login/src/commonMain/kotlin/com/funny/trans/login/ui/LoginPage.kt
1912757017
package com.funny.trans.login.ui import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.statusBarsPadding import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.ui.Modifier import com.funny.translation.bean.UserInfoBean import com.funny.translation.kmp.NavGraphBuilder import com.funny.translation.kmp.NavHost import com.funny.translation.kmp.NavHostController import com.funny.translation.kmp.animateComposable import com.funny.translation.kmp.rememberNavController import com.funny.translation.translate.LocalNavController import com.funny.translation.ui.animatedGradientBackground sealed class LoginRoute(val route: String) { object LoginPage: LoginRoute("login_page") object ResetPasswordPage: LoginRoute("reset_password") object FindUsernamePage: LoginRoute("find_user_name") object ChangeUsernamePage: LoginRoute("change_user_name") object CancelAccountPage: LoginRoute("cancel_account") } @Composable fun LoginNavigation( onLoginSuccess: (UserInfoBean) -> Unit, ) { val navController = rememberNavController() CompositionLocalProvider(LocalNavController provides navController) { NavHost( navController = navController, startDestination = LoginRoute.LoginPage.route, modifier = Modifier .fillMaxSize() .animatedGradientBackground( MaterialTheme.colorScheme.surface, MaterialTheme.colorScheme.tertiaryContainer, ) .statusBarsPadding(), ) { addLoginRoutes(navController, onLoginSuccess = onLoginSuccess) } } } fun NavGraphBuilder.addLoginRoutes( navController: NavHostController, onLoginSuccess: (UserInfoBean) -> Unit, ){ animateComposable(LoginRoute.LoginPage.route){ LoginPage(navController = navController, onLoginSuccess = onLoginSuccess) } animateComposable(LoginRoute.ResetPasswordPage.route){ ResetPasswordPage(navController = navController) } animateComposable(LoginRoute.FindUsernamePage.route){ FindUsernamePage() } animateComposable(LoginRoute.ChangeUsernamePage.route){ ChangeUsernamePage(navController = navController) } animateComposable(LoginRoute.CancelAccountPage.route){ CancelAccountPage(navController = navController) } }
Transtation-KMP/login/src/commonMain/kotlin/com/funny/trans/login/ui/LoginNavigation.kt
3385224663
package com.funny.trans.login.ui import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.material3.Button import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import com.funny.translation.helper.toastOnUi import com.funny.translation.kmp.LocalKMPContext import com.funny.translation.kmp.viewModel import com.funny.translation.login.strings.ResStrings import com.funny.translation.ui.CommonPage import com.funny.translation.ui.TransparentTopBar @Composable fun FindUsernamePage() { CommonPage( topBar = { TransparentTopBar() } ) { val vm = viewModel<LoginViewModel>() val context = LocalKMPContext.current Spacer(modifier = Modifier.height(60.dp)) Column(Modifier.fillMaxWidth(WIDTH_FRACTION)) { InputEmail( modifier = Modifier.fillMaxWidth(), value = vm.email, onValueChange = { vm.email = it }, isError = vm.email != "" && !vm.isValidEmail, verifyCode = vm.verifyCode, onVerifyCodeChange = { vm.verifyCode = it }, initialSent = false, onClick = { vm.sendFindUsernameEmail(context) } ) Spacer(modifier = Modifier.height(8.dp)) val enable by remember { derivedStateOf { vm.isValidEmail && vm.verifyCode.length == 6 } } val usernameList = remember { mutableStateListOf<String>() } Button(modifier = Modifier.fillMaxWidth(), onClick = { vm.findUsername { usernameList.clear() usernameList.addAll(it) context.toastOnUi(ResStrings.find_account_amount.format(it.size.toString())) } }, enabled = enable) { Text(text = ResStrings.query_related_account) } Spacer(modifier = Modifier.height(8.dp)) LazyColumn(Modifier.fillMaxWidth()) { items(usernameList.size) { Text(text = usernameList[it], modifier = Modifier.padding(8.dp), color = MaterialTheme.colorScheme.primary) } } } } }
Transtation-KMP/login/src/commonMain/kotlin/com/funny/trans/login/ui/FindUsernamePage.kt
4016684484
package com.funny.trans.login.bean import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.compose.runtime.toMutableStateList import com.funny.translation.helper.Log import com.funny.translation.helper.VibratorUtils import com.funny.translation.helper.choice import com.funny.translation.helper.randInt import java.util.LinkedList import kotlin.math.roundToInt import kotlin.math.sqrt import kotlin.random.Random sealed class GameStatus { object Waiting: GameStatus() class Playing(var type: Int): GameStatus() object Fail: GameStatus() } abstract class BaseGame { var width by mutableStateOf(0) var height by mutableStateOf(0) var status: GameStatus by mutableStateOf(GameStatus.Waiting) abstract val tipText: String abstract fun update(deltaTime: Int) abstract fun init() } interface IGameListener { fun onInput(char: Char) fun onFail() fun onDelete() } class MemoryNumberGame : BaseGame() { companion object { // 正在记忆 const val PLAYING_TYPE_MEMORIZING = 0x1001 // 数字模式:点击数字 const val PLAYING_MODE_NUMBER = 0x1002 // 字符模式 const val PLAYING_MODE_CHAR = 0x1004 const val DELETE_CHAR = '⌫' private const val TAG = "MemoryNumberGame" } sealed class Block(var place: Pair<Int, Int>){ var isShow:Boolean by mutableStateOf(true) class EmptyBlock(place: Pair<Int, Int>): Block(place) class NumberBlock(val number:Int, place: Pair<Int, Int>): Block(place) class CharacterBlock(val char: Char, place: Pair<Int, Int>): Block(place) } var rows by mutableStateOf(5) var cols by mutableStateOf(5) // 最大的数字,生成的范围为1..maxNumber private var maxNumber = 5 // 一共几个block,包括空白的 private var maxBlocks = 10 val blocks = mutableListOf<Block>() private var isNumberMode = true private var retryTimes = 3 private var difficulty = 0 set(value) { if (value >= 10) field = 10 else field = value } private var countDownTime by mutableStateOf(10000) private val needToClickNumbers = LinkedList<Int>() private var currentNeedToClickNumber by mutableStateOf( if(needToClickNumbers.isNotEmpty()) needToClickNumbers.toMutableStateList()[0] else -1 ) private val chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ@_1234567890".toList() private val random = Random(System.currentTimeMillis()) var gameListener: IGameListener? = null override fun init() { status = GameStatus.Waiting setParams() } override val tipText: String by derivedStateOf { when(status){ is GameStatus.Waiting -> "点击按钮开始游戏~\n" is GameStatus.Playing -> when((status as GameStatus.Playing).type){ PLAYING_TYPE_MEMORIZING -> "记忆中,倒计时:${countDownTime/1000}s\n" PLAYING_MODE_NUMBER -> "请点击【${currentNeedToClickNumber}】 倒计时:${countDownTime/1000}s\n${maxNumber-needToClickNumbers.size}/${maxNumber} 生命:${retryTimes}" PLAYING_MODE_CHAR -> "点击输入,空白结束~\n倒计时:${countDownTime/1000}s" else -> "\n" } else -> "\n" } } private fun setParams(){ isNumberMode = random.nextBoolean() retryTimes = Math.max(4 - Math.ceil(difficulty.toFloat() * 0.4).toInt(), 1) rows = 5 + (difficulty * 0.4).roundToInt() cols = rows maxBlocks = Math.min((10 * sqrt(1+difficulty / 3.0)).toInt(), rows*cols*2/3) maxNumber = random.nextInt(maxBlocks/3, maxBlocks/2) countDownTime = maxNumber * 5000 - (difficulty/5*3000) Log.d(TAG, "setParams: difficulty:$difficulty maxBlocks:$maxBlocks maxNmber:$maxNumber") } // 继续,回到记忆状态 fun restart(){ status = GameStatus.Playing(PLAYING_TYPE_MEMORIZING) setParams() generateBlocks() } private fun fail(){ status = GameStatus.Fail difficulty = 0 gameListener?.onFail() } fun clickBlock(block: Block){ if (status !is GameStatus.Playing) return val playing = status as GameStatus.Playing if (playing.type == PLAYING_TYPE_MEMORIZING) return if (playing.type == PLAYING_MODE_NUMBER){ when(block){ is Block.NumberBlock -> clickBlockNumber(block) else -> kotlin.run { retryTimes-- VibratorUtils.vibrate(100) if (retryTimes == 0) fail() } } }else if (playing.type == PLAYING_MODE_CHAR){ when(block){ is Block.CharacterBlock -> kotlin.run { if (block.char == DELETE_CHAR) gameListener?.onDelete() else gameListener?.onInput(block.char) block.isShow = true } else -> kotlin.run { difficulty++ restart() } } } } private fun clickBlockNumber(block: Block.NumberBlock){ // 如果是第一个,说明点对了 if(block.number == needToClickNumbers.first){ block.isShow = true needToClickNumbers.removeFirst() if (needToClickNumbers.isEmpty()) { // 点完了,成功 // 开始下一轮或结束 difficulty++ restart() return } currentNeedToClickNumber = needToClickNumbers.first }else{ retryTimes-- if (retryTimes == 0) { fail() return } } } private fun generateBlocks(){ blocks.clear() // 先生成所有的block val allBlockPlaces = random.randInt(0, cols * rows, maxBlocks) if (isNumberMode){ // 再挑几个idx,作为有数字的 val numbersBlocksIdx = random.randInt(0, maxBlocks, maxNumber).sorted() var n = 0 allBlockPlaces.forEachIndexed { i, place -> if (n >= maxNumber) return@forEachIndexed if (i == numbersBlocksIdx[n]){ blocks.add(Block.NumberBlock(++n, place / cols to place % cols)) }else{ blocks.add(Block.EmptyBlock(place / cols to place % cols)) } } }else{ val randomChars = random.choice(chars, maxBlocks - 2) var j = 0 allBlockPlaces.forEachIndexed { i, place -> if (i == 0) blocks.add(Block.EmptyBlock(place / cols to place % cols)) else if (i == 1) blocks.add( Block.CharacterBlock( DELETE_CHAR, place / cols to place % cols ) ) else blocks.add( Block.CharacterBlock( randomChars[j++], place / cols to place % cols ) ) } } } private fun hideAll(){ for (block in blocks) { block.isShow = false } } override fun update(deltaTime: Int) { if (status is GameStatus.Playing){ countDownTime -= deltaTime val playingStatus = status as GameStatus.Playing when(playingStatus.type){ PLAYING_TYPE_MEMORIZING -> kotlin.run { if (countDownTime <= 0){ countDownTime = maxNumber * 5000 - (difficulty/5*3000) hideAll() if (isNumberMode){ needToClickNumbers.clear() repeat(maxNumber){ i -> needToClickNumbers.add(i+1) } if (difficulty >= 4) needToClickNumbers.shuffled() currentNeedToClickNumber = needToClickNumbers.first playingStatus.type = PLAYING_MODE_NUMBER }else{ playingStatus.type = PLAYING_MODE_CHAR } } } PLAYING_MODE_NUMBER -> kotlin.run { if (countDownTime <= 0){ fail() } } PLAYING_MODE_CHAR -> kotlin.run { if (countDownTime <= 0){ restart() } } } } } }
Transtation-KMP/login/src/commonMain/kotlin/com/funny/trans/login/bean/Game.kt
341194914
package com.funny.trans.login import com.funny.translation.BaseActivity expect class LoginActivity: BaseActivity
Transtation-KMP/login/src/commonMain/kotlin/com/funny/trans/login/LoginActivity.kt
1078341826
package com.funny.trans.login.ui actual val supportBiometric: Boolean = false
Transtation-KMP/login/src/desktopMain/kotlin/com/funny/trans/login/ui/LoginViewModel.desktop.kt
550049800
package com.funny.trans.login import com.funny.translation.BaseActivity actual class LoginActivity : BaseActivity() { }
Transtation-KMP/login/src/desktopMain/kotlin/com/funny/trans/login/LoginActivity.desktop.kt
2764632559
package com.funny.trans.login.ui import android.os.Build import androidx.annotation.ChecksSdkIntAtLeast @ChecksSdkIntAtLeast(api = Build.VERSION_CODES.M) actual val supportBiometric: Boolean = Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
Transtation-KMP/login/src/androidMain/kotlin/com/funny/trans/login/ui/LoginViewModel.android.kt
1179549730
package com.funny.trans.login import android.content.Intent import android.os.Build import android.os.Bundle import androidx.activity.compose.setContent import com.funny.trans.login.ui.LoginNavigation import com.funny.translation.AppConfig import com.funny.translation.BaseActivity import com.funny.translation.helper.Log import com.funny.translation.helper.biomertic.BiometricUtils import com.funny.translation.ui.App actual class LoginActivity : BaseActivity() { companion object { private const val TAG = "LoginActivity" } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { BiometricUtils.init() } setContent { App { LoginNavigation(onLoginSuccess = { Log.d(TAG, "登录成功: 用户: $it") if(it.isValid()) AppConfig.login(it, updateVipFeatures = true) setResult(RESULT_OK, Intent()) finish() }) } } } override fun onDestroy() { super.onDestroy() } }
Transtation-KMP/login/src/androidMain/kotlin/com/funny/trans/login/LoginActivity.kt
2418563260
package br.com.fiap.app 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("br.com.fiap.app", appContext.packageName) } }
AppTheme/app/src/androidTest/java/br/com/fiap/app/ExampleInstrumentedTest.kt
3512230158
package br.com.fiap.app 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) } }
AppTheme/app/src/test/java/br/com/fiap/app/ExampleUnitTest.kt
2854097634
package br.com.fiap.app.ui.theme import androidx.compose.ui.graphics.Color val Purple80 = Color(0xFFD0BCFF) val PurpleGrey80 = Color(0xFFCCC2DC) val Pink80 = Color(0xFFEFB8C8) val Purple40 = Color(0xFF6650a4) val PurpleGrey40 = Color(0xFF625b71) val Pink40 = Color(0xFF7D5260)
AppTheme/app/src/main/java/br/com/fiap/app/ui/theme/Color.kt
1985786903
package br.com.fiap.app.ui.theme import android.app.Activity import android.os.Build import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import androidx.core.view.WindowCompat private val DarkColorScheme = darkColorScheme( primary = Purple80, secondary = PurpleGrey80, tertiary = Pink80 ) private val LightColorScheme = lightColorScheme( primary = Purple40, secondary = PurpleGrey40, tertiary = Pink40 /* Other default colors to override background = Color(0xFFFFFBFE), surface = Color(0xFFFFFBFE), onPrimary = Color.White, onSecondary = Color.White, onTertiary = Color.White, onBackground = Color(0xFF1C1B1F), onSurface = Color(0xFF1C1B1F), */ ) @Composable fun AppTheme( darkTheme: Boolean = isSystemInDarkTheme(), // Dynamic color is available on Android 12+ dynamicColor: Boolean = true, content: @Composable () -> Unit ) { val colorScheme = when { dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { val context = LocalContext.current if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) } darkTheme -> DarkColorScheme else -> LightColorScheme } val view = LocalView.current if (!view.isInEditMode) { SideEffect { val window = (view.context as Activity).window window.statusBarColor = colorScheme.primary.toArgb() WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme } } MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content ) }
AppTheme/app/src/main/java/br/com/fiap/app/ui/theme/Theme.kt
144398102
package br.com.fiap.app.ui.theme import androidx.compose.material3.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp // Set of Material typography styles to start with val Typography = Typography( bodyLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp, lineHeight = 24.sp, letterSpacing = 0.5.sp ) /* Other default text styles to override titleLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 22.sp, lineHeight = 28.sp, letterSpacing = 0.sp ), labelSmall = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Medium, fontSize = 11.sp, lineHeight = 16.sp, letterSpacing = 0.5.sp ) */ )
AppTheme/app/src/main/java/br/com/fiap/app/ui/theme/Type.kt
558531972
package br.com.fiap.app import android.os.Bundle import android.provider.MediaStore.Audio.Radio import android.util.Log import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Add import androidx.compose.material.icons.materialIcon import androidx.compose.material3.Button import androidx.compose.material3.ButtonColors import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.Checkbox import androidx.compose.material3.CheckboxDefaults import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.OutlinedTextFieldDefaults import androidx.compose.material3.RadioButton import androidx.compose.material3.RadioButtonDefaults import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TextField import androidx.compose.material3.TextFieldColors import androidx.compose.material3.TextFieldDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateMapOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.painter.Painter import androidx.compose.ui.res.colorResource import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.input.KeyboardCapitalization import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import br.com.fiap.app.ui.theme.AppTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { AppTheme { Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { Greeting() } } } } } @Composable fun Greeting() { var corBackground by remember{ mutableStateOf(Color.White) } Column(modifier = Modifier .fillMaxSize() .background(corBackground), verticalArrangement = Arrangement.Center) { Row (modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceEvenly){ //Modo Claro Button( onClick = { corBackground = Color.White }, modifier = Modifier .padding(top = 12.dp) .width(150.dp), colors = ButtonDefaults.buttonColors(Color(0xFFFFFFFF), contentColor = Color( 0xFF050505 ) ), border = BorderStroke(2.dp, Color(0xFF000000)) ) { Row(modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween ) { Text(text = "Modo Claro") Icon(painterResource(id = R.drawable.baseline_light_mode_24), contentDescription = "") } } //Modo Escuro Button( onClick = { corBackground = Color.Black }, modifier = Modifier .padding(top = 12.dp) .width(150.dp), colors = ButtonDefaults.buttonColors(Color(0xFF000000), contentColor = Color( 0xFFFFFFFF ) ), border = BorderStroke(2.dp, Color(0xFFFFFFFF)) ) { Row(modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween ) { Text(text = "Modo Escuro") Spacer(modifier = Modifier.padding(horizontal = 2.dp)) Icon(painterResource(id = R.drawable.baseline_dark_mode_24), contentDescription = "") } } } } } @Preview(showSystemUi = true ,showBackground = true) @Composable fun GreetingPreview() { Greeting() }
AppTheme/app/src/main/java/br/com/fiap/app/MainActivity.kt
1277256839
package com.example.bottomnavigationanim 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.bottomnavigationanim", appContext.packageName) } }
BottomNavigationAnimation/app/src/androidTest/java/com/example/bottomnavigationanim/ExampleInstrumentedTest.kt
423960068
package com.example.bottomnavigationanim 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) } }
BottomNavigationAnimation/app/src/test/java/com/example/bottomnavigationanim/ExampleUnitTest.kt
775933561
package com.example.bottomnavigationanim.ui.theme import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Shapes import androidx.compose.ui.unit.dp val Shapes = Shapes( small = RoundedCornerShape(4.dp), medium = RoundedCornerShape(4.dp), large = RoundedCornerShape(0.dp) )
BottomNavigationAnimation/app/src/main/java/com/example/bottomnavigationanim/ui/theme/Shape.kt
25462581
package com.example.bottomnavigationanim.ui.theme import androidx.compose.ui.graphics.Color val Purple200 = Color(0xFFBB86FC) val Purple500 = Color(0xFF6200EE) val Purple700 = Color(0xFF3700B3) val Teal200 = Color(0xFF03DAC5) val ElectricViolet = Color(0xFF7D26FE) val Purple = Color(0xFF742DF6) val LightPurple = Color(0xFFBCA1E7) val RoyalPurple = Color(0xFF64419F) val LightGrey = Color(0xFFB1B1B1)
BottomNavigationAnimation/app/src/main/java/com/example/bottomnavigationanim/ui/theme/Color.kt
447479574
package com.example.bottomnavigationanim.ui.theme import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material.MaterialTheme import androidx.compose.material.darkColors import androidx.compose.material.lightColors import androidx.compose.runtime.Composable private val DarkColorPalette = darkColors( primary = Purple200, primaryVariant = Purple700, secondary = Teal200 ) private val LightColorPalette = lightColors( primary = Purple500, primaryVariant = Purple700, secondary = Teal200 /* Other default colors to override background = Color.White, surface = Color.White, onPrimary = Color.White, onSecondary = Color.Black, onBackground = Color.Black, onSurface = Color.Black, */ ) @Composable fun BottomNavigationAnimTheme( darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable () -> Unit ) { val colors = if (darkTheme) { DarkColorPalette } else { LightColorPalette } MaterialTheme( colors = colors, typography = Typography, shapes = Shapes, content = content ) }
BottomNavigationAnimation/app/src/main/java/com/example/bottomnavigationanim/ui/theme/Theme.kt
575104436
package com.example.bottomnavigationanim.ui.theme import androidx.compose.material.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp // Set of Material typography styles to start with val Typography = Typography( body1 = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp ) /* Other default text styles to override button = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.W500, fontSize = 14.sp ), caption = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 12.sp ) */ )
BottomNavigationAnimation/app/src/main/java/com/example/bottomnavigationanim/ui/theme/Type.kt
876826725
package com.example.bottomnavigationanim.contents import androidx.annotation.DrawableRes import androidx.annotation.StringRes import androidx.compose.animation.core.Spring import androidx.compose.animation.core.spring import androidx.compose.animation.core.tween import androidx.compose.runtime.Stable import androidx.compose.ui.unit.DpOffset import androidx.compose.ui.unit.dp import com.example.bottomnavigationanim.R import com.example.bottomnavigationanim.colorButtons.BellColorButton import com.example.bottomnavigationanim.colorButtons.ButtonBackground import com.example.bottomnavigationanim.colorButtons.CalendarAnimation import com.example.bottomnavigationanim.colorButtons.ColorButtonAnimation import com.example.bottomnavigationanim.colorButtons.GearColorButton import com.example.bottomnavigationanim.colorButtons.PlusColorButton @Stable data class WiggleButtonItem( @DrawableRes val backgroundIcon: Int, @DrawableRes val icon: Int, var isSelected: Boolean, @StringRes val description: Int, val animationType: ColorButtonAnimation = BellColorButton( tween(500), background = ButtonBackground(R.drawable.plus) ), ) @Stable data class Item( @DrawableRes val icon: Int, var isSelected: Boolean, @StringRes val description: Int, val animationType: ColorButtonAnimation = BellColorButton( tween(500), background = ButtonBackground(R.drawable.plus) ), ) val wiggleButtonItems = listOf( WiggleButtonItem( icon = R.drawable.outline_favorite, backgroundIcon = R.drawable.favorite, isSelected = false, description = R.string.Heart, ), WiggleButtonItem( icon = R.drawable.outline_energy_leaf, backgroundIcon = R.drawable.energy_savings_leaf, isSelected = false, description = R.string.Leaf ), WiggleButtonItem( icon = R.drawable.outline_water_drop, backgroundIcon = R.drawable.water_drop_icon, isSelected = false, description = R.string.Drop ), WiggleButtonItem( icon = R.drawable.outline_circle, backgroundIcon = R.drawable.circle, isSelected = false, description = R.string.Circle ), WiggleButtonItem( icon = R.drawable.baseline_laptop, backgroundIcon = R.drawable.laptop, isSelected = false, description = R.string.Laptop ), ) val dropletButtons = listOf( Item( icon = R.drawable.home, isSelected = false, description = R.string.Home ), Item( icon = R.drawable.bell, isSelected = false, description = R.string.Bell ), Item( icon = R.drawable.message_buble, isSelected = false, description = R.string.Message ), Item( icon = R.drawable.heart, isSelected = false, description = R.string.Heart ), Item( icon = R.drawable.person, isSelected = false, description = R.string.Person ), ) val colorButtons = listOf( Item( icon = R.drawable.outline_home, isSelected = true, description = R.string.Home, animationType = BellColorButton( animationSpec = spring(dampingRatio = 0.7f, stiffness = 20f), background = ButtonBackground( icon = R.drawable.circle_background, offset = DpOffset(2.5.dp, 3.dp) ), ) ), Item( icon = R.drawable.outline_bell, isSelected = false, description = R.string.Bell, animationType = BellColorButton( animationSpec = spring(dampingRatio = 0.7f, stiffness = 20f), background = ButtonBackground( icon = R.drawable.rectangle_background, offset = DpOffset(1.dp, 2.dp) ), ) ), Item( icon = R.drawable.rounded_rect, isSelected = false, description = R.string.Plus, animationType = PlusColorButton( animationSpec = spring( dampingRatio = 0.3f, stiffness = Spring.StiffnessVeryLow ), background = ButtonBackground( icon = R.drawable.polygon_background, offset = DpOffset(1.6.dp, 2.dp) ), ) ), Item( icon = R.drawable.calendar, isSelected = false, description = R.string.Calendar, animationType = CalendarAnimation( animationSpec = spring( dampingRatio = 0.3f, stiffness = Spring.StiffnessVeryLow ), background = ButtonBackground( icon = R.drawable.quadrangle_background, offset = DpOffset(1.dp, 1.5.dp) ), ) ), Item( icon = R.drawable.gear, isSelected = false, description = R.string.Settings, animationType = GearColorButton( animationSpec = spring( dampingRatio = 0.3f, stiffness = Spring.StiffnessVeryLow ), background = ButtonBackground( icon = R.drawable.gear_background, offset = DpOffset(2.5.dp, 3.dp) ), ) ) )
BottomNavigationAnimation/app/src/main/java/com/example/bottomnavigationanim/contents/ItemsData.kt
1310778959
package com.example.bottomnavigationanim import android.os.Bundle import android.view.animation.OvershootInterpolator import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.animation.core.* import androidx.compose.foundation.background import androidx.compose.foundation.layout.* import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import androidx.core.view.WindowCompat //import com.example.bottom_navigation_module.AnimatedNavigationBar //import com.example.bottom_navigation_module.animation.balltrajectory.Parabolic //import com.example.bottom_navigation_module.animation.balltrajectory.Straight //import com.example.bottom_navigation_module.animation.balltrajectory.Teleport //import com.example.bottom_navigation_module.animation.indendshape.Height //import com.example.bottom_navigation_module.animation.indendshape.StraightIndent //import com.example.bottom_navigation_module.animation.indendshape.shapeCornerRadius //import com.example.bottom_navigation_module.items.dropletbutton.DropletButton //import com.example.bottom_navigation_module.items.wigglebutton.WiggleButton import com.example.bottomnavigationanim.colorButtons.ColorButton import com.example.bottomnavigationanim.contents.colorButtons import com.example.bottomnavigationanim.contents.dropletButtons import com.example.bottomnavigationanim.contents.wiggleButtonItems import com.example.bottomnavigationanim.ui.theme.ElectricViolet import com.example.bottomnavigationanim.ui.theme.LightPurple import com.example.bottomnavigationanim.ui.theme.Purple import com.example.bottomnavigationanim.ui.theme.RoyalPurple class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) WindowCompat.setDecorFitsSystemWindows(window, false) setContent { // val systemUiController: SystemUiController = rememberSystemUiController() // SideEffect { // systemUiController.isStatusBarVisible = false // systemUiController.isNavigationBarVisible = false // } // Box( // modifier = Modifier // .fillMaxSize() // .background(ElectricViolet) // ) { // Column( // modifier = Modifier.align(Alignment.BottomCenter) // ) { // ColorButtonNavBar() // DropletButtonNavBar() // WiggleButtonNavBar() // } // } } } } //@Composable //fun ColorButtonNavBar() { // var selectedItem by remember { mutableStateOf(0) } // var prevSelectedIndex by remember { mutableStateOf(0) } // // AnimatedNavigationBar( // modifier = Modifier // .padding(horizontal = 8.dp, vertical = 60.dp) // .height(85.dp), // selectedIndex = selectedItem, // ballColor = Color.White, // cornerRadius = shapeCornerRadius(25.dp), // ballAnimation = Straight( // spring(dampingRatio = 0.6f, stiffness = Spring.StiffnessVeryLow) // ), // indentAnimation = StraightIndent( // indentWidth = 56.dp, // indentHeight = 15.dp, // animationSpec = tween(1000) // ) // ) { // colorButtons.forEachIndexed { index, it -> // ColorButton( // modifier = Modifier.fillMaxSize(), // prevSelectedIndex = prevSelectedIndex, // selectedIndex = selectedItem, // index = index, // onClick = { // prevSelectedIndex = selectedItem // selectedItem = index // }, // icon = it.icon, // contentDescription = stringResource(id = it.description), // animationType = it.animationType, // background = it.animationType.background // ) // } // } //} // //@Composable //fun DropletButtonNavBar() { // var selectedItem by remember { mutableStateOf(0) } // AnimatedNavigationBar( // modifier = Modifier // .padding(horizontal = 8.dp, vertical = 40.dp) // .height(85.dp), // selectedIndex = selectedItem, // ballColor = Color.White, // cornerRadius = shapeCornerRadius(25.dp), // ballAnimation = Parabolic(tween(Duration, easing = LinearOutSlowInEasing)), // indentAnimation = Height( // indentWidth = 56.dp, // indentHeight = 15.dp, // animationSpec = tween( // DoubleDuration, // easing = { OvershootInterpolator().getInterpolation(it) }) // ) // ) { // dropletButtons.forEachIndexed { index, it -> // DropletButton( // modifier = Modifier.fillMaxSize(), // isSelected = selectedItem == index, // onClick = { selectedItem = index }, // icon = it.icon, // dropletColor = Purple, // animationSpec = tween(durationMillis = Duration, easing = LinearEasing) // ) // } // } //} // //@Composable //fun WiggleButtonNavBar() { // var selectedItem by remember { mutableStateOf(0) } // // AnimatedNavigationBar( // modifier = Modifier // .padding(horizontal = 8.dp, vertical = 40.dp) // .height(85.dp), // selectedIndex = selectedItem, // ballColor = Color.White, // cornerRadius = shapeCornerRadius(25.dp), // ballAnimation = Teleport(tween(Duration, easing = LinearEasing)), // indentAnimation = Height( // indentWidth = 56.dp, // indentHeight = 15.dp, // animationSpec = tween( // DoubleDuration, // easing = { OvershootInterpolator().getInterpolation(it) }) // ) // ) { // wiggleButtonItems.forEachIndexed { index, it -> // WiggleButton( // modifier = Modifier.fillMaxSize(), // isSelected = selectedItem == index, // onClick = { selectedItem = index }, // icon = it.icon, // backgroundIcon = it.backgroundIcon, // wiggleColor = LightPurple, // outlineColor = RoyalPurple, // contentDescription = stringResource(id = it.description), // enterExitAnimationSpec = tween(durationMillis = Duration, easing = LinearEasing), // wiggleAnimationSpec = spring(dampingRatio = .45f, stiffness = 35f) // ) // } // } //} // //const val Duration = 500 //const val DoubleDuration = 1000 //
BottomNavigationAnimation/app/src/main/java/com/example/bottomnavigationanim/MainActivity.kt
1100114190
package com.example.bottomnavigationanim.colorButtons import androidx.annotation.DrawableRes import androidx.compose.animation.core.AnimationSpec import androidx.compose.animation.core.FiniteAnimationSpec import androidx.compose.animation.core.LinearEasing import androidx.compose.animation.core.animateFloatAsState import androidx.compose.animation.core.tween import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.offset import androidx.compose.runtime.Composable import androidx.compose.runtime.Stable import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.scale import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.DpOffset import androidx.compose.ui.unit.dp //import com.example.bottom_navigation_module.utils.lerp //import com.example.bottom_navigation_module.utils.noRippleClickable //import com.example.bottom_navigation_module.utils.toDp //import com.example.bottom_navigation_module.utils.toPxf data class ButtonBackground( @DrawableRes val icon: Int, val offset: DpOffset = DpOffset.Zero ) @Stable abstract class ColorButtonAnimation( open val animationSpec: FiniteAnimationSpec<Float> = tween(10000), open val background: ButtonBackground, ) { @Composable abstract fun AnimatingIcon( modifier: Modifier, isSelected: Boolean, isFromLeft: Boolean, icon: Int, ) } @Composable fun ColorButton( modifier: Modifier = Modifier, index: Int, selectedIndex: Int, prevSelectedIndex: Int, onClick: () -> Unit, @DrawableRes icon: Int, contentDescription: String? = null, background: ButtonBackground, backgroundAnimationSpec: AnimationSpec<Float> = remember { tween(300, easing = LinearEasing) }, animationType: ColorButtonAnimation, maxBackgroundOffset: Dp = 25.dp ) { Box( // modifier = modifier.noRippleClickable { onClick() } ) { val isSelected = remember(selectedIndex, index) { selectedIndex == index } val fraction = animateFloatAsState( targetValue = if (isSelected) 1f else 0f, animationSpec = backgroundAnimationSpec, // label = "fractionAnimation", ) val density = LocalDensity.current // val maxOffset = remember(maxBackgroundOffset) { maxBackgroundOffset.toPxf(density) } val isFromLeft = remember(prevSelectedIndex, index, selectedIndex) { (prevSelectedIndex < index) || (selectedIndex > index) } // val offset by remember(isSelected, isFromLeft) { // derivedStateOf { // calculateBackgroundOffset( // isSelected = isSelected, // isFromLeft = isFromLeft, //// maxOffset = maxOffset, // fraction = fraction.value // ) // } // } Image( modifier = Modifier // .offset(x = background.offset.x + offset.toDp(), y = background.offset.y) .scale(fraction.value) .align(Alignment.Center), painter = painterResource(id = background.icon), contentDescription = contentDescription ) animationType.AnimatingIcon( modifier = Modifier.align(Alignment.Center), isSelected = isSelected, isFromLeft = isFromLeft, icon = icon, ) } } private fun calculateBackgroundOffset( isSelected: Boolean, isFromLeft: Boolean, fraction: Float, maxOffset: Float ): Float { // val offset = if (isFromLeft) -maxOffset else maxOffset // return if (isSelected) { //// lerp(offset, 0f, fraction) // } else { //// lerp(-offset, 0f, fraction) // } return 0f }
BottomNavigationAnimation/app/src/main/java/com/example/bottomnavigationanim/colorButtons/ColorButton.kt
3959910050
package com.example.bottomnavigationanim.colorButtons import androidx.compose.animation.animateColorAsState import androidx.compose.animation.core.FiniteAnimationSpec import androidx.compose.animation.core.animateFloatAsState import androidx.compose.material.Icon import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.draw.rotate import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalLayoutDirection import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.LayoutDirection import com.example.bottomnavigationanim.ui.theme.LightGrey class GearColorButton( override val animationSpec: FiniteAnimationSpec<Float>, override val background: ButtonBackground, private val maxGearAnimationDegree: Float = 50f, ) : ColorButtonAnimation(animationSpec, background) { @Composable override fun AnimatingIcon( modifier: Modifier, isSelected: Boolean, isFromLeft: Boolean, icon: Int, ) { val layoutDirection = LocalLayoutDirection.current val gearAnimationDegree = remember { if (layoutDirection == LayoutDirection.Ltr) { maxGearAnimationDegree } else { -maxGearAnimationDegree } } val degree = animateFloatAsState( targetValue = if (isSelected) gearAnimationDegree else 0f, animationSpec = animationSpec, // label = "degreeAnimation" ) val color = animateColorAsState( targetValue = if (isSelected) Color.Black else LightGrey, // label = "colorAnimation" ) Icon( modifier = modifier .rotate(if (isSelected) degree.value else 0f), painter = painterResource(id = icon), contentDescription = null, tint = color.value ) } }
BottomNavigationAnimation/app/src/main/java/com/example/bottomnavigationanim/colorButtons/GearColorButton.kt
1781851287
package com.example.bottomnavigationanim.colorButtons import androidx.compose.animation.animateColorAsState import androidx.compose.animation.core.FiniteAnimationSpec import androidx.compose.animation.core.animateFloatAsState import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.Icon import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.LocalLayoutDirection import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.dp import com.example.bottomnavigationanim.ui.theme.LightGrey //import com.example.bottom_navigation_module.utils.toPxf data class CalendarAnimation( override val animationSpec: FiniteAnimationSpec<Float>, override val background: ButtonBackground, ) : ColorButtonAnimation(animationSpec, background) { @Composable override fun AnimatingIcon( modifier: Modifier, isSelected: Boolean, isFromLeft: Boolean, icon: Int, ) { Box( modifier = modifier ) { val fraction = animateFloatAsState( targetValue = if (isSelected) 1f else 0f, animationSpec = animationSpec, // label = "fractionAnimation" ) val layoutDirection = LocalLayoutDirection.current val isLeftAnimation = remember(isFromLeft) { if (layoutDirection == LayoutDirection.Ltr) { isFromLeft } else { !isFromLeft } } val color = animateColorAsState( targetValue = if (isSelected) Color.Black else LightGrey, // label = "colorAnimation" ) Icon( modifier = Modifier .align(Alignment.Center) .graphicsLayer( translationX = if (isSelected) offset( 10f, fraction.value, isLeftAnimation ) else 0f ), painter = painterResource(id = icon), contentDescription = null, tint = color.value ) CalendarPoint( modifier = Modifier.align(Alignment.Center), offsetX = if (isSelected) offset( 15f, fraction.value, isLeftAnimation ) else 0f, iconColor = color.value ) } } private fun offset(maxHorizontalOffset: Float, fraction: Float, isFromLeft: Boolean): Float { val maxOffset = if (isFromLeft) -maxHorizontalOffset else maxHorizontalOffset return if (fraction < 0.5) { 2 * fraction * maxOffset } else { 2 * (1 - fraction) * maxOffset } } } @Composable fun CalendarPoint( modifier: Modifier = Modifier, offsetX: Float, iconColor: Color, ) { val layoutDirection = LocalLayoutDirection.current val density = LocalDensity.current val internalOffset = remember { if (layoutDirection == LayoutDirection.Ltr) { // Offset(3.5.dp.toPxf(density), 5.dp.toPxf(density)) } else { // Offset((-3.5).dp.toPxf(density), 5.dp.toPxf(density)) } } // Box( // modifier = modifier // .graphicsLayer( // translationX = internalOffset.x + offsetX, // translationY = internalOffset.y // ) // .size(3.dp) // .clip(CircleShape) // .background(iconColor) // ) }
BottomNavigationAnimation/app/src/main/java/com/example/bottomnavigationanim/colorButtons/CalendarColorButton.kt
2377622724
package com.example.bottomnavigationanim.colorButtons import androidx.compose.animation.animateColorAsState import androidx.compose.animation.core.FiniteAnimationSpec import androidx.compose.animation.core.animateFloatAsState import androidx.compose.foundation.layout.Box import androidx.compose.material.Icon import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.rotate import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalLayoutDirection import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.LayoutDirection import com.example.bottomnavigationanim.R class PlusColorButton( override val animationSpec: FiniteAnimationSpec<Float>, override val background: ButtonBackground, ) : ColorButtonAnimation(animationSpec, background) { @Composable override fun AnimatingIcon( modifier: Modifier, isSelected: Boolean, isFromLeft: Boolean, icon: Int, ) { Box( modifier = modifier ) { val color = animateColorAsState( targetValue = if (isSelected) Color.Black else Color.LightGray, // label = "colorAnimation" ) Icon( modifier = Modifier .align(Alignment.Center), painter = painterResource(id = R.drawable.rounded_rect), contentDescription = null, tint = color.value ) val layoutDirection = LocalLayoutDirection.current val requiredDegrees = remember(isFromLeft) { val rotateDegrees = if (isFromLeft) ROTATE_DEGREES else -ROTATE_DEGREES if (layoutDirection == LayoutDirection.Rtl) -rotateDegrees else rotateDegrees } val degrees = animateFloatAsState( targetValue = if (isSelected) requiredDegrees else 0f, animationSpec = animationSpec, // label = "degreesAnimation" ) Icon( modifier = Modifier .align(Alignment.Center) .rotate(if (isSelected) degrees.value else 0f), painter = painterResource(id = R.drawable.plus), contentDescription = null, tint = color.value ) } } } const val ROTATE_DEGREES = 90f
BottomNavigationAnimation/app/src/main/java/com/example/bottomnavigationanim/colorButtons/PlusColorButton.kt
3915338216
package com.example.bottomnavigationanim.colorButtons import androidx.compose.animation.animateColorAsState import androidx.compose.animation.core.FiniteAnimationSpec import androidx.compose.animation.core.animateFloatAsState import androidx.compose.animation.core.tween import androidx.compose.material.Icon import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Color.Companion.LightGray import androidx.compose.ui.res.painterResource //import com.example.bottom_navigation_module.utils.rotationWithTopCenterAnchor import kotlin.math.PI import kotlin.math.sin class BellColorButton( override val animationSpec: FiniteAnimationSpec<Float> = tween(), override val background: ButtonBackground, private val maxDegrees: Float = 30f, ) : ColorButtonAnimation(animationSpec, background) { @Composable override fun AnimatingIcon( modifier: Modifier, isSelected: Boolean, isFromLeft: Boolean, icon: Int, ) { val rotationFraction = animateFloatAsState( targetValue = if (isSelected) 1f else 0f, animationSpec = animationSpec, // label = "rotationFractionAnimation" ) val color = animateColorAsState( targetValue = if (isSelected) Color.Black else LightGray, // label = "colorAnimation" ) // Icon( // modifier = modifier // .rotationWithTopCenterAnchor( // if (isSelected) degreesRotationInterpolation( // maxDegrees, // rotationFraction.value // ) else 0f // ), // painter = painterResource(id = icon), // contentDescription = null, // tint = color.value // ) } private fun degreesRotationInterpolation(maxDegrees: Float, fraction: Float) = sin(fraction * 2 * PI).toFloat() * maxDegrees }
BottomNavigationAnimation/app/src/main/java/com/example/bottomnavigationanim/colorButtons/BellColorButton.kt
343807931
package com.example.bottom_navigation_module 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.bottom_navigation_module.test", appContext.packageName) } }
BottomNavigationAnimation/bottom-navigation-module/src/androidTest/java/com/example/bottom_navigation_module/ExampleInstrumentedTest.kt
1441071651
package com.example.bottom_navigation_module 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) } }
BottomNavigationAnimation/bottom-navigation-module/src/test/java/com/example/bottom_navigation_module/ExampleUnitTest.kt
2366787376
package com.example.bottom_navigation_module.shape import com.example.bottom_navigation_module.animation.indendshape.ShapeCornerRadius import com.example.bottom_navigation_module.animation.indendshape.shapeCornerRadius data class IndentShapeData( val xIndent: Float = 0f, val height: Float = 0f, val width: Float = 0f, val cornerRadius: ShapeCornerRadius = shapeCornerRadius(0f), val ballOffset: Float = 0f, )
BottomNavigationAnimation/bottom-navigation-module/src/main/java/com/example/bottom_navigation_module/shape/IndentShapeData.kt
2609448037
package com.example.bottom_navigation_module.shape import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Rect import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Outline import androidx.compose.ui.graphics.Path import androidx.compose.ui.graphics.Shape import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.LayoutDirection import com.example.bottom_navigation_module.animation.indendshape.ShapeCornerRadius class IndentRectShape( private val indentShapeData: IndentShapeData, ) : Shape { override fun createOutline( size: Size, layoutDirection: LayoutDirection, density: Density ): Outline = Outline.Generic( Path().addRoundRectWithIndent(size, indentShapeData, layoutDirection) ) fun copy( cornerRadius: ShapeCornerRadius = indentShapeData.cornerRadius, xIndent: Float = indentShapeData.xIndent, yIndent: Float = indentShapeData.height, ballSize: Float = indentShapeData.ballOffset, ) = IndentRectShape( indentShapeData.copy( cornerRadius = cornerRadius, xIndent = xIndent, height = yIndent, ballOffset = ballSize ) ) } fun Path.addRoundRectWithIndent( size: Size, indentShapeData: IndentShapeData, layoutDirection: LayoutDirection, ): Path { val width = size.width val height = size.height val cornerRadius = indentShapeData.cornerRadius val sweepAngleDegrees = 90f return apply { moveTo(chooseCornerSize(size.height, cornerRadius.topLeft), 0f) val xOffset = if (layoutDirection == LayoutDirection.Ltr) { indentShapeData.xIndent - indentShapeData.width / 2 } else { size.width - indentShapeData.xIndent - indentShapeData.width / 2 } if (xOffset > cornerRadius.topLeft / 4) { addPath( IndentPath( Rect( Offset( x = xOffset, y = 0f ), Size(indentShapeData.width, indentShapeData.height) ) ).createPath() ) } lineTo(width - cornerRadius.topRight, 0f) arcTo( rect = Rect( offset = Offset(width - cornerRadius.topRight, 0f), size = Size(cornerRadius.topRight, cornerRadius.topRight) ), startAngleDegrees = 270f, sweepAngleDegrees = sweepAngleDegrees, forceMoveTo = false ) lineTo(width, height - cornerRadius.bottomRight) arcTo( rect = Rect( offset = Offset( width - cornerRadius.bottomRight, height - cornerRadius.bottomRight ), size = Size(cornerRadius.bottomRight, cornerRadius.bottomRight) ), startAngleDegrees = 0f, sweepAngleDegrees = sweepAngleDegrees, forceMoveTo = false ) lineTo(width - cornerRadius.bottomLeft, height) arcTo( rect = Rect( offset = Offset(0f, height - cornerRadius.bottomLeft), size = Size(cornerRadius.bottomLeft, cornerRadius.bottomLeft) ), startAngleDegrees = 90f, sweepAngleDegrees = sweepAngleDegrees, forceMoveTo = false ) lineTo(0f, cornerRadius.topLeft) arcTo( rect = Rect( offset = Offset(0f, 0f), size = Size(cornerRadius.topLeft, cornerRadius.topLeft) ), startAngleDegrees = 180f, sweepAngleDegrees = sweepAngleDegrees, forceMoveTo = false ) close() } } fun chooseCornerSize(sizeHeight: Float, cornerRadius: Float): Float { return if (sizeHeight > cornerRadius) { cornerRadius } else { sizeHeight } }
BottomNavigationAnimation/bottom-navigation-module/src/main/java/com/example/bottom_navigation_module/shape/IndentRectShape.kt
1544476828
package com.example.bottom_navigation_module.shape import android.graphics.PointF import androidx.compose.ui.geometry.Rect import androidx.compose.ui.graphics.Path class IndentPath( private val rect: Rect, ) { private val maxX = 110f private val maxY = 34f private fun translate(x: Float, y: Float): PointF { return PointF( ((x / maxX) * rect.width) + rect.left, ((y / maxY) * rect.height) + rect.top ) } fun createPath(): Path { val start = translate(x = 0f, y = 0f) val middle = translate(x = 55f, y = 34f) val end = translate(x = 110f, y = 0f) val control1 = translate(x = 23f, y = 0f) val control2 = translate(x = 39f, y = 34f) val control3 = translate(x = 71f, y = 34f) val control4 = translate(x = 87f, y = 0f) val path = Path() path.moveTo(start.x, start.y) path.cubicTo(control1.x, control1.y, control2.x, control2.y, middle.x, middle.y) path.cubicTo(control3.x, control3.y, control4.x, control4.y, end.x, end.y) return path } }
BottomNavigationAnimation/bottom-navigation-module/src/main/java/com/example/bottom_navigation_module/shape/IndentPath.kt
1591074693
package com.example.bottom_navigation_module.shape import androidx.compose.ui.geometry.Offset import androidx.compose.ui.unit.Dp internal data class ShapeInfo( val cornerRadius: Dp, val layoutOffset: Offset )
BottomNavigationAnimation/bottom-navigation-module/src/main/java/com/example/bottom_navigation_module/shape/ShapeInfo.kt
2564376332
package com.example.bottom_navigation_module.layout import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.layout.MeasurePolicy import androidx.compose.ui.layout.Placeable @Composable fun animatedNavBarMeasurePolicy( onBallPositionsCalculated: (ArrayList<Float>) -> Unit ) = remember { barMeasurePolicy(onBallPositionsCalculated = onBallPositionsCalculated) } internal fun barMeasurePolicy(onBallPositionsCalculated: (ArrayList<Float>) -> Unit) = MeasurePolicy { measurables, constraints -> check(measurables.isNotEmpty()){ "There must be at least one element" } val itemWidth = constraints.maxWidth / measurables.size val placeables = measurables.map { measurable -> measurable.measure(constraints.copy(maxWidth = itemWidth)) } val gap = calculateGap(placeables, constraints.maxWidth) val height = placeables.maxOf { it.height } layout(constraints.maxWidth, height) { var xPosition = gap val positions = arrayListOf<Float>() placeables.forEachIndexed { index, _ -> placeables[index].placeRelative(xPosition, 0) positions.add( element = calculatePointPosition( xPosition, placeables[index].width, ) ) xPosition += placeables[index].width + gap } onBallPositionsCalculated(positions) } } fun calculatePointPosition(xButtonPosition: Int, buttonWidth: Int): Float { return xButtonPosition + (buttonWidth / 2f) } fun calculateGap(placeables: List<Placeable>, width: Int): Int { var allWidth = 0 placeables.forEach { placeable -> allWidth += placeable.width } return (width - allWidth) / (placeables.size + 1) }
BottomNavigationAnimation/bottom-navigation-module/src/main/java/com/example/bottom_navigation_module/layout/AnimatedNavBarMeasurePolicy.kt
2760493582
package com.example.bottom_navigation_module.animation.balltrajectory import androidx.compose.animation.core.AnimationSpec import androidx.compose.animation.core.animateOffsetAsState import androidx.compose.runtime.Composable import androidx.compose.runtime.Stable import androidx.compose.runtime.State import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.produceState import androidx.compose.runtime.remember import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.isUnspecified import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.unit.dp import com.example.bottom_navigation_module.ballSize import com.example.bottom_navigation_module.utils.toPxf /** *Describing straight ball animation *@param [animationSpec] animation spec of straight ball trajectory */ @Stable class Straight( private val animationSpec: AnimationSpec<Offset> ) : BallAnimation { @Composable override fun animateAsState(targetOffset: Offset): State<BallAnimInfo> { if (targetOffset.isUnspecified) { return remember { mutableStateOf(BallAnimInfo()) } } val density = LocalDensity.current val verticalOffset = remember { 2.dp.toPxf(density) } val ballSizePx = remember { ballSize.toPxf(density) } val offset = animateOffsetAsState( targetValue = calculateOffset(targetOffset, ballSizePx, verticalOffset), animationSpec = animationSpec ) return produceState( initialValue = BallAnimInfo(), key1 = offset.value ) { this.value = this.value.copy(offset = offset.value) } } private fun calculateOffset( offset: Offset, ballSizePx: Float, verticalOffset: Float ) = Offset( x = offset.x - ballSizePx / 2f, y = offset.y - verticalOffset ) }
BottomNavigationAnimation/bottom-navigation-module/src/main/java/com/example/bottom_navigation_module/animation/balltrajectory/Straight.kt
2972210839
package com.example.bottom_navigation_module.animation.balltrajectory import android.graphics.Path import android.graphics.PathMeasure import androidx.compose.animation.core.Animatable import androidx.compose.animation.core.FiniteAnimationSpec import androidx.compose.animation.core.spring import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.Stable import androidx.compose.runtime.State import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.produceState import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.isUnspecified import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import com.example.bottom_navigation_module.ballSize import com.example.bottom_navigation_module.utils.toPxf /** *Describing parabola ball animation *@param [animationSpec] animation spec of parabolic ball trajectory *@param [maxHeight] max height of parabola trajectory */ @Stable class Parabolic( private val animationSpec: FiniteAnimationSpec<Float> = spring(), private val maxHeight: Dp = 100.dp, ) : BallAnimation { @Composable override fun animateAsState(targetOffset: Offset): State<BallAnimInfo> { if (targetOffset.isUnspecified) { return remember { mutableStateOf(BallAnimInfo()) } } var from by remember { mutableStateOf(targetOffset) } var to by remember { mutableStateOf(targetOffset) } val fraction = remember { Animatable(0f) } val path = remember { Path() } val pathMeasurer = remember { PathMeasure() } val pathLength = remember { mutableStateOf(0f) } val pos = remember { floatArrayOf(Float.MAX_VALUE, Float.MAX_VALUE) } val tan = remember { floatArrayOf(0f, 0f) } val density = LocalDensity.current val maxHeightPx = remember(maxHeight) { maxHeight.toPxf(density) } fun measurePosition() { pathMeasurer.getPosTan(pathLength.value * fraction.value, pos, tan) } LaunchedEffect(targetOffset) { var height = if (to != targetOffset) { maxHeightPx } else { startMinHeight } if (isNotRunning(fraction.value)) { from = to to = targetOffset } else { measurePosition() from = Offset(x = pos[0], y = pos[1]) to = targetOffset height = maxHeightPx + pos[1] } path.createParabolaTrajectory(from = from, to = to, height = height) pathMeasurer.setPath(path, false) pathLength.value = pathMeasurer.length fraction.snapTo(0f) fraction.animateTo(1f, animationSpec) } val verticalOffset = remember { 2.dp.toPxf(density) } val ballSizePx = remember { ballSize.toPxf(density) } return produceState( initialValue = BallAnimInfo(), key1 = pos, key2 = ballSizePx, key3 = fraction.value, ) { measurePosition() if (pos[0] == Float.MAX_VALUE) { BallAnimInfo() } else { this.value = this.value.copy( offset = calculateNewOffset( pos, ballSizePx, verticalOffset ) ) } } } private fun Path.createParabolaTrajectory(from: Offset, to: Offset, height: Float) { reset() moveTo(from.x, from.y) quadTo( (from.x + to.x) / 2f, from.y - height, to.x, to.y ) } private fun calculateNewOffset( pos: FloatArray, ballSizePx: Float, verticalOffset: Float ) = Offset( x = pos[0] - (ballSizePx / 2), y = pos[1] - verticalOffset ) private fun isNotRunning(fraction: Float) = fraction == 0f || fraction == 1f companion object { const val startMinHeight = -50f } }
BottomNavigationAnimation/bottom-navigation-module/src/main/java/com/example/bottom_navigation_module/animation/balltrajectory/Parabolic.kt
786883391
package com.example.bottom_navigation_module.animation.balltrajectory import androidx.compose.animation.core.Animatable import androidx.compose.animation.core.AnimationSpec import androidx.compose.animation.core.spring import androidx.compose.runtime.* import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.isUnspecified import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.unit.dp import com.example.bottom_navigation_module.ballSize import com.example.bottom_navigation_module.utils.toPxf /** *Describing teleport ball animation. Ball disappears in old location and reappears in the new one *@param [animationSpec] animation spec of teleport ball process */ @Stable class Teleport( private val animationSpec: AnimationSpec<Float> = spring() ) : BallAnimation { @Composable override fun animateAsState( targetOffset: Offset, ): State<BallAnimInfo> { if (targetOffset.isUnspecified) { return remember { mutableStateOf(BallAnimInfo()) } } var from by remember { mutableStateOf(Offset.Unspecified) } var to by remember { mutableStateOf(Offset.Unspecified) } val fraction = remember { Animatable(0f) } val density = LocalDensity.current val verticalOffset = remember { 2.dp.toPxf(density) } val offset by remember(targetOffset) { derivedStateOf { mutableStateOf( Offset( x = targetOffset.x - ballSize.toPxf(density) / 2, y = targetOffset.y - verticalOffset ) ) } } suspend fun setNewAnimationPoints() { if (from == Offset.Unspecified) { from = offset.value fraction.snapTo(1f) } else { from = to fraction.snapTo(0f) } to = offset.value } suspend fun changeToAndFromPointsWhileAnimating() { from = to to = offset.value fraction.snapTo(2f - fraction.value) } fun changeToAnimationPointWhileAnimating() { to = offset.value } LaunchedEffect(offset) { when { isAnimationNotRunning(fraction.value) -> { setNewAnimationPoints() } isExitBallAnimation(fraction.value) -> { changeToAnimationPointWhileAnimating() } isEnterBallAnimation(fraction.value) -> { changeToAndFromPointsWhileAnimating() } } fraction.animateTo(2f, animationSpec) } return produceState( initialValue = BallAnimInfo(), key1 = fraction.value ) { this.value = this.value.copy( scale = if (fraction.value < 1f) 1f - fraction.value else fraction.value - 1f, offset = if (fraction.value < 1f) from else to ) } } private fun isExitBallAnimation(fraction: Float) = fraction <= 1f private fun isEnterBallAnimation(fraction: Float) = fraction > 1f private fun isAnimationNotRunning(fraction: Float) = fraction == 0f || fraction == 2f }
BottomNavigationAnimation/bottom-navigation-module/src/main/java/com/example/bottom_navigation_module/animation/balltrajectory/Teleport.kt
1007607469
package com.example.bottom_navigation_module.animation.balltrajectory import androidx.compose.runtime.* import androidx.compose.ui.geometry.Offset /** * Interface defining the ball animation */ interface BallAnimation { /** *@param [targetOffset] target offset */ @Composable fun animateAsState(targetOffset: Offset): State<BallAnimInfo> } /** * Describes parameters of the ball animation */ data class BallAnimInfo( val scale: Float = 1f, val offset: Offset = Offset.Unspecified )
BottomNavigationAnimation/bottom-navigation-module/src/main/java/com/example/bottom_navigation_module/animation/balltrajectory/BallTrajectory.kt
2859085361
package com.example.bottom_navigation_module.animation.indendshape import androidx.compose.animation.core.FiniteAnimationSpec import androidx.compose.animation.core.animateFloatAsState import androidx.compose.runtime.Composable import androidx.compose.runtime.Stable import androidx.compose.runtime.State import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.produceState import androidx.compose.runtime.remember import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.isUnspecified import androidx.compose.ui.graphics.Shape import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import com.example.bottom_navigation_module.ballSize import com.example.bottom_navigation_module.shape.IndentRectShape import com.example.bottom_navigation_module.shape.IndentShapeData import com.example.bottom_navigation_module.utils.toPxf @Stable class StraightIndent( private val animationSpec: FiniteAnimationSpec<Float>, private val indentWidth: Dp = 50.dp, private val indentHeight: Dp = 20.dp, ) : IndentAnimation { @Composable override fun animateIndentShapeAsState( targetOffset: Offset, shapeCornerRadius: ShapeCornerRadius ): State<Shape> { if (targetOffset.isUnspecified) { return remember { mutableStateOf(IndentRectShape(IndentShapeData())) } } val density = LocalDensity.current val position = animateFloatAsState( targetValue = targetOffset.x, animationSpec = animationSpec ) return produceState( initialValue = IndentRectShape( indentShapeData = IndentShapeData( xIndent = targetOffset.x, height = indentHeight.toPxf(density), ballOffset = ballSize.toPxf(density) / 2f, width = indentWidth.toPxf(density), cornerRadius = shapeCornerRadius ) ), key1 = position.value, key2 = shapeCornerRadius ) { this.value = this.value.copy( xIndent = position.value, cornerRadius = shapeCornerRadius ) } } }
BottomNavigationAnimation/bottom-navigation-module/src/main/java/com/example/bottom_navigation_module/animation/indendshape/StraightIndentAnimation.kt
3004607319
package com.example.bottom_navigation_module.animation.indendshape import androidx.compose.runtime.Composable import androidx.compose.runtime.State import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Shape import androidx.compose.ui.unit.Dp import com.example.bottom_navigation_module.utils.toPxf /** * defining indent animation, that is above selected item. */ interface IndentAnimation { /** *@param [targetOffset] target offset *@param [shapeCornerRadius] corner radius of the navBar layout */ @Composable fun animateIndentShapeAsState( targetOffset: Offset, shapeCornerRadius: ShapeCornerRadius ): State<Shape> } data class ShapeCornerRadius( val topLeft: Float, val topRight: Float, val bottomRight: Float, val bottomLeft: Float, ) fun shapeCornerRadius(cornerRadius: Float) = ShapeCornerRadius( topLeft = cornerRadius, topRight = cornerRadius, bottomRight = cornerRadius, bottomLeft = cornerRadius ) @Composable fun shapeCornerRadius(cornerRadius: Dp) = ShapeCornerRadius( topLeft = cornerRadius.toPxf(), topRight = cornerRadius.toPxf(), bottomRight = cornerRadius.toPxf(), bottomLeft = cornerRadius.toPxf() ) @Composable fun shapeCornerRadius( topLeft: Dp, topRight: Dp, bottomRight: Dp, bottomLeft: Dp ) = ShapeCornerRadius( topLeft = topLeft.toPxf(), topRight = topRight.toPxf(), bottomRight = bottomRight.toPxf(), bottomLeft = bottomLeft.toPxf() )
BottomNavigationAnimation/bottom-navigation-module/src/main/java/com/example/bottom_navigation_module/animation/indendshape/IndentAnimation.kt
3706639961
package com.example.bottom_navigation_module.animation.indendshape import androidx.compose.animation.core.Animatable import androidx.compose.animation.core.FiniteAnimationSpec import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.Stable import androidx.compose.runtime.State import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.produceState import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.isUnspecified import androidx.compose.ui.graphics.Shape import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import com.example.bottom_navigation_module.ballSize import com.example.bottom_navigation_module.shape.IndentRectShape import com.example.bottom_navigation_module.shape.IndentShapeData import com.example.bottom_navigation_module.utils.lerp import com.example.bottom_navigation_module.utils.toPxf @Stable class Height( private val animationSpec: FiniteAnimationSpec<Float>, private val indentWidth: Dp = 50.dp, private val indentHeight: Dp = 10.dp, ) : IndentAnimation { @Composable override fun animateIndentShapeAsState( targetOffset: Offset, shapeCornerRadius: ShapeCornerRadius ): State<Shape> { if (targetOffset.isUnspecified) { return remember { mutableStateOf(IndentRectShape(IndentShapeData())) } } val fraction = remember { Animatable(0f) } var to by remember { mutableStateOf(Offset.Zero) } var from by remember { mutableStateOf(Offset.Zero) } val density = LocalDensity.current suspend fun setNewAnimationPoints() { from = to to = targetOffset fraction.snapTo(0f) } suspend fun changeToAndFromPointsWhileAnimating() { from = to to = targetOffset fraction.snapTo(2f - fraction.value) } fun changeToAnimationPointWhileAnimating() { to = targetOffset } LaunchedEffect(targetOffset) { when { isNotRunning(fraction.value) -> { setNewAnimationPoints() } isExitIndentAnimating(fraction.value) -> { changeToAnimationPointWhileAnimating() } isEnterIndentAnimating(fraction.value) -> { changeToAndFromPointsWhileAnimating() } } fraction.animateTo(2f, animationSpec) } return produceState( initialValue = IndentRectShape( indentShapeData = IndentShapeData( ballOffset = ballSize.toPxf(density) / 2f, width = indentWidth.toPxf(density), ) ), key1 = fraction.value, key2 = shapeCornerRadius ) { this.value = this.value.copy( yIndent = calculateYIndent(fraction.value,density), xIndent = if (fraction.value <= 1f) from.x else to.x, cornerRadius = shapeCornerRadius ) } } private fun calculateYIndent(fraction: Float, density: Density): Float { return if (fraction <= 1f) { lerp(indentHeight.toPxf(density), 0f, fraction) } else { lerp(0f, indentHeight.toPxf(density), fraction - 1f) } } private fun isExitIndentAnimating(fraction: Float) = (fraction <= 1f) private fun isEnterIndentAnimating(fraction: Float) = (fraction > 1f) private fun isNotRunning(fraction: Float) = fraction == 0f || fraction == 2f }
BottomNavigationAnimation/bottom-navigation-module/src/main/java/com/example/bottom_navigation_module/animation/indendshape/HeightIndentAnimation.kt
3434521940
package com.example.bottom_navigation_module.utils import androidx.compose.runtime.Composable import androidx.compose.runtime.Stable import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.Dp @Stable fun Float.toDp(density: Density): Dp = with(density) { [email protected]() } @Stable fun Dp.toPxf(density: Density): Float = with(density) { [email protected]() } @Stable @Composable fun Dp.toPxf(): Float = toPxf(LocalDensity.current) @Stable @Composable fun Float.toDp() = this.toDp(LocalDensity.current)
BottomNavigationAnimation/bottom-navigation-module/src/main/java/com/example/bottom_navigation_module/utils/DensityUtils.kt
1364427091
package com.example.bottom_navigation_module.utils import androidx.compose.foundation.clickable import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.offset import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.composed import androidx.compose.ui.graphics.TransformOrigin import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.unit.IntOffset import com.example.bottom_navigation_module.animation.balltrajectory.BallAnimInfo fun Modifier.noRippleClickable( onClick: () -> Unit ) = composed { this.clickable( indication = null, interactionSource = remember { MutableInteractionSource() } ) { onClick() } } fun Modifier.ballTransform(ballAnimInfo: BallAnimInfo) = this .offset { IntOffset( x = ballAnimInfo.offset.x.toInt(), y = ballAnimInfo.offset.y.toInt() ) } .graphicsLayer { scaleY = ballAnimInfo.scale scaleX = ballAnimInfo.scale transformOrigin = TransformOrigin(pivotFractionX = 0.5f, 0f) } fun Modifier.rotationWithTopCenterAnchor(degrees: Float) = this .graphicsLayer( transformOrigin = TransformOrigin( pivotFractionX = 0.5f, pivotFractionY = 0.1f, ), rotationZ = degrees )
BottomNavigationAnimation/bottom-navigation-module/src/main/java/com/example/bottom_navigation_module/utils/ModifierExtensions.kt
2151003916
package com.example.bottom_navigation_module.utils fun lerp(start: Float, stop: Float, fraction: Float) = (start * (1 - fraction) + stop * fraction)
BottomNavigationAnimation/bottom-navigation-module/src/main/java/com/example/bottom_navigation_module/utils/GeometricUtils.kt
66784453
package com.example.bottom_navigation_module import androidx.compose.animation.core.tween import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.CircleShape import androidx.compose.runtime.Composable import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.isSpecified import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.layout.Layout import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import com.example.bottom_navigation_module.animation.balltrajectory.BallAnimInfo import com.example.bottom_navigation_module.animation.balltrajectory.BallAnimation import com.example.bottom_navigation_module.animation.balltrajectory.Parabolic import com.example.bottom_navigation_module.animation.indendshape.Height import com.example.bottom_navigation_module.animation.indendshape.IndentAnimation import com.example.bottom_navigation_module.animation.indendshape.ShapeCornerRadius import com.example.bottom_navigation_module.animation.indendshape.shapeCornerRadius import com.example.bottom_navigation_module.layout.animatedNavBarMeasurePolicy import com.example.bottom_navigation_module.utils.ballTransform /** *A composable function that creates an animated navigation bar with a moving ball and indent * to indicate the selected item. * *@param [modifier] Modifier to be applied to the navigation bar *@param [selectedIndex] The index of the currently selected item *@param [barColor] The color of the navigation bar *@param [ballColor] The color of the moving ball *@param [cornerRadius] The corner radius of the navigation bar *@param [ballAnimation] The animation to be applied to the moving ball *@param [indentAnimation] The animation to be applied to the navigation bar to indent selected item *@param [content] The composable content of the navigation bar */ @Composable fun AnimatedNavigationBar( modifier: Modifier = Modifier, selectedIndex: Int, barColor: Color = Color.White, ballColor: Color = Color.Black, cornerRadius: ShapeCornerRadius = shapeCornerRadius(0f), ballAnimation: BallAnimation = Parabolic(tween(300)), indentAnimation: IndentAnimation = Height(tween(300)), content: @Composable () -> Unit, ) { var itemPositions by remember { mutableStateOf(listOf<Offset>()) } val measurePolicy = animatedNavBarMeasurePolicy { itemPositions = it.map { xCord -> Offset(xCord, 0f) } } val selectedItemOffset by remember(selectedIndex, itemPositions) { derivedStateOf { if (itemPositions.isNotEmpty()) itemPositions[selectedIndex] else Offset.Unspecified } } val indentShape = indentAnimation.animateIndentShapeAsState( shapeCornerRadius = cornerRadius, targetOffset = selectedItemOffset ) val ballAnimInfoState = ballAnimation.animateAsState( targetOffset = selectedItemOffset, ) Box( modifier = modifier ) { Layout( modifier = Modifier .graphicsLayer { clip = true shape = indentShape.value } .background(barColor), content = content, measurePolicy = measurePolicy ) if (ballAnimInfoState.value.offset.isSpecified) { ColorBall( ballAnimInfo = ballAnimInfoState.value, ballColor = ballColor, sizeDp = ballSize ) } } } val ballSize = 10.dp @Composable private fun ColorBall( modifier: Modifier = Modifier, ballColor: Color, ballAnimInfo: BallAnimInfo, sizeDp: Dp, ) { Box( modifier = modifier .ballTransform(ballAnimInfo) .size(sizeDp) .clip(shape = CircleShape) .background(ballColor) ) }
BottomNavigationAnimation/bottom-navigation-module/src/main/java/com/example/bottom_navigation_module/NavBar.kt
4147906559
package com.example.bottom_navigation_module.items.dropletbutton import androidx.annotation.FloatRange import androidx.compose.animation.core.AnimationSpec import androidx.compose.animation.core.animateFloatAsState import androidx.compose.animation.core.tween import androidx.compose.runtime.Composable import androidx.compose.runtime.Stable import androidx.compose.runtime.State import androidx.compose.runtime.getValue import androidx.compose.runtime.produceState import androidx.compose.runtime.remember import androidx.compose.runtime.rememberUpdatedState import com.example.bottom_navigation_module.utils.lerp import java.lang.Float.max @Stable data class DropletButtonParams( @FloatRange(from = 0.0, to = 1.0) val scale: Float = 1f, val radius: Float = 10f, val verticalOffset: Float = 0f, ) @Composable internal fun animateDropletButtonAsState( isSelected: Boolean, animationSpec: AnimationSpec<Float> = remember { tween(300) }, size: Float, ): State<DropletButtonParams> { val fraction = animateFloatAsState( targetValue = if (isSelected) 1f else 0f, animationSpec = animationSpec ) val isAnimationRequired by rememberUpdatedState(newValue = isSelected) return produceState( initialValue = DropletButtonParams(), key1 = fraction.value ) { this.value = this.value.copy( scale = if (isAnimationRequired) scaleInterpolation(fraction.value) else 1f, radius = if (isAnimationRequired) lerp(0f, size, fraction.value) else 0f, verticalOffset = lerp(0f, size, fraction.value) ) } } fun scaleInterpolation(fraction: Float): Float { val f = if (fraction < 0.3f) { fraction * 3.33f } else { max((0.6f - fraction) * 3.33f, 0f) } return 1f - 0.2f * f }
BottomNavigationAnimation/bottom-navigation-module/src/main/java/com/example/bottom_navigation_module/items/dropletbutton/AnimateDropletButtonParamsAsState.kt
2274843488
package com.example.bottom_navigation_module.items.dropletbutton import androidx.compose.animation.core.AnimationSpec import androidx.compose.animation.core.tween import androidx.compose.foundation.Canvas import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.layout.* import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.* import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.rememberVectorPainter import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.res.vectorResource import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import com.example.bottom_navigation_module.utils.noRippleClickable import com.example.bottom_navigation_module.utils.toPxf /** * *A composable button that displays an icon with a droplet-shaped background. The button supports animation *and selection states. *@param modifier Modifier to be applied to the composable *@param isSelected Boolean representing whether the button is currently selected or not *@param onClick Callback to be executed when the button is clicked *@param icon Drawable resource of the icon to be displayed on the button *@param contentDescription A description for the button to be used by accessibility *@param iconColor Color to tint the icon *@param dropletColor Color of the droplet-shaped background *@param size Icon size *@param animationSpec Animation specification to be used when animating the button */ @OptIn(ExperimentalFoundationApi::class) @Composable fun DropletButton( modifier: Modifier = Modifier, isSelected: Boolean, onClick: () -> Unit, icon: Int, contentDescription: String? = null, iconColor: Color = Color.LightGray, dropletColor: Color = Color.Red, size: Dp = 20.dp, animationSpec: AnimationSpec<Float> = remember { tween(300) } ) { Box( modifier = modifier.noRippleClickable { onClick() } ) { val density = LocalDensity.current val dropletButtonParams = animateDropletButtonAsState( isSelected = isSelected, animationSpec = animationSpec, size = size.toPxf(density) ) val sizePx = remember(size) { size.toPxf(density) } val circleCenter by remember { derivedStateOf { mutableStateOf(sizePx / 2) } } val vector = ImageVector.vectorResource(id = icon) val painter = rememberVectorPainter(image = vector) Canvas( modifier = Modifier .size(size) .align(Alignment.Center) .graphicsLayer( alpha = 0.99f, scaleX = dropletButtonParams.value.scale, scaleY = dropletButtonParams.value.scale, ), contentDescription = contentDescription ?: "" ) { with(painter) { draw( size = Size(sizePx, sizePx), colorFilter = ColorFilter.tint(color = iconColor) ) } drawCircle( color = dropletColor, radius = dropletButtonParams.value.radius, center = Offset( circleCenter.value, dropletButtonParams.value.verticalOffset - 20f ), blendMode = BlendMode.SrcIn ) } } }
BottomNavigationAnimation/bottom-navigation-module/src/main/java/com/example/bottom_navigation_module/items/dropletbutton/DropletButton.kt
2832707889
package com.example.bottom_navigation_module.items.wigglebutton import androidx.annotation.DrawableRes import androidx.compose.animation.core.AnimationSpec import androidx.compose.animation.core.spring import androidx.compose.foundation.Canvas import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.size import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.* import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.rememberVectorPainter import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.res.vectorResource import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.toSize import com.example.bottom_navigation_module.utils.noRippleClickable import com.example.bottom_navigation_module.utils.toPxf /** * *A composable button that displays an icon with a wiggle part background. * *@param modifier Modifier to be applied to the composable *@param isSelected Boolean value indicating whether the view is selected or not *@param onClick Callback to be executed when the button is clicked *@param icon Drawable resource of the ImageVector resource used for the icon *@param backgroundIcon Drawable resource of the ImageVector resource used for the background icon *@param contentDescription Content description used to describe the view for accessibility purposes *@param wiggleColor Color of the arc drawn on top of the view *@param iconSize Icon size *@param backgroundIconColor Color of the background icon in the view, *@param outlineColor Outline icon color *@param enterExitAnimationSpec Animation spec for appearing/disappearing *@param wiggleAnimationSpec Animation spec for wiggle effect */ @Composable fun WiggleButton( modifier: Modifier = Modifier, isSelected: Boolean, onClick: () -> Unit, @DrawableRes icon: Int, @DrawableRes backgroundIcon: Int, contentDescription: String? = null, backgroundIconColor: Color = Color.White, wiggleColor: Color = Color.Blue, outlineColor: Color = Color.LightGray, iconSize: Dp = 25.dp, enterExitAnimationSpec: AnimationSpec<Float> = spring(), wiggleAnimationSpec: AnimationSpec<Float> = spring(dampingRatio = 0.6f, stiffness = 35f) ) { Box( modifier = modifier .noRippleClickable { onClick() } ) { DrawWithBlendMode( modifier = Modifier .size(iconSize) .align(Alignment.Center), icon = icon, backgroundIcon = backgroundIcon, isSelected = isSelected, wiggleColor = wiggleColor, backgroundIconColor = backgroundIconColor, outlineColor = outlineColor, contentDescription = contentDescription, enterExitAnimationSpec = enterExitAnimationSpec, wiggleAnimationSpec = wiggleAnimationSpec, size = iconSize, ) } } @OptIn(ExperimentalFoundationApi::class) @Composable fun DrawWithBlendMode( modifier: Modifier, isSelected: Boolean, @DrawableRes icon: Int, @DrawableRes backgroundIcon: Int, contentDescription: String? = null, wiggleColor: Color, size: Dp, backgroundIconColor: Color, enterExitAnimationSpec: AnimationSpec<Float>, wiggleAnimationSpec: AnimationSpec<Float>, outlineColor: Color, ) { val vector = ImageVector.vectorResource(id = icon) val painter = rememberVectorPainter(image = vector) val backgroundVector = ImageVector.vectorResource(id = backgroundIcon) val backgroundPainter = rememberVectorPainter(image = backgroundVector) var canvasSize by remember { mutableStateOf(Size.Zero) } val density = LocalDensity.current val sizePx = remember(size) { size.toPxf(density) } val wiggleButtonParams = animateWiggleButtonAsState( isSelected = isSelected, enterExitAnimationSpec = enterExitAnimationSpec, wiggleAnimationSpec = wiggleAnimationSpec, maxRadius = sizePx ) val offset by remember { derivedStateOf { mutableStateOf( Offset(x = canvasSize.width / 2, y = canvasSize.height) ) } } Canvas( modifier = modifier .graphicsLayer( alpha = wiggleButtonParams.value.alpha, scaleX = wiggleButtonParams.value.scale, scaleY = wiggleButtonParams.value.scale ) .fillMaxSize() .onGloballyPositioned { canvasSize = it.size.toSize() }, contentDescription = contentDescription ?: "" ) { with(backgroundPainter) { draw( size = Size(sizePx, sizePx), colorFilter = ColorFilter.tint(color = backgroundIconColor) ) } drawCircle( color = wiggleColor, center = offset.value, radius = wiggleButtonParams.value.radius, blendMode = BlendMode.SrcIn ) with(painter) { draw( size = Size(sizePx, sizePx), colorFilter = ColorFilter.tint(color = outlineColor) ) } } }
BottomNavigationAnimation/bottom-navigation-module/src/main/java/com/example/bottom_navigation_module/items/wigglebutton/WiggleButton.kt
963539585
package com.example.bottom_navigation_module.items.wigglebutton import androidx.annotation.FloatRange import androidx.compose.animation.core.* import androidx.compose.runtime.* @Stable data class WiggleButtonParams( @FloatRange(from = 0.0, to = 1.0) val scale: Float = 1f, @FloatRange(from = 0.0, to = 1.0) val alpha: Float = 1f, val radius: Float = 10f ) @Composable fun animateWiggleButtonAsState( isSelected: Boolean, enterExitAnimationSpec: AnimationSpec<Float>, wiggleAnimationSpec: AnimationSpec<Float>, maxRadius: Float, ): State<WiggleButtonParams> { val enterExitFraction = animateFloatAsState( targetValue = if (isSelected) 1f else 0f, animationSpec = enterExitAnimationSpec ) val wiggleFraction = animateFloatAsState( targetValue = if (isSelected) 1f else 0f, animationSpec = wiggleAnimationSpec ) val isAnimationRequired by rememberUpdatedState(newValue = isSelected) return produceState( initialValue = WiggleButtonParams(), key1 = enterExitFraction.value, key2 = wiggleFraction.value ) { this.value = this.value.copy( scale = scaleInterpolator(enterExitFraction.value), alpha = alphaInterpolator(enterExitFraction.value), radius = if (isAnimationRequired) calculateRadius( maxRadius = maxRadius * 0.8f, fraction = radiusInterpolator(wiggleFraction.value), minRadius = mildRadius * maxRadius ) else mildRadius * maxRadius ) } } const val mildRadius = 0.55f fun scaleInterpolator(fraction: Float): Float = 1 + fraction * 0.2f fun alphaInterpolator(fraction: Float): Float = fraction / 2 + 0.5f - 0.01f fun calculateRadius( maxRadius: Float, fraction: Float, minRadius: Float, ) = (fraction * (maxRadius - minRadius)) + minRadius fun radiusInterpolator( fraction: Float ): Float = if (fraction < 0.5f) { fraction * 2 } else { (1 - fraction) * 2 }
BottomNavigationAnimation/bottom-navigation-module/src/main/java/com/example/bottom_navigation_module/items/wigglebutton/AnimateWiggleButtonAsState.kt
779980270
package com.example.hallserviceapp 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.hallserviceapp", appContext.packageName) } }
HallService--App/app/src/androidTest/java/com/example/hallserviceapp/ExampleInstrumentedTest.kt
1547689463
package com.example.hallserviceapp 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) } }
HallService--App/app/src/test/java/com/example/hallserviceapp/ExampleUnitTest.kt
378884670
package com.example.hallserviceapp import android.content.Intent import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.example.hallserviceapp.ui.theme.HallServiceAppTheme class UploadNoticeActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { HallServiceAppTheme { Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { UploadNoticeScreen() } } } } } @Composable fun UploadNoticeScreen() { val lightBlue = Color(0xFF8FABE7) val yellow = Color(0xFF40E48A) val gray = Color(0xFFE7E3E7) val context = LocalContext.current Box( modifier = Modifier .fillMaxSize() ) { // Add the background image Image( painter = painterResource(id = R.drawable.bgpic4), // Replace with your image resource contentDescription = null, // Content description can be null for decorative images modifier = Modifier.fillMaxSize(), contentScale = ContentScale.FillBounds // Scale the image to fill the bounds ) Column( modifier = Modifier .fillMaxSize() //.background(lightBlue) .padding(16.dp), verticalArrangement = Arrangement.Top, horizontalAlignment = Alignment.CenterHorizontally ) { HeaderSectionAll("Upload Notice") Spacer(modifier = Modifier.height(160.dp)) OptionText("Upload Text File", Color.LightGray) { context.startActivity(Intent(context, NoticeTextActivity::class.java)) } Spacer(modifier = Modifier.height(20.dp)) /* OptionText("Upload Notice File", gray) { context.startActivity(Intent(context, NoticeFileTextActivity::class.java)) } */ } } } @Composable fun OptionText(text: String, backgroundColor: Color, onClick: () -> Unit) { Text( text = text, fontSize = 24.sp, textAlign = TextAlign.Center, modifier = Modifier .fillMaxWidth() .padding(horizontal = 20.dp, vertical = 12.dp) .background(backgroundColor, shape = RoundedCornerShape(16.dp)) .height(60.dp) .clickable(onClick = onClick) ) } @Preview(showBackground = true) @Composable fun UploadNoticePreview() { HallServiceAppTheme { UploadNoticeScreen() } }
HallService--App/app/src/main/java/com/example/hallserviceapp/UploadNoticeActivity.kt
1285508210
package com.example.hallserviceapp.ui.theme import androidx.compose.ui.graphics.Color val Purple80 = Color(0xFFD0BCFF) val PurpleGrey80 = Color(0xFFCCC2DC) val Pink80 = Color(0xFFEFB8C8) val Purple40 = Color(0xFF6650a4) val PurpleGrey40 = Color(0xFF625b71) val Pink40 = Color(0xFF7D5260)
HallService--App/app/src/main/java/com/example/hallserviceapp/ui/theme/Color.kt
2798395585
package com.example.hallserviceapp.ui.theme import android.app.Activity import android.os.Build import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import androidx.core.view.WindowCompat private val DarkColorScheme = darkColorScheme( primary = Purple80, secondary = PurpleGrey80, tertiary = Pink80 ) private val LightColorScheme = lightColorScheme( primary = Purple40, secondary = PurpleGrey40, tertiary = Pink40 /* Other default colors to override background = Color(0xFFFFFBFE), surface = Color(0xFFFFFBFE), onPrimary = Color.White, onSecondary = Color.White, onTertiary = Color.White, onBackground = Color(0xFF1C1B1F), onSurface = Color(0xFF1C1B1F), */ ) @Composable fun HallServiceAppTheme( darkTheme: Boolean = isSystemInDarkTheme(), // Dynamic color is available on Android 12+ dynamicColor: Boolean = true, content: @Composable () -> Unit ) { val colorScheme = when { dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { val context = LocalContext.current if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) } darkTheme -> DarkColorScheme else -> LightColorScheme } val view = LocalView.current if (!view.isInEditMode) { SideEffect { val window = (view.context as Activity).window window.statusBarColor = colorScheme.primary.toArgb() WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme } } MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content ) }
HallService--App/app/src/main/java/com/example/hallserviceapp/ui/theme/Theme.kt
3613595102
package com.example.hallserviceapp.ui.theme import androidx.compose.material3.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp // Set of Material typography styles to start with val Typography = Typography( bodyLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp, lineHeight = 24.sp, letterSpacing = 0.5.sp ) /* Other default text styles to override titleLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 22.sp, lineHeight = 28.sp, letterSpacing = 0.sp ), labelSmall = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Medium, fontSize = 11.sp, lineHeight = 16.sp, letterSpacing = 0.5.sp ) */ )
HallService--App/app/src/main/java/com/example/hallserviceapp/ui/theme/Type.kt
903306908
package com.example.hallserviceapp import android.content.Context import android.net.Uri import android.os.Bundle import android.widget.Toast import androidx.activity.ComponentActivity import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.compose.setContent import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Add import androidx.compose.material3.AlertDialog import androidx.compose.material3.Button import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.TextStyle import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import coil.compose.rememberImagePainter import com.example.hallserviceapp.ui.theme.HallServiceAppTheme import com.google.firebase.database.DatabaseReference import com.google.firebase.database.ktx.database import com.google.firebase.ktx.Firebase import com.google.firebase.storage.FirebaseStorage import com.google.firebase.storage.StorageReference import java.text.SimpleDateFormat import java.util.Date import java.util.Locale import java.util.UUID class AddCanteenActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { HallServiceAppTheme { Surface( modifier = Modifier.fillMaxSize(), color = Color.White ) { AddCanteenScreen() } } } } } @Composable fun AddCanteenScreen() { var imageUri by remember { mutableStateOf<Uri?>(null) } var addCanteenName by remember { mutableStateOf("") } var price by remember { mutableStateOf("") } var time by remember { mutableStateOf("") } var date by remember { mutableStateOf("") } val context = LocalContext.current val storageReference = FirebaseStorage.getInstance().reference val databaseReference = Firebase.database.reference val lightBlue = Color(0xFF8FABE7) // Light blue color 0xFF8FABE7 var showDialog by remember { mutableStateOf(false) } var isLoading by remember { mutableStateOf(false) } // Loading state Surface( modifier = Modifier .fillMaxSize() ) { // Add the background image Image( painter = painterResource(id = R.drawable.bgpic4), // Replace with your image resource contentDescription = null, // Content description can be null for decorative images modifier = Modifier.fillMaxSize(), contentScale = ContentScale.FillBounds // Scale the image to fill the bounds ) Column( modifier = Modifier .fillMaxSize() //.background(lightBlue) .padding(16.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Top ) { HeaderSectionAll("Add Canteen Food") Spacer(modifier = Modifier.size(40.dp)) LazyColumn { item { Row( modifier = Modifier .fillMaxWidth() .padding(vertical = 10.dp), verticalAlignment = Alignment.CenterVertically ) { LoadImageAC { uri -> imageUri = uri } Spacer(modifier = Modifier.width(40.dp)) ShowImageAC(imageUri) } // Show selected image OutlinedTextField( value = addCanteenName, onValueChange = { addCanteenName = it }, label = { Text("Food Name", color = Color.White // Set label text color to white ) }, modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp), textStyle = TextStyle(color = Color.White) // Set text color to white ) OutlinedTextField( value = price, onValueChange = { price = it }, label = { Text("Price", color = Color.White // Set label text color to white ) }, modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp), textStyle = TextStyle(color = Color.White) // Set text color to white ) OutlinedTextField( value = time, onValueChange = { time = it }, label = { Text("Time", color = Color.White // Set label text color to white ) }, modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp), textStyle = TextStyle(color = Color.White) // Set text color to white ) date = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(Date()) Spacer(modifier = Modifier.size(16.dp)) if (isLoading) { Column( horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center, modifier = Modifier.fillMaxSize() ) { CircularProgressIndicator() Text( text = "Uploading... Please wait", style = MaterialTheme.typography.titleSmall, color = Color.Gray ) } } Button( onClick = { // Validate authority information if (addCanteenName.isNotEmpty() && price.isNotEmpty() && time.isNotEmpty() && imageUri != null ) { showDialog = true isLoading = true addCanteenToFirebase( context, imageUri, addCanteenName, price, time, date, storageReference, databaseReference ) // isLoading= false // showDialog = false } else { Toast.makeText( context, "Please fill all fields and select an image", Toast.LENGTH_SHORT ).show() } }, modifier = Modifier.align(Alignment.CenterHorizontally).fillMaxWidth() ) { Text("Upload Food Information") } if (showDialog) { AlertDialog( onDismissRequest = { showDialog = false isLoading = false }, title = { Text("Uploading") }, text = { Text("Uploading... Please wait") }, confirmButton = { TextButton( onClick = { showDialog = false isLoading = false } ) { Text("Dismiss") } } ) } } } } } } @Composable fun LoadImageAC( onImageSelected: (Uri) -> Unit ) { //var uri by remember { mutableStateOf<Uri?>(null) } val launcher = rememberLauncherForActivityResult( contract = ActivityResultContracts.GetContent() ) { uri -> uri?.let { onImageSelected(it) } } Box( modifier = Modifier .size(80.dp) .clickable { launcher.launch("image/*") } .background(Color(0xFFFBF9FC), RoundedCornerShape(8.dp)), contentAlignment = Alignment.Center ) { Image( imageVector = Icons.Default.Add, contentDescription = "Plus Icon", modifier = Modifier .size(60.dp) ) } } @Composable fun ShowImageAC(imageUri: Uri?) { if (imageUri != null) { // Show the selected image Image( painter = rememberImagePainter(imageUri), contentDescription = null, modifier = Modifier .size(150.dp) .padding(vertical = 8.dp) .clip(shape = RoundedCornerShape(8.dp)) ) } } fun addCanteenToFirebase( context: Context, imageUri: Uri?, addCanteenName: String, price: String, time: String, date: String, storageReference: StorageReference, databaseReference: DatabaseReference, ) { imageUri?.let { uri -> val imageRef = storageReference.child("images/${UUID.randomUUID()}") imageRef.putFile(uri) .addOnSuccessListener { taskSnapshot -> taskSnapshot.storage.downloadUrl.addOnSuccessListener { uri -> val imageUrl = uri.toString() // Create Authority object val canteenFood = CanteenFood( addCanteenName, price, time, date, imageUrl ) // Push Authority object to Firebase Database databaseReference.child("CanteenFoods").push().setValue(canteenFood) .addOnSuccessListener { Toast.makeText( context, "Food information uploaded successfully", Toast.LENGTH_SHORT ).show() } .addOnFailureListener { Toast.makeText( context, "Failed to upload Food information", Toast.LENGTH_SHORT ).show() } } } .addOnFailureListener { Toast.makeText( context, "Failed to upload image", Toast.LENGTH_SHORT ).show() } } } data class CanteenFood( val addCanteenName: String = "", val price: String = "", val time: String = "", val date: String = "", val imageUrl: String = "" ) @Preview(showBackground = true) @Composable fun AddCanteenScreenPreview() { HallServiceAppTheme { AddCanteenScreen() } }
HallService--App/app/src/main/java/com/example/hallserviceapp/AddCanteenActivity.kt
473725024
package com.example.hallserviceapp import android.content.Intent import android.net.Uri import android.os.Bundle import android.widget.Toast import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material3.Button import androidx.compose.material3.Card import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.example.hallserviceapp.ui.theme.HallServiceAppTheme import com.google.firebase.database.DataSnapshot import com.google.firebase.database.DatabaseError import com.google.firebase.database.FirebaseDatabase import com.google.firebase.database.ValueEventListener class DeleteNoticeActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { HallServiceAppTheme { DeleteNoticeContent() } } } } @Composable fun DeleteNoticeContent() { val lightBlue = Color(0xFF8FABE7) // Light blue color val database = FirebaseDatabase.getInstance().getReference("notices") var noticeList by remember { mutableStateOf(listOf<NoticeDN>()) } var isLoading by remember { mutableStateOf(true) } var isError by remember { mutableStateOf(false) } LaunchedEffect(key1 = Unit) { database.orderByChild("date").addValueEventListener(object : ValueEventListener { override fun onDataChange(snapshot: DataSnapshot) { isLoading = false noticeList = snapshot.children.mapNotNull { it.getValue(NoticeDN::class.java)?.copy(id = it.key ?: "") } } override fun onCancelled(error: DatabaseError) { isLoading = false isError = true } }) } val notices = noticeList Box( modifier = Modifier .fillMaxSize() ) { // Add the background image Image( painter = painterResource(id = R.drawable.bgpic4), // Replace with your image resource contentDescription = null, // Content description can be null for decorative images modifier = Modifier.fillMaxSize(), contentScale = ContentScale.FillBounds // Scale the image to fill the bounds ) Column( modifier = Modifier .fillMaxSize() //.background(lightBlue, shape = RoundedCornerShape(10.dp)) .padding(16.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Top ) { HeaderSectionAll("Delete Notice") Spacer(modifier = Modifier.height(16.dp)) if (isLoading) { CircularProgressIndicator() } else if (isError) { Text("Error loading complaints.") } else { if (notices.isNotEmpty()) { LazyColumn { items(notices) { notice -> DeleteNoticeItem(notice) { noticestId -> database.child(noticestId).removeValue() } } } } else { Text(text = "No notices found", style = MaterialTheme.typography.titleMedium) } } } } } @Composable fun DeleteNoticeItem(notice: NoticeDN, onDelete: (String) -> Unit) { Card( modifier = Modifier .fillMaxWidth() .padding(vertical = 8.dp) ) { Column(modifier = Modifier.padding(16.dp)) { Text(text = "Date: ${notice.date}", style = MaterialTheme.typography.bodySmall) Spacer(modifier = Modifier.height(4.dp)) Text(text = "Title: ${notice.title}", style = MaterialTheme.typography.titleMedium) Spacer(modifier = Modifier.height(4.dp)) Text(text = "Text: ${notice.text}", style = MaterialTheme.typography.titleSmall) Spacer(modifier = Modifier.height(4.dp)) Text(text = "File: ${notice.pdfUri}", style = MaterialTheme.typography.bodyMedium) if (notice.pdfUri.isNotEmpty()) { val context = LocalContext.current Button(onClick = { val intent = Intent(Intent.ACTION_VIEW) intent.data = Uri.parse(notice.pdfUri) intent.type = "application/pdf" // Specify the MIME type val chooser = Intent.createChooser(intent, "Open PDF") // Verify that the intent will resolve to an activity if (intent.resolveActivity(context.packageManager) != null) { context.startActivity(chooser) } else { // Handle the case where no activity can handle the intent Toast.makeText(context, "No application found to open PDF", Toast.LENGTH_SHORT).show() } }) { Text(text = "View PDF") } } Spacer(modifier = Modifier.height(4.dp)) Button(onClick = { onDelete(notice.id) } ) { Text(text = "Delete") } } } } data class NoticeDN( val id: String = "", val userid: String = "", val title: String = "", val date: String = "", val text: String = "", val pdfUri: String = "" ) @Preview(showBackground = true) @Composable fun DeleteNoticePreview() { HallServiceAppTheme { DeleteNoticeContent() } }
HallService--App/app/src/main/java/com/example/hallserviceapp/DeleteNoticeActivity.kt
24409192
package com.example.hallserviceapp import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Construction import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.example.hallserviceapp.ui.theme.HallServiceAppTheme class ServicesActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { HallServiceAppTheme { Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { ServicesScreen() } } } } } @Composable fun ServicesScreen() { val lightBlue = Color(0xFF8FABE7) // Light blue color val green = Color(0xFF43B83A) val context = LocalContext.current Box( modifier = Modifier .fillMaxSize() ) { // Add the background image Image( painter = painterResource(id = R.drawable.bgpic4), // Replace with your image resource contentDescription = null, // Content description can be null for decorative images modifier = Modifier.fillMaxSize(), contentScale = ContentScale.FillBounds // Scale the image to fill the bounds ) Column( modifier = Modifier .fillMaxSize() //.background(lightBlue, shape = RoundedCornerShape(10.dp)) .padding(16.dp), verticalArrangement = Arrangement.Top, ) { Headlineee("Services") ServicesList() } } } @Composable fun ServicesList() { Column( modifier = Modifier .fillMaxSize() .padding(16.dp) ) { ServiceItem( icon = Icons.Default.Construction, serviceName = "Room Cleaning", roomNumber = "Room no: 101" ) ServiceItem( icon = Icons.Default.Construction, serviceName = "Glass Repairing", roomNumber = "Room no: 102" ) ServiceItem( icon = Icons.Default.Construction, serviceName = "Light Repairing", roomNumber = "Room no: 103" ) ServiceItem( icon = Icons.Default.Construction, serviceName = "Drilling", roomNumber = "Room no: 104" ) ServiceItem( icon = Icons.Default.Construction, serviceName = "Wash Room Cleaning", roomNumber = "Room no: 105" ) } } @Composable fun ServiceItem(icon: ImageVector, serviceName: String, roomNumber: String) { Row( modifier = Modifier .fillMaxWidth() .background(Color.White, shape = RoundedCornerShape(10.dp)) .padding(5.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Start ) { Icon( imageVector = icon, contentDescription = null, modifier = Modifier .size(80.dp, 80.dp) .padding(end = 16.dp) ) Column { Text(text = serviceName, fontWeight = FontWeight.Bold, fontSize = 20.sp) //Text(text = roomNumber, fontSize = 16.sp) } } Spacer(modifier = Modifier.height(20.dp)) // For spacing } @Preview(showBackground = true) @Composable fun ServicesScreenPreview() { HallServiceAppTheme { ServicesScreen() } }
HallService--App/app/src/main/java/com/example/hallserviceapp/ServicesActivity.kt
2395298755
package com.example.hallserviceapp import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.shape.CircleShape import androidx.compose.material3.Card import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.Divider import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.painter.Painter import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import coil.compose.rememberImagePainter import com.example.hallserviceapp.ui.theme.HallServiceAppTheme import com.google.firebase.database.DataSnapshot import com.google.firebase.database.DatabaseError import com.google.firebase.database.FirebaseDatabase import com.google.firebase.database.ValueEventListener class StudentsInformationActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { HallServiceAppTheme { Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { StudentsInformationScreen() } } } } } @Composable fun StudentsInformationScreen() { val lightBlue = Color(0xFF8FABE7) // Light blue color Box( modifier = Modifier .fillMaxSize() ) { // Add the background image Image( painter = painterResource(id = R.drawable.bgpic4), // Replace with your image resource contentDescription = null, // Content description can be null for decorative images modifier = Modifier.fillMaxSize(), contentScale = ContentScale.FillBounds // Scale the image to fill the bounds ) Column( modifier = Modifier .fillMaxSize() .padding(16.dp) ) { Headlineee("Student Information") StudentsInformationSection() } } } @Composable fun StudentsInformationSection() { val database = FirebaseDatabase.getInstance().getReference("students") var studentList by remember { mutableStateOf(listOf<Student>()) } var isLoading by remember { mutableStateOf(true) } var isError by remember { mutableStateOf(false) } LaunchedEffect(key1 = Unit) { database.addValueEventListener(object : ValueEventListener { override fun onDataChange(snapshot: DataSnapshot) { isLoading = false studentList = snapshot.children.mapNotNull { it.getValue(Student::class.java) } } override fun onCancelled(error: DatabaseError) { isLoading = false isError = true } }) } if (isLoading) { //CircularProgressIndicator() Column( horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center, modifier = Modifier.fillMaxSize() ) { CircularProgressIndicator() Text( text = "Loading... Please wait", style = MaterialTheme.typography.titleSmall, color = Color.Gray ) } } else if (isError) { Text("Error loading student information.") } else { LazyColumn(modifier = Modifier.fillMaxSize()) { items(studentList) { student -> StudentItem(student) } } } } @Composable fun StudentItem(student: Student) { val gree = Color(0xFF36A2D8) Card( modifier = Modifier .fillMaxWidth() .padding(vertical = 8.dp) //.background(Color.White) ,// Set a white background color for the card //elevation = 4.dp // Add elevation for a shadow effect ) { Column( modifier = Modifier .padding(16.dp) .fillMaxWidth() ) { Row( verticalAlignment = Alignment.CenterVertically ) { val painter: Painter = rememberImagePainter(student.imageUrl) Image( painter = painter, contentDescription = "Student Image", modifier = Modifier .size(80.dp) .clip(CircleShape) // Clip the image to a circle shape ) Spacer(modifier = Modifier.width(16.dp)) Column( modifier = Modifier.weight(1f) ) { Text( text = student.name, style = MaterialTheme.typography.headlineSmall, fontWeight = FontWeight.Bold, color = Color(0xFF3D82D5) ) Spacer(modifier = Modifier.height(4.dp)) Text( text = "Registration: ${student.registrationNumber}", style = MaterialTheme.typography.bodyMedium, color = Color.Black ) Spacer(modifier = Modifier.height(4.dp)) Text( text = "Department: ${student.department}", style = MaterialTheme.typography.bodyMedium, color = gree ) Spacer(modifier = Modifier.height(4.dp)) Text( text = "Hometown: ${student.hometown}", style = MaterialTheme.typography.bodyMedium, color = gree ) Spacer(modifier = Modifier.height(4.dp)) Text( text = "Phone: ${student.phoneNumber}", style = MaterialTheme.typography.bodyMedium, color = gree ) Spacer(modifier = Modifier.height(4.dp)) Text( text = "Room No: ...", style = MaterialTheme.typography.bodyMedium, color = gree ) } } Divider( // Add a divider line between student items color = Color.Black, thickness = 2.dp, modifier = Modifier.padding(vertical = 8.dp) ) } } } @Composable fun StudentItem2(student: Student) { Card( modifier = Modifier .fillMaxWidth() .padding(vertical = 8.dp) ) { Row( modifier = Modifier .padding(vertical = 8.dp) .fillMaxWidth(), verticalAlignment = Alignment.CenterVertically ) { //ShowImages(authority.imageUrl) val painter: Painter = rememberImagePainter(student.imageUrl) Image( painter = painter, contentDescription = "Student Image", modifier = Modifier .size(80.dp) .padding(start = 8.dp) ) Spacer(modifier = Modifier.width(14.dp)) Column( modifier = Modifier.padding(16.dp) ) { Text( text = "Name: ${student.name}", style = MaterialTheme.typography.titleMedium ) Spacer(modifier = Modifier.height(6.dp)) Text( text = "Registration Number: ${student.registrationNumber}", style = MaterialTheme.typography.bodyMedium ) Spacer(modifier = Modifier.height(4.dp)) Text( text = "Department: ${student.department}", style = MaterialTheme.typography.bodySmall ) Spacer(modifier = Modifier.height(4.dp)) Text( text = "Hometown: ${student.hometown}", style = MaterialTheme.typography.bodySmall ) Spacer(modifier = Modifier.height(4.dp)) Text( text = "Phone Number: ${student.phoneNumber}", style = MaterialTheme.typography.bodySmall ) Spacer(modifier = Modifier.height(4.dp)) // Add more details or actions for each student item here } } } } data class Student( val id : String = "", val department: String = "", val hometown: String = "", val imageUrl: String = "", val name: String = "", val phoneNumber: String = "", val registrationNumber: String = "" ) @Preview(showBackground = true) @Composable fun StudentsInformationScreenPreview() { HallServiceAppTheme { StudentsInformationScreen() } }
HallService--App/app/src/main/java/com/example/hallserviceapp/StudentsIActivity.kt
2006562167
package com.example.hallserviceapp import android.content.Intent import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.Button import androidx.compose.material.ButtonDefaults import androidx.compose.material3.Card import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.example.hallserviceapp.ui.theme.HallServiceAppTheme import kotlinx.coroutines.delay class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { HallServiceAppTheme { MainScreen() } } // Write a message to the database } } @Composable fun MainScreen() { var isShowingFirstImage by remember { mutableStateOf(true) } LaunchedEffect(key1 = true) { // Wait for 0.5 seconds before showing the second image delay(2500) isShowingFirstImage = false } if (isShowingFirstImage) { ColumnWithBackgroundImage( backgroundImageRes = R.drawable.bgpic2, contentPadding = 1.dp ) { // Your content goes here Column( modifier = Modifier .fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { Text( text = "Syed Mujtaba Ali", color = Color.White, fontSize = 30.sp, // Adjusted for better fit modifier = Modifier .padding(vertical = 16.dp) .fillMaxWidth(), //.background(color = Color(51, 165, 125, 255),shape = MaterialTheme.shapes.medium), textAlign = TextAlign.Center ) Spacer(modifier = Modifier.height(2.dp)) Text( text = "Hall", color = Color.White, fontSize = 34.sp, // Adjusted for better fit modifier = Modifier //.padding(vertical = 16.dp) .fillMaxWidth(), //.background(color = Color(51, 165, 125, 255),shape = MaterialTheme.shapes.medium), textAlign = TextAlign.Center ) } } /* Image( painter = painterResource(id = R.drawable.back_pic2), contentDescription = "Image", modifier = Modifier.fillMaxSize() ) */ // Display the first image with a delay } else { Scaffold( topBar = { AppBar() }, content = { padding -> MainContent(padding) } // Remove the floatingActionButton if not needed ) } } @Composable fun ColumnWithBackgroundImage( backgroundImageRes: Int, contentPadding: Dp = 1.dp, content: @Composable () -> Unit ) { BoxWithConstraints( modifier = Modifier.fillMaxSize() ) { //val constraints = maxWidth.toFloat() to maxHeight.toFloat() val backgroundPainter = painterResource(id = backgroundImageRes) Box( modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center, ) { Image( painter = backgroundPainter, contentDescription = null, modifier = Modifier .wrapContentSize(Alignment.Center) .fillMaxSize() ) } // Add content on top of the background image Box( modifier = Modifier.fillMaxSize().padding(contentPadding), contentAlignment = Alignment.Center, ) { content() } } } @OptIn(ExperimentalMaterial3Api::class) @Composable fun AppBar() { val lightblueTo = Color(0xFF4FF5CD) // Light blue color val context = LocalContext.current Box( modifier = Modifier .fillMaxWidth() .height(65.dp) .background(lightblueTo) // Set the Topbackground color here ) { Row ( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween, modifier = Modifier .fillMaxWidth() //.background(lightblueTo) // Set the Topbackground color here ){ Text( text = "Hall App", color = Color(0xFF302B2B), fontSize = 20.sp, // Adjusted for better fit modifier = Modifier .padding(vertical = 16.dp) .padding(start = 14.dp) .width(270.dp) ) Spacer(modifier = Modifier.width(25.dp)) Text( text = "Admin", color = Color(0xFF727070), fontSize = 15.sp, // Adjusted for better fit modifier = Modifier .padding(vertical = 16.dp) .fillMaxWidth() //.padding(end = 5.dp) .clickable { context.startActivity(Intent(context, FrontAdminActivity::class.java)) }, ) } } } @Composable fun MainContent(padding: PaddingValues) { // Define a light blue color val lightBlue = Color(0xFF8FABE7) // Light blue color Box( modifier = Modifier .fillMaxSize() ) { // Add the background image Image( painter = painterResource(id = R.drawable.bgppic6), // Replace with your image resource contentDescription = null, // Content description can be null for decorative images modifier = Modifier.fillMaxSize(), contentScale = ContentScale.FillBounds // Scale the image to fill the bounds ) // Content layout Column( modifier = Modifier .fillMaxSize() .padding(16.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { //CircularImageView(imageRes = R.drawable.logo_var_3, size = 120.dp) Image( painter = painterResource(id = R.drawable.logo_var_3), contentDescription = "Image", modifier = Modifier .size(width = 120.dp, height = 120.dp) .padding(2.dp) ) Spacer(modifier = Modifier.height(30.dp)) CircularImageView(imageRes = R.drawable.hall_pic, size = 290.dp, height = 145.dp) HallTitle() Spacer(modifier = Modifier.height(40.dp)) EnterButton() } } } @Composable fun CircularImageView(imageRes: Int, size: Dp, height: Dp = size) { Card( shape = CircleShape, modifier = Modifier .size(width = size, height = height) .padding(2.dp) ) { Image( painter = painterResource(id = imageRes), contentDescription = "Image", modifier = Modifier.fillMaxSize() ) } //Spacer(modifier = Modifier.height(30.dp)) } @Composable fun HallTitle() { Text( text = "SUST Hall 3", color = Color(0xFF49A7D3), fontSize = 30.sp, // Adjusted for better fit modifier = Modifier .padding(vertical = 16.dp) .fillMaxWidth(), textAlign = TextAlign.Center ) } @Composable fun EnterButton() { val context = LocalContext.current Button( onClick = { context.startActivity(Intent(context, LoginActivity::class.java)) // Change to the desired activity }, colors = ButtonDefaults.buttonColors(backgroundColor = Color(0xFF04CFB2)), modifier = Modifier .fillMaxWidth() .height(67.dp) .padding(vertical = 16.dp) //.background(Color(0xFF04CFB2), shape = RoundedCornerShape(15.dp)) ) { Text(text = "Enter") } } @Preview(showBackground = true) @Composable fun DefaultPreview() { HallServiceAppTheme { MainScreen() } }
HallService--App/app/src/main/java/com/example/hallserviceapp/MainActivity.kt
1584972609
package com.example.hallserviceapp import android.content.Intent import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Divider import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.example.hallserviceapp.ui.theme.HallServiceAppTheme class FoodActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { HallServiceAppTheme { Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { FoodScreen() } } } } } @Composable fun FoodScreen() { val lightBlue = Color(0xFF8FABE7) // Light blue color val gray = Color(0xFFA5960D) val context = LocalContext.current Box( modifier = Modifier .fillMaxSize() ) { // Add the background image Image( painter = painterResource(id = R.drawable.bgpic4), // Replace with your image resource contentDescription = null, // Content description can be null for decorative images modifier = Modifier.fillMaxSize(), contentScale = ContentScale.FillBounds // Scale the image to fill the bounds ) Column( modifier = Modifier .fillMaxSize() //.background(lightBlue) .padding(16.dp), verticalArrangement = Arrangement.Top, ) { Box( contentAlignment = Alignment.TopCenter, modifier = Modifier .padding(horizontal = 18.dp) ) { Headlineee("Food") } val lightGoldB = Color(0xFFE1E6E5) Box( contentAlignment = Alignment.TopCenter, modifier = Modifier.fillMaxSize() ) { Column( horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier .fillMaxWidth() .padding(3.dp) ) { // Your other UI elements go here Spacer(modifier = Modifier.height(25.dp)) // For spacing Divider( // Add a divider line between student items color = Color.White, thickness = 10.dp, modifier = Modifier .padding(8.dp) .padding(horizontal = 10.dp) .background(Color.White, shape = RoundedCornerShape(10.dp)) ) Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween, modifier = Modifier .fillMaxWidth() .padding(horizontal = 16.dp) ) { Column( verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier .clickable { context.startActivity( Intent( context, ReadDiningActivity::class.java ) ) // Change to the desired activity } ){ Image( painter = painterResource(id = R.drawable.dyningfood), contentDescription = "Dining", modifier = Modifier .size(80.dp) .padding(8.dp) ) Text( text = "Enter Dining Food", fontSize = 15.sp, color = Color.White, textAlign = TextAlign.Center, modifier = Modifier//.padding(start = 16.dp) .padding(start = 12.dp) ) } Column( verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier .clickable { context.startActivity( Intent( context, ReadCanteenActivity::class.java ) ) // Change to the desired activity } ){ Image( painter = painterResource(id = R.drawable.foodd), contentDescription = "Dining", modifier = Modifier .size(80.dp) .padding(8.dp) ) Text( text = "Enter Canteen Food", fontSize = 15.sp, color = Color.White, textAlign = TextAlign.Justify, ) } } Spacer(modifier = Modifier.height(45.dp)) // For spacing Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Center, modifier = Modifier.padding(vertical = 8.dp) //.background(lightGoldB, shape = RoundedCornerShape(10.dp)) .clickable { context.startActivity( Intent( context, DiningActivity::class.java ) ) // Change to the desired activity } .padding(horizontal = 12.dp) .background(lightGoldB, shape = RoundedCornerShape(10.dp)) ) { Image( painter = painterResource(id = R.drawable.dyningfood), contentDescription = "Dining", modifier = Modifier .size(80.dp) .padding(10.dp) ) //Spacer(modifier = Modifier.width(12.dp)) // For spacing Text( text = "Dining", fontSize = 34.sp, textAlign = TextAlign.Center, modifier = Modifier//.padding(start = 16.dp) .fillMaxWidth() ) } //Spacer(modifier = Modifier.height(20.dp)) // For spacing // Add more Rows or other components as needed Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(vertical = 8.dp) //.background(lightGoldB, shape = RoundedCornerShape(10.dp)) .clickable { context.startActivity( Intent( context, CanteenActivity::class.java ) ) // Change to the desired activity } .padding(horizontal = 12.dp) .background(lightGoldB, shape = RoundedCornerShape(10.dp)) ) { Image( painter = painterResource(id = R.drawable.foodd), contentDescription = "Canteen", modifier = Modifier .size(80.dp) .padding(10.dp) ) Text( text = "Canteen", fontSize = 34.sp, textAlign = TextAlign.Center, modifier = Modifier//.padding(start = 16.dp) .fillMaxWidth() ) } Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(vertical = 8.dp) //.background(lightGoldB, shape = RoundedCornerShape(10.dp)) .clickable { context.startActivity( Intent( context, ShopActivity::class.java ) ) // Change to the desired activity } .padding(horizontal = 12.dp) .background(lightGoldB, shape = RoundedCornerShape(10.dp)) ) { Image( painter = painterResource(id = R.drawable.shop_food), contentDescription = "Shop", modifier = Modifier .size(80.dp) .padding(10.dp) ) Text( text = "Food Shop", fontSize = 34.sp, textAlign = TextAlign.Center, modifier = Modifier//.padding(start = 16.dp) .fillMaxWidth() ) } } } } } } @Preview(showBackground = true) @Composable fun FoodScreenPreview() { FoodScreen() }
HallService--App/app/src/main/java/com/example/hallserviceapp/FoodActivity.kt
2191559189
package com.example.hallserviceapp import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material3.Button import androidx.compose.material3.Card import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.painter.Painter import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import coil.compose.rememberImagePainter import com.example.hallserviceapp.ui.theme.HallServiceAppTheme import com.google.firebase.database.DataSnapshot import com.google.firebase.database.DatabaseError import com.google.firebase.database.FirebaseDatabase import com.google.firebase.database.ValueEventListener class DeleteCanteenActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { HallServiceAppTheme { Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { DeleteCanteenScreen() } } } } } @Composable fun DeleteCanteenScreen() { val lightBlue = Color(0xFF8FABE7) // Light blue color Box( modifier = Modifier .fillMaxSize() ) { // Add the background image Image( painter = painterResource(id = R.drawable.bgpic4), // Replace with your image resource contentDescription = null, // Content description can be null for decorative images modifier = Modifier.fillMaxSize(), contentScale = ContentScale.FillBounds // Scale the image to fill the bounds ) Column( modifier = Modifier .fillMaxSize() //.background(lightBlue) .padding(16.dp) ) { HeaderSectionAll("Delete Food") DeleteCanteenSections() // Pass the registration number to filter the list } } } @Composable fun DeleteCanteenSections() { val database = FirebaseDatabase.getInstance().getReference("CanteenFoods") var canteenFoodsList by remember { mutableStateOf(listOf<CanteenFoods>()) } var isLoading by remember { mutableStateOf(true) } var isError by remember { mutableStateOf(false) } LaunchedEffect(key1 = Unit) { database.addValueEventListener(object : ValueEventListener { override fun onDataChange(snapshot: DataSnapshot) { isLoading = false canteenFoodsList = snapshot.children.mapNotNull { it.getValue(CanteenFoods::class.java)?.copy(id = it.key ?: "") } } override fun onCancelled(error: DatabaseError) { isLoading = false isError = true } }) } if (isLoading) { CircularProgressIndicator() } else if (isError) { Text("Error loading Food information.") } else { LazyColumn(modifier = Modifier.fillMaxSize()) { items(canteenFoodsList) { canteenFood -> CanteenFoodItemWithDelete(canteenFood){ CanteenFoodId-> database.child(CanteenFoodId).removeValue() } } } } } @Composable fun CanteenFoodItemWithDelete(canteenFood: CanteenFoods, onDelete: (String) -> Unit) { val context = LocalContext.current Card(modifier = Modifier .fillMaxWidth() .padding(vertical = 8.dp)) { Row( modifier = Modifier .padding(vertical = 8.dp) .fillMaxWidth(), verticalAlignment = Alignment.CenterVertically ) { val painter: Painter = rememberImagePainter(canteenFood.imageUrl) Image( painter = painter, contentDescription = "Canteen Image", modifier = Modifier .size(80.dp) .padding(start = 8.dp) ) Spacer(modifier = Modifier.width(14.dp)) Column(modifier = Modifier.padding(16.dp)) { Text(text = "Date: ${canteenFood.date}", style = MaterialTheme.typography.titleMedium) Spacer(modifier = Modifier.height(6.dp)) Text(text = "Time: ${canteenFood.time}", style = MaterialTheme.typography.bodySmall) Spacer(modifier = Modifier.height(4.dp)) Text(text = "FoodName: ${canteenFood.addCanteenName}", style = MaterialTheme.typography.bodyMedium) Spacer(modifier = Modifier.height(4.dp)) Text(text = "Price: ${canteenFood.price}", style = MaterialTheme.typography.bodySmall) Spacer(modifier = Modifier.height(4.dp)) Button(onClick = { onDelete(canteenFood.id) }) { Text("Delete") } } } } } @Preview(showBackground = true) @Composable fun DeleteCanteenPreview() { HallServiceAppTheme { DeleteCanteenScreen() } }
HallService--App/app/src/main/java/com/example/hallserviceapp/DeleteCanteenActivity.kt
418318757
package com.example.hallserviceapp import android.os.Bundle import android.widget.Toast import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Button import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TextField import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.example.hallserviceapp.ui.theme.HallServiceAppTheme import com.google.firebase.auth.FirebaseAuth class AddUserActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { HallServiceAppTheme { Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { AddUserContent() } } } } } @Composable fun AddUserContent() { var email by remember { mutableStateOf("") } var password by remember { mutableStateOf("") } var createUserState by remember { mutableStateOf<UserState?>(null) } val lightBlue = Color(0xFF8FABE7) // Light blue color Box( modifier = Modifier .fillMaxSize() ) { // Add the background image Image( painter = painterResource(id = R.drawable.bgpic4), // Replace with your image resource contentDescription = null, // Content description can be null for decorative images modifier = Modifier.fillMaxSize(), contentScale = ContentScale.FillBounds // Scale the image to fill the bounds ) Column( modifier = Modifier.fillMaxSize() //.background(lightBlue) .padding(16.dp), verticalArrangement = Arrangement.Top, horizontalAlignment = Alignment.CenterHorizontally ) { val context = LocalContext.current HeaderSectionAll("Add User") Spacer(modifier = Modifier.height(150.dp)) Spacer(modifier = Modifier.height(16.dp)) // TextFields for email and password input TextField( value = email, onValueChange = { email = it }, label = { Text("Email") }, modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp) .clip(RoundedCornerShape(8.dp)), ) Spacer(modifier = Modifier.height(8.dp)) TextField( value = password, onValueChange = { password = it }, label = { Text("Password") }, modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp) .clip(RoundedCornerShape(8.dp)), ) Spacer(modifier = Modifier.height(16.dp)) Button( onClick = { // Call function to add user using Firebase Authentication createUserWithEmailAndPassword(email, password) { isSuccess, errorMessage -> if (isSuccess) { Toast.makeText(context, "User added successfully!", Toast.LENGTH_SHORT) .show() } else { Toast.makeText( context, "Failed to add user: $errorMessage", Toast.LENGTH_SHORT ).show() } } }, modifier = Modifier.padding(horizontal = 16.dp) ) { Text("Add User") } // Display user creation state createUserState?.let { userState -> when (userState) { is UserState.Success -> { Text("User added successfully!") } is UserState.Error -> { Text("Failed to add user: ${userState.errorMessage}") } } } } } } fun createUserWithEmailAndPassword(email: String, password: String, onComplete: (Boolean, String?) -> Unit) { val auth = FirebaseAuth.getInstance() auth.createUserWithEmailAndPassword(email, password) .addOnCompleteListener { task -> if (task.isSuccessful) { onComplete(true, null) // User added successfully } else { val errorMessage = task.exception?.message ?: "Unknown error" onComplete(false, errorMessage) // Error occurred while adding user } } } sealed class UserState { object Success : UserState() data class Error(val errorMessage: String) : UserState() } // Function to add a user using email and password fun createUserWithEmailAndPassword(email: String, password: String, onComplete: (UserState) -> Unit) { val auth = FirebaseAuth.getInstance() auth.createUserWithEmailAndPassword(email, password) .addOnCompleteListener { task -> if (task.isSuccessful) { onComplete(UserState.Success) // User added successfully } else { val errorMessage = task.exception?.message ?: "Unknown error" onComplete(UserState.Error(errorMessage)) // Error occurred while adding user } } } @Preview(showBackground = true) @Composable fun AddUserPreview() { HallServiceAppTheme { AddUserContent() } }
HallService--App/app/src/main/java/com/example/hallserviceapp/AddUserActivity.kt
133646959
package com.example.hallserviceapp import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material3.Button import androidx.compose.material3.Card import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.painter.Painter import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import coil.compose.rememberImagePainter import com.example.hallserviceapp.ui.theme.HallServiceAppTheme import com.google.firebase.database.DataSnapshot import com.google.firebase.database.DatabaseError import com.google.firebase.database.FirebaseDatabase import com.google.firebase.database.ValueEventListener class DeleteAuthorityActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { HallServiceAppTheme { Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { DeleteAuthorityScreen() } } } } } @Composable fun DeleteAuthorityScreen() { val lightBlue = Color(0xFF8FABE7) // Light blue color Box( modifier = Modifier .fillMaxSize() ) { // Add the background image Image( painter = painterResource(id = R.drawable.bgpic4), // Replace with your image resource contentDescription = null, // Content description can be null for decorative images modifier = Modifier.fillMaxSize(), contentScale = ContentScale.FillBounds // Scale the image to fill the bounds ) Column( modifier = Modifier .fillMaxSize() //.background(lightBlue) .padding(16.dp) ) { HeaderSectionAlii("Authority Information") DeleteAuthoritySections() // Pass the registration number to filter the list } } } @Composable fun DeleteAuthoritySections() { val database = FirebaseDatabase.getInstance().getReference("authorities") var authoritytList by remember { mutableStateOf(listOf<Authoritys>()) } var isLoading by remember { mutableStateOf(true) } var isError by remember { mutableStateOf(false) } LaunchedEffect(key1 = Unit) { database.addValueEventListener(object : ValueEventListener { override fun onDataChange(snapshot: DataSnapshot) { isLoading = false authoritytList = snapshot.children.mapNotNull { it.getValue(Authoritys::class.java)?.copy(id = it.key ?: "") } } override fun onCancelled(error: DatabaseError) { isLoading = false isError = true } }) } if (isLoading) { CircularProgressIndicator() } else if (isError) { Text("Error loading authority information.") } else { LazyColumn(modifier = Modifier.fillMaxSize()) { items(authoritytList) { authority -> AuthorityItemWithDelete(authority){ authorityId-> database.child(authorityId).removeValue() } } } } } @Composable fun AuthorityItemWithDelete(authority: Authoritys, onDelete: (String) -> Unit) { val context = LocalContext.current Card(modifier = Modifier .fillMaxWidth() .padding(vertical = 8.dp)) { Row( modifier = Modifier .padding(vertical = 8.dp) .fillMaxWidth(), verticalAlignment = Alignment.CenterVertically ) { val painter: Painter = rememberImagePainter(authority.imageUrl) Image( painter = painter, contentDescription = "Authority Image", modifier = Modifier .size(80.dp) .padding(start = 8.dp) ) Spacer(modifier = Modifier.width(14.dp)) Column(modifier = Modifier.padding(16.dp)) { Text(text = "Name: ${authority.name}", style = MaterialTheme.typography.titleMedium) Spacer(modifier = Modifier.height(6.dp)) Text(text = "Designation: ${authority.designation}", style = MaterialTheme.typography.bodyMedium) Spacer(modifier = Modifier.height(4.dp)) Text(text = "Email: ${authority.email}", style = MaterialTheme.typography.bodySmall) Spacer(modifier = Modifier.height(4.dp)) Text(text = "Phone Number: ${authority.phoneNumber}", style = MaterialTheme.typography.bodySmall) Spacer(modifier = Modifier.height(4.dp)) Button(onClick = { onDelete(authority.id) }) { Text("Delete") } } } } } @Preview(showBackground = true) @Composable fun DeleteAuthorityPreview() { HallServiceAppTheme { DeleteAuthorityScreen() } }
HallService--App/app/src/main/java/com/example/hallserviceapp/DeleteAuthorityActivity.kt
1713477172
package com.example.hallserviceapp import android.content.Context import android.content.Intent import android.os.Bundle import android.widget.Toast import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Button import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TextField import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.input.TextFieldValue import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.example.hallserviceapp.ui.theme.HallServiceAppTheme import com.google.firebase.auth.FirebaseAuth import com.google.firebase.database.ktx.database import com.google.firebase.ktx.Firebase import java.text.SimpleDateFormat import java.util.Date import java.util.Locale class NoticeTextActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { HallServiceAppTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { NoticeTextScreen() } } } } } @Composable fun NoticeTextScreen() { val context = LocalContext.current var titleState by remember { mutableStateOf(TextFieldValue()) } var textState by remember { mutableStateOf(TextFieldValue()) } var isUploading by remember { mutableStateOf(false) } val lightBlue = Color(0xFF8FABE7) // Light blue color Box( modifier = Modifier .fillMaxSize() ) { // Add the background image Image( painter = painterResource(id = R.drawable.bgpic4), // Replace with your image resource contentDescription = null, // Content description can be null for decorative images modifier = Modifier.fillMaxSize(), contentScale = ContentScale.FillBounds // Scale the image to fill the bounds ) Column( modifier = Modifier .fillMaxSize() //.background(lightBlue) .padding(16.dp) ) { HeaderSectionAl("TextNotice") Spacer(modifier = Modifier.height(20.dp)) InputTitleNT(titleState, "Enter complaint title") { titleState = it } Spacer(modifier = Modifier.height(15.dp)) InputFieldNT(textState, "Write your complaint here") { textState = it } Spacer(modifier = Modifier.height(16.dp)) Row( modifier = Modifier .fillMaxWidth() .padding(horizontal = 20.dp), horizontalArrangement = Arrangement.SpaceBetween ) { Button(onClick = { textState = TextFieldValue("") titleState = TextFieldValue("") }) { Text("Clear") } Button( onClick = { if (titleState.text.isNotBlank() && textState.text.isNotBlank()) { isUploading = true submitNotice(context, titleState.text, textState.text) { success -> if (success) { titleState = TextFieldValue("") textState = TextFieldValue("") } isUploading = false } } else { Toast.makeText(context, "Please fill all fields", Toast.LENGTH_LONG) .show() } }, //modifier = Modifier.fillMaxWidth() ) { Text("Submit Notice") } } if (isUploading) { Column( horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center, modifier = Modifier.fillMaxSize() ) { CircularProgressIndicator() Text( text = "Uploading... Please wait", style = MaterialTheme.typography.titleSmall, color = Color.Gray ) } } } } } @Composable fun InputTitleNT( state: TextFieldValue, placeholder: String, onValueChange: (TextFieldValue) -> Unit ) { // TextField UI modifications TextField( value = state, onValueChange = onValueChange, placeholder = { Text(placeholder) }, modifier = Modifier .fillMaxWidth() .height(65.dp) .padding(4.dp) .background(Color.White, shape = MaterialTheme.shapes.medium) ) } @Composable fun InputFieldNT( state: TextFieldValue, placeholder: String, onValueChange: (TextFieldValue) -> Unit ) { // TextField UI modifications TextField( value = state, onValueChange = onValueChange, placeholder = { Text(placeholder) }, modifier = Modifier .fillMaxWidth() .height(350.dp) .padding(4.dp) .background(Color.White, shape = MaterialTheme.shapes.medium) ) } @Composable fun HeaderSectionAl(headlinee : String) { val context = LocalContext.current Box( modifier = Modifier .fillMaxWidth() ) { Row( modifier = Modifier .fillMaxWidth() .padding(vertical = 10.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Center ) { //Spacer(modifier = Modifier.width(35.dp)) // For spacing Text( text = headlinee, color = Color.Black, fontSize = 20.sp, modifier = Modifier .background(Color.White, shape = RoundedCornerShape(10.dp)) .padding(10.dp) .clip(RoundedCornerShape(8.dp)), textAlign = TextAlign.Center ) } Image( painter = painterResource(id = R.drawable.arrow_back), contentDescription = "arrow", modifier = Modifier .clickable { context.startActivity( Intent( context, UploadNoticeActivity::class.java ) ) // Change to the desired activity } .padding(vertical = 10.dp) //.padding(top = 4.dp) .size(50.dp) .padding(9.dp) ) } } data class Notice(val userId: String, val title: String, val text: String, val date: String) { constructor(userId: String, title: String, text: String) : this( userId, title, text, SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(Date()) ) } fun submitNotice(context: Context, title: String, noticeText: String, onCompletion: (Boolean) -> Unit) { val auth = FirebaseAuth.getInstance() val userId = auth.currentUser?.uid ?: return onCompletion(false).also { Toast.makeText(context, "Please log in to submit a notice", Toast.LENGTH_LONG).show() } val database = Firebase.database val noticesRef = database.getReference("notices") val noticeId = noticesRef.push().key ?: return val notice = Notice(userId, title, noticeText) noticesRef.child(noticeId).setValue(notice) .addOnSuccessListener { Toast.makeText(context, "Notice submitted successfully", Toast.LENGTH_SHORT).show() onCompletion(true) } .addOnFailureListener { Toast.makeText(context, "Failed to submit notice", Toast.LENGTH_SHORT).show() onCompletion(false) } } @Preview(showBackground = true) @Composable fun NoticeTextScreenPreview() { HallServiceAppTheme { NoticeTextScreen() } }
HallService--App/app/src/main/java/com/example/hallserviceapp/NoticeTextActivity.kt
2614139564