content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.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.android.geto.feature.appsettings
import androidx.lifecycle.SavedStateHandle
import com.android.geto.core.data.repository.ClipboardResult
import com.android.geto.core.data.repository.ShortcutResult
import com.android.geto.core.domain.AppSettingsResult
import com.android.geto.core.domain.ApplyAppSettingsUseCase
import com.android.geto.core.domain.AutoLaunchUseCase
import com.android.geto.core.domain.RevertAppSettingsUseCase
import com.android.geto.core.model.AppSetting
import com.android.geto.core.model.SecureSetting
import com.android.geto.core.model.SettingType
import com.android.geto.core.model.TargetApplicationInfo
import com.android.geto.core.model.TargetShortcutInfoCompat
import com.android.geto.core.testing.repository.TestAppSettingsRepository
import com.android.geto.core.testing.repository.TestClipboardRepository
import com.android.geto.core.testing.repository.TestPackageRepository
import com.android.geto.core.testing.repository.TestSecureSettingsRepository
import com.android.geto.core.testing.repository.TestShortcutRepository
import com.android.geto.core.testing.repository.TestUserDataRepository
import com.android.geto.core.testing.util.MainDispatcherRule
import com.android.geto.feature.appsettings.navigation.APP_NAME_ARG
import com.android.geto.feature.appsettings.navigation.PACKAGE_NAME_ARG
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.runTest
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import kotlin.test.assertIs
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.test.assertTrue
@OptIn(ExperimentalCoroutinesApi::class)
class AppSettingsViewModelTest {
@get:Rule
val mainDispatcherRule = MainDispatcherRule()
private val packageRepository = TestPackageRepository()
private val appSettingsRepository = TestAppSettingsRepository()
private val secureSettingsRepository = TestSecureSettingsRepository()
private val clipboardRepository = TestClipboardRepository()
private val shortcutRepository = TestShortcutRepository()
private val userDataRepository = TestUserDataRepository()
private val savedStateHandle = SavedStateHandle()
private lateinit var applyAppSettingsUseCase: ApplyAppSettingsUseCase
private lateinit var revertAppSettingsUseCase: RevertAppSettingsUseCase
private lateinit var autoLaunchUseCase: AutoLaunchUseCase
private lateinit var viewModel: AppSettingsViewModel
private val packageName = "com.android.geto"
private val appName = "Geto"
@Before
fun setup() {
savedStateHandle[PACKAGE_NAME_ARG] = packageName
savedStateHandle[APP_NAME_ARG] = appName
applyAppSettingsUseCase = ApplyAppSettingsUseCase(
packageRepository = packageRepository,
appSettingsRepository = appSettingsRepository,
secureSettingsRepository = secureSettingsRepository,
)
revertAppSettingsUseCase = RevertAppSettingsUseCase(
appSettingsRepository = appSettingsRepository,
secureSettingsRepository = secureSettingsRepository,
)
autoLaunchUseCase = AutoLaunchUseCase(
packageRepository = packageRepository,
userDataRepository = userDataRepository,
appSettingsRepository = appSettingsRepository,
secureSettingsRepository = secureSettingsRepository,
)
viewModel = AppSettingsViewModel(
savedStateHandle = savedStateHandle,
appSettingsRepository = appSettingsRepository,
clipboardRepository = clipboardRepository,
packageRepository = packageRepository,
secureSettingsRepository = secureSettingsRepository,
shortcutRepository = shortcutRepository,
applyAppSettingsUseCase = applyAppSettingsUseCase,
revertAppSettingsUseCase = revertAppSettingsUseCase,
autoLaunchUseCase = autoLaunchUseCase,
)
}
@Test
fun appSettingsUiState_isLoading_whenStarted() {
assertIs<AppSettingsUiState.Loading>(viewModel.appSettingUiState.value)
}
@Test
fun applyAppSettingsResult_isNone_whenStarted() {
assertIs<AppSettingsResult.NoResult>(viewModel.applyAppSettingsResult.value)
}
@Test
fun revertAppSettingsResult_isNone_whenStarted() {
assertIs<AppSettingsResult.NoResult>(viewModel.revertAppSettingsResult.value)
}
@Test
fun shortcutResult_isNone_whenStarted() {
assertIs<ShortcutResult.NoResult>(viewModel.shortcutResult.value)
}
@Test
fun clipboardResult_isNone_whenStarted() {
assertIs<ClipboardResult.NoResult>(viewModel.clipboardResult.value)
}
@Test
fun applicationIcon_isNull_whenStarted() {
assertNull(viewModel.applicationIcon.value)
}
@Test
fun appSettingsUiState_isSuccess_whenAppSettings_isNotEmpty() = runTest {
val appSettings = List(5) { index ->
AppSetting(
id = index,
enabled = false,
settingType = SettingType.SYSTEM,
packageName = packageName,
label = "Geto",
key = "Geto $index",
valueOnLaunch = "0",
valueOnRevert = "1",
)
}
appSettingsRepository.setAppSettings(appSettings)
val collectJob =
launch(UnconfinedTestDispatcher()) { viewModel.appSettingUiState.collect() }
assertIs<AppSettingsUiState.Success>(viewModel.appSettingUiState.value)
collectJob.cancel()
}
@Test
fun applyAppSettingsResult_isSuccess_whenApplySettings() = runTest {
val appSettings = List(5) { index ->
AppSetting(
id = index,
enabled = true,
settingType = SettingType.SYSTEM,
packageName = packageName,
label = "Geto",
key = "Geto $index",
valueOnLaunch = "0",
valueOnRevert = "1",
)
}
appSettingsRepository.setAppSettings(appSettings)
secureSettingsRepository.setWriteSecureSettings(true)
viewModel.applyAppSettings()
assertIs<AppSettingsResult.Success>(viewModel.applyAppSettingsResult.value)
}
@Test
fun applyAppSettingsResult_isSecurityException_whenApplySettings() = runTest {
val appSettings = List(5) { index ->
AppSetting(
id = index,
enabled = true,
settingType = SettingType.SYSTEM,
packageName = packageName,
label = "Geto",
key = "Geto $index",
valueOnLaunch = "0",
valueOnRevert = "1",
)
}
appSettingsRepository.setAppSettings(appSettings)
secureSettingsRepository.setWriteSecureSettings(false)
viewModel.applyAppSettings()
assertIs<AppSettingsResult.SecurityException>(viewModel.applyAppSettingsResult.value)
}
@Test
fun applyAppSettingsResult_isIllegalArgumentException_whenApplySettings() = runTest {
val appSettings = List(5) { index ->
AppSetting(
id = index,
enabled = true,
settingType = SettingType.SYSTEM,
packageName = packageName,
label = "Geto",
key = "Geto $index",
valueOnLaunch = "0",
valueOnRevert = "1",
)
}
appSettingsRepository.setAppSettings(appSettings)
secureSettingsRepository.setWriteSecureSettings(true)
secureSettingsRepository.setInvalidValues(true)
viewModel.applyAppSettings()
assertIs<AppSettingsResult.IllegalArgumentException>(viewModel.applyAppSettingsResult.value)
}
@Test
fun applyAppSettingsResult_isEmptyAppSettings_whenApplySettings() = runTest {
appSettingsRepository.setAppSettings(emptyList())
secureSettingsRepository.setWriteSecureSettings(true)
viewModel.applyAppSettings()
assertIs<AppSettingsResult.EmptyAppSettings>(viewModel.applyAppSettingsResult.value)
}
@Test
fun applyAppSettingsResult_isAppSettingsDisabled_whenApplySettings() = runTest {
val appSettings = List(5) { index ->
AppSetting(
id = index,
enabled = false,
settingType = SettingType.SYSTEM,
packageName = packageName,
label = "Geto",
key = "Geto $index",
valueOnLaunch = "0",
valueOnRevert = "1",
)
}
appSettingsRepository.setAppSettings(appSettings)
secureSettingsRepository.setWriteSecureSettings(true)
viewModel.applyAppSettings()
assertIs<AppSettingsResult.DisabledAppSettings>(viewModel.applyAppSettingsResult.value)
}
@Test
fun revertAppSettingsResult_isSuccess_whenRevertSettings() = runTest {
val appSettings = List(5) { index ->
AppSetting(
id = index,
enabled = true,
settingType = SettingType.SYSTEM,
packageName = packageName,
label = "Geto",
key = "Geto $index",
valueOnLaunch = "0",
valueOnRevert = "1",
)
}
secureSettingsRepository.setWriteSecureSettings(true)
appSettingsRepository.setAppSettings(appSettings)
viewModel.revertAppSettings()
assertIs<AppSettingsResult.Success>(viewModel.revertAppSettingsResult.value)
}
@Test
fun revertAppSettingsResult_isSecurityException_whenRevertSettings() = runTest {
val appSettings = List(5) { index ->
AppSetting(
id = index,
enabled = true,
settingType = SettingType.SYSTEM,
packageName = packageName,
label = "Geto",
key = "Geto $index",
valueOnLaunch = "0",
valueOnRevert = "1",
)
}
secureSettingsRepository.setWriteSecureSettings(false)
appSettingsRepository.setAppSettings(appSettings)
viewModel.revertAppSettings()
assertIs<AppSettingsResult.SecurityException>(viewModel.revertAppSettingsResult.value)
}
@Test
fun revertAppSettingsResultI_isIllegalArgumentException_whenRevertSettings() = runTest {
val appSettings = List(5) { index ->
AppSetting(
id = index,
enabled = true,
settingType = SettingType.SYSTEM,
packageName = packageName,
label = "Geto",
key = "Geto $index",
valueOnLaunch = "0",
valueOnRevert = "1",
)
}
appSettingsRepository.setAppSettings(appSettings)
secureSettingsRepository.setWriteSecureSettings(true)
secureSettingsRepository.setInvalidValues(true)
viewModel.revertAppSettings()
assertIs<AppSettingsResult.IllegalArgumentException>(viewModel.revertAppSettingsResult.value)
}
@Test
fun revertAppSettingsResult_isEmptyAppSettings_whenRevertSettings() = runTest {
appSettingsRepository.setAppSettings(emptyList())
viewModel.revertAppSettings()
assertIs<AppSettingsResult.EmptyAppSettings>(viewModel.revertAppSettingsResult.value)
}
@Test
fun revertAppSettingsResult_isAppSettingsDisabled_whenRevertSettings() = runTest {
val appSettings = List(5) { index ->
AppSetting(
id = index,
enabled = false,
settingType = SettingType.SYSTEM,
packageName = packageName,
label = "Geto",
key = "Geto $index",
valueOnLaunch = "0",
valueOnRevert = "1",
)
}
appSettingsRepository.setAppSettings(appSettings)
secureSettingsRepository.setWriteSecureSettings(true)
viewModel.revertAppSettings()
assertIs<AppSettingsResult.DisabledAppSettings>(viewModel.revertAppSettingsResult.value)
}
@Test
fun clipboardResult_isNotify_whenCopyPermissionCommand() = runTest {
clipboardRepository.setAtLeastApi32(false)
viewModel.copyPermissionCommand()
assertIs<ClipboardResult.Notify>(viewModel.clipboardResult.value)
}
@Test
fun clipboardResult_isNoResult_whenCopyPermissionCommand() = runTest {
clipboardRepository.setAtLeastApi32(true)
viewModel.copyPermissionCommand()
assertIs<ClipboardResult.NoResult>(viewModel.clipboardResult.value)
}
@Test
fun secureSettings_isNotEmpty_whenGetSecureSettingsByName_ofSettingTypeSystem() = runTest {
val secureSettings = List(5) { index ->
SecureSetting(
settingType = SettingType.SYSTEM,
id = index.toLong(),
name = "SecureSetting",
value = index.toString(),
)
}
secureSettingsRepository.setSecureSettings(secureSettings)
viewModel.getSecureSettingsByName(settingType = SettingType.SYSTEM, text = "SecureSetting")
assertTrue(viewModel.secureSettings.value.isNotEmpty())
}
@Test
fun secureSettings_isNotEmpty_whenGetSecureSettingsByName_ofSettingTypeSecure() = runTest {
val secureSettings = List(5) { index ->
SecureSetting(
settingType = SettingType.SECURE,
id = index.toLong(),
name = "SecureSetting",
value = index.toString(),
)
}
secureSettingsRepository.setSecureSettings(secureSettings)
viewModel.getSecureSettingsByName(settingType = SettingType.SECURE, text = "SecureSetting")
assertTrue(viewModel.secureSettings.value.isNotEmpty())
}
@Test
fun secureSettings_isNotEmpty_whenGetSecureSettingsByName_ofSettingTypeGlobal() = runTest {
val secureSettings = List(5) { index ->
SecureSetting(
settingType = SettingType.GLOBAL,
id = index.toLong(),
name = "SecureSetting",
value = index.toString(),
)
}
secureSettingsRepository.setSecureSettings(secureSettings)
viewModel.getSecureSettingsByName(settingType = SettingType.GLOBAL, text = "SecureSetting")
assertTrue(viewModel.secureSettings.value.isNotEmpty())
}
@Test
fun secureSettings_isEmpty_whenGetSecureSettingsByName_ofSettingTypeSystem() = runTest {
val secureSettings = List(5) { index ->
SecureSetting(
settingType = SettingType.SYSTEM,
id = index.toLong(),
name = "SecureSetting",
value = index.toString(),
)
}
secureSettingsRepository.setSecureSettings(secureSettings)
viewModel.getSecureSettingsByName(settingType = SettingType.SYSTEM, text = "text")
assertTrue(viewModel.secureSettings.value.isEmpty())
}
@Test
fun secureSettings_isEmpty_whenGetSecureSettingsByName_ofSettingTypeSecure() = runTest {
val secureSettings = List(5) { index ->
SecureSetting(
settingType = SettingType.SECURE,
id = index.toLong(),
name = "SecureSetting",
value = index.toString(),
)
}
secureSettingsRepository.setSecureSettings(secureSettings)
viewModel.getSecureSettingsByName(settingType = SettingType.SECURE, text = "text")
assertTrue(viewModel.secureSettings.value.isEmpty())
}
@Test
fun secureSettings_isEmpty_whenGetSecureSettingsByName_ofSettingTypeGlobal() = runTest {
val secureSettings = List(5) { index ->
SecureSetting(
settingType = SettingType.GLOBAL,
id = index.toLong(),
name = "SecureSetting",
value = index.toString(),
)
}
secureSettingsRepository.setSecureSettings(secureSettings)
viewModel.getSecureSettingsByName(settingType = SettingType.GLOBAL, text = "text")
assertTrue(viewModel.secureSettings.value.isEmpty())
}
@Test
fun shortcutResult_isSupportedLauncher_whenRequestPinShortcut() = runTest {
shortcutRepository.setRequestPinShortcutSupported(true)
viewModel.requestPinShortcut(
targetShortcutInfoCompat = TargetShortcutInfoCompat(
id = "0",
shortLabel = "shortLabel",
longLabel = "longLabel",
),
)
assertIs<ShortcutResult.SupportedLauncher>(viewModel.shortcutResult.value)
}
@Test
fun shortcutResult_isUnSupportedLauncher_whenRequestPinShortcut() = runTest {
shortcutRepository.setRequestPinShortcutSupported(false)
viewModel.requestPinShortcut(
targetShortcutInfoCompat = TargetShortcutInfoCompat(
id = "0",
shortLabel = "shortLabel",
longLabel = "longLabel",
),
)
assertIs<ShortcutResult.UnsupportedLauncher>(viewModel.shortcutResult.value)
}
@Test
fun shortcutResult_isShortcutUpdateImmutableShortcuts_whenUpdateRequestPinShortcut() = runTest {
shortcutRepository.setUpdateImmutableShortcuts(true)
viewModel.updateRequestPinShortcut(
targetShortcutInfoCompat = TargetShortcutInfoCompat(
id = "0",
shortLabel = "Geto",
longLabel = "Geto",
),
)
assertIs<ShortcutResult.ShortcutUpdateImmutableShortcuts>(viewModel.shortcutResult.value)
}
@Test
fun shortcutResult_isShortcutUpdateSuccess_whenUpdateRequestPinShortcut() = runTest {
shortcutRepository.setUpdateImmutableShortcuts(false)
viewModel.updateRequestPinShortcut(
targetShortcutInfoCompat = TargetShortcutInfoCompat(
id = "0",
shortLabel = "Geto",
longLabel = "Geto",
),
)
assertIs<ShortcutResult.ShortcutUpdateSuccess>(viewModel.shortcutResult.value)
}
@Test
fun shortcutResult_isShortcutFound_whenGetShortcut() = runTest {
val shortcuts = List(2) {
TargetShortcutInfoCompat(
id = "com.android.geto",
shortLabel = "Geto",
longLabel = "Geto",
)
}
shortcutRepository.setUpdateImmutableShortcuts(false)
shortcutRepository.setShortcuts(shortcuts)
viewModel.getShortcut()
assertIs<ShortcutResult.ShortcutFound>(viewModel.shortcutResult.value)
}
@Test
fun shortcutResult_isNoShortcutFound_whenGetShortcut() = runTest {
val shortcuts = List(2) {
TargetShortcutInfoCompat(
id = "com.android.geto",
shortLabel = "Geto",
longLabel = "Geto",
)
}
shortcutRepository.setUpdateImmutableShortcuts(false)
shortcutRepository.setShortcuts(shortcuts)
viewModel.getShortcut("")
assertIs<ShortcutResult.NoShortcutFound>(viewModel.shortcutResult.value)
}
@Test
fun applicationIcon_isNotNull_whenGetApplicationIcon() = runTest {
val installedApplications = List(1) { _ ->
TargetApplicationInfo(
flags = 0,
packageName = packageName,
label = appName,
)
}
packageRepository.setInstalledApplications(installedApplications)
val collectJob = launch(UnconfinedTestDispatcher()) { viewModel.applicationIcon.collect() }
assertNotNull(viewModel.applicationIcon.value)
collectJob.cancel()
}
}
| Geto/feature/appsettings/src/test/kotlin/com/android/geto/feature/appsettings/AppSettingsViewModelTest.kt | 1532136114 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.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.android.geto.feature.appsettings
import androidx.activity.ComponentActivity
import androidx.compose.material3.SnackbarHostState
import androidx.compose.ui.test.junit4.createAndroidComposeRule
import com.android.geto.core.data.repository.ClipboardResult
import com.android.geto.core.data.repository.ShortcutResult
import com.android.geto.core.designsystem.component.GetoBackground
import com.android.geto.core.designsystem.theme.GetoTheme
import com.android.geto.core.domain.AppSettingsResult
import com.android.geto.core.model.AppSetting
import com.android.geto.core.model.SettingType
import com.android.geto.core.screenshot.testing.util.DefaultTestDevices
import com.android.geto.core.screenshot.testing.util.captureForDevice
import com.android.geto.core.screenshot.testing.util.captureMultiDevice
import dagger.hilt.android.testing.HiltTestApplication
import org.junit.Rule
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import org.robolectric.annotation.GraphicsMode
import org.robolectric.annotation.LooperMode
import kotlin.test.Test
@RunWith(RobolectricTestRunner::class)
@GraphicsMode(GraphicsMode.Mode.NATIVE)
@Config(application = HiltTestApplication::class)
@LooperMode(LooperMode.Mode.PAUSED)
class AppSettingsScreenScreenshotTest {
@get:Rule
val composeTestRule = createAndroidComposeRule<ComponentActivity>()
private val appSettings = List(5) { index ->
AppSetting(
id = index,
enabled = true,
settingType = SettingType.SYSTEM,
packageName = "com.android.geto",
label = "Geto",
key = "Geto $index",
valueOnLaunch = "0",
valueOnRevert = "1",
)
}
@Test
fun appSettingsScreen_populated() {
composeTestRule.captureMultiDevice("AppSettingsScreenPopulated") {
GetoTheme {
AppSettingsScreen(
packageName = "com.android.geto",
appName = "Geto",
appSettingsUiState = AppSettingsUiState.Success(appSettings),
snackbarHostState = SnackbarHostState(),
applicationIcon = null,
secureSettings = emptyList(),
applyAppSettingsResult = AppSettingsResult.NoResult,
revertAppSettingsResult = AppSettingsResult.NoResult,
shortcutResult = ShortcutResult.NoResult,
clipboardResult = ClipboardResult.NoResult,
onNavigationIconClick = {},
onRevertAppSettings = {},
onGetShortcut = {},
onCheckAppSetting = { _, _ -> },
onDeleteAppSetting = {},
onLaunchApp = {},
onAutoLaunchApp = {},
onResetAppSettingsResult = {},
onResetShortcutResult = {},
onResetClipboardResult = {},
onGetSecureSettingsByName = { _, _ -> },
onAddAppSetting = {},
onCopyPermissionCommand = {},
onAddShortcut = {},
onUpdateShortcut = {},
)
}
}
}
@Test
fun appSettingsScreen_loading() {
composeTestRule.captureMultiDevice("AppSettingsScreenLoading") {
GetoTheme {
AppSettingsScreen(
packageName = "com.android.geto",
appName = "Geto",
appSettingsUiState = AppSettingsUiState.Loading,
snackbarHostState = SnackbarHostState(),
applicationIcon = null,
secureSettings = emptyList(),
applyAppSettingsResult = AppSettingsResult.NoResult,
revertAppSettingsResult = AppSettingsResult.NoResult,
shortcutResult = ShortcutResult.NoResult,
clipboardResult = ClipboardResult.NoResult,
onNavigationIconClick = {},
onRevertAppSettings = {},
onGetShortcut = {},
onCheckAppSetting = { _, _ -> },
onDeleteAppSetting = {},
onLaunchApp = {},
onAutoLaunchApp = {},
onResetAppSettingsResult = {},
onResetShortcutResult = {},
onResetClipboardResult = {},
onGetSecureSettingsByName = { _, _ -> },
onAddAppSetting = {},
onCopyPermissionCommand = {},
onAddShortcut = {},
onUpdateShortcut = {},
)
}
}
}
@Test
fun appSettingsScreen_empty() {
composeTestRule.captureMultiDevice("AppSettingsScreenEmpty") {
GetoTheme {
AppSettingsScreen(
packageName = "com.android.geto",
appName = "Geto",
appSettingsUiState = AppSettingsUiState.Success(emptyList()),
snackbarHostState = SnackbarHostState(),
applicationIcon = null,
secureSettings = emptyList(),
applyAppSettingsResult = AppSettingsResult.NoResult,
revertAppSettingsResult = AppSettingsResult.NoResult,
shortcutResult = ShortcutResult.NoResult,
clipboardResult = ClipboardResult.NoResult,
onNavigationIconClick = {},
onRevertAppSettings = {},
onGetShortcut = {},
onCheckAppSetting = { _, _ -> },
onDeleteAppSetting = {},
onLaunchApp = {},
onAutoLaunchApp = {},
onResetAppSettingsResult = {},
onResetShortcutResult = {},
onResetClipboardResult = {},
onGetSecureSettingsByName = { _, _ -> },
onAddAppSetting = {},
onCopyPermissionCommand = {},
onAddShortcut = {},
onUpdateShortcut = {},
)
}
}
}
@Test
fun appSettingsScreen_populated_dark() {
composeTestRule.captureForDevice(
deviceName = "phone_dark",
deviceSpec = DefaultTestDevices.PHONE.spec,
fileName = "AppSettingsScreenPopulated",
darkMode = true,
) {
GetoTheme {
GetoBackground {
AppSettingsScreen(
packageName = "com.android.geto",
appName = "Geto",
appSettingsUiState = AppSettingsUiState.Success(appSettings),
snackbarHostState = SnackbarHostState(),
applicationIcon = null,
secureSettings = emptyList(),
applyAppSettingsResult = AppSettingsResult.NoResult,
revertAppSettingsResult = AppSettingsResult.NoResult,
shortcutResult = ShortcutResult.NoResult,
clipboardResult = ClipboardResult.NoResult,
onNavigationIconClick = {},
onRevertAppSettings = {},
onGetShortcut = {},
onCheckAppSetting = { _, _ -> },
onDeleteAppSetting = {},
onLaunchApp = {},
onAutoLaunchApp = {},
onResetAppSettingsResult = {},
onResetShortcutResult = {},
onResetClipboardResult = {},
onGetSecureSettingsByName = { _, _ -> },
onAddAppSetting = {},
onCopyPermissionCommand = {},
onAddShortcut = {},
onUpdateShortcut = {},
)
}
}
}
}
@Test
fun appSettingsScreen_loading_dark() {
composeTestRule.captureForDevice(
deviceName = "phone_dark",
deviceSpec = DefaultTestDevices.PHONE.spec,
fileName = "AppSettingsScreenLoading",
darkMode = true,
) {
GetoTheme {
GetoBackground {
AppSettingsScreen(
packageName = "com.android.geto",
appName = "Geto",
appSettingsUiState = AppSettingsUiState.Loading,
snackbarHostState = SnackbarHostState(),
applicationIcon = null,
secureSettings = emptyList(),
applyAppSettingsResult = AppSettingsResult.NoResult,
revertAppSettingsResult = AppSettingsResult.NoResult,
shortcutResult = ShortcutResult.NoResult,
clipboardResult = ClipboardResult.NoResult,
onNavigationIconClick = {},
onRevertAppSettings = {},
onGetShortcut = {},
onCheckAppSetting = { _, _ -> },
onDeleteAppSetting = {},
onLaunchApp = {},
onAutoLaunchApp = {},
onResetAppSettingsResult = {},
onResetShortcutResult = {},
onResetClipboardResult = {},
onGetSecureSettingsByName = { _, _ -> },
onAddAppSetting = {},
onCopyPermissionCommand = {},
onAddShortcut = {},
onUpdateShortcut = {},
)
}
}
}
}
@Test
fun appSettingsScreen_empty_dark() {
composeTestRule.captureForDevice(
deviceName = "phone_dark",
deviceSpec = DefaultTestDevices.PHONE.spec,
fileName = "AppSettingsScreenEmpty",
darkMode = true,
) {
GetoTheme {
GetoBackground {
AppSettingsScreen(
packageName = "com.android.geto",
appName = "Geto",
appSettingsUiState = AppSettingsUiState.Success(emptyList()),
snackbarHostState = SnackbarHostState(),
applicationIcon = null,
secureSettings = emptyList(),
applyAppSettingsResult = AppSettingsResult.NoResult,
revertAppSettingsResult = AppSettingsResult.NoResult,
shortcutResult = ShortcutResult.NoResult,
clipboardResult = ClipboardResult.NoResult,
onNavigationIconClick = {},
onRevertAppSettings = {},
onGetShortcut = {},
onCheckAppSetting = { _, _ -> },
onDeleteAppSetting = {},
onLaunchApp = {},
onAutoLaunchApp = {},
onResetAppSettingsResult = {},
onResetShortcutResult = {},
onResetClipboardResult = {},
onGetSecureSettingsByName = { _, _ -> },
onAddAppSetting = {},
onCopyPermissionCommand = {},
onAddShortcut = {},
onUpdateShortcut = {},
)
}
}
}
}
}
| Geto/feature/appsettings/src/test/kotlin/com/android/geto/feature/appsettings/AppSettingsScreenScreenshotTest.kt | 2212031339 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.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.android.geto.feature.appsettings
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material3.Checkbox
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.android.geto.core.designsystem.theme.GetoTheme
import com.android.geto.core.model.AppSetting
import com.android.geto.core.model.SettingType
@Composable
fun AppSettingItem(
modifier: Modifier = Modifier,
appSetting: AppSetting,
onUserAppSettingsItemCheckBoxChange: (Boolean) -> Unit,
onDeleteUserAppSettingsItem: () -> Unit,
) {
Row(
modifier = modifier,
verticalAlignment = Alignment.CenterVertically,
) {
Checkbox(
checked = appSetting.enabled,
onCheckedChange = onUserAppSettingsItemCheckBoxChange,
)
Column(modifier = Modifier.weight(1f)) {
Text(
text = appSetting.label,
style = MaterialTheme.typography.bodyLarge,
)
Spacer(modifier = Modifier.height(5.dp))
Text(
text = appSetting.settingType.label,
style = MaterialTheme.typography.bodySmall,
)
Spacer(modifier = Modifier.height(5.dp))
Text(
text = appSetting.key,
style = MaterialTheme.typography.bodySmall,
)
}
IconButton(onClick = onDeleteUserAppSettingsItem) {
Icon(
imageVector = Icons.Default.Delete,
contentDescription = null,
)
}
}
}
@Preview
@Composable
private fun AppSettingsItemPreview() {
GetoTheme {
AppSettingItem(
appSetting = AppSetting(
enabled = false,
settingType = SettingType.SECURE,
packageName = "com.android.geto",
label = "Label",
key = "key",
valueOnLaunch = "0",
valueOnRevert = "1",
),
onUserAppSettingsItemCheckBoxChange = {},
onDeleteUserAppSettingsItem = {},
)
}
}
| Geto/feature/appsettings/src/main/kotlin/com/android/geto/feature/appsettings/AppSettingItem.kt | 3308011640 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.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.android.geto.feature.appsettings
import android.graphics.drawable.Drawable
import androidx.annotation.VisibleForTesting
import androidx.compose.foundation.ExperimentalFoundationApi
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.PaddingValues
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.consumeWindowInsets
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.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.BottomAppBar
import androidx.compose.material3.BottomAppBarDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.FloatingActionButtonDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.PreviewParameter
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.android.geto.core.data.repository.ClipboardResult
import com.android.geto.core.data.repository.ShortcutResult
import com.android.geto.core.designsystem.component.GetoLoadingWheel
import com.android.geto.core.designsystem.component.SimpleDialog
import com.android.geto.core.designsystem.icon.GetoIcons
import com.android.geto.core.designsystem.theme.GetoTheme
import com.android.geto.core.domain.AppSettingsResult
import com.android.geto.core.domain.AutoLaunchResult
import com.android.geto.core.model.AppSetting
import com.android.geto.core.model.SecureSetting
import com.android.geto.core.model.SettingType
import com.android.geto.core.model.TargetShortcutInfoCompat
import com.android.geto.core.ui.AppSettingsPreviewParameterProvider
import com.android.geto.core.ui.DevicePreviews
import com.android.geto.feature.appsettings.dialog.appsetting.AppSettingDialog
import com.android.geto.feature.appsettings.dialog.appsetting.AppSettingDialogState
import com.android.geto.feature.appsettings.dialog.appsetting.rememberAppSettingDialogState
import com.android.geto.feature.appsettings.dialog.copypermissioncommand.CopyPermissionCommandDialogState
import com.android.geto.feature.appsettings.dialog.copypermissioncommand.rememberCopyPermissionCommandDialogState
import com.android.geto.feature.appsettings.dialog.shortcut.ShortcutDialog
import com.android.geto.feature.appsettings.dialog.shortcut.ShortcutDialogState
import com.android.geto.feature.appsettings.dialog.shortcut.rememberShortcutDialogState
@Composable
internal fun AppSettingsRoute(
modifier: Modifier = Modifier,
viewModel: AppSettingsViewModel = hiltViewModel(),
onNavigationIconClick: () -> Unit,
) {
val appSettingsUiState = viewModel.appSettingUiState.collectAsStateWithLifecycle().value
val secureSettings = viewModel.secureSettings.collectAsStateWithLifecycle().value
val applyAppSettingsResult =
viewModel.applyAppSettingsResult.collectAsStateWithLifecycle().value
val revertAppSettingsResult =
viewModel.revertAppSettingsResult.collectAsStateWithLifecycle().value
val applicationIcon = viewModel.applicationIcon.collectAsStateWithLifecycle().value
val shortcutResult = viewModel.shortcutResult.collectAsStateWithLifecycle().value
val clipboardResult = viewModel.clipboardResult.collectAsStateWithLifecycle().value
val snackbarHostState = remember {
SnackbarHostState()
}
AppSettingsScreen(
modifier = modifier,
packageName = viewModel.packageName,
appName = viewModel.appName,
appSettingsUiState = appSettingsUiState,
snackbarHostState = snackbarHostState,
applicationIcon = applicationIcon,
secureSettings = secureSettings,
applyAppSettingsResult = applyAppSettingsResult,
revertAppSettingsResult = revertAppSettingsResult,
shortcutResult = shortcutResult,
clipboardResult = clipboardResult,
onNavigationIconClick = onNavigationIconClick,
onRevertAppSettings = viewModel::revertAppSettings,
onGetShortcut = viewModel::getShortcut,
onCheckAppSetting = viewModel::checkAppSetting,
onDeleteAppSetting = viewModel::deleteAppSetting,
onLaunchApp = viewModel::applyAppSettings,
onAutoLaunchApp = viewModel::autoLaunchApp,
onResetAppSettingsResult = viewModel::resetAppSettingsResult,
onResetShortcutResult = viewModel::resetShortcutResult,
onResetClipboardResult = viewModel::resetClipboardResult,
onGetSecureSettingsByName = viewModel::getSecureSettingsByName,
onAddAppSetting = viewModel::addAppSettings,
onCopyPermissionCommand = viewModel::copyPermissionCommand,
onAddShortcut = viewModel::requestPinShortcut,
onUpdateShortcut = viewModel::updateRequestPinShortcut,
)
}
@VisibleForTesting
@Composable
internal fun AppSettingsScreen(
modifier: Modifier = Modifier,
packageName: String,
appName: String,
appSettingsUiState: AppSettingsUiState,
snackbarHostState: SnackbarHostState,
applicationIcon: Drawable?,
secureSettings: List<SecureSetting>,
applyAppSettingsResult: AppSettingsResult,
revertAppSettingsResult: AppSettingsResult,
shortcutResult: ShortcutResult,
clipboardResult: ClipboardResult,
onNavigationIconClick: () -> Unit,
onRevertAppSettings: () -> Unit,
onGetShortcut: () -> Unit,
onCheckAppSetting: (Boolean, AppSetting) -> Unit,
onDeleteAppSetting: (AppSetting) -> Unit,
onLaunchApp: () -> Unit,
onAutoLaunchApp: () -> Unit,
onResetAppSettingsResult: () -> Unit,
onResetShortcutResult: () -> Unit,
onResetClipboardResult: () -> Unit,
onGetSecureSettingsByName: (SettingType, String) -> Unit,
onAddAppSetting: (AppSetting) -> Unit,
onCopyPermissionCommand: () -> Unit,
onAddShortcut: (TargetShortcutInfoCompat) -> Unit,
onUpdateShortcut: (TargetShortcutInfoCompat) -> Unit,
) {
val copyPermissionCommandDialogState = rememberCopyPermissionCommandDialogState()
val appSettingDialogState = rememberAppSettingDialogState()
val addShortcutDialogState = rememberShortcutDialogState()
val updateShortcutDialogState = rememberShortcutDialogState()
AppSettingsLaunchedEffects(
snackbarHostState = snackbarHostState,
copyPermissionCommandDialogState = copyPermissionCommandDialogState,
appSettingDialogState = appSettingDialogState,
addShortcutDialogState = addShortcutDialogState,
updateShortcutDialogState = updateShortcutDialogState,
applicationIcon = applicationIcon,
secureSettings = secureSettings,
applyAppSettingsResult = applyAppSettingsResult,
revertAppSettingsResult = revertAppSettingsResult,
shortcutResult = shortcutResult,
clipboardResult = clipboardResult,
onAutoLaunchApp = onAutoLaunchApp,
onResetAppSettingsResult = onResetAppSettingsResult,
onResetShortcutResult = onResetShortcutResult,
onResetClipboardResult = onResetClipboardResult,
onGetSecureSettingsByName = onGetSecureSettingsByName,
)
AppSettingsDialogs(
copyPermissionCommandDialogState = copyPermissionCommandDialogState,
appSettingDialogState = appSettingDialogState,
addShortcutDialogState = addShortcutDialogState,
updateShortcutDialogState = updateShortcutDialogState,
packageName = packageName,
onAddAppSetting = onAddAppSetting,
onCopyPermissionCommand = onCopyPermissionCommand,
onAddShortcut = onAddShortcut,
onUpdateShortcut = {
updateShortcutDialogState.getShortcut(
packageName = packageName,
)?.let(onUpdateShortcut)
},
)
Scaffold(
topBar = {
AppSettingsTopAppBar(
title = appName,
onNavigationIconClick = onNavigationIconClick,
)
},
bottomBar = {
AppSettingsBottomAppBar(
onRevertSettingsIconClick = onRevertAppSettings,
onSettingsIconClick = {
appSettingDialogState.updateShowDialog(true)
},
onShortcutIconClick = onGetShortcut,
onLaunchApp = onLaunchApp,
)
},
snackbarHost = {
SnackbarHost(
hostState = snackbarHostState,
modifier = Modifier.testTag("appSettings:snackbar"),
)
},
) { innerPadding ->
Box(
modifier = modifier
.fillMaxSize()
.consumeWindowInsets(innerPadding),
) {
when (appSettingsUiState) {
AppSettingsUiState.Loading -> {
LoadingState(modifier = Modifier.align(Alignment.Center))
}
is AppSettingsUiState.Success -> {
if (appSettingsUiState.appSettingList.isNotEmpty()) {
SuccessState(
appSettingsUiState = appSettingsUiState,
contentPadding = innerPadding,
onAppSettingsItemCheckBoxChange = onCheckAppSetting,
onDeleteAppSettingsItem = onDeleteAppSetting,
)
} else {
EmptyState(text = stringResource(R.string.add_your_first_settings))
}
}
}
}
}
}
@Composable
private fun AppSettingsLaunchedEffects(
snackbarHostState: SnackbarHostState,
copyPermissionCommandDialogState: CopyPermissionCommandDialogState,
appSettingDialogState: AppSettingDialogState,
addShortcutDialogState: ShortcutDialogState,
updateShortcutDialogState: ShortcutDialogState,
applicationIcon: Drawable?,
secureSettings: List<SecureSetting>,
applyAppSettingsResult: AppSettingsResult,
revertAppSettingsResult: AppSettingsResult,
shortcutResult: ShortcutResult,
clipboardResult: ClipboardResult,
onAutoLaunchApp: () -> Unit,
onResetAppSettingsResult: () -> Unit,
onResetShortcutResult: () -> Unit,
onResetClipboardResult: () -> Unit,
onGetSecureSettingsByName: (SettingType, String) -> Unit,
) {
val appSettingsDisabled = stringResource(id = R.string.app_settings_disabled)
val emptyAppSettingsList = stringResource(id = R.string.empty_app_settings_list)
val applyFailure = stringResource(id = R.string.apply_failure)
val revertFailure = stringResource(id = R.string.revert_failure)
val revertSuccess = stringResource(id = R.string.revert_success)
val shortcutIdNotFound = stringResource(id = R.string.shortcut_id_not_found)
val shortcutDisableImmutableShortcuts =
stringResource(id = R.string.shortcut_disable_immutable_shortcuts)
val shortcutUpdateImmutableShortcuts =
stringResource(id = R.string.shortcut_update_immutable_shortcuts)
val shortcutUpdateFailed = stringResource(id = R.string.shortcut_update_failed)
val shortcutUpdateSuccess = stringResource(id = R.string.shortcut_update_success)
val supportedLauncher = stringResource(id = R.string.supported_launcher)
val unsupportedLauncher = stringResource(id = R.string.unsupported_launcher)
val userIsLocked = stringResource(id = R.string.user_is_locked)
val copiedToClipboard = stringResource(id = R.string.copied_to_clipboard)
val invalidValues = stringResource(R.string.settings_has_invalid_values)
val context = LocalContext.current
val keyDebounce = appSettingDialogState.keyDebounce.collectAsStateWithLifecycle("").value
LaunchedEffect(key1 = true) {
onAutoLaunchApp()
}
LaunchedEffect(key1 = applyAppSettingsResult) {
when (applyAppSettingsResult) {
AppSettingsResult.DisabledAppSettings -> snackbarHostState.showSnackbar(message = appSettingsDisabled)
AppSettingsResult.EmptyAppSettings -> snackbarHostState.showSnackbar(message = emptyAppSettingsList)
AppSettingsResult.Failure -> snackbarHostState.showSnackbar(message = applyFailure)
AppSettingsResult.SecurityException -> copyPermissionCommandDialogState.updateShowDialog(
true,
)
is AppSettingsResult.Success -> applyAppSettingsResult.launchIntent?.let(context::startActivity)
AutoLaunchResult.Ignore -> Unit
AppSettingsResult.IllegalArgumentException -> snackbarHostState.showSnackbar(message = invalidValues)
AppSettingsResult.NoResult -> Unit
}
onResetAppSettingsResult()
}
LaunchedEffect(key1 = revertAppSettingsResult) {
when (revertAppSettingsResult) {
AppSettingsResult.DisabledAppSettings -> snackbarHostState.showSnackbar(message = appSettingsDisabled)
AppSettingsResult.EmptyAppSettings -> snackbarHostState.showSnackbar(message = emptyAppSettingsList)
AppSettingsResult.Failure -> snackbarHostState.showSnackbar(message = revertFailure)
AppSettingsResult.SecurityException -> copyPermissionCommandDialogState.updateShowDialog(
true,
)
is AppSettingsResult.Success -> snackbarHostState.showSnackbar(message = revertSuccess)
AutoLaunchResult.Ignore -> Unit
AppSettingsResult.IllegalArgumentException -> snackbarHostState.showSnackbar(message = invalidValues)
AppSettingsResult.NoResult -> Unit
}
onResetAppSettingsResult()
}
LaunchedEffect(key1 = shortcutResult) {
when (shortcutResult) {
ShortcutResult.IDNotFound -> snackbarHostState.showSnackbar(message = shortcutIdNotFound)
ShortcutResult.ShortcutDisableImmutableShortcuts -> snackbarHostState.showSnackbar(
message = shortcutDisableImmutableShortcuts,
)
ShortcutResult.ShortcutUpdateFailed -> snackbarHostState.showSnackbar(message = shortcutUpdateFailed)
ShortcutResult.ShortcutUpdateImmutableShortcuts -> snackbarHostState.showSnackbar(
message = shortcutUpdateImmutableShortcuts,
)
ShortcutResult.ShortcutUpdateSuccess -> snackbarHostState.showSnackbar(message = shortcutUpdateSuccess)
ShortcutResult.SupportedLauncher -> snackbarHostState.showSnackbar(message = supportedLauncher)
ShortcutResult.UnsupportedLauncher -> snackbarHostState.showSnackbar(message = unsupportedLauncher)
ShortcutResult.UserIsLocked -> snackbarHostState.showSnackbar(message = userIsLocked)
is ShortcutResult.ShortcutFound -> {
updateShortcutDialogState.updateShortLabel(shortcutResult.targetShortcutInfoCompat.shortLabel)
updateShortcutDialogState.updateLongLabel(shortcutResult.targetShortcutInfoCompat.longLabel)
updateShortcutDialogState.updateShowDialog(true)
}
ShortcutResult.NoShortcutFound -> addShortcutDialogState.updateShowDialog(true)
ShortcutResult.NoResult -> Unit
}
onResetShortcutResult()
}
LaunchedEffect(key1 = clipboardResult) {
when (clipboardResult) {
ClipboardResult.NoResult -> Unit
is ClipboardResult.Notify -> snackbarHostState.showSnackbar(
message = String.format(
copiedToClipboard,
clipboardResult.text,
),
)
ClipboardResult.NoResult -> Unit
}
onResetClipboardResult()
}
LaunchedEffect(
key1 = appSettingDialogState.selectedRadioOptionIndex,
key2 = keyDebounce,
) {
val settingType = SettingType.entries[appSettingDialogState.selectedRadioOptionIndex]
onGetSecureSettingsByName(
settingType,
appSettingDialogState.key,
)
}
LaunchedEffect(key1 = secureSettings) {
appSettingDialogState.updateSecureSettings(secureSettings)
}
LaunchedEffect(key1 = applicationIcon) {
applicationIcon?.let {
addShortcutDialogState.updateIcon(it)
updateShortcutDialogState.updateIcon(it)
}
}
}
@Composable
private fun AppSettingsDialogs(
copyPermissionCommandDialogState: CopyPermissionCommandDialogState,
appSettingDialogState: AppSettingDialogState,
addShortcutDialogState: ShortcutDialogState,
updateShortcutDialogState: ShortcutDialogState,
packageName: String,
onAddAppSetting: (AppSetting) -> Unit,
onCopyPermissionCommand: () -> Unit,
onAddShortcut: (TargetShortcutInfoCompat) -> Unit,
onUpdateShortcut: (TargetShortcutInfoCompat) -> Unit,
) {
if (appSettingDialogState.showDialog) {
AppSettingDialog(
appSettingDialogState = appSettingDialogState,
packageName = packageName,
onAddSetting = onAddAppSetting,
contentDescription = "Add App Settings Dialog",
)
}
if (copyPermissionCommandDialogState.showDialog) {
SimpleDialog(
title = stringResource(id = R.string.permission_error),
text = stringResource(id = R.string.copy_permission_command_message),
onDismissRequest = { copyPermissionCommandDialogState.updateShowDialog(false) },
negativeButtonText = stringResource(id = R.string.cancel),
positiveButtonText = stringResource(id = R.string.copy),
onNegativeButtonClick = { copyPermissionCommandDialogState.updateShowDialog(false) },
onPositiveButtonClick = {
onCopyPermissionCommand()
copyPermissionCommandDialogState.updateShowDialog(false)
},
contentDescription = "Copy Permission Command Dialog",
)
}
if (addShortcutDialogState.showDialog) {
ShortcutDialog(
shortcutDialogState = addShortcutDialogState,
packageName = packageName,
contentDescription = "Add Shortcut Dialog",
title = stringResource(id = R.string.add_shortcut),
negativeButtonText = stringResource(id = R.string.cancel),
positiveButtonText = stringResource(id = R.string.add),
onPositiveButtonClick = onAddShortcut,
)
}
if (updateShortcutDialogState.showDialog) {
ShortcutDialog(
shortcutDialogState = updateShortcutDialogState,
packageName = packageName,
contentDescription = "Update Shortcut Dialog",
title = stringResource(id = R.string.update_shortcut),
negativeButtonText = stringResource(id = R.string.cancel),
positiveButtonText = stringResource(id = R.string.update),
onPositiveButtonClick = onUpdateShortcut,
)
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun AppSettingsTopAppBar(
modifier: Modifier = Modifier,
title: String,
onNavigationIconClick: () -> Unit,
) {
TopAppBar(
title = {
Text(text = title, maxLines = 1)
},
modifier = modifier.testTag("appSettings:topAppBar"),
navigationIcon = {
IconButton(onClick = onNavigationIconClick) {
Icon(
imageVector = GetoIcons.Back,
contentDescription = "Navigation icon",
)
}
},
)
}
@Composable
private fun AppSettingsBottomAppBar(
onRevertSettingsIconClick: () -> Unit,
onSettingsIconClick: () -> Unit,
onShortcutIconClick: () -> Unit,
onLaunchApp: () -> Unit,
) {
BottomAppBar(
actions = {
AppSettingsBottomAppBarActions(
onRevertSettingsIconClick = onRevertSettingsIconClick,
onSettingsIconClick = onSettingsIconClick,
onShortcutIconClick = onShortcutIconClick,
)
},
floatingActionButton = {
AppSettingsFloatingActionButton(
onClick = onLaunchApp,
)
},
)
}
@Composable
private fun AppSettingsFloatingActionButton(onClick: () -> Unit) {
FloatingActionButton(
onClick = onClick,
containerColor = BottomAppBarDefaults.bottomAppBarFabColor,
elevation = FloatingActionButtonDefaults.bottomAppBarFabElevation(),
) {
Icon(
imageVector = GetoIcons.Android,
contentDescription = "Launch icon",
)
}
}
@Composable
private fun AppSettingsBottomAppBarActions(
onRevertSettingsIconClick: () -> Unit,
onSettingsIconClick: () -> Unit,
onShortcutIconClick: () -> Unit,
) {
IconButton(onClick = onRevertSettingsIconClick) {
Icon(
imageVector = GetoIcons.Refresh,
contentDescription = "Revert icon",
)
}
IconButton(onClick = onSettingsIconClick) {
Icon(
GetoIcons.Settings,
contentDescription = "Settings icon",
)
}
IconButton(onClick = onShortcutIconClick) {
Icon(
GetoIcons.Shortcut,
contentDescription = "Shortcut icon",
)
}
}
@Composable
private fun EmptyState(
modifier: Modifier = Modifier,
text: String,
) {
Column(
modifier = modifier
.fillMaxSize()
.testTag("appSettings:emptyListPlaceHolderScreen"),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally,
) {
Image(
imageVector = GetoIcons.Empty,
contentDescription = null,
modifier = Modifier.size(100.dp),
colorFilter = ColorFilter.tint(
MaterialTheme.colorScheme.onSurface,
),
)
Spacer(modifier = Modifier.height(10.dp))
Text(text = text, style = MaterialTheme.typography.bodyLarge)
}
}
@Composable
private fun LoadingState(modifier: Modifier = Modifier) {
GetoLoadingWheel(
modifier = modifier,
contentDescription = "GetoLoadingWheel",
)
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun SuccessState(
modifier: Modifier = Modifier,
appSettingsUiState: AppSettingsUiState.Success,
contentPadding: PaddingValues,
onAppSettingsItemCheckBoxChange: (Boolean, AppSetting) -> Unit,
onDeleteAppSettingsItem: (AppSetting) -> Unit,
) {
LazyColumn(
modifier = modifier
.fillMaxSize()
.testTag("appSettings:lazyColumn"),
contentPadding = contentPadding,
) {
items(appSettingsUiState.appSettingList, key = { it.id!! }) { appSettings ->
AppSettingItem(
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 10.dp, horizontal = 5.dp)
.animateItemPlacement(),
appSetting = appSettings,
onUserAppSettingsItemCheckBoxChange = { check ->
onAppSettingsItemCheckBoxChange(
check,
appSettings,
)
},
onDeleteUserAppSettingsItem = {
onDeleteAppSettingsItem(appSettings)
},
)
}
}
}
@DevicePreviews
@Composable
private fun AppSettingsScreenLoadingStatePreview() {
GetoTheme {
AppSettingsScreen(
packageName = "com.android.geto",
appName = "Geto",
appSettingsUiState = AppSettingsUiState.Loading,
snackbarHostState = SnackbarHostState(),
applicationIcon = null,
secureSettings = emptyList(),
applyAppSettingsResult = AppSettingsResult.NoResult,
revertAppSettingsResult = AppSettingsResult.NoResult,
shortcutResult = ShortcutResult.NoResult,
clipboardResult = ClipboardResult.NoResult,
onNavigationIconClick = {},
onRevertAppSettings = {},
onGetShortcut = {},
onCheckAppSetting = { _, _ -> },
onDeleteAppSetting = {},
onLaunchApp = {},
onAutoLaunchApp = {},
onResetAppSettingsResult = {},
onResetShortcutResult = {},
onResetClipboardResult = {},
onGetSecureSettingsByName = { _, _ -> },
onAddAppSetting = {},
onCopyPermissionCommand = {},
onAddShortcut = {},
onUpdateShortcut = {},
)
}
}
@DevicePreviews
@Composable
private fun AppSettingsScreenEmptyStatePreview() {
GetoTheme {
AppSettingsScreen(
packageName = "com.android.geto",
appName = "Geto",
appSettingsUiState = AppSettingsUiState.Success(emptyList()),
snackbarHostState = SnackbarHostState(),
applicationIcon = null,
secureSettings = emptyList(),
applyAppSettingsResult = AppSettingsResult.NoResult,
revertAppSettingsResult = AppSettingsResult.NoResult,
shortcutResult = ShortcutResult.NoResult,
clipboardResult = ClipboardResult.NoResult,
onNavigationIconClick = {},
onRevertAppSettings = {},
onGetShortcut = {},
onCheckAppSetting = { _, _ -> },
onDeleteAppSetting = {},
onLaunchApp = {},
onAutoLaunchApp = {},
onResetAppSettingsResult = {},
onResetShortcutResult = {},
onResetClipboardResult = {},
onGetSecureSettingsByName = { _, _ -> },
onAddAppSetting = {},
onCopyPermissionCommand = {},
onAddShortcut = {},
onUpdateShortcut = {},
)
}
}
@DevicePreviews
@Composable
private fun AppSettingsScreenSuccessStatePreview(
@PreviewParameter(AppSettingsPreviewParameterProvider::class) appSettings: List<AppSetting>,
) {
GetoTheme {
AppSettingsScreen(
packageName = "com.android.geto",
appName = "Geto",
appSettingsUiState = AppSettingsUiState.Success(appSettings),
snackbarHostState = SnackbarHostState(),
applicationIcon = null,
secureSettings = emptyList(),
applyAppSettingsResult = AppSettingsResult.NoResult,
revertAppSettingsResult = AppSettingsResult.NoResult,
shortcutResult = ShortcutResult.NoResult,
clipboardResult = ClipboardResult.NoResult,
onNavigationIconClick = {},
onRevertAppSettings = {},
onGetShortcut = {},
onCheckAppSetting = { _, _ -> },
onDeleteAppSetting = {},
onLaunchApp = {},
onAutoLaunchApp = {},
onResetAppSettingsResult = {},
onResetShortcutResult = {},
onResetClipboardResult = {},
onGetSecureSettingsByName = { _, _ -> },
onAddAppSetting = {},
onCopyPermissionCommand = {},
onAddShortcut = {},
onUpdateShortcut = {},
)
}
}
| Geto/feature/appsettings/src/main/kotlin/com/android/geto/feature/appsettings/AppSettingsScreen.kt | 577214415 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.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.android.geto.feature.appsettings.navigation
import androidx.annotation.VisibleForTesting
import androidx.lifecycle.SavedStateHandle
import androidx.navigation.NavController
import androidx.navigation.NavGraphBuilder
import androidx.navigation.compose.composable
import androidx.navigation.navDeepLink
import com.android.geto.feature.appsettings.AppSettingsRoute
import java.net.URLDecoder
import kotlin.text.Charsets.UTF_8
private val URL_CHARACTER_ENCODING = UTF_8.name()
@VisibleForTesting
internal const val PACKAGE_NAME_ARG = "package_name"
@VisibleForTesting
internal const val APP_NAME_ARG = "app_name"
internal const val DEEP_LINK_URI = "https://www.android.geto.com"
internal class AppSettingsArgs(val packageName: String, val appName: String) {
constructor(savedStateHandle: SavedStateHandle) : this(
URLDecoder.decode(
checkNotNull(
savedStateHandle[PACKAGE_NAME_ARG],
),
URL_CHARACTER_ENCODING,
),
URLDecoder.decode(checkNotNull(savedStateHandle[APP_NAME_ARG]), URL_CHARACTER_ENCODING),
)
}
fun NavController.navigateToAppSettings(packageName: String, appName: String) {
navigate("app_settings_route/$packageName/$appName")
}
fun NavGraphBuilder.appSettingsScreen(onNavigationIconClick: () -> Unit) {
composable(
route = "app_settings_route/{$PACKAGE_NAME_ARG}/{$APP_NAME_ARG}",
deepLinks = listOf(
navDeepLink {
uriPattern = "$DEEP_LINK_URI/{$PACKAGE_NAME_ARG}/{$APP_NAME_ARG}"
},
),
) {
AppSettingsRoute(onNavigationIconClick = onNavigationIconClick)
}
}
| Geto/feature/appsettings/src/main/kotlin/com/android/geto/feature/appsettings/navigation/AppSettingsNavigation.kt | 1371045102 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.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.android.geto.feature.appsettings.dialog.shortcut
import android.graphics.Bitmap
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.layout.size
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.android.geto.core.designsystem.component.DialogButtons
import com.android.geto.core.designsystem.component.DialogContainer
import com.android.geto.core.designsystem.component.DynamicAsyncImage
import com.android.geto.core.designsystem.theme.GetoTheme
import com.android.geto.core.model.TargetShortcutInfoCompat
import com.android.geto.feature.appsettings.R
@Composable
internal fun ShortcutDialog(
modifier: Modifier = Modifier,
shortcutDialogState: ShortcutDialogState,
packageName: String,
contentDescription: String,
title: String,
negativeButtonText: String,
positiveButtonText: String,
onPositiveButtonClick: (TargetShortcutInfoCompat) -> Unit,
) {
DialogContainer(
modifier = modifier,
onDismissRequest = { shortcutDialogState.updateShowDialog(false) },
contentDescription = contentDescription,
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(10.dp),
) {
ShortcutDialogTitle(title = title)
ShortcutDialogApplicationIcon(
icon = shortcutDialogState.icon,
modifier = Modifier
.size(50.dp)
.align(Alignment.CenterHorizontally),
)
ShortcutDialogTextFields(
shortcutDialogState = shortcutDialogState,
)
DialogButtons(
negativeButtonText = negativeButtonText,
positiveButtonText = positiveButtonText,
onNegativeButtonClick = {
shortcutDialogState.updateShowDialog(false)
},
onPositiveButtonClick = {
shortcutDialogState.getShortcut(
packageName = packageName,
)?.let {
onPositiveButtonClick(it)
shortcutDialogState.resetState()
}
},
)
}
}
}
@Composable
private fun ShortcutDialogTitle(modifier: Modifier = Modifier, title: String) {
Spacer(modifier = Modifier.height(10.dp))
Text(
modifier = modifier.padding(horizontal = 5.dp),
text = title,
style = MaterialTheme.typography.titleLarge,
)
}
@Composable
private fun ShortcutDialogApplicationIcon(modifier: Modifier = Modifier, icon: Bitmap?) {
Spacer(modifier = Modifier.height(10.dp))
DynamicAsyncImage(
model = icon,
contentDescription = null,
modifier = modifier,
)
}
@Composable
private fun ShortcutDialogTextFields(
shortcutDialogState: ShortcutDialogState,
) {
val shortLabelIsBlank = stringResource(id = R.string.short_label_is_blank)
val longLabelIsBlank = stringResource(id = R.string.long_label_is_blank)
Spacer(modifier = Modifier.height(10.dp))
OutlinedTextField(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 5.dp)
.testTag("shortcutDialog:shortLabelTextField"),
value = shortcutDialogState.shortLabel,
onValueChange = shortcutDialogState::updateShortLabel,
label = {
Text(text = stringResource(R.string.short_label))
},
isError = shortcutDialogState.showShortLabelError,
supportingText = {
if (shortcutDialogState.showShortLabelError) {
Text(
text = shortLabelIsBlank,
modifier = Modifier.testTag("shortcutDialog:shortLabelSupportingText"),
)
} else {
Text(
text = "${shortcutDialogState.shortLabel.length}/${shortcutDialogState.shortLabelMaxLength}",
modifier = Modifier
.fillMaxWidth()
.testTag("shortcutDialog:shortLabelCounterSupportingText"),
)
}
},
singleLine = true,
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Next),
)
OutlinedTextField(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 5.dp)
.testTag("shortcutDialog:longLabelTextField"),
value = shortcutDialogState.longLabel,
onValueChange = shortcutDialogState::updateLongLabel,
label = {
Text(text = stringResource(R.string.long_label))
},
isError = shortcutDialogState.showLongLabelError,
supportingText = {
if (shortcutDialogState.showLongLabelError) {
Text(
text = longLabelIsBlank,
modifier = Modifier.testTag("shortcutDialog:longLabelSupportingText"),
)
} else {
Text(
text = "${shortcutDialogState.longLabel.length}/${shortcutDialogState.longLabelMaxLength}",
modifier = Modifier
.fillMaxWidth()
.testTag("shortcutDialog:longLabelCounterSupportingText"),
)
}
},
singleLine = true,
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Next),
)
}
@Preview
@Composable
private fun ShortcutDialogPreview() {
GetoTheme {
ShortcutDialog(
shortcutDialogState = rememberShortcutDialogState(),
packageName = "com.android.geto",
contentDescription = "Shortcut",
title = "Shortcut",
negativeButtonText = "Cancel",
positiveButtonText = "Okay",
onPositiveButtonClick = {},
)
}
}
| Geto/feature/appsettings/src/main/kotlin/com/android/geto/feature/appsettings/dialog/shortcut/ShortcutDialog.kt | 2830390226 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.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.android.geto.feature.appsettings.dialog.shortcut
import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Stable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.listSaver
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.core.graphics.drawable.toBitmap
import com.android.geto.core.model.TargetShortcutInfoCompat
@Composable
internal fun rememberShortcutDialogState(): ShortcutDialogState {
return rememberSaveable(saver = ShortcutDialogState.Saver) {
ShortcutDialogState()
}
}
@Stable
internal class ShortcutDialogState {
var showDialog by mutableStateOf(false)
private set
var icon by mutableStateOf<Bitmap?>(null)
private set
var shortLabel by mutableStateOf("")
private set
var showShortLabelError by mutableStateOf(false)
private set
var longLabel by mutableStateOf("")
private set
var showLongLabelError by mutableStateOf(false)
private set
val shortLabelMaxLength = 10
val longLabelMaxLength = 25
fun updateShowDialog(value: Boolean) {
showDialog = value
}
fun updateIcon(value: Drawable?) {
icon = value?.toBitmap()
}
fun updateShortLabel(value: String) {
if (value.length <= shortLabelMaxLength) {
shortLabel = value
}
}
fun updateLongLabel(value: String) {
if (value.length <= longLabelMaxLength) {
longLabel = value
}
}
fun resetState() {
showDialog = false
longLabel = ""
shortLabel = ""
}
fun getShortcut(packageName: String): TargetShortcutInfoCompat? {
showShortLabelError = shortLabel.isBlank()
showLongLabelError = longLabel.isBlank()
return if (showShortLabelError.not() && showLongLabelError.not()) {
TargetShortcutInfoCompat(
id = packageName,
icon = icon,
shortLabel = shortLabel,
longLabel = longLabel,
)
} else {
null
}
}
companion object {
val Saver = listSaver<ShortcutDialogState, Any>(
save = { state ->
listOf(
state.showDialog,
state.shortLabel,
state.showShortLabelError,
state.longLabel,
state.showLongLabelError,
)
},
restore = {
ShortcutDialogState().apply {
showDialog = it[0] as Boolean
shortLabel = it[1] as String
showShortLabelError = it[2] as Boolean
longLabel = it[3] as String
showLongLabelError = it[4] as Boolean
}
},
)
}
}
| Geto/feature/appsettings/src/main/kotlin/com/android/geto/feature/appsettings/dialog/shortcut/ShortcutDialogState.kt | 3232029450 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.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.android.geto.feature.appsettings.dialog.appsetting
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Stable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.listSaver
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import com.android.geto.core.model.AppSetting
import com.android.geto.core.model.SecureSetting
import com.android.geto.core.model.SettingType
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.debounce
@Composable
internal fun rememberAppSettingDialogState(): AppSettingDialogState {
return rememberSaveable(saver = AppSettingDialogState.Saver) {
AppSettingDialogState()
}
}
@Stable
internal class AppSettingDialogState {
var secureSettings by mutableStateOf<List<SecureSetting>>(emptyList())
var secureSettingsExpanded by mutableStateOf(false)
var showDialog by mutableStateOf(false)
private set
var selectedRadioOptionIndex by mutableIntStateOf(0)
private set
var label by mutableStateOf("")
private set
var showLabelError by mutableStateOf(false)
private set
var key by mutableStateOf("")
private set
var showKeyError by mutableStateOf(false)
private set
var showKeyNotFoundError by mutableStateOf(false)
private set
var valueOnLaunch by mutableStateOf("")
private set
var showValueOnLaunchError by mutableStateOf(false)
private set
var valueOnRevert by mutableStateOf("")
private set
var showValueOnRevertError by mutableStateOf(false)
private set
private val _keyDebounce = MutableStateFlow("")
@OptIn(FlowPreview::class)
val keyDebounce = _keyDebounce.debounce(500)
fun updateSecureSettings(value: List<SecureSetting>) {
secureSettings = value
}
fun updateSecureSettingsExpanded(value: Boolean) {
secureSettingsExpanded = value
}
fun updateShowDialog(value: Boolean) {
showDialog = value
}
fun updateSelectedRadioOptionIndex(value: Int) {
selectedRadioOptionIndex = value
}
fun updateLabel(value: String) {
label = value
}
fun updateKey(value: String) {
key = value
_keyDebounce.value = value
}
fun updateValueOnLaunch(value: String) {
valueOnLaunch = value
}
fun updateValueOnRevert(value: String) {
valueOnRevert = value
}
fun resetState() {
showDialog = false
secureSettingsExpanded = false
secureSettings = emptyList()
selectedRadioOptionIndex = 0
key = ""
label = ""
valueOnLaunch = ""
valueOnRevert = ""
}
fun getAppSetting(packageName: String): AppSetting? {
showLabelError = label.isBlank()
showKeyError = key.isBlank()
showKeyNotFoundError =
key.isNotBlank() && !secureSettings.mapNotNull { it.name }.contains(key)
showValueOnLaunchError = valueOnLaunch.isBlank()
showValueOnRevertError = valueOnRevert.isBlank()
return if (showLabelError.not() && showKeyNotFoundError.not() && showKeyError.not() && showValueOnLaunchError.not() && showValueOnRevertError.not()) {
AppSetting(
enabled = true,
settingType = SettingType.entries[selectedRadioOptionIndex],
packageName = packageName,
label = label,
key = key,
valueOnLaunch = valueOnLaunch,
valueOnRevert = valueOnRevert,
)
} else {
null
}
}
companion object {
val Saver = listSaver<AppSettingDialogState, Any>(
save = { state ->
listOf(
state.showDialog,
state.selectedRadioOptionIndex,
state.label,
state.showLabelError,
state.key,
state.showKeyError,
state.showKeyNotFoundError,
state.valueOnLaunch,
state.showValueOnLaunchError,
state.valueOnRevert,
state.showValueOnRevertError,
)
},
restore = {
AppSettingDialogState().apply {
showDialog = it[0] as Boolean
selectedRadioOptionIndex = it[1] as Int
label = it[2] as String
showLabelError = it[3] as Boolean
key = it[4] as String
showKeyError = it[5] as Boolean
showKeyNotFoundError = it[6] as Boolean
valueOnLaunch = it[7] as String
showValueOnLaunchError = it[8] as Boolean
valueOnRevert = it[9] as String
showValueOnRevertError = it[10] as Boolean
}
},
)
}
}
| Geto/feature/appsettings/src/main/kotlin/com/android/geto/feature/appsettings/dialog/appsetting/AppSettingDialogState.kt | 839729311 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.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.android.geto.feature.appsettings.dialog.appsetting
import androidx.compose.foundation.ScrollState
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.rememberScrollState
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ExposedDropdownMenuBox
import androidx.compose.material3.ExposedDropdownMenuDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.android.geto.core.designsystem.component.DialogButtons
import com.android.geto.core.designsystem.component.DialogContainer
import com.android.geto.core.designsystem.component.DialogTitle
import com.android.geto.core.designsystem.component.GetoRadioButtonGroup
import com.android.geto.core.designsystem.theme.GetoTheme
import com.android.geto.core.model.AppSetting
import com.android.geto.core.model.SettingType
import com.android.geto.feature.appsettings.R
@Composable
internal fun AppSettingDialog(
modifier: Modifier = Modifier,
appSettingDialogState: AppSettingDialogState,
scrollState: ScrollState = rememberScrollState(),
packageName: String,
onAddSetting: (AppSetting) -> Unit,
contentDescription: String,
) {
DialogContainer(
modifier = modifier,
onDismissRequest = { appSettingDialogState.updateShowDialog(false) },
contentDescription = contentDescription,
) {
Column(
modifier = Modifier
.fillMaxWidth()
.verticalScroll(scrollState)
.padding(10.dp),
) {
DialogTitle(title = stringResource(R.string.add_app_setting))
GetoRadioButtonGroup(
selected = appSettingDialogState.selectedRadioOptionIndex,
onSelect = appSettingDialogState::updateSelectedRadioOptionIndex,
items = SettingType.entries.map { it.label }.toTypedArray(),
)
AppSettingDialogTextFields(
appSettingDialogState = appSettingDialogState,
)
DialogButtons(
negativeButtonText = stringResource(R.string.cancel),
positiveButtonText = stringResource(R.string.add),
onNegativeButtonClick = {
appSettingDialogState.updateShowDialog(false)
},
onPositiveButtonClick = {
appSettingDialogState.getAppSetting(packageName = packageName)?.let {
onAddSetting(it)
appSettingDialogState.resetState()
}
},
)
}
}
}
@Composable
private fun AppSettingDialogTextFields(
appSettingDialogState: AppSettingDialogState,
) {
val labelIsBlank = stringResource(id = R.string.setting_label_is_blank)
val valueOnLaunchIsBlank = stringResource(id = R.string.setting_value_on_launch_is_blank)
val valueOnRevertIsBlank = stringResource(id = R.string.setting_value_on_revert_is_blank)
Spacer(modifier = Modifier.height(10.dp))
OutlinedTextField(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 5.dp)
.testTag("appSettingDialog:labelTextField"),
value = appSettingDialogState.label,
onValueChange = appSettingDialogState::updateLabel,
label = {
Text(text = stringResource(R.string.setting_label))
},
isError = appSettingDialogState.showLabelError,
supportingText = {
if (appSettingDialogState.showLabelError) {
Text(
text = labelIsBlank,
modifier = Modifier.testTag("appSettingDialog:labelSupportingText"),
)
}
},
singleLine = true,
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Next),
)
AppSettingDialogTextFieldWithDropdownMenu(
appSettingDialogState = appSettingDialogState,
)
OutlinedTextField(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 5.dp)
.testTag("appSettingDialog:valueOnLaunchTextField"),
value = appSettingDialogState.valueOnLaunch,
onValueChange = appSettingDialogState::updateValueOnLaunch,
label = {
Text(text = stringResource(R.string.setting_value_on_launch))
},
isError = appSettingDialogState.showValueOnLaunchError,
supportingText = {
if (appSettingDialogState.showValueOnLaunchError) {
Text(
text = valueOnLaunchIsBlank,
modifier = Modifier.testTag("appSettingDialog:valueOnLaunchSupportingText"),
)
}
},
singleLine = true,
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Next),
)
OutlinedTextField(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 5.dp)
.testTag("appSettingDialog:valueOnRevertTextField"),
value = appSettingDialogState.valueOnRevert,
onValueChange = appSettingDialogState::updateValueOnRevert,
label = {
Text(text = stringResource(R.string.setting_value_on_revert))
},
isError = appSettingDialogState.showValueOnRevertError,
supportingText = {
if (appSettingDialogState.showValueOnRevertError) {
Text(
text = valueOnRevertIsBlank,
modifier = Modifier.testTag("appSettingDialog:valueOnRevertSupportingText"),
)
}
},
singleLine = true,
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Next),
)
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun AppSettingDialogTextFieldWithDropdownMenu(
appSettingDialogState: AppSettingDialogState,
) {
val keyIsBlank = stringResource(id = R.string.setting_key_is_blank)
val keyNotFound = stringResource(id = R.string.setting_key_not_found)
ExposedDropdownMenuBox(
expanded = appSettingDialogState.secureSettingsExpanded,
onExpandedChange = appSettingDialogState::updateSecureSettingsExpanded,
modifier = Modifier.testTag("appSettingDialog:exposedDropdownMenuBox"),
) {
OutlinedTextField(
modifier = Modifier
.menuAnchor()
.fillMaxWidth()
.padding(horizontal = 5.dp)
.testTag("appSettingDialog:keyTextField"),
value = appSettingDialogState.key,
onValueChange = appSettingDialogState::updateKey,
label = {
Text(text = stringResource(R.string.setting_key))
},
trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = appSettingDialogState.secureSettingsExpanded) },
colors = ExposedDropdownMenuDefaults.textFieldColors(),
isError = appSettingDialogState.showKeyError || appSettingDialogState.showKeyNotFoundError,
supportingText = {
if (appSettingDialogState.showKeyError) {
Text(
text = keyIsBlank,
modifier = Modifier.testTag("appSettingDialog:keySupportingText"),
)
}
if (appSettingDialogState.showKeyNotFoundError) {
Text(
text = keyNotFound,
modifier = Modifier.testTag("appSettingDialog:settingsKeyNotFoundSupportingText"),
)
}
},
singleLine = true,
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Next),
)
if (appSettingDialogState.secureSettings.isNotEmpty()) {
ExposedDropdownMenu(
expanded = appSettingDialogState.secureSettingsExpanded,
onDismissRequest = {
appSettingDialogState.updateSecureSettingsExpanded(false)
},
) {
appSettingDialogState.secureSettings.forEach { secureSetting ->
DropdownMenuItem(
text = {
Text(
text = secureSetting.name ?: "null",
style = MaterialTheme.typography.bodySmall,
)
},
onClick = {
appSettingDialogState.updateKey(
secureSetting.name ?: "null",
)
appSettingDialogState.updateValueOnRevert(
secureSetting.value ?: "null",
)
appSettingDialogState.updateSecureSettingsExpanded(
false,
)
},
contentPadding = ExposedDropdownMenuDefaults.ItemContentPadding,
)
}
}
}
}
}
@Preview
@Composable
private fun AppSettingDialogPreview() {
GetoTheme {
AppSettingDialog(
appSettingDialogState = rememberAppSettingDialogState(),
packageName = "com.android.geto",
onAddSetting = { },
contentDescription = "App setting dialog",
)
}
}
| Geto/feature/appsettings/src/main/kotlin/com/android/geto/feature/appsettings/dialog/appsetting/AppSettingDialog.kt | 144735941 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.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.android.geto.feature.appsettings.dialog.copypermissioncommand
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Stable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.listSaver
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
@Composable
internal fun rememberCopyPermissionCommandDialogState(): CopyPermissionCommandDialogState {
return rememberSaveable(saver = CopyPermissionCommandDialogState.Saver) {
CopyPermissionCommandDialogState()
}
}
@Stable
internal class CopyPermissionCommandDialogState {
var showDialog by mutableStateOf(false)
private set
fun updateShowDialog(value: Boolean) {
showDialog = value
}
companion object {
val Saver = listSaver<CopyPermissionCommandDialogState, Any>(
save = { state ->
listOf(
state.showDialog,
)
},
restore = {
CopyPermissionCommandDialogState().apply {
showDialog = it[0] as Boolean
}
},
)
}
}
| Geto/feature/appsettings/src/main/kotlin/com/android/geto/feature/appsettings/dialog/copypermissioncommand/CopyPermissionCommandDialogState.kt | 2733679183 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.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.android.geto.feature.appsettings
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.android.geto.core.data.repository.AppSettingsRepository
import com.android.geto.core.data.repository.ClipboardRepository
import com.android.geto.core.data.repository.ClipboardResult
import com.android.geto.core.data.repository.PackageRepository
import com.android.geto.core.data.repository.SecureSettingsRepository
import com.android.geto.core.data.repository.ShortcutRepository
import com.android.geto.core.data.repository.ShortcutResult
import com.android.geto.core.domain.AppSettingsResult
import com.android.geto.core.domain.ApplyAppSettingsUseCase
import com.android.geto.core.domain.AutoLaunchUseCase
import com.android.geto.core.domain.RevertAppSettingsUseCase
import com.android.geto.core.model.AppSetting
import com.android.geto.core.model.SecureSetting
import com.android.geto.core.model.SettingType
import com.android.geto.core.model.TargetShortcutInfoCompat
import com.android.geto.feature.appsettings.navigation.AppSettingsArgs
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class AppSettingsViewModel @Inject constructor(
savedStateHandle: SavedStateHandle,
private val appSettingsRepository: AppSettingsRepository,
private val clipboardRepository: ClipboardRepository,
private val packageRepository: PackageRepository,
private val secureSettingsRepository: SecureSettingsRepository,
private val shortcutRepository: ShortcutRepository,
private val applyAppSettingsUseCase: ApplyAppSettingsUseCase,
private val revertAppSettingsUseCase: RevertAppSettingsUseCase,
private val autoLaunchUseCase: AutoLaunchUseCase,
) : ViewModel() {
private var _secureSetting = MutableStateFlow<List<SecureSetting>>(emptyList())
val secureSettings = _secureSetting.asStateFlow()
private val _applyAppSettingsResult =
MutableStateFlow<AppSettingsResult>(AppSettingsResult.NoResult)
val applyAppSettingsResult = _applyAppSettingsResult.asStateFlow()
private val _revertAppSettingsResult =
MutableStateFlow<AppSettingsResult>(AppSettingsResult.NoResult)
val revertAppSettingsResult = _revertAppSettingsResult.asStateFlow()
private val _shortcutResult = MutableStateFlow<ShortcutResult>(ShortcutResult.NoResult)
val shortcutResult = _shortcutResult.asStateFlow()
private val _clipboardResult = MutableStateFlow<ClipboardResult>(ClipboardResult.NoResult)
val clipboardResult = _clipboardResult.asStateFlow()
private val appSettingsArgs = AppSettingsArgs(savedStateHandle)
val packageName = appSettingsArgs.packageName
val appName = appSettingsArgs.appName
val appSettingUiState = appSettingsRepository.getAppSettingsByPackageName(packageName)
.map<List<AppSetting>, AppSettingsUiState>(AppSettingsUiState::Success).stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000),
initialValue = AppSettingsUiState.Loading,
)
val applicationIcon = flow {
emit(packageRepository.getApplicationIcon(packageName))
}.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000),
initialValue = null,
)
fun applyAppSettings() {
viewModelScope.launch {
_applyAppSettingsResult.update { applyAppSettingsUseCase(packageName = packageName) }
}
}
fun autoLaunchApp() {
viewModelScope.launch {
_applyAppSettingsResult.update { autoLaunchUseCase(packageName = packageName) }
}
}
fun checkAppSetting(checked: Boolean, appSetting: AppSetting) {
viewModelScope.launch {
val updatedUserAppSettingsItem = appSetting.copy(enabled = checked)
appSettingsRepository.upsertAppSetting(
updatedUserAppSettingsItem,
)
}
}
fun deleteAppSetting(appSetting: AppSetting) {
viewModelScope.launch {
appSettingsRepository.deleteAppSetting(appSetting)
}
}
fun addAppSettings(appSetting: AppSetting) {
viewModelScope.launch {
appSettingsRepository.upsertAppSetting(appSetting)
}
}
fun getShortcut(id: String = packageName) {
viewModelScope.launch {
_shortcutResult.update { shortcutRepository.getShortcut(id) }
}
}
fun copyPermissionCommand() {
_clipboardResult.update {
clipboardRepository.setPrimaryClip(
label = "Command",
text = "pm grant com.android.geto android.permission.WRITE_SECURE_SETTINGS",
)
}
}
fun revertAppSettings() {
viewModelScope.launch {
_revertAppSettingsResult.update { revertAppSettingsUseCase(packageName = packageName) }
}
}
fun requestPinShortcut(targetShortcutInfoCompat: TargetShortcutInfoCompat) {
viewModelScope.launch {
_shortcutResult.update {
shortcutRepository.requestPinShortcut(
packageName = packageName,
appName = appName,
targetShortcutInfoCompat = targetShortcutInfoCompat,
)
}
}
}
fun updateRequestPinShortcut(targetShortcutInfoCompat: TargetShortcutInfoCompat) {
viewModelScope.launch {
_shortcutResult.update {
shortcutRepository.updateRequestPinShortcut(
packageName = packageName,
appName = appName,
targetShortcutInfoCompat,
)
}
}
}
fun getSecureSettingsByName(settingType: SettingType, text: String) {
viewModelScope.launch {
_secureSetting.update {
secureSettingsRepository.getSecureSettingsByName(
settingType = settingType,
text = text,
)
}
}
}
fun resetAppSettingsResult() {
_applyAppSettingsResult.update { AppSettingsResult.NoResult }
_revertAppSettingsResult.update { AppSettingsResult.NoResult }
}
fun resetShortcutResult() {
_shortcutResult.update { ShortcutResult.NoResult }
}
fun resetClipboardResult() {
_clipboardResult.update { ClipboardResult.NoResult }
}
}
| Geto/feature/appsettings/src/main/kotlin/com/android/geto/feature/appsettings/AppSettingsViewModel.kt | 2101996651 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.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.android.geto.feature.appsettings
import com.android.geto.core.model.AppSetting
sealed interface AppSettingsUiState {
data class Success(val appSettingList: List<AppSetting>) : AppSettingsUiState
data object Loading : AppSettingsUiState
}
| Geto/feature/appsettings/src/main/kotlin/com/android/geto/feature/appsettings/AppSettingsUiState.kt | 460460771 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.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.android.geto.feature.apps
import androidx.activity.ComponentActivity
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.junit4.createAndroidComposeRule
import androidx.compose.ui.test.onNodeWithContentDescription
import androidx.compose.ui.test.onNodeWithTag
import com.android.geto.core.model.TargetApplicationInfo
import org.junit.Rule
import org.junit.Test
class AppsScreenTest {
@get:Rule
val composeTestRule = createAndroidComposeRule<ComponentActivity>()
@Test
fun getoLoadingWheel_isDisplayed_whenAppsUiState_isLoading() {
composeTestRule.setContent {
AppsScreen(
appsUiState = AppsUiState.Loading,
onItemClick = { _, _ -> },
onSettingsClick = {},
)
}
composeTestRule.onNodeWithContentDescription("GetoLoadingWheel").assertIsDisplayed()
}
@Test
fun lazyColumn_isDisplayed_whenAppsUiState_isSuccess() {
val installedApplications = List(2) { index ->
TargetApplicationInfo(
flags = 0,
packageName = "com.android.geto$index",
label = "Geto $index",
)
}
composeTestRule.setContent {
AppsScreen(
appsUiState = AppsUiState.Success(installedApplications),
onItemClick = { _, _ -> },
onSettingsClick = {},
)
}
composeTestRule.onNodeWithTag("apps:lazyColumn").assertIsDisplayed()
}
}
| Geto/feature/apps/src/androidTest/kotlin/com/android/geto/feature/apps/AppsScreenTest.kt | 140285779 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.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.android.geto.feature.apps
import androidx.activity.ComponentActivity
import androidx.compose.ui.test.junit4.createAndroidComposeRule
import com.android.geto.core.designsystem.component.GetoBackground
import com.android.geto.core.designsystem.theme.GetoTheme
import com.android.geto.core.model.TargetApplicationInfo
import com.android.geto.core.screenshot.testing.util.DefaultTestDevices
import com.android.geto.core.screenshot.testing.util.captureForDevice
import com.android.geto.core.screenshot.testing.util.captureMultiDevice
import dagger.hilt.android.testing.HiltTestApplication
import org.junit.Rule
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import org.robolectric.annotation.GraphicsMode
import org.robolectric.annotation.LooperMode
import kotlin.test.Test
@RunWith(RobolectricTestRunner::class)
@GraphicsMode(GraphicsMode.Mode.NATIVE)
@Config(application = HiltTestApplication::class)
@LooperMode(LooperMode.Mode.PAUSED)
class AppsScreenScreenshotTest {
@get:Rule
val composeTestRule = createAndroidComposeRule<ComponentActivity>()
private val installedApplications = List(5) { index ->
TargetApplicationInfo(
flags = 0,
packageName = "com.android.geto$index",
label = "Geto $index",
)
}
@Test
fun appsScreen_populated() {
composeTestRule.captureMultiDevice("AppsScreenPopulated") {
GetoTheme {
AppsScreen(
appsUiState = AppsUiState.Success(installedApplications),
onItemClick = { _, _ -> },
onSettingsClick = {},
)
}
}
}
@Test
fun appsScreen_loading() {
composeTestRule.captureMultiDevice("AppsScreenLoading") {
GetoTheme {
AppsScreen(
appsUiState = AppsUiState.Loading,
onItemClick = { _, _ -> },
onSettingsClick = {},
)
}
}
}
@Test
fun appsScreen_populated_dark() {
composeTestRule.captureForDevice(
deviceName = "phone_dark",
deviceSpec = DefaultTestDevices.PHONE.spec,
fileName = "AppsScreenPopulated",
darkMode = true,
) {
GetoTheme {
GetoBackground {
AppsScreen(
appsUiState = AppsUiState.Success(
installedApplications,
),
onItemClick = { _, _ -> },
onSettingsClick = {},
)
}
}
}
}
@Test
fun appsScreen_loading_dark() {
composeTestRule.captureForDevice(
deviceName = "phone_dark",
deviceSpec = DefaultTestDevices.PHONE.spec,
fileName = "AppsScreenLoading",
darkMode = true,
) {
GetoTheme {
GetoBackground {
AppsScreen(
appsUiState = AppsUiState.Loading,
onItemClick = { _, _ -> },
onSettingsClick = {},
)
}
}
}
}
}
| Geto/feature/apps/src/test/kotlin/com/android/geto/feature/apps/AppsScreenScreenshotTest.kt | 52270154 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.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.android.geto.feature.apps
import com.android.geto.core.model.TargetApplicationInfo
import com.android.geto.core.testing.repository.TestPackageRepository
import com.android.geto.core.testing.util.MainDispatcherRule
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.runTest
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import kotlin.test.assertIs
class AppsViewModelTest {
@get:Rule
val mainDispatcherRule = MainDispatcherRule()
private val packageRepository = TestPackageRepository()
private lateinit var viewModel: AppsViewModel
@Before
fun setup() {
viewModel = AppsViewModel(packageRepository)
}
@Test
fun appsUiState_isLoading_whenStarted() {
assertIs<AppsUiState.Loading>(viewModel.appsUiState.value)
}
@Test
fun appsUiState_isSuccess_whenGetInstalledApplications() = runTest {
val installedApplications = List(2) { index ->
TargetApplicationInfo(
flags = 0,
packageName = "com.android.geto$index",
label = "Geto $index",
)
}
packageRepository.setInstalledApplications(installedApplications)
val collectJob = launch(UnconfinedTestDispatcher()) { viewModel.appsUiState.collect() }
assertIs<AppsUiState.Success>(viewModel.appsUiState.value)
collectJob.cancel()
}
}
| Geto/feature/apps/src/test/kotlin/com/android/geto/feature/apps/AppsViewModelTest.kt | 198637670 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.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.android.geto.feature.apps
import androidx.annotation.VisibleForTesting
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.consumeWindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.semantics.testTagsAsResourceId
import androidx.compose.ui.tooling.preview.PreviewParameter
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.android.geto.core.designsystem.component.GetoLoadingWheel
import com.android.geto.core.designsystem.icon.GetoIcons
import com.android.geto.core.designsystem.theme.GetoTheme
import com.android.geto.core.model.TargetApplicationInfo
import com.android.geto.core.ui.DevicePreviews
import com.android.geto.core.ui.TargetApplicationInfoPreviewParameterProvider
@Composable
internal fun AppsRoute(
modifier: Modifier = Modifier,
viewModel: AppsViewModel = hiltViewModel(),
onItemClick: (String, String) -> Unit,
onSettingsClick: () -> Unit,
) {
val appListUiState = viewModel.appsUiState.collectAsStateWithLifecycle().value
AppsScreen(
modifier = modifier,
appsUiState = appListUiState,
onItemClick = onItemClick,
onSettingsClick = onSettingsClick,
)
}
@OptIn(ExperimentalComposeUiApi::class)
@VisibleForTesting
@Composable
internal fun AppsScreen(
modifier: Modifier = Modifier,
appsUiState: AppsUiState,
onSettingsClick: () -> Unit,
onItemClick: (String, String) -> Unit,
) {
Scaffold(
topBar = {
AppsTopAppBar(
title = stringResource(R.string.geto),
onSettingsClick = onSettingsClick,
)
},
) { innerPadding ->
Box(
modifier = modifier
.fillMaxSize()
.consumeWindowInsets(innerPadding)
.semantics {
testTagsAsResourceId = true
}
.testTag("apps"),
) {
when (appsUiState) {
AppsUiState.Loading -> LoadingState(
modifier = Modifier.align(Alignment.Center),
)
is AppsUiState.Success -> SuccessState(
modifier = modifier,
appsUiState = appsUiState,
contentPadding = innerPadding,
onItemClick = onItemClick,
)
}
}
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun AppsTopAppBar(
modifier: Modifier = Modifier,
title: String,
onSettingsClick: () -> Unit,
) {
TopAppBar(
title = {
Text(text = title)
},
modifier = modifier.testTag("apps:topAppBar"),
actions = {
IconButton(onClick = onSettingsClick) {
Icon(imageVector = GetoIcons.Settings, contentDescription = "Settings icon")
}
},
)
}
@Composable
private fun LoadingState(modifier: Modifier = Modifier) {
GetoLoadingWheel(
modifier = modifier,
contentDescription = "GetoLoadingWheel",
)
}
@Composable
private fun SuccessState(
modifier: Modifier = Modifier,
appsUiState: AppsUiState.Success,
contentPadding: PaddingValues,
onItemClick: (String, String) -> Unit,
) {
LazyColumn(
modifier = modifier
.fillMaxSize()
.testTag("apps:lazyColumn"),
contentPadding = contentPadding,
) {
items(appsUiState.targetApplicationInfoList) { targetApplicationInfo ->
AppItem(
targetApplicationInfo = targetApplicationInfo,
onItemClick = onItemClick,
)
}
}
}
@DevicePreviews
@Composable
private fun AppListScreenLoadingStatePreview() {
GetoTheme {
AppsScreen(
appsUiState = AppsUiState.Loading,
onSettingsClick = {},
onItemClick = { _, _ -> },
)
}
}
@DevicePreviews
@Composable
private fun AppListScreenSuccessStatePreview(
@PreviewParameter(TargetApplicationInfoPreviewParameterProvider::class) installedApplications: List<TargetApplicationInfo>,
) {
GetoTheme {
AppsScreen(
appsUiState = AppsUiState.Success(installedApplications),
onSettingsClick = {},
onItemClick = { _, _ -> },
)
}
}
| Geto/feature/apps/src/main/kotlin/com/android/geto/feature/apps/AppsScreen.kt | 999761796 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.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.android.geto.feature.apps.navigation
import androidx.navigation.NavGraphBuilder
import androidx.navigation.compose.composable
import com.android.geto.feature.apps.AppsRoute
const val APPS_NAVIGATION_ROUTE = "apps_route"
fun NavGraphBuilder.appsScreen(
onItemClick: (String, String) -> Unit,
onSettingsClick: () -> Unit,
) {
composable(
route = APPS_NAVIGATION_ROUTE,
) {
AppsRoute(
onItemClick = onItemClick,
onSettingsClick = onSettingsClick,
)
}
}
| Geto/feature/apps/src/main/kotlin/com/android/geto/feature/apps/navigation/AppsNavigation.kt | 2271405439 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.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.android.geto.feature.apps
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.android.geto.core.data.repository.PackageRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.stateIn
import javax.inject.Inject
@HiltViewModel
class AppsViewModel @Inject constructor(
private val packageRepository: PackageRepository,
) : ViewModel() {
val appsUiState = flow {
emit(AppsUiState.Success(packageRepository.getInstalledApplications()))
}.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000),
initialValue = AppsUiState.Loading,
)
}
| Geto/feature/apps/src/main/kotlin/com/android/geto/feature/apps/AppsViewModel.kt | 1347227179 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.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.android.geto.feature.apps
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
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.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.android.geto.core.designsystem.component.DynamicAsyncImage
import com.android.geto.core.designsystem.theme.GetoTheme
import com.android.geto.core.model.TargetApplicationInfo
@Composable
fun AppItem(
modifier: Modifier = Modifier,
targetApplicationInfo: TargetApplicationInfo,
onItemClick: (String, String) -> Unit,
) {
Row(
modifier = modifier
.fillMaxWidth()
.testTag("apps:appItem")
.clickable {
onItemClick(
targetApplicationInfo.packageName,
targetApplicationInfo.label,
)
}
.padding(10.dp),
verticalAlignment = Alignment.CenterVertically,
) {
DynamicAsyncImage(
model = targetApplicationInfo.icon,
contentDescription = null,
modifier = Modifier.size(50.dp),
)
Spacer(modifier = Modifier.width(10.dp))
Column(modifier = Modifier.weight(1f)) {
Text(
text = targetApplicationInfo.label,
style = MaterialTheme.typography.bodyLarge,
)
Spacer(modifier = Modifier.height(5.dp))
Text(
text = targetApplicationInfo.packageName,
style = MaterialTheme.typography.bodySmall,
)
}
}
}
@Preview
@Composable
private fun AppItemPreview() {
GetoTheme {
AppItem(
targetApplicationInfo = TargetApplicationInfo(
flags = 0,
packageName = "com.android.geto",
label = "Geto",
),
onItemClick = { _, _ -> },
)
}
}
| Geto/feature/apps/src/main/kotlin/com/android/geto/feature/apps/AppItem.kt | 1095417155 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.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.android.geto.feature.apps
import com.android.geto.core.model.TargetApplicationInfo
sealed interface AppsUiState {
data class Success(val targetApplicationInfoList: List<TargetApplicationInfo>) : AppsUiState
data object Loading : AppsUiState
}
| Geto/feature/apps/src/main/kotlin/com/android/geto/feature/apps/AppsUiState.kt | 3328290393 |
package com.example.mtgbazaar
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.mtgbazaar", appContext.packageName)
}
} | mtg-bazaar/app/src/androidTest/java/com/example/mtgbazaar/ExampleInstrumentedTest.kt | 2267103852 |
package com.example.mtgbazaar
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)
}
} | mtg-bazaar/app/src/test/java/com/example/mtgbazaar/ExampleUnitTest.kt | 1680517415 |
package com.example.mtgbazaar
import android.content.res.Resources
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Snackbar
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.Surface
import androidx.compose.material3.SnackbarHostState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.ReadOnlyComposable
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.navigation.compose.rememberNavController
import androidx.navigation.NavHostController
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.navigation.NavGraphBuilder
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.navArgument
import com.example.mtgbazaar.common.snackbar.SnackbarManager
import com.example.mtgbazaar.screens.collection.CollectionScreen
import com.example.mtgbazaar.screens.edit_binder.EditBinderScreen
import com.example.mtgbazaar.screens.login.LoginScreen
import com.example.mtgbazaar.screens.settings.SettingsScreen
import com.example.mtgbazaar.screens.sign_up.SignUpScreen
import com.example.mtgbazaar.screens.splash.SplashScreen
import com.example.mtgbazaar.ui.theme.MTGBazaarTheme
import kotlinx.coroutines.CoroutineScope
@Composable
fun MTGBazaarApp() {
MTGBazaarTheme {
Surface(color = MaterialTheme.colorScheme.surface) {
val appState = rememberAppState()
Scaffold(
snackbarHost = {
SnackbarHost(
hostState = appState.snackbarHostState,
modifier = Modifier.padding(8.dp),
snackbar = { snackbarData ->
Snackbar(snackbarData, contentColor = MaterialTheme.colorScheme.onPrimary)
}
)
}
) { innerPaddingModifier ->
NavHost(
navController = appState.navController,
startDestination = SPLASH_SCREEN,
modifier = Modifier.padding(innerPaddingModifier)
) {
mtgBazaarGraph(appState)
}
}
}
}
}
@Composable
fun rememberAppState(
snackbarHostState: SnackbarHostState = SnackbarHostState(),
navController: NavHostController = rememberNavController(),
snackbarManager: SnackbarManager = SnackbarManager,
resources: Resources = resources(),
coroutineScope: CoroutineScope = rememberCoroutineScope()
) =
remember(snackbarHostState, navController, snackbarManager, resources, coroutineScope) {
MTGBazaarAppState(snackbarHostState, navController, snackbarManager, resources, coroutineScope)
}
@Composable
@ReadOnlyComposable
fun resources(): Resources {
LocalConfiguration.current
return LocalContext.current.resources
}
fun NavGraphBuilder.mtgBazaarGraph(appState: MTGBazaarAppState) {
composable(SPLASH_SCREEN) {
SplashScreen(openAndPopUp = { route, popUp -> appState.navigateAndPopUp(route, popUp)})
}
composable(SETTINGS_SCREEN) {
SettingsScreen(
restartApp = { route -> appState.clearAndNavigate(route) },
openScreen = { route -> appState.navigate(route) }
)
}
composable(LOGIN_SCREEN) {
LoginScreen(openAndPopUp = { route, popUp -> appState.navigateAndPopUp(route, popUp) })
}
composable(SIGN_UP_SCREEN) {
SignUpScreen(openAndPopUp = { route, popUp -> appState.navigateAndPopUp(route, popUp) })
}
composable(COLLECTION_SCREEN) {
CollectionScreen(openScreen = { route -> appState.navigate(route) })
}
composable(
route = "$EDIT_BINDER_SCREEN$BINDER_ID_ARG",
arguments = listOf(navArgument(BINDER_ID) {
nullable = true
defaultValue = null
})
) {
EditBinderScreen(popUpScreen = { appState.popUp() })
}
} | mtg-bazaar/app/src/main/java/com/example/mtgbazaar/MTGBazaarApp.kt | 2532791889 |
package com.example.mtgbazaar.ui.theme
import androidx.compose.ui.graphics.Color
val md_theme_light_primary = Color(0xFF4F6603)
val md_theme_light_onPrimary = Color(0xFFFFFFFF)
val md_theme_light_primaryContainer = Color(0xFFD0EE82)
val md_theme_light_onPrimaryContainer = Color(0xFF151F00)
val md_theme_light_secondary = Color(0xFF3C6A1B)
val md_theme_light_onSecondary = Color(0xFFFFFFFF)
val md_theme_light_secondaryContainer = Color(0xFFBCF293)
val md_theme_light_onSecondaryContainer = Color(0xFF0B2000)
val md_theme_light_tertiary = Color(0xFF875200)
val md_theme_light_onTertiary = Color(0xFFFFFFFF)
val md_theme_light_tertiaryContainer = Color(0xFFFFDDBA)
val md_theme_light_onTertiaryContainer = Color(0xFF2B1700)
val md_theme_light_error = Color(0xFFBA1A1A)
val md_theme_light_errorContainer = Color(0xFFFFDAD6)
val md_theme_light_onError = Color(0xFFFFFFFF)
val md_theme_light_onErrorContainer = Color(0xFF410002)
val md_theme_light_background = Color(0xFFF9FFE8)
val md_theme_light_onBackground = Color(0xFF112000)
val md_theme_light_surface = Color(0xFFF9FFE8)
val md_theme_light_onSurface = Color(0xFF112000)
val md_theme_light_surfaceVariant = Color(0xFFE2E4D4)
val md_theme_light_onSurfaceVariant = Color(0xFF45483C)
val md_theme_light_outline = Color(0xFF76786B)
val md_theme_light_inverseOnSurface = Color(0xFFD4FF97)
val md_theme_light_inverseSurface = Color(0xFF203600)
val md_theme_light_inversePrimary = Color(0xFFB4D269)
val md_theme_light_surfaceTint = Color(0xFF4F6603)
val md_theme_light_outlineVariant = Color(0xFFC6C8B8)
val md_theme_light_scrim = Color(0xFF000000)
val md_theme_dark_primary = Color(0xFFB4D269)
val md_theme_dark_onPrimary = Color(0xFF273500)
val md_theme_dark_primaryContainer = Color(0xFF3A4D00)
val md_theme_dark_onPrimaryContainer = Color(0xFFD0EE82)
val md_theme_dark_secondary = Color(0xFFA1D57A)
val md_theme_dark_onSecondary = Color(0xFF173800)
val md_theme_dark_secondaryContainer = Color(0xFF255102)
val md_theme_dark_onSecondaryContainer = Color(0xFFBCF293)
val md_theme_dark_tertiary = Color(0xFFFFB866)
val md_theme_dark_onTertiary = Color(0xFF482900)
val md_theme_dark_tertiaryContainer = Color(0xFF673D00)
val md_theme_dark_onTertiaryContainer = Color(0xFFFFDDBA)
val md_theme_dark_error = Color(0xFFFFB4AB)
val md_theme_dark_errorContainer = Color(0xFF93000A)
val md_theme_dark_onError = Color(0xFF690005)
val md_theme_dark_onErrorContainer = Color(0xFFFFDAD6)
val md_theme_dark_background = Color(0xFF112000)
val md_theme_dark_onBackground = Color(0xFFC6F08A)
val md_theme_dark_surface = Color(0xFF112000)
val md_theme_dark_onSurface = Color(0xFFC6F08A)
val md_theme_dark_surfaceVariant = Color(0xFF45483C)
val md_theme_dark_onSurfaceVariant = Color(0xFFC6C8B8)
val md_theme_dark_outline = Color(0xFF909284)
val md_theme_dark_inverseOnSurface = Color(0xFF112000)
val md_theme_dark_inverseSurface = Color(0xFFC6F08A)
val md_theme_dark_inversePrimary = Color(0xFF4F6603)
val md_theme_dark_surfaceTint = Color(0xFFB4D269)
val md_theme_dark_outlineVariant = Color(0xFF45483C)
val md_theme_dark_scrim = Color(0xFF000000)
val seed = Color(0xFF92A957)
| mtg-bazaar/app/src/main/java/com/example/mtgbazaar/ui/theme/Color.kt | 1862090019 |
package com.example.mtgbazaar.ui.theme
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.ui.platform.LocalContext
private val LightColorScheme = lightColorScheme(
primary = md_theme_light_primary,
onPrimary = md_theme_light_onPrimary,
primaryContainer = md_theme_light_primaryContainer,
onPrimaryContainer = md_theme_light_onPrimaryContainer,
secondary = md_theme_light_secondary,
onSecondary = md_theme_light_onSecondary,
secondaryContainer = md_theme_light_secondaryContainer,
onSecondaryContainer = md_theme_light_onSecondaryContainer,
tertiary = md_theme_light_tertiary,
onTertiary = md_theme_light_onTertiary,
tertiaryContainer = md_theme_light_tertiaryContainer,
onTertiaryContainer = md_theme_light_onTertiaryContainer,
error = md_theme_light_error,
errorContainer = md_theme_light_errorContainer,
onError = md_theme_light_onError,
onErrorContainer = md_theme_light_onErrorContainer,
background = md_theme_light_background,
onBackground = md_theme_light_onBackground,
surface = md_theme_light_surface,
onSurface = md_theme_light_onSurface,
surfaceVariant = md_theme_light_surfaceVariant,
onSurfaceVariant = md_theme_light_onSurfaceVariant,
outline = md_theme_light_outline,
inverseOnSurface = md_theme_light_inverseOnSurface,
inverseSurface = md_theme_light_inverseSurface,
inversePrimary = md_theme_light_inversePrimary,
surfaceTint = md_theme_light_surfaceTint,
outlineVariant = md_theme_light_outlineVariant,
scrim = md_theme_light_scrim,
)
private val DarkColorScheme = darkColorScheme(
primary = md_theme_dark_primary,
onPrimary = md_theme_dark_onPrimary,
primaryContainer = md_theme_dark_primaryContainer,
onPrimaryContainer = md_theme_dark_onPrimaryContainer,
secondary = md_theme_dark_secondary,
onSecondary = md_theme_dark_onSecondary,
secondaryContainer = md_theme_dark_secondaryContainer,
onSecondaryContainer = md_theme_dark_onSecondaryContainer,
tertiary = md_theme_dark_tertiary,
onTertiary = md_theme_dark_onTertiary,
tertiaryContainer = md_theme_dark_tertiaryContainer,
onTertiaryContainer = md_theme_dark_onTertiaryContainer,
error = md_theme_dark_error,
errorContainer = md_theme_dark_errorContainer,
onError = md_theme_dark_onError,
onErrorContainer = md_theme_dark_onErrorContainer,
background = md_theme_dark_background,
onBackground = md_theme_dark_onBackground,
surface = md_theme_dark_surface,
onSurface = md_theme_dark_onSurface,
surfaceVariant = md_theme_dark_surfaceVariant,
onSurfaceVariant = md_theme_dark_onSurfaceVariant,
outline = md_theme_dark_outline,
inverseOnSurface = md_theme_dark_inverseOnSurface,
inverseSurface = md_theme_dark_inverseSurface,
inversePrimary = md_theme_dark_inversePrimary,
surfaceTint = md_theme_dark_surfaceTint,
outlineVariant = md_theme_dark_outlineVariant,
scrim = md_theme_dark_scrim,
)
@Composable
fun MTGBazaarTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
content: @Composable () -> Unit
) {
// val dynamicColor = Build.VERSION.SDK_INT >= Build.VERSION_CODES.S
val colorScheme = when {
// dynamicColor && darkTheme -> dynamicDarkColorScheme(LocalContext.current)
// dynamicColor && !darkTheme -> dynamicLightColorScheme(LocalContext.current)
darkTheme -> DarkColorScheme
else -> LightColorScheme
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
} | mtg-bazaar/app/src/main/java/com/example/mtgbazaar/ui/theme/Theme.kt | 981295573 |
package com.example.mtgbazaar.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
)
*/
) | mtg-bazaar/app/src/main/java/com/example/mtgbazaar/ui/theme/Type.kt | 3433556961 |
package com.example.mtgbazaar
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.appcompat.app.AppCompatActivity
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class MTGBazaarActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent { MTGBazaarApp() }
}
} | mtg-bazaar/app/src/main/java/com/example/mtgbazaar/MTGBazaarActivity.kt | 1081552416 |
package com.example.mtgbazaar
import android.content.res.Resources
import androidx.compose.material3.SnackbarHostState
import androidx.compose.runtime.Stable
import androidx.navigation.NavHostController
import com.example.mtgbazaar.common.snackbar.SnackbarManager
import com.example.mtgbazaar.common.snackbar.SnackbarMessage.Companion.toMessage
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.launch
@Stable
class MTGBazaarAppState(
val snackbarHostState: SnackbarHostState,
val navController: NavHostController,
private val snackbarManager: SnackbarManager,
private val resources: Resources,
coroutineScope: CoroutineScope
) {
init {
coroutineScope.launch {
snackbarManager.snackbarMessages.filterNotNull().collect { snackbarMessage ->
val text = snackbarMessage.toMessage(resources)
snackbarHostState.showSnackbar(text)
snackbarManager.clearSnackbarState()
}
}
}
fun popUp() {
navController.popBackStack()
}
fun navigate(route: String) {
navController.navigate(route) { launchSingleTop = true}
}
fun navigateAndPopUp(route: String, popUp: String) {
navController.navigate(route) {
launchSingleTop = true
popUpTo(popUp) { inclusive = true }
}
}
fun clearAndNavigate(route: String) {
navController.navigate(route) {
launchSingleTop = true
popUpTo(0) { inclusive = true }
}
}
}
| mtg-bazaar/app/src/main/java/com/example/mtgbazaar/MTGBazaarAppState.kt | 2820291666 |
package com.example.mtgbazaar
const val SPLASH_SCREEN = "SplashScreen"
const val SETTINGS_SCREEN = "SettingsScreen"
const val LOGIN_SCREEN = "LoginScreen"
const val SIGN_UP_SCREEN = "SignUpScreen"
const val TRADE_SCREEN = "TradeScreen"
const val COLLECTION_SCREEN = "CollectionScreen"
const val EDIT_BINDER_SCREEN = "EditBinderScreen"
const val BINDER_ID = "binderId"
const val BINDER_ID_ARG = "?$BINDER_ID={$BINDER_ID}"
| mtg-bazaar/app/src/main/java/com/example/mtgbazaar/MTGBazaarRoutes.kt | 674409933 |
package com.example.mtgbazaar.screens.settings
data class SettingsUiState(val isAnonymousAccount: Boolean = true)
| mtg-bazaar/app/src/main/java/com/example/mtgbazaar/screens/settings/SettingsUiState.kt | 1324969253 |
package com.example.mtgbazaar.screens.settings
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.hilt.navigation.compose.hiltViewModel
import com.example.mtgbazaar.common.composable.BasicToolbar
import com.example.mtgbazaar.common.composable.DangerousCardEditor
import com.example.mtgbazaar.common.composable.DialogCancelButton
import com.example.mtgbazaar.common.composable.DialogConfirmButton
import com.example.mtgbazaar.common.composable.RegularCardEditor
import com.example.mtgbazaar.common.ext.card
import com.example.mtgbazaar.common.ext.spacer
import com.example.mtgbazaar.ui.theme.MTGBazaarTheme
import com.example.mtgbazaar.R.string as AppText
import com.example.mtgbazaar.R.drawable as AppIcon
@Composable
fun SettingsScreen(
restartApp: (String) -> Unit,
openScreen: (String) -> Unit,
viewModel: SettingsViewModel = hiltViewModel()
) {
val uiState by viewModel.uiState.collectAsState(initial = SettingsUiState(false))
SettingsScreenContent(
uiState = uiState,
onLoginClick = { viewModel.onLoginClick(openScreen) },
onSignUpClick = { viewModel.onSignUpClick(openScreen) },
onSignOutClick = { viewModel.onSignOutClick(restartApp) },
onDeleteMyAccountClick = { viewModel.onDeleteMyAccountClick(restartApp) }
)
}
@Composable
fun SettingsScreenContent(
modifier: Modifier = Modifier,
uiState: SettingsUiState,
onLoginClick: () -> Unit,
onSignUpClick: () -> Unit,
onSignOutClick: () -> Unit,
onDeleteMyAccountClick: () -> Unit
) {
Column(
modifier
.fillMaxHeight()
.fillMaxWidth()
.verticalScroll(rememberScrollState()),
horizontalAlignment = Alignment.CenterHorizontally
) {
BasicToolbar(AppText.settings)
Spacer(modifier = Modifier.spacer())
if (uiState.isAnonymousAccount) {
RegularCardEditor(AppText.sign_in, AppIcon.ic_sign_in, "", Modifier.card()) {
onLoginClick()
}
RegularCardEditor(AppText.create_account, AppIcon.ic_create_account, "", Modifier.card()) {
onSignUpClick()
}
} else {
SignOutCard { onSignOutClick() }
DeleteMyAccountCard { onDeleteMyAccountClick() }
}
}
}
@Composable
private fun SignOutCard(signOut: () -> Unit) {
var showWarningDialog by remember { mutableStateOf(false) }
RegularCardEditor(AppText.sign_out, AppIcon.ic_exit, "", modifier = Modifier.card()) {
showWarningDialog = true
}
if (showWarningDialog) {
AlertDialog(
onDismissRequest = { showWarningDialog = false },
confirmButton = {
DialogConfirmButton(AppText.sign_out) {
signOut()
showWarningDialog = false
}
},
title = { Text(stringResource(AppText.sign_out_dialog_title)) },
text = { Text(stringResource(AppText.sign_out_dialog_description))},
dismissButton = { DialogCancelButton(AppText.cancel) { showWarningDialog = false } }
)
}
}
@Composable
private fun DeleteMyAccountCard(deleteMyAccount: () -> Unit) {
var showWarningDialog by remember { mutableStateOf(false) }
DangerousCardEditor(
AppText.delete_my_account,
AppIcon.ic_delete_my_account,
"",
Modifier.card()
) {
showWarningDialog = true
}
if (showWarningDialog) {
AlertDialog(
onDismissRequest = { showWarningDialog = false },
confirmButton = {
DialogConfirmButton(AppText.delete_my_account) {
deleteMyAccount()
showWarningDialog = false
}
},
title = { Text(stringResource(AppText.delete_account_dialog_title)) },
text = { Text(stringResource(AppText.delete_account_dialog_description)) },
dismissButton = { DialogCancelButton(AppText.cancel) { showWarningDialog = false }
}
)
}
}
@Preview(showBackground = true)
@Composable
fun SettingsScreenPreview() {
val uiState = SettingsUiState(isAnonymousAccount = false)
MTGBazaarTheme {
SettingsScreenContent(
uiState = uiState,
onLoginClick = { },
onSignUpClick = { },
onSignOutClick = { },
onDeleteMyAccountClick = { }
)
}
} | mtg-bazaar/app/src/main/java/com/example/mtgbazaar/screens/settings/SettingsScreen.kt | 2427110092 |
package com.example.mtgbazaar.screens.settings
import com.example.mtgbazaar.LOGIN_SCREEN
import com.example.mtgbazaar.SIGN_UP_SCREEN
import com.example.mtgbazaar.SPLASH_SCREEN
import com.example.mtgbazaar.model.service.AccountService
import com.example.mtgbazaar.model.service.LogService
import com.example.mtgbazaar.model.service.StorageService
import com.example.mtgbazaar.screens.MTGBazaarViewModel
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.map
import javax.inject.Inject
@HiltViewModel
class SettingsViewModel @Inject constructor(
logService: LogService,
private val accountService: AccountService,
private val storageService: StorageService
) : MTGBazaarViewModel(logService) {
val uiState = accountService.currentUser.map { SettingsUiState(it.isAnonymous) }
fun onLoginClick(openScreen: (String) -> Unit) = openScreen(LOGIN_SCREEN)
fun onSignUpClick(openScreen: (String) -> Unit) = openScreen(SIGN_UP_SCREEN)
fun onSignOutClick(restartApp: (String) -> Unit) {
launchCatching {
accountService.signOut()
restartApp(SPLASH_SCREEN)
}
}
fun onDeleteMyAccountClick(restartApp: (String) -> Unit) {
launchCatching {
accountService.deleteAccount()
restartApp(SPLASH_SCREEN)
}
}
}
| mtg-bazaar/app/src/main/java/com/example/mtgbazaar/screens/settings/SettingsViewModel.kt | 3069987316 |
package com.example.mtgbazaar.screens.splash
import androidx.compose.runtime.mutableStateOf
import com.example.mtgbazaar.COLLECTION_SCREEN
import com.example.mtgbazaar.SPLASH_SCREEN
import com.example.mtgbazaar.model.service.AccountService
import com.example.mtgbazaar.model.service.ConfigurationService
import com.example.mtgbazaar.model.service.LogService
import com.example.mtgbazaar.screens.MTGBazaarViewModel
import com.google.firebase.auth.FirebaseAuthException
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
@HiltViewModel
class SplashViewModel @Inject constructor(
configurationService: ConfigurationService,
private val accountService: AccountService,
logService: LogService
): MTGBazaarViewModel(logService) {
val showError = mutableStateOf(false)
init {
launchCatching { configurationService.fetchConfiguration() }
}
fun onAppStart(openAndPopUp: (String, String) -> Unit) {
showError.value = false
if(accountService.hasUser) openAndPopUp(COLLECTION_SCREEN, SPLASH_SCREEN)
else createAnonymousAccount(openAndPopUp)
}
private fun createAnonymousAccount(openAndPopUp: (String, String) -> Unit) {
launchCatching(snackbar = false) {
try {
accountService.createAnonymousAccount()
} catch (ex: FirebaseAuthException) {
showError.value = true
throw ex
}
openAndPopUp(COLLECTION_SCREEN, SPLASH_SCREEN)
}
}
} | mtg-bazaar/app/src/main/java/com/example/mtgbazaar/screens/splash/SplashViewModel.kt | 2833960450 |
package com.example.mtgbazaar.screens.splash
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
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.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.hilt.navigation.compose.hiltViewModel
import com.example.mtgbazaar.common.composable.BasicButton
import com.example.mtgbazaar.common.ext.basicButton
import com.example.mtgbazaar.R.string as AppText
import com.example.mtgbazaar.ui.theme.MTGBazaarTheme
import kotlinx.coroutines.delay
private const val SPLASH_TIMEOUT = 1000L
@Composable
fun SplashScreen(
openAndPopUp: (String, String) -> Unit,
viewModel: SplashViewModel = hiltViewModel()
) {
SplashScreenContent(
onAppStart = { viewModel.onAppStart(openAndPopUp) },
shouldShowError = viewModel.showError.value
)
}
@Composable
fun SplashScreenContent(
modifier: Modifier = Modifier,
onAppStart: () -> Unit,
shouldShowError: Boolean
) {
Column (
modifier =
modifier
.fillMaxWidth()
.fillMaxHeight()
.background(color = MaterialTheme.colorScheme.background)
.verticalScroll(rememberScrollState()),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
if (shouldShowError) {
Text(text = stringResource(AppText.generic_error))
BasicButton(AppText.try_again, Modifier.basicButton()) { onAppStart() }
} else {
CircularProgressIndicator(color = MaterialTheme.colorScheme.onBackground)
}
}
LaunchedEffect(true) {
delay(SPLASH_TIMEOUT)
onAppStart()
}
}
@Preview(showBackground = true)
@Composable
fun SplashScreenPreview() {
MTGBazaarTheme {
SplashScreenContent(
onAppStart = { },
shouldShowError = true
)
}
} | mtg-bazaar/app/src/main/java/com/example/mtgbazaar/screens/splash/SplashScreen.kt | 2131913806 |
package com.example.mtgbazaar.screens.collection
import androidx.compose.runtime.mutableStateOf
import com.example.mtgbazaar.BINDER_ID
import com.example.mtgbazaar.EDIT_BINDER_SCREEN
import com.example.mtgbazaar.SETTINGS_SCREEN
import com.example.mtgbazaar.model.Binder
import com.example.mtgbazaar.model.service.ConfigurationService
import com.example.mtgbazaar.model.service.LogService
import com.example.mtgbazaar.model.service.StorageService
import com.example.mtgbazaar.screens.MTGBazaarViewModel
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.emptyFlow
import javax.inject.Inject
@HiltViewModel
class CollectionViewModel @Inject constructor(
logService: LogService,
private val storageService: StorageService,
private val configurationService: ConfigurationService
) : MTGBazaarViewModel(logService){
val options = mutableStateOf<List<String>>(listOf())
val collection = emptyFlow<List<Binder>>()
fun loadBinderOptions() {
// TODO
}
fun onAddClick(openScreen: (String) -> Unit) = openScreen(EDIT_BINDER_SCREEN)
fun onSettingsClick(openScreen: (String) -> Unit) = openScreen(SETTINGS_SCREEN)
fun onBinderActionClick(openScreen: (String) -> Unit, binder: Binder, action: String) {
when (BinderActionOption.getByTitle(action)) {
BinderActionOption.EditBinder -> openScreen("$EDIT_BINDER_SCREEN?$BINDER_ID={${binder.id}}")
BinderActionOption.DeleteBinder -> onDeleteBinderClick(binder)
}
}
private fun onDeleteBinderClick(binder: Binder) {
launchCatching { storageService.deleteBinder(binder.id) }
}
} | mtg-bazaar/app/src/main/java/com/example/mtgbazaar/screens/collection/CollectionViewModel.kt | 287514928 |
package com.example.mtgbazaar.screens.collection
import androidx.compose.runtime.Composable
import com.example.mtgbazaar.model.Binder
@Composable
fun BinderItem (
binder: Binder,
options: List<String>,
onActionClick: (String) -> Unit
) {
} | mtg-bazaar/app/src/main/java/com/example/mtgbazaar/screens/collection/BinderItem.kt | 1345434789 |
package com.example.mtgbazaar.screens.collection
import android.annotation.SuppressLint
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import com.example.mtgbazaar.common.composable.ActionToolbar
import com.example.mtgbazaar.common.ext.smallSpacer
import com.example.mtgbazaar.common.ext.toolbarActions
import com.example.mtgbazaar.model.Binder
import com.example.mtgbazaar.ui.theme.MTGBazaarTheme
import com.example.mtgbazaar.R.string as AppText
import com.example.mtgbazaar.R.drawable as AppIcon
@Composable
fun CollectionScreen(
openScreen: (String) -> Unit,
viewModel: CollectionViewModel = hiltViewModel()
) {
CollectionScreenContent(
onAddClick = viewModel::onAddClick,
onSettingsClick = viewModel::onSettingsClick,
onBinderActionClick = viewModel::onBinderActionClick,
openScreen = openScreen
)
LaunchedEffect(viewModel) { viewModel.loadBinderOptions() }
}
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
@Composable
fun CollectionScreenContent(
modifier: Modifier = Modifier,
onAddClick: ((String) -> Unit) -> Unit,
onSettingsClick: ((String) -> Unit) -> Unit,
onBinderActionClick: ((String) -> Unit, Binder, String) -> Unit,
openScreen: (String) -> Unit
) {
Scaffold(
floatingActionButton = {
FloatingActionButton(
onClick = { onAddClick(openScreen) },
containerColor = MaterialTheme.colorScheme.secondary,
contentColor = MaterialTheme.colorScheme.onSecondary,
modifier = modifier.padding(16.dp)
) {
Icon(Icons.Filled.Add, "Add")
}
}
) {
Column(modifier = Modifier
.fillMaxWidth()
.fillMaxHeight()) {
ActionToolbar(
title = AppText.collection_title,
modifier = Modifier.toolbarActions(),
endActionIcon = AppIcon.ic_settings,
endAction = { onSettingsClick(openScreen) }
)
Spacer(modifier = Modifier.smallSpacer())
LazyColumn {
items(items = emptyList<Binder>(), key = { it.id }) { binderItem ->
BinderItem(
binder = binderItem,
options = listOf(),
onActionClick = { action -> onBinderActionClick(openScreen, binderItem, action) }
)
}
}
}
}
}
@Preview(showBackground = true)
@Composable
fun CollectionScreenPreview() {
MTGBazaarTheme {
CollectionScreenContent(
onAddClick = { },
onSettingsClick = { },
onBinderActionClick = { _, _, _ -> },
openScreen = { }
)
}
}
| mtg-bazaar/app/src/main/java/com/example/mtgbazaar/screens/collection/CollectionScreen.kt | 2394627613 |
package com.example.mtgbazaar.screens.collection
enum class BinderActionOption(val title: String) {
EditBinder("Edit Binder"),
DeleteBinder("Delete Binder");
companion object {
fun getByTitle(title: String): BinderActionOption {
entries.forEach { action -> if (title == action.title) return action }
return EditBinder
}
fun getOptions(hasEditOption: Boolean): List<String> {
val options = mutableListOf<String>()
entries.forEach { taskAction ->
if (hasEditOption || taskAction != EditBinder) {
options.add(taskAction.title)
}
}
return options
}
}
}
| mtg-bazaar/app/src/main/java/com/example/mtgbazaar/screens/collection/BinderActionOption.kt | 4109037779 |
package com.example.mtgbazaar.screens.edit_binder
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.SavedStateHandle
import com.example.mtgbazaar.BINDER_ID
import com.example.mtgbazaar.common.ext.idFromParameter
import com.example.mtgbazaar.model.Binder
import com.example.mtgbazaar.model.service.LogService
import com.example.mtgbazaar.model.service.StorageService
import com.example.mtgbazaar.screens.MTGBazaarViewModel
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
@HiltViewModel
class EditBinderViewModel @Inject constructor(
savedStateHandle: SavedStateHandle,
logService: LogService,
private val storageService: StorageService,
) : MTGBazaarViewModel(logService) {
val binder = mutableStateOf(Binder())
init {
val binderId = savedStateHandle.get<String>(BINDER_ID)
if (binderId != null) {
launchCatching {
binder.value = storageService.getBinder(binderId.idFromParameter()) ?: Binder()
}
}
}
fun onNameChange(newValue: String) {
binder.value = binder.value.copy(name = newValue)
}
fun onDescriptionChange(newValue: String) {
binder.value = binder.value.copy(description = newValue)
}
fun onTradeableToggle(newValue: String) {
val newFlagOption = EditTradeFlagOption.getBooleanValue(newValue)
binder.value = binder.value.copy(isTradeable = newFlagOption)
}
fun onDoneClick(popUpScreen: () -> Unit) {
launchCatching {
val editedBinder = binder.value
if (editedBinder.id.isBlank()) {
storageService.saveBinder(editedBinder)
} else {
storageService.updateBinder(editedBinder)
}
popUpScreen()
}
}
} | mtg-bazaar/app/src/main/java/com/example/mtgbazaar/screens/edit_binder/EditBinderViewModel.kt | 3346140334 |
package com.example.mtgbazaar.screens.edit_binder
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.hilt.navigation.compose.hiltViewModel
import com.example.mtgbazaar.common.composable.ActionToolbar
import com.example.mtgbazaar.common.composable.BasicField
import com.example.mtgbazaar.common.composable.CardSelector
import com.example.mtgbazaar.common.ext.card
import com.example.mtgbazaar.common.ext.fieldModifier
import com.example.mtgbazaar.common.ext.spacer
import com.example.mtgbazaar.common.ext.toolbarActions
import com.example.mtgbazaar.model.Binder
import com.example.mtgbazaar.ui.theme.MTGBazaarTheme
import com.example.mtgbazaar.R.string as AppText
import com.example.mtgbazaar.R.drawable as AppIcon
@Composable
fun EditBinderScreen(
popUpScreen: () -> Unit,
viewModel: EditBinderViewModel = hiltViewModel()
) {
val binder by viewModel.binder
EditBinderScreenContent(
binder = binder,
onDoneClick = { viewModel.onDoneClick(popUpScreen) },
onNameChange = viewModel::onNameChange,
onDescriptionChange = viewModel::onDescriptionChange,
onTradeableToggle = viewModel::onTradeableToggle
)
}
@Composable
fun EditBinderScreenContent(
modifier: Modifier = Modifier,
binder: Binder,
onDoneClick: () -> Unit,
onNameChange: (String) -> Unit,
onDescriptionChange: (String) -> Unit,
onTradeableToggle: (String) -> Unit
) {
Column(
modifier = modifier
.fillMaxWidth()
.fillMaxHeight()
.verticalScroll(rememberScrollState()),
horizontalAlignment = Alignment.CenterHorizontally
) {
ActionToolbar(
title = AppText.edit_binder,
endActionIcon = AppIcon.ic_check,
modifier = Modifier.toolbarActions(),
endAction = { onDoneClick() }
)
Spacer(modifier = Modifier.spacer())
val fieldModifier = Modifier.fieldModifier()
BasicField(AppText.name, binder.name, onNameChange, fieldModifier)
BasicField(AppText.description, binder.description, onDescriptionChange, fieldModifier)
Spacer(modifier = Modifier.spacer())
val flagSelection = EditTradeFlagOption.getByCheckedState(binder.isTradeable).name
CardSelector(
label = AppText.tradeable,
options = EditTradeFlagOption.getOptions(),
selection = flagSelection,
modifier = Modifier.card()) {
newValue -> onTradeableToggle(newValue)
}
}
}
@Preview(
showBackground = true
)
@Composable
fun EditBinderScreenPreview() {
val binder = Binder(
name = "Binder Name",
description = "Binder description",
isTradeable = true
)
MTGBazaarTheme {
EditBinderScreenContent(
binder = binder,
onDoneClick = { },
onNameChange = { },
onDescriptionChange = { },
onTradeableToggle = { }
)
}
} | mtg-bazaar/app/src/main/java/com/example/mtgbazaar/screens/edit_binder/EditBinderScreen.kt | 221061956 |
package com.example.mtgbazaar.screens.edit_binder
enum class EditTradeFlagOption {
Trade,
Keep;
companion object {
fun getByCheckedState(checkedState: Boolean?): EditTradeFlagOption {
val hasFlag = checkedState ?: false
return if (hasFlag) Trade else Keep
}
fun getBooleanValue(flagOption: String): Boolean {
return flagOption == Trade.name
}
fun getOptions(): List<String> {
val options = mutableListOf<String>()
entries.forEach { flagOption -> options.add(flagOption.name) }
return options
}
}
} | mtg-bazaar/app/src/main/java/com/example/mtgbazaar/screens/edit_binder/EditTradeFlagOption.kt | 2228979049 |
package com.example.mtgbazaar.screens
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.mtgbazaar.common.snackbar.SnackbarManager
import com.example.mtgbazaar.common.snackbar.SnackbarMessage.Companion.toSnackbarMessage
import com.example.mtgbazaar.model.service.LogService
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
open class MTGBazaarViewModel(private val logService: LogService) : ViewModel() {
fun launchCatching(snackbar: Boolean = true, block: suspend CoroutineScope.() -> Unit) =
viewModelScope.launch(
CoroutineExceptionHandler { _, throwable ->
if(snackbar) {
SnackbarManager.showMessage(throwable.toSnackbarMessage())
}
logService.logNonFatalCrash(throwable)
},
block = block
)
}
| mtg-bazaar/app/src/main/java/com/example/mtgbazaar/screens/MTGBazaarViewModel.kt | 386364831 |
package com.example.mtgbazaar.screens.sign_up
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.hilt.navigation.compose.hiltViewModel
import com.example.mtgbazaar.common.composable.BasicButton
import com.example.mtgbazaar.common.composable.BasicToolbar
import com.example.mtgbazaar.common.composable.EmailField
import com.example.mtgbazaar.common.composable.PasswordField
import com.example.mtgbazaar.common.composable.RepeatPasswordField
import com.example.mtgbazaar.common.ext.basicButton
import com.example.mtgbazaar.common.ext.fieldModifier
import com.example.mtgbazaar.ui.theme.MTGBazaarTheme
import com.example.mtgbazaar.R.string as AppText
@Composable
fun SignUpScreen(
openAndPopUp: (String, String) -> Unit,
viewModel: SignUpViewModel = hiltViewModel()
) {
val uiState by viewModel.uiState
SignUpScreenContent(
uiState = uiState,
onEmailChange = viewModel::onEmailChange,
onPasswordChange = viewModel::onPasswordChange,
onRepeatPasswordChange = viewModel::onRepeatPasswordChange,
onSignUpClick = { viewModel.onSignUpClick(openAndPopUp) }
)
}
@Composable
fun SignUpScreenContent(
modifier: Modifier = Modifier,
uiState: SignUpUiState,
onEmailChange: (String) -> Unit,
onPasswordChange: (String) -> Unit,
onRepeatPasswordChange: (String) -> Unit,
onSignUpClick: () -> Unit
) {
val fieldModifier = Modifier.fieldModifier()
BasicToolbar(AppText.create_account)
Column(
modifier = modifier
.fillMaxWidth()
.fillMaxHeight()
.verticalScroll(rememberScrollState()),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
EmailField(uiState.email, onEmailChange, fieldModifier)
PasswordField(uiState.password, onPasswordChange, fieldModifier)
RepeatPasswordField(uiState.repeatPassword, onRepeatPasswordChange, fieldModifier)
BasicButton(AppText.create_account, Modifier.basicButton()) {
onSignUpClick()
}
}
}
@Preview(showBackground = true)
@Composable
fun SignUpScreenPreview() {
val uiState = SignUpUiState(
email = "[email protected]"
)
MTGBazaarTheme {
SignUpScreenContent(
uiState = uiState,
onEmailChange = { },
onPasswordChange = { },
onRepeatPasswordChange = { },
onSignUpClick = { }
)
}
} | mtg-bazaar/app/src/main/java/com/example/mtgbazaar/screens/sign_up/SignUpScreen.kt | 4057715740 |
package com.example.mtgbazaar.screens.sign_up
import androidx.compose.runtime.mutableStateOf
import com.example.mtgbazaar.SETTINGS_SCREEN
import com.example.mtgbazaar.SIGN_UP_SCREEN
import com.example.mtgbazaar.common.ext.*
import com.example.mtgbazaar.common.snackbar.SnackbarManager
import com.example.mtgbazaar.model.service.AccountService
import com.example.mtgbazaar.model.service.LogService
import com.example.mtgbazaar.screens.MTGBazaarViewModel
import com.example.mtgbazaar.R.string as AppText
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
@HiltViewModel
class SignUpViewModel @Inject constructor(
private val accountService: AccountService,
logService: LogService
) : MTGBazaarViewModel(logService) {
var uiState = mutableStateOf(SignUpUiState())
private set
private val email
get() = uiState.value.email
private val password
get() = uiState.value.password
fun onEmailChange(newValue: String) {
uiState.value = uiState.value.copy(email = newValue)
}
fun onPasswordChange(newValue: String) {
uiState.value = uiState.value.copy(password = newValue)
}
fun onRepeatPasswordChange(newValue: String) {
uiState.value = uiState.value.copy(repeatPassword = newValue)
}
fun onSignUpClick(openAndPopUp: (String, String) -> Unit) {
if (!email.isValidEmail()) {
SnackbarManager.showMessage(AppText.email_error)
return
}
if (!password.isValidPassword()) {
SnackbarManager.showMessage(AppText.password_error)
return
}
if (!password.passwordMatches(uiState.value.repeatPassword)) {
SnackbarManager.showMessage(AppText.password_match_error)
return
}
launchCatching {
accountService.linkAccount(email, password)
openAndPopUp(SETTINGS_SCREEN, SIGN_UP_SCREEN)
}
}
} | mtg-bazaar/app/src/main/java/com/example/mtgbazaar/screens/sign_up/SignUpViewModel.kt | 4050944406 |
package com.example.mtgbazaar.screens.sign_up
data class SignUpUiState(
val email: String = "",
val password: String = "",
val repeatPassword: String = ""
)
| mtg-bazaar/app/src/main/java/com/example/mtgbazaar/screens/sign_up/SignUpUiState.kt | 4197793204 |
package com.example.mtgbazaar.screens.login
import androidx.compose.runtime.mutableStateOf
import com.example.mtgbazaar.LOGIN_SCREEN
import com.example.mtgbazaar.SETTINGS_SCREEN
import com.example.mtgbazaar.common.ext.isValidEmail
import com.example.mtgbazaar.R.string as AppText
import com.example.mtgbazaar.common.snackbar.SnackbarManager
import com.example.mtgbazaar.model.service.AccountService
import com.example.mtgbazaar.model.service.LogService
import com.example.mtgbazaar.screens.MTGBazaarViewModel
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
@HiltViewModel
class LoginViewModel @Inject constructor(
private val accountService: AccountService,
logService: LogService
) : MTGBazaarViewModel(logService) {
var uiState = mutableStateOf(LoginUiState())
private set
private val email
get() = uiState.value.email
private val password
get() = uiState.value.password
fun onEmailChange(newValue: String) {
uiState.value = uiState.value.copy(email = newValue)
}
fun onPasswordChange(newValue: String) {
uiState.value = uiState.value.copy(password = newValue)
}
fun onSignInClick(openAndPopUp: (String, String) -> Unit) {
if (!email.isValidEmail()) {
SnackbarManager.showMessage(AppText.email_error)
return
}
if (password.isBlank()) {
SnackbarManager.showMessage(AppText.empty_password_error)
return
}
launchCatching {
accountService.authenticate(email, password)
openAndPopUp(SETTINGS_SCREEN, LOGIN_SCREEN)
}
}
fun onForgotPasswordClick() {
if (!email.isValidEmail()) {
SnackbarManager.showMessage(AppText.email_error)
return
}
launchCatching {
accountService.sendRecoveryEmail(email)
SnackbarManager.showMessage(AppText.recovery_email_sent)
}
}
}
| mtg-bazaar/app/src/main/java/com/example/mtgbazaar/screens/login/LoginViewModel.kt | 3601053846 |
package com.example.mtgbazaar.screens.login
data class LoginUiState(
val email: String = "",
val password: String = ""
)
| mtg-bazaar/app/src/main/java/com/example/mtgbazaar/screens/login/LoginUiState.kt | 3111382325 |
package com.example.mtgbazaar.screens.login
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.hilt.navigation.compose.hiltViewModel
import com.example.mtgbazaar.common.composable.BasicButton
import com.example.mtgbazaar.common.composable.BasicTextButton
import com.example.mtgbazaar.R.string as AppText
import com.example.mtgbazaar.common.composable.BasicToolbar
import com.example.mtgbazaar.common.composable.EmailField
import com.example.mtgbazaar.common.composable.PasswordField
import com.example.mtgbazaar.common.ext.basicButton
import com.example.mtgbazaar.common.ext.fieldModifier
import com.example.mtgbazaar.common.ext.textButton
import com.example.mtgbazaar.ui.theme.MTGBazaarTheme
@Composable
fun LoginScreen(
openAndPopUp: (String, String) -> Unit,
viewModel: LoginViewModel = hiltViewModel()
) {
val uiState by viewModel.uiState
LoginScreenContent(
uiState = uiState,
onEmailChange = viewModel::onEmailChange,
onPasswordChange = viewModel::onPasswordChange,
onSignInClick = { viewModel.onSignInClick(openAndPopUp) },
onForgotPasswordClick = viewModel::onForgotPasswordClick
)
}
@Composable
fun LoginScreenContent(
modifier: Modifier = Modifier,
uiState: LoginUiState,
onEmailChange: (String) -> Unit,
onPasswordChange: (String) -> Unit,
onSignInClick: () -> Unit,
onForgotPasswordClick: () -> Unit
) {
BasicToolbar(AppText.login_details)
Column(
modifier = modifier
.fillMaxWidth()
.fillMaxHeight()
.verticalScroll(rememberScrollState()),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
EmailField(uiState.email, onEmailChange, Modifier.fieldModifier())
PasswordField(uiState.password, onPasswordChange, Modifier.fieldModifier())
BasicButton(AppText.sign_in, Modifier.basicButton()) { onSignInClick() }
BasicTextButton(AppText.forgot_password, Modifier.textButton()) { onForgotPasswordClick() }
}
}
@Preview(showBackground = true)
@Composable
fun LoginScreenPreview() {
val uiState = LoginUiState(email = "[email protected]")
MTGBazaarTheme {
LoginScreenContent(
uiState = uiState,
onEmailChange = { },
onPasswordChange = { },
onSignInClick = { },
onForgotPasswordClick = { }
)
}
}
| mtg-bazaar/app/src/main/java/com/example/mtgbazaar/screens/login/LoginScreen.kt | 3854332534 |
/*
Copyright 2022 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.example.mtgbazaar.common.snackbar
import android.content.res.Resources
import androidx.annotation.StringRes
import com.example.mtgbazaar.R.string as AppText
sealed class SnackbarMessage {
class StringSnackbar(val message: String) : SnackbarMessage()
class ResourceSnackbar(@StringRes val message: Int) : SnackbarMessage()
companion object {
fun SnackbarMessage.toMessage(resources: Resources): String {
return when (this) {
is StringSnackbar -> this.message
is ResourceSnackbar -> resources.getString(this.message)
}
}
fun Throwable.toSnackbarMessage(): SnackbarMessage {
val message = this.message.orEmpty()
return if (message.isNotBlank()) StringSnackbar(message)
else ResourceSnackbar(AppText.generic_error)
}
}
}
| mtg-bazaar/app/src/main/java/com/example/mtgbazaar/common/snackbar/SnackbarMessage.kt | 59089633 |
/*
Copyright 2022 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.example.mtgbazaar.common.snackbar
import androidx.annotation.StringRes
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
object SnackbarManager {
private val messages: MutableStateFlow<SnackbarMessage?> = MutableStateFlow(null)
val snackbarMessages: StateFlow<SnackbarMessage?>
get() = messages.asStateFlow()
fun showMessage(@StringRes message: Int) {
messages.value = SnackbarMessage.ResourceSnackbar(message)
}
fun showMessage(message: SnackbarMessage) {
messages.value = message
}
fun clearSnackbarState() {
messages.value = null
}
}
| mtg-bazaar/app/src/main/java/com/example/mtgbazaar/common/snackbar/SnackbarManager.kt | 2102405803 |
package com.example.mtgbazaar.common.ext
import android.util.Patterns
import java.util.regex.Pattern
private const val MIN_PASS_LENGTH = 6
private const val PASS_PATTERN = "^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=\\S+$).{4,}$"
fun String.isValidEmail(): Boolean {
return this.isNotBlank() && Patterns.EMAIL_ADDRESS.matcher(this).matches()
}
fun String.isValidPassword(): Boolean {
return this.isNotBlank() &&
this.length >= MIN_PASS_LENGTH &&
Pattern.compile(PASS_PATTERN).matcher(this).matches()
}
fun String.passwordMatches(repeated: String): Boolean {
return this == repeated
}
fun String.idFromParameter(): String {
return this.substring(1, this.length - 1)
} | mtg-bazaar/app/src/main/java/com/example/mtgbazaar/common/ext/StringExt.kt | 3154526119 |
package com.example.mtgbazaar.common.ext
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
fun Modifier.textButton(): Modifier {
return this.fillMaxWidth().padding(16.dp, 8.dp, 16.dp, 0.dp)
}
fun Modifier.basicButton(): Modifier {
return this.fillMaxWidth().padding(16.dp, 8.dp)
}
fun Modifier.dropdownSelector(): Modifier {
return this.fillMaxWidth()
}
fun Modifier.fieldModifier(): Modifier {
return this.fillMaxWidth().padding(16.dp, 4.dp)
}
fun Modifier.spacer(): Modifier {
return this.fillMaxWidth().padding(12.dp)
}
fun Modifier.smallSpacer(): Modifier {
return this.fillMaxWidth().height(8.dp)
}
fun Modifier.card(): Modifier {
return this.padding(16.dp, 0.dp, 16.dp, 8.dp)
}
fun Modifier.toolbarActions(): Modifier {
return this.wrapContentSize(Alignment.TopEnd)
} | mtg-bazaar/app/src/main/java/com/example/mtgbazaar/common/ext/ModifierExt.kt | 2605533005 |
package com.example.mtgbazaar.common.composable
import androidx.annotation.StringRes
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ExposedDropdownMenuBox
import androidx.compose.material3.ExposedDropdownMenuDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.material3.TextFieldColors
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.stringResource
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun DropdownSelector(
@StringRes label: Int,
options: List<String>,
selection: String,
modifier: Modifier,
onNewValue: (String) -> Unit
) {
var isExpanded by remember { mutableStateOf(false) }
ExposedDropdownMenuBox(
expanded = isExpanded,
modifier = modifier,
onExpandedChange = { isExpanded = !isExpanded }
) {
TextField(
modifier = modifier.fillMaxWidth(),
readOnly = true,
value = selection,
onValueChange = {},
label = { Text(stringResource(label)) },
trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(isExpanded) },
colors = dropdownColors()
)
ExposedDropdownMenu(expanded = isExpanded, onDismissRequest = { isExpanded = false }) {
options.forEach{selectionOption ->
DropdownMenuItem(
text = { Text(selectionOption) },
onClick = {
onNewValue(selectionOption)
isExpanded = false
}
)
}
}
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun dropdownColors(): TextFieldColors {
return ExposedDropdownMenuDefaults.textFieldColors(
focusedContainerColor = MaterialTheme.colorScheme.secondaryContainer,
unfocusedContainerColor = MaterialTheme.colorScheme.background,
focusedIndicatorColor = Color.Transparent,
unfocusedIndicatorColor = Color.Transparent,
focusedTrailingIconColor = MaterialTheme.colorScheme.onSecondaryContainer,
unfocusedTrailingIconColor = MaterialTheme.colorScheme.onSurface,
focusedLabelColor = MaterialTheme.colorScheme.onSecondaryContainer,
unfocusedLabelColor = MaterialTheme.colorScheme.onSurface
)
}
| mtg-bazaar/app/src/main/java/com/example/mtgbazaar/common/composable/DropdownComposable.kt | 4028249166 |
package com.example.mtgbazaar.common.composable
import androidx.annotation.DrawableRes
import androidx.annotation.StringRes
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import com.example.mtgbazaar.common.ext.dropdownSelector
@Composable
fun RegularCardEditor(
@StringRes title: Int,
@DrawableRes icon: Int,
content: String,
modifier: Modifier,
onEditClick: () -> Unit
) {
CardEditor(title, icon, content, MaterialTheme.colorScheme.onSurface, modifier, onEditClick)
}
@Composable
fun DangerousCardEditor(
@StringRes title: Int,
@DrawableRes icon: Int,
content: String,
modifier: Modifier,
onEditClick: () -> Unit
) {
CardEditor(title, icon, content, MaterialTheme.colorScheme.primary, modifier, onEditClick)
}
@Composable
private fun CardEditor(
@StringRes title: Int,
@DrawableRes icon: Int,
content: String,
highlightColor: Color,
modifier: Modifier,
onEditClick: () -> Unit
) {
Card(
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.secondaryContainer),
modifier = modifier,
onClick = onEditClick
) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
) {
Column(modifier = Modifier.weight(1f)) {
Text(stringResource(title), color = highlightColor)
}
if (content.isNotBlank()) {
Text(text = content, modifier = Modifier.padding(16.dp, 0.dp))
}
Icon(painter = painterResource(icon), contentDescription = "Icon", tint = highlightColor)
}
}
}
@Composable
fun CardSelector(
@StringRes label: Int,
options: List<String>,
selection: String,
modifier: Modifier,
onNewValue: (String) -> Unit
) {
Card(
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.secondaryContainer),
modifier = modifier
) {
DropdownSelector(label, options, selection, Modifier.dropdownSelector() , onNewValue)
}
} | mtg-bazaar/app/src/main/java/com/example/mtgbazaar/common/composable/CardComposable.kt | 594900014 |
package com.example.mtgbazaar.common.composable
import androidx.annotation.DrawableRes
import androidx.annotation.StringRes
import androidx.compose.foundation.layout.Box
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun BasicToolbar(@StringRes title: Int) {
TopAppBar(title = { Text(stringResource(title)) })
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ActionToolbar(
@StringRes title: Int,
@DrawableRes endActionIcon: Int,
modifier: Modifier,
endAction: () -> Unit
) {
TopAppBar(
title = { Text(stringResource(title)) },
colors = TopAppBarDefaults.topAppBarColors(containerColor = MaterialTheme.colorScheme.primaryContainer),
actions = {
Box(modifier) {
IconButton(onClick = endAction) {
Icon(painter = painterResource(endActionIcon), contentDescription = "Action")
}
}
}
)
}
| mtg-bazaar/app/src/main/java/com/example/mtgbazaar/common/composable/ToolbarComposable.kt | 1950912070 |
package com.example.mtgbazaar.common.composable
import androidx.annotation.StringRes
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Email
import androidx.compose.material.icons.filled.Lock
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.VisualTransformation
import com.example.mtgbazaar.R.string as AppText
import com.example.mtgbazaar.R.drawable as AppIcon
@Composable
fun BasicField(
@StringRes text: Int,
value: String,
onNewValue: (String) -> Unit,
modifier: Modifier = Modifier
) {
OutlinedTextField(
singleLine = true,
modifier = modifier,
value = value,
onValueChange = { onNewValue(it) },
placeholder = { Text(stringResource(text)) }
)
}
@Composable
fun EmailField(value: String, onNewValue: (String) -> Unit, modifier: Modifier = Modifier) {
OutlinedTextField(
value = value,
onValueChange = { onNewValue(it) },
singleLine = true,
modifier = modifier,
placeholder = { Text(stringResource(AppText.email)) },
leadingIcon = { Icon(imageVector = Icons.Default.Email, contentDescription = "Email") }
)
}
@Composable
fun PasswordField(value: String, onNewValue: (String) -> Unit, modifier: Modifier = Modifier) {
PasswordField(value, AppText.password, onNewValue, modifier)
}
@Composable
fun RepeatPasswordField(
value: String,
onNewValue: (String) -> Unit,
modifier: Modifier = Modifier
) {
PasswordField(value, AppText.repeat_password, onNewValue, modifier)
}
@Composable
private fun PasswordField(
value: String,
@StringRes placeholder: Int,
onNewValue: (String) -> Unit,
modifier: Modifier = Modifier
) {
var isVisible by remember { mutableStateOf(false) }
val icon =
if (isVisible) painterResource(AppIcon.ic_visibility_on)
else painterResource(AppIcon.ic_visibility_off)
val visualTransformation =
if (isVisible) VisualTransformation.None else PasswordVisualTransformation()
OutlinedTextField(
value = value,
onValueChange = { onNewValue(it) },
modifier = modifier,
placeholder = { Text(text = stringResource(placeholder)) },
leadingIcon = { Icon(imageVector = Icons.Default.Lock, contentDescription = "Lock") },
trailingIcon = {
IconButton(onClick = { isVisible = !isVisible }) {
Icon(painter = icon, contentDescription = "Visibility")
}
},
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),
visualTransformation = visualTransformation
)
} | mtg-bazaar/app/src/main/java/com/example/mtgbazaar/common/composable/TextFieldComposable.kt | 1930307110 |
package com.example.mtgbazaar.common.composable
import androidx.annotation.StringRes
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.sp
@Composable
fun BasicTextButton(@StringRes text: Int, modifier: Modifier, action: () -> Unit) {
TextButton(onClick = action, modifier = modifier) { Text(text = stringResource(text)) }
}
@Composable
fun BasicButton(@StringRes text: Int, modifier: Modifier, action: () -> Unit) {
Button(
onClick = action,
modifier = modifier,
colors =
ButtonDefaults.buttonColors(
containerColor = MaterialTheme.colorScheme.primary,
contentColor = MaterialTheme.colorScheme.onPrimary
)
) {
Text(text = stringResource(text), fontSize = 16.sp)
}
}
@Composable
fun DialogConfirmButton(@StringRes text: Int, action: () -> Unit) {
Button(
onClick = action,
colors =
ButtonDefaults.buttonColors(
containerColor = MaterialTheme.colorScheme.primary,
contentColor = MaterialTheme.colorScheme.onPrimary
)
) {
Text(text = stringResource(text))
}
}
@Composable
fun DialogCancelButton(@StringRes text: Int, action: () -> Unit) {
Button(
onClick = action,
colors =
ButtonDefaults.buttonColors(
containerColor = MaterialTheme.colorScheme.onPrimary,
contentColor = MaterialTheme.colorScheme.primary
)
) {
Text(text = stringResource(text))
}
} | mtg-bazaar/app/src/main/java/com/example/mtgbazaar/common/composable/ButtonComposable.kt | 4039519823 |
package com.example.mtgbazaar.model
import com.google.firebase.firestore.DocumentId
data class Binder(
@DocumentId val id: String = "",
val name: String = "",
val description: String = "",
val isTradeable: Boolean = false,
val userId: String = ""
)
| mtg-bazaar/app/src/main/java/com/example/mtgbazaar/model/Binder.kt | 4275500836 |
package com.example.mtgbazaar.model
data class User(
val id: String = "",
val isAnonymous: Boolean = true
) | mtg-bazaar/app/src/main/java/com/example/mtgbazaar/model/User.kt | 1325550219 |
package com.example.mtgbazaar.model.service
import com.example.mtgbazaar.model.User
import kotlinx.coroutines.flow.Flow
interface AccountService {
val currentUserId: String
val hasUser: Boolean
val currentUser: Flow<User>
suspend fun authenticate(email: String, password: String)
suspend fun sendRecoveryEmail(email: String)
suspend fun createAnonymousAccount()
suspend fun linkAccount(email: String, password: String)
suspend fun deleteAccount()
suspend fun signOut()
} | mtg-bazaar/app/src/main/java/com/example/mtgbazaar/model/service/AccountService.kt | 957692830 |
package com.example.mtgbazaar.model.service.impl
import com.example.mtgbazaar.BuildConfig
import com.example.mtgbazaar.R.xml as AppConfig
import com.example.mtgbazaar.model.service.ConfigurationService
import com.google.firebase.Firebase
import com.google.firebase.remoteconfig.remoteConfig
import com.google.firebase.remoteconfig.remoteConfigSettings
import javax.inject.Inject
class ConfigurationServiceImpl @Inject constructor() : ConfigurationService {
private val remoteConfig
get() = Firebase.remoteConfig
init {
if(BuildConfig.DEBUG) {
val configSettings = remoteConfigSettings { minimumFetchIntervalInSeconds = 0 }
remoteConfig.setConfigSettingsAsync(configSettings)
}
remoteConfig.setDefaultsAsync(AppConfig.remote_config_defaults)
}
override suspend fun fetchConfiguration(): Boolean = true
override val isShowTaskEditButtonConfig: Boolean
get() = true
companion object {
private const val SHOW_BINDER_EDIT_BUTTON_KEY = "show_binder_edit_button"
private const val FETCH_CONFIG_TRACE = "fetchConfig"
}
} | mtg-bazaar/app/src/main/java/com/example/mtgbazaar/model/service/impl/ConfigurationServiceImpl.kt | 1766936142 |
package com.example.mtgbazaar.model.service.impl
import com.example.mtgbazaar.model.service.LogService
import com.google.firebase.crashlytics.crashlytics
import com.google.firebase.Firebase
import javax.inject.Inject
class LogServiceImpl @Inject constructor() : LogService {
override fun logNonFatalCrash(throwable: Throwable) {
Firebase.crashlytics.recordException(throwable)
}
} | mtg-bazaar/app/src/main/java/com/example/mtgbazaar/model/service/impl/LogServiceImpl.kt | 3514251115 |
package com.example.mtgbazaar.model.service.impl
import com.example.mtgbazaar.model.Binder
import com.example.mtgbazaar.model.service.AccountService
import com.example.mtgbazaar.model.service.StorageService
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.firestore.toObject
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.emptyFlow
import kotlinx.coroutines.tasks.await
import javax.inject.Inject
class StorageServiceImpl @Inject constructor(
private val firestore: FirebaseFirestore,
private val auth: AccountService
) : StorageService {
override val binders: Flow<List<Binder>>
get() = emptyFlow()
override suspend fun getBinder(binderId: String): Binder? =
firestore.collection(BINDER_COLLECTION).document(binderId).get().await().toObject()
override suspend fun saveBinder(binder: Binder): String =
trace(SAVE_BINDER_TRACE) {
val binderWithUserId = binder.copy(userId = auth.currentUserId)
firestore.collection(BINDER_COLLECTION).add(binderWithUserId).await().id
}
override suspend fun updateBinder(binder: Binder): Unit =
trace(UPDATE_BINDER_TRACE) {
firestore.collection(BINDER_COLLECTION).document(binder.id).set(binder).await()
}
override suspend fun deleteBinder(binderId: String) {
firestore.collection(BINDER_COLLECTION).document(binderId).delete().await()
}
companion object {
private const val USER_ID_FIELD = "userId"
private const val BINDER_COLLECTION = "binders"
private const val SAVE_BINDER_TRACE = "saveBinder"
private const val UPDATE_BINDER_TRACE = "updateBinder"
}
} | mtg-bazaar/app/src/main/java/com/example/mtgbazaar/model/service/impl/StorageServiceImpl.kt | 2447661418 |
package com.example.mtgbazaar.model.service.impl
import com.example.mtgbazaar.model.User
import com.example.mtgbazaar.model.service.AccountService
import com.google.firebase.auth.EmailAuthProvider
import com.google.firebase.auth.FirebaseAuth
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.tasks.await
import javax.inject.Inject
class AccountServiceImpl @Inject constructor(private val auth: FirebaseAuth) : AccountService {
override val currentUserId: String
get() = auth.currentUser?.uid.orEmpty()
override val hasUser: Boolean
get() = auth.currentUser != null
override val currentUser: Flow<User>
get() = callbackFlow {
val listener =
FirebaseAuth.AuthStateListener { auth ->
this.trySend(auth.currentUser?.let { User(it.uid, it.isAnonymous) } ?: User())
}
auth.addAuthStateListener(listener)
awaitClose { auth.removeAuthStateListener(listener) }
}
override suspend fun authenticate(email: String, password: String) {
auth.signInWithEmailAndPassword(email, password).await()
}
override suspend fun sendRecoveryEmail(email: String) {
auth.sendPasswordResetEmail(email).await()
}
override suspend fun createAnonymousAccount() {
auth.signInAnonymously().await()
}
override suspend fun linkAccount(email: String, password: String): Unit =
trace(LINK_ACCOUNT_TRACE) {
val credential = EmailAuthProvider.getCredential(email, password)
auth.currentUser!!.linkWithCredential(credential).await()
}
override suspend fun deleteAccount() {
auth.currentUser!!.delete().await()
}
override suspend fun signOut() {
if (auth.currentUser!!.isAnonymous) {
auth.currentUser!!.delete()
}
auth.signOut()
createAnonymousAccount()
}
companion object {
private const val LINK_ACCOUNT_TRACE = "linkAccount"
}
} | mtg-bazaar/app/src/main/java/com/example/mtgbazaar/model/service/impl/AccountServiceImpl.kt | 3270020213 |
package com.example.mtgbazaar.model.service.impl
import com.google.firebase.perf.metrics.Trace
import com.google.firebase.perf.trace
inline fun <T> trace(name: String, block: Trace.() -> T): T = Trace.create(name).trace(block) | mtg-bazaar/app/src/main/java/com/example/mtgbazaar/model/service/impl/Performance.kt | 911519011 |
package com.example.mtgbazaar.model.service
import com.example.mtgbazaar.model.Binder
import kotlinx.coroutines.flow.Flow
interface StorageService {
val binders: Flow<List<Binder>>
suspend fun getBinder(binderId: String): Binder?
suspend fun saveBinder(binder: Binder): String
suspend fun updateBinder(binder: Binder)
suspend fun deleteBinder(binderId: String)
} | mtg-bazaar/app/src/main/java/com/example/mtgbazaar/model/service/StorageService.kt | 1841294924 |
package com.example.mtgbazaar.model.service
interface LogService {
fun logNonFatalCrash(throwable: Throwable)
} | mtg-bazaar/app/src/main/java/com/example/mtgbazaar/model/service/LogService.kt | 2738814708 |
package com.example.mtgbazaar.model.service.module
import com.google.firebase.Firebase
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.auth
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.firestore.firestore
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
@Module
@InstallIn(SingletonComponent::class)
object FirebaseModule {
@Provides fun auth(): FirebaseAuth = Firebase.auth
@Provides fun firestore(): FirebaseFirestore = Firebase.firestore
} | mtg-bazaar/app/src/main/java/com/example/mtgbazaar/model/service/module/FirebaseModule.kt | 3183759420 |
package com.example.mtgbazaar.model.service.module
import com.example.mtgbazaar.model.service.AccountService
import com.example.mtgbazaar.model.service.ConfigurationService
import com.example.mtgbazaar.model.service.LogService
import com.example.mtgbazaar.model.service.StorageService
import com.example.mtgbazaar.model.service.impl.AccountServiceImpl
import com.example.mtgbazaar.model.service.impl.ConfigurationServiceImpl
import com.example.mtgbazaar.model.service.impl.LogServiceImpl
import com.example.mtgbazaar.model.service.impl.StorageServiceImpl
import dagger.Binds
import dagger.Module
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
@Module
@InstallIn(SingletonComponent::class)
abstract class ServiceModule {
@Binds abstract fun provideAccountService(impl: AccountServiceImpl): AccountService
@Binds abstract fun provideLogService(impl: LogServiceImpl): LogService
@Binds abstract fun provideStorageService(impl: StorageServiceImpl): StorageService
@Binds
abstract fun provideConfigurationService(impl: ConfigurationServiceImpl): ConfigurationService
} | mtg-bazaar/app/src/main/java/com/example/mtgbazaar/model/service/module/ServiceModule.kt | 1557140216 |
package com.example.mtgbazaar.model.service
interface ConfigurationService {
suspend fun fetchConfiguration(): Boolean
val isShowTaskEditButtonConfig: Boolean
} | mtg-bazaar/app/src/main/java/com/example/mtgbazaar/model/service/ConfigurationService.kt | 1360977998 |
package com.example.mtgbazaar.model
import com.google.firebase.firestore.DocumentId
data class MagicCard (
@DocumentId val id: String = "",
val name: String = "",
val binderId: String = ""
)
| mtg-bazaar/app/src/main/java/com/example/mtgbazaar/model/MagicCard.kt | 1681969201 |
package com.example.mtgbazaar
import android.app.Application
import dagger.hilt.android.HiltAndroidApp
@HiltAndroidApp
class MTGBazaarHiltApp : Application() {
} | mtg-bazaar/app/src/main/java/com/example/mtgbazaar/MTGBazaarHiltApp.kt | 3196841947 |
package com.mhellwig.technisatcontrol
import kotlinx.coroutines.runBlocking
fun main() {
val technisatControl = TechnisatControl("192.168.0.10")
runBlocking {
technisatControl.sendControlEnums(listOf(ControlEnum.BTN_1, ControlEnum.BTN_1))
}
} | TechnisatControl/src/main/kotlin/com/mhellwig/technisatcontrol/ExampleMain.kt | 1648947394 |
/**
* Copyright (c) 2023, Martin Hellwig
*/
package com.mhellwig.technisatcontrol
import io.ktor.network.selector.SelectorManager
import io.ktor.network.sockets.Datagram
import io.ktor.network.sockets.InetSocketAddress
import io.ktor.network.sockets.aSocket
import io.ktor.utils.io.core.ByteReadPacket
import kotlinx.coroutines.Dispatchers
class TechnisatControl(private val ipAddress: String) {
suspend fun sendControlEnums(controlEnums: List<ControlEnum>) {
val selectorManager = SelectorManager(Dispatchers.IO)
val socket = aSocket(selectorManager)
.udp()
.bind(InetSocketAddress("0.0.0.0", 8090))
val receiverAddress = InetSocketAddress(ipAddress, 8090)
socket.use { autoCloseSocket ->
controlEnums.forEach {
var sendData = ("<rcuButtonRequest code=\"${it.technicalValue}\" state=\"pressed\" />").toByteArray()
var sendPacket = Datagram(ByteReadPacket(sendData), receiverAddress)
autoCloseSocket.send(sendPacket)
sendData = "<rcuButtonRequest code=\"${it.technicalValue}\" state=\"released\" />".toByteArray()
sendPacket = Datagram(ByteReadPacket(sendData), receiverAddress)
autoCloseSocket.send(sendPacket)
}
}
}
suspend fun sendControlEnum(controlEnum: ControlEnum) {
sendControlEnums(listOf(controlEnum))
}
} | TechnisatControl/src/main/kotlin/com/mhellwig/technisatcontrol/TechnisatControl.kt | 571537764 |
/**
* Copyright (c) 2023, Martin Hellwig
*/
package com.mhellwig.technisatcontrol
enum class ControlEnum(val technicalValue: Int) {
BTN_0(0),
BTN_1(1),
BTN_2(2),
BTN_3(3),
BTN_4(4),
BTN_5(5),
BTN_6(6),
BTN_7(7),
BTN_8(8),
BTN_9(9),
BTN_SWITCHDEC(10),
BTN_STANDBY(11),
BTN_MUTE(12),
BTN_NOTUSED13(13),
BTN_LIST(14),
BTN_VOL_UP(15),
BTN_VOL_DOWN(16),
BTN_HELP(17),
BTN_PROG_UP(18),
BTN_PROG_DOWN(19),
BTN_BACK(20),
BTN_AUDIO(21),
BTN_STILL(22),
BTN_EPG(23),
BTN_EXT(24),
BTN_TXT(25),
BTN_OFF(26),
BTN_TOGGLEIRC(27),
BTN_TVSAT(28),
BTN_INFO(29),
BTN_UP(30),
BTN_DOWN(31),
BTN_MENU(32),
BTN_TVRADIO(33),
BTN_LEFT(34),
BTN_RIGHT(35),
BTN_OK(36),
BTN_RED(37),
BTN_GREEN(38),
BTN_YELLOW(39),
BTN_BLUE(40),
BTN_OPTION(41),
BTN_SLEEP(42),
BTN_REC(43),
BTN_PIP(44),
BTN_ZOOM(45),
BTN_GENRE(46),
BTN_HDMI(47),
BTN_MORE(48),
BTN_REWIND(49),
BTN_STOP(50),
BTN_PLAYPAUSE(51),
BTN_WIND(52),
BTN_CODESAT1(53),
BTN_CODESAT2(54),
BTN_CODETV1(55),
BTN_CODETV2(56),
BTN_CODEVCR1(57),
BTN_CODEVCR2(58),
BTN_FREESATBACK(59),
BTN_AD(60),
BTN_SUBTITLE(61),
BTN_NAV(62),
BTN_PAGEUP(63),
BTN_PAGEDOWN(64),
BTN_PVR(65),
BTN_WWW(66),
BTN_TIMER(67),
BTN_NOTUSED68(68),
BTN_NOTUSED69(69),
BTN_NOTUSED70(70),
BTN_NOTUSED71(71),
BTN_NOTUSED72(72),
BTN_NOTUSED73(73),
BTN_NOTUSED74(74),
BTN_NOTUSED75(75),
BTN_NOTUSED76(76),
BTN_NOTUSED77(77),
BTN_NOTUSED78(78),
BTN_NOTUSED79(79),
BTN_NOTUSED80(80),
BTN_NOTUSED81(81),
BTN_NOTUSED82(82),
BTN_NOTUSED83(83),
BTN_NOTUSED84(84),
BTN_NOTUSED85(85),
BTN_NOTUSED86(86),
BTN_NOTUSED87(87),
BTN_NOTUSED88(88),
BTN_NOTUSED89(89),
BTN_NOTUSED90(90),
BTN_NOTUSED91(91),
BTN_NOTUSED92(92),
BTN_NOTUSED93(93),
BTN_NOTUSED94(94),
BTN_NOTUSED95(95),
BTN_NOTUSED96(96),
BTN_NOTUSED97(97),
BTN_NOTUSED98(98),
BTN_NOTUSED99(99),
BTN_NOTUSED100(100),
BTN_NOTUSED101(101),
BTN_NOTUSED102(102),
BTN_NOTUSED103(103),
BTN_NOTUSED104(104),
BTN_NOTUSED105(105),
BTN_KBDF1(106),
BTN_KBDF2(107),
BTN_KBDF3(108),
BTN_KBDF4(109),
BTN_KBDF5(110),
BTN_KBDF6(111),
BTN_KBDF7(112),
BTN_KBDF8(113),
BTN_KBDF9(114),
BTN_KBDF10(115),
BTN_KBDF11(116),
BTN_KBDF12(117),
BTN_SOFTKEY1(118),
BTN_SOFTKEY2(119),
BTN_SOFTKEY3(120),
BTN_SOFTKEY4(121),
BTN_KBDINFO(122),
BTN_KBDDOWN(123),
BTN_KBDUP(124),
BTN_KBDMODE(125),
BTN_DOFLASH(126),
BTN_NOTDEFINED(127),
BTN_INVALID(128)
} | TechnisatControl/src/main/kotlin/com/mhellwig/technisatcontrol/ControlEnum.kt | 180224130 |
interface DashboardFragment {
} | SPYM/app/DashboardFragment.kt | 4168772697 |
interface Dash {
} | SPYM/app/Dash.kt | 3527040541 |
package com.xcd.navbot.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) | SPYM/app/src/main/java/com/xcd/navbot/ui/theme/Color.kt | 3021851032 |
package com.xcd.navbot.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 NavbotTheme(
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
)
} | SPYM/app/src/main/java/com/xcd/navbot/ui/theme/Theme.kt | 2101065662 |
package com.xcd.navbot.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
)
*/
) | SPYM/app/src/main/java/com/xcd/navbot/ui/theme/Type.kt | 3678404950 |
package com.xcd.navbot
import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.AutoCompleteTextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.fragment.app.Fragment
import androidx.viewpager2.widget.ViewPager2
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.google.android.material.tabs.TabLayout
import com.xcd.navbot.databinding.ActivityMainBinding
import com.xcd.navbot.ui.theme.NavbotTheme
class MainActivity : AppCompatActivity() {
private lateinit var bottomNavigationView: BottomNavigationView
private lateinit var tabLayout: TabLayout
private lateinit var viewPager2: ViewPager2
private lateinit var adapter: FragmentPageAdapter
@SuppressLint("MissingInflatedId")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
bottomNavigationView = findViewById(R.id.bottom_navigation)
bottomNavigationView.setOnItemSelectedListener { menuItem ->
when(menuItem.itemId){
R.id.bottom_home -> {
replaceFragment(HomeFragment())
true
}
R.id.bottom_add -> {
replaceFragment(AddFragment())
true
}
else -> false
}
}
/**replaceFragment(HomeFragment())**/
tabLayout = findViewById(R.id.tabLayout)
viewPager2 = findViewById(R.id.viewPager2)
adapter = FragmentPageAdapter(supportFragmentManager, lifecycle)
tabLayout.addTab(tabLayout.newTab().setText("Demographics"))
tabLayout.addTab(tabLayout.newTab().setText("SocialConnect"))
viewPager2.adapter = adapter
tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener{
override fun onTabSelected(tab: TabLayout.Tab?) {
if (tab != null) {
viewPager2.currentItem = tab.position
}
}
override fun onTabUnselected(tab: TabLayout.Tab?) {
}
override fun onTabReselected(tab: TabLayout.Tab?) {
}
})
viewPager2.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback(){
override fun onPageSelected(position: Int) {
super.onPageSelected(position)
tabLayout.selectTab(tabLayout.getTabAt(position))
}
})
/**
val items = listOf("Cannabis", "Stimulants", "Hallucinogens", "Inhalants", "Not Classified")
val autoComplete : AutoCompleteTextView = findViewById(R.id.auto_complete)
ArrayAdapter(this, R.layout.item_list, items)
autoComplete.setAdapter(adapter)
autoComplete.onItemClickListener = AdapterView.OnItemClickListener {
adapterView, view, i, l ->
val itemSelected = adapterView.getItemAtPosition(i)
Toast.makeText(this, "Selected : $itemSelected", Toast.LENGTH_SHORT).show()
}
**/
}
@SuppressLint("CommitTransaction")
private fun replaceFragment(fragment: Fragment){
supportFragmentManager.beginTransaction().replace(R.id.frame_container, fragment).commit()
}
}
private fun AutoCompleteTextView.setAdapter(adapter: FragmentPageAdapter) {
TODO("Not yet implemented")
}
| SPYM/app/src/main/java/com/xcd/navbot/MainActivity.kt | 3923099867 |
package com.xcd.navbot
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
class DashboardFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_dashboard, container, false)
}
} | SPYM/app/src/main/java/com/xcd/navbot/DashboardFragment.kt | 3663844306 |
package com.xcd.navbot
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
class SocialConnect : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_social_connect, container, false)
}
} | SPYM/app/src/main/java/com/xcd/navbot/SocialConnect.kt | 466452435 |
package com.xcd.navbot
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.Lifecycle
import androidx.viewpager2.adapter.FragmentStateAdapter
class FragmentPageAdapter(
fragmentManager: FragmentManager,
lifecycle: Lifecycle
) : FragmentStateAdapter(fragmentManager, lifecycle) {
override fun getItemCount(): Int {
return 2
}
override fun createFragment(position: Int): Fragment{
return if (position == 0)
Demographics()
else
SocialConnect()
}
} | SPYM/app/src/main/java/com/xcd/navbot/FragmentPageAdapter.kt | 2611889173 |
package com.xcd.navbot
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import com.xcd.navbot.databinding.FragmentDemographicsBinding
class Demographics : Fragment() {
private lateinit var binding: FragmentDemographicsBinding
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentDemographicsBinding.inflate(inflater, container, false)
val drugs = resources.getStringArray(R.array.drugs)
val arrayAdapter = ArrayAdapter(requireContext(), R.layout.dropdown_item, drugs)
binding.autoComplete.setAdapter(arrayAdapter)
return binding.root
/**
return inflater.inflate(R.layout.fragment_demographics, container, false)
**/
}
} | SPYM/app/src/main/java/com/xcd/navbot/DemographicsFragment.kt | 2687308236 |
package com.xcd.navbot
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.xcd.navbot.databinding.FragmentAddBinding
import com.xcd.navbot.databinding.FragmentHomeBinding
class HomeFragment : Fragment() {
private lateinit var binding: FragmentAddBinding
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
/**
binding = FragmentHomeBinding.inflate(layoutInflater)
return binding.root
**/
return inflater.inflate(R.layout.fragment_home, container, false)
}
} | SPYM/app/src/main/java/com/xcd/navbot/HomeFragment.kt | 1101813057 |
package com.xcd.navbot
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.xcd.navbot.databinding.FragmentAddBinding
class AddFragment : Fragment() {
private lateinit var binding: FragmentAddBinding
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = FragmentAddBinding.inflate(layoutInflater)
return binding.root
}
} | SPYM/app/src/main/java/com/xcd/navbot/AddFragment.kt | 2774340136 |
package com.example.kcb
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.kcb", appContext.packageName)
}
} | KCB-Android/app/src/androidTest/java/com/example/kcb/ExampleInstrumentedTest.kt | 1166756290 |
package com.example.kcb
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)
}
} | KCB-Android/app/src/test/java/com/example/kcb/ExampleUnitTest.kt | 503922943 |
package com.example.kcb.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)
val Brown = Color(0xFF952348)
val Pink= Color(0xFFD01A56)
val Grey= Color(0xFFECE6E7) | KCB-Android/app/src/main/java/com/example/kcb/ui/theme/Color.kt | 1396685230 |
package com.example.kcb.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 KCBTheme(
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
)
} | KCB-Android/app/src/main/java/com/example/kcb/ui/theme/Theme.kt | 1468843090 |
package com.example.kcb.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
)
*/
) | KCB-Android/app/src/main/java/com/example/kcb/ui/theme/Type.kt | 4082949 |
package com.example.kcb
import android.os.Bundle
import android.widget.Space
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.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Card
import androidx.compose.material3.CardColors
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.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.font.FontFamily
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.kcb.ui.theme.KCBTheme
class AssignmentActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
Assign()
}
}
}
@Composable
fun Assign() {
Column(
modifier = Modifier
.padding(10.dp)
.fillMaxSize()
.verticalScroll(rememberScrollState())
) {
val mContext = LocalContext.current
//Row 1
Card(modifier = Modifier
.padding(start = 5.dp, end = 10.dp)
.height(70.dp)
.width(370.dp),
shape = RoundedCornerShape(bottomStart = 13.dp, topEnd = 13.dp),
) {
Row(modifier = Modifier
.padding(10.dp)
.fillMaxWidth()
) {
Image(painter = painterResource(id = R.drawable.dog1), contentDescription ="dog",
modifier = Modifier
.size(50.dp)
.clip(CircleShape),
contentScale = ContentScale.Crop
)
Spacer(modifier = Modifier.width(6.dp))
Column {
androidx.compose.material3.Text(text = "Koda", fontSize = 18.sp, fontWeight = FontWeight.Bold, color = Color.DarkGray)
androidx.compose.material3.Text(text = "2 years old", fontWeight = FontWeight.Normal, fontSize = 15.sp, fontFamily = FontFamily.SansSerif, color = Color.Gray)
}
}
}
//End of Row1
Spacer(modifier = Modifier.height(15.dp))
//Row 2
Card(modifier = Modifier
.padding(start = 5.dp, end = 10.dp)
.height(70.dp)
.width(370.dp),
shape = RoundedCornerShape(bottomStart = 13.dp, topEnd = 13.dp),)
{
Row(modifier = Modifier
.padding(10.dp)
.fillMaxWidth()
) {
Image(painter = painterResource(id = R.drawable.dog2), contentDescription ="dog",
modifier = Modifier
.size(50.dp)
.clip(CircleShape),
contentScale = ContentScale.Crop
)
Spacer(modifier = Modifier.width(10.dp))
Column {
androidx.compose.material3.Text(text = "Lola", fontSize = 18.sp, fontWeight = FontWeight.Bold, color = Color.DarkGray)
androidx.compose.material3.Text(text = "16 years old", fontWeight = FontWeight.Normal, fontSize = 15.sp, fontFamily = FontFamily.SansSerif, color = Color.Gray)
}
}
}
Spacer(modifier = Modifier.height(15.dp))
Card(modifier = Modifier
.padding(start = 5.dp, end = 10.dp)
.height(70.dp)
.width(370.dp),
shape = RoundedCornerShape(bottomStart = 13.dp, topEnd = 13.dp),)
{
Row(modifier = Modifier
.padding(10.dp)
.fillMaxWidth()
) {
Image(painter = painterResource(id = R.drawable.dog2), contentDescription ="dog",
modifier = Modifier
.size(50.dp)
.clip(CircleShape),
contentScale = ContentScale.Crop
)
Spacer(modifier = Modifier.width(10.dp))
Column {
androidx.compose.material3.Text(text = "Frankie", fontSize = 18.sp, fontWeight = FontWeight.Bold, color = Color.DarkGray)
androidx.compose.material3.Text(text = "2years old", fontWeight = FontWeight.Normal, fontSize = 15.sp, fontFamily = FontFamily.SansSerif, color = Color.Gray)
}
}
}
//end of Row3
Spacer(modifier = Modifier.height(15.dp))
Card(modifier = Modifier
.padding(start = 5.dp, end = 10.dp)
.height(70.dp)
.width(370.dp),
shape = RoundedCornerShape(bottomStart = 13.dp, topEnd = 13.dp),)
{
//Row 4
Row(modifier = Modifier
.padding(10.dp)
.fillMaxWidth()
) {
Image(painter = painterResource(id = R.drawable.dog4), contentDescription ="dog",
modifier = Modifier
.size(50.dp)
.clip(CircleShape),
contentScale = ContentScale.Crop
)
Spacer(modifier = Modifier.width(10.dp))
Column {
androidx.compose.material3.Text(text = "Nox", fontSize = 18.sp, fontWeight = FontWeight.Bold, color = Color.DarkGray)
androidx.compose.material3.Text(text = "8 years old", fontWeight = FontWeight.Normal, fontSize = 15.sp, fontFamily = FontFamily.SansSerif,
color = Color.Gray)
}
}
}
Spacer(modifier = Modifier.height(15.dp))
//Row
Card(modifier = Modifier
.padding(start = 5.dp, end = 10.dp)
.height(70.dp)
.width(370.dp),
shape = RoundedCornerShape(bottomStart = 13.dp, topEnd = 13.dp),)
{
//Row 5
Row(modifier = Modifier
.padding(10.dp)
.fillMaxWidth()
) {
Image(painter = painterResource(id = R.drawable.dog5), contentDescription ="dog",
modifier = Modifier
.size(50.dp)
.clip(CircleShape),
contentScale = ContentScale.Crop
)
Spacer(modifier = Modifier.width(10.dp))
Column {
androidx.compose.material3.Text(text = "Faye", fontSize = 18.sp, fontWeight = FontWeight.Bold, color = Color.DarkGray)
androidx.compose.material3.Text(text = "8 years old", fontWeight = FontWeight.Normal, fontSize = 15.sp, fontFamily = FontFamily.SansSerif, color = Color.Gray)
}
}
}
Spacer(modifier = Modifier.height(15.dp))
//
Card(modifier = Modifier
.padding(start = 5.dp, end = 10.dp)
.height(70.dp)
.width(370.dp),
shape = RoundedCornerShape(bottomStart = 13.dp, topEnd = 13.dp)) {
//Row 6
Row(modifier = Modifier
.padding(10.dp)
.fillMaxWidth()
) {
Image(painter = painterResource(id = R.drawable.dog6), contentDescription ="dog",
modifier = Modifier
.size(50.dp)
.clip(CircleShape),
contentScale = ContentScale.Crop
)
Spacer(modifier = Modifier.width(10.dp))
Column {
androidx.compose.material3.Text(text = "Bella", fontSize = 18.sp, fontWeight = FontWeight.Bold)
androidx.compose.material3.Text(text = "14 years old", fontWeight = FontWeight.Normal, fontSize = 15.sp, fontFamily = FontFamily.SansSerif, color = Color.Gray)
}
}
//end of Row 6
}
Spacer(modifier = Modifier.height(10.dp))
Card(modifier = Modifier
.padding(start = 5.dp, end = 10.dp)
.height(70.dp)
.width(370.dp),
shape = RoundedCornerShape(bottomStart = 13.dp, topEnd = 13.dp)) {
//Row 7
Row(modifier = Modifier
.padding(10.dp)
.fillMaxWidth()
) {
Image(painter = painterResource(id = R.drawable.dog7), contentDescription ="dog",
modifier = Modifier
.size(50.dp)
.clip(CircleShape),
contentScale = ContentScale.Crop
)
Spacer(modifier = Modifier.width(10.dp))
Column {
androidx.compose.material3.Text(text = "Moana", fontSize = 18.sp, fontWeight = FontWeight.Bold, color = Color.DarkGray)
androidx.compose.material3.Text(text = "2 years old", fontWeight = FontWeight.Normal, fontSize = 15.sp, fontFamily = FontFamily.SansSerif, color = Color.Gray)
}
}
}
//end of row 7
Spacer(modifier = Modifier.height(15.dp))
Card(modifier = Modifier
.padding(start = 5.dp, end = 10.dp)
.height(70.dp)
.width(370.dp),
shape = RoundedCornerShape(bottomStart = 13.dp, topEnd = 13.dp)) {
Row(modifier = Modifier
.padding(10.dp)
.fillMaxWidth()
) {
Image(painter = painterResource(id = R.drawable.dog8), contentDescription ="dog",
modifier = Modifier
.size(50.dp)
.clip(CircleShape),
contentScale = ContentScale.Crop
)
Spacer(modifier = Modifier.width(10.dp))
Column {
androidx.compose.material3.Text(text = "Tzeitel", fontSize = 18.sp, fontWeight = FontWeight.Bold, color = Color.DarkGray)
androidx.compose.material3.Text(text = "18 years old", fontWeight = FontWeight.Normal, fontSize = 15.sp, fontFamily = FontFamily.SansSerif, color = Color.Gray)
}
}
//end of Row8
}
//End of row 8
Spacer(modifier = Modifier.height(15.dp))
Card(modifier = Modifier
.padding(start = 5.dp, end = 10.dp)
.height(70.dp)
.width(370.dp),
shape = RoundedCornerShape(bottomStart = 13.dp, topEnd = 13.dp)) {
//Row 9
Row(modifier = Modifier
.padding(10.dp)
.fillMaxWidth()
) {
Image(painter = painterResource(id = R.drawable.dog9), contentDescription ="dog",
modifier = Modifier
.size(50.dp)
.clip(CircleShape),
contentScale = ContentScale.Crop
)
Spacer(modifier = Modifier.width(10.dp))
Column {
androidx.compose.material3.Text(text = "Kery", fontSize = 18.sp, fontWeight = FontWeight.Bold, color = Color.DarkGray)
androidx.compose.material3.Text(text = "3 years old", fontWeight = FontWeight.Normal, fontSize = 15.sp, fontFamily = FontFamily.SansSerif, color = Color.Gray)
}
}
//end of Row9
}
Spacer(modifier = Modifier.height(10.dp))
}
}
@Preview(showBackground = true)
@Composable
fun AssignPreview(){
Assign()
}
| KCB-Android/app/src/main/java/com/example/kcb/AssignmentActivity.kt | 75662535 |
package com.example.kcb
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Arrangement
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.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
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.airbnb.lottie.compose.LottieAnimation
import com.airbnb.lottie.compose.LottieCompositionSpec
import com.airbnb.lottie.compose.animateLottieCompositionAsState
import com.airbnb.lottie.compose.rememberLottieComposition
import com.example.kcb.ui.theme.KCBTheme
class LottiePracActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MyLottiePractice()
}
}
}
@Composable
fun MyLottiePractice(){
Column(
modifier = Modifier.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center) {
val mContext = LocalContext.current
//Lottie Animation
val composition by rememberLottieComposition(spec = LottieCompositionSpec.RawRes(R.raw.music))
val progress by animateLottieCompositionAsState(composition)
LottieAnimation(composition, progress,
modifier = Modifier.size(300.dp)
)
Spacer(modifier = Modifier.height(20.dp))
Text(
text = "Explore...",
fontWeight = FontWeight.ExtraBold,
fontSize = 30.sp,
modifier = Modifier.fillMaxWidth(),
textAlign = TextAlign.Center,
color = Color.Black
)
Spacer(modifier = Modifier.height(20.dp))
Button(
onClick = { },
shape = RoundedCornerShape(22.dp),
colors = ButtonDefaults.buttonColors(Color.Black),
modifier = Modifier
.fillMaxWidth()
.padding(start = 30.dp, end = 30.dp)
) {
Text(text = "Continue ",
fontSize = 22.sp)
Spacer(modifier = Modifier.height(20.dp))
}
}
}
@Preview(showBackground = true)
@Composable
fun MyLottiePracticePreview(){
}
| KCB-Android/app/src/main/java/com/example/kcb/LottiePracActivity.kt | 96256799 |
package com.example.kcb
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.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.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
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.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.font.FontWeight
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.kcb.ui.theme.KCBTheme
import com.example.kcb.ui.theme.Pink
class AddActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
Add()
}
}
}
@Composable
fun Add(){
Column(modifier = Modifier
.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
val mContext = LocalContext.current
Box(modifier = Modifier.fillMaxWidth(),
contentAlignment = Alignment.Center) {
Image(painter = painterResource(id = R.drawable.shopping1) ,
contentDescription ="shopping" ,
modifier = Modifier
.size(300.dp)
.clip(shape = CircleShape),
contentScale = ContentScale.Crop)
}
Spacer(modifier = Modifier.height(20.dp))
Text(text = "Add to Your Cart",
fontSize = 22.sp,
modifier = Modifier.fillMaxWidth(),
textAlign = TextAlign.Center,
fontWeight = FontWeight.ExtraBold
)
Spacer(modifier = Modifier.height(20.dp))
Text(text = "We provide a variety of items to be selected from by customers.Choose any that please you and place your order ",
fontSize = 18.sp,
modifier = Modifier.fillMaxWidth(),
textAlign = TextAlign.Center,
fontWeight = FontWeight.Normal
)
Spacer(modifier = Modifier.height(10.dp))
Text(text = "...",
fontSize = 32.sp,
modifier = Modifier.fillMaxWidth(),
textAlign = TextAlign.Center,
fontWeight = FontWeight.ExtraBold,
color = Color.DarkGray
)
Spacer(modifier = Modifier.height(30.dp))
Button(
onClick = {
mContext.startActivity(Intent(mContext,PayActivity::class.java))
},
shape = RoundedCornerShape(22.dp),
colors = ButtonDefaults.buttonColors(Pink),
modifier = Modifier
.fillMaxWidth()
.padding(start = 30.dp, end = 30.dp)
) {
Text(text = "Next ",
fontSize = 22.sp)
Spacer(modifier = Modifier)
}
}
}
@Preview(showBackground = true, showSystemUi = true)
@Composable
fun AddPreview(){
Add()
}
| KCB-Android/app/src/main/java/com/example/kcb/AddActivity.kt | 2415006782 |
package com.example.kcb
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
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.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
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.getValue
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.Shape
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.layout.layoutId
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.airbnb.lottie.compose.LottieAnimation
import com.airbnb.lottie.compose.LottieCompositionSpec
import com.airbnb.lottie.compose.animateLottieCompositionAsState
import com.airbnb.lottie.compose.rememberLottieComposition
import com.example.kcb.ui.theme.KCBTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
Text()
}
}
}
@Composable
fun Text(){
Column(modifier = Modifier.fillMaxSize()) {
val mContext = LocalContext.current
androidx.compose.material3.Text(text = "Annual Car Expo :",
fontSize = 25.sp,
color = Color.DarkGray,
fontWeight = FontWeight.Bold,
fontStyle = FontStyle.Italic,
)
Spacer(modifier = Modifier.height(20.dp))
androidx.compose.material3.Text(text = "This year's expo is scheduled for 22nd- 26th of July 2023 .",
fontSize = 18.sp)
Spacer(modifier = Modifier.height(16.dp))
androidx.compose.material3.Text(text = "High-end Cars",
fontSize = 23.sp,
modifier = Modifier
.fillMaxWidth()
.background(Color.Black)
.height(40.dp),
textAlign = TextAlign.Center,
textDecoration = TextDecoration.Underline,
color = Color.Gray
)
androidx.compose.material3.Text(text = "1.Mercedes- Benz")
androidx.compose.material3.Text(text = "2.Lamborghini")
androidx.compose.material3.Text(text = "3.Porsche")
Box {
//Lottie Animation
val composition by rememberLottieComposition(spec = LottieCompositionSpec.RawRes(R.raw.car))
val progress by animateLottieCompositionAsState(composition)
LottieAnimation(composition, progress,
modifier = Modifier.size(300.dp)
)
}
Box( modifier = Modifier
.fillMaxWidth(),
contentAlignment = Alignment.Center)
{
Spacer(modifier = Modifier.height(20.dp))
Button(onClick = {
mContext.startActivity(Intent(mContext,formactivity::class.java)) },
colors = ButtonDefaults.buttonColors(Color.Black)) {
Text("See More!!")
}
}
Spacer(modifier = Modifier.height(22.dp))
androidx.compose.material3.Text(text = "Mansory Company",
fontSize = 27.sp,
color = Color.DarkGray,
fontWeight = FontWeight.Bold,
fontStyle = FontStyle.Italic,
textAlign = TextAlign.Center
)
androidx.compose.material3.Text(text = "List of projects",
fontSize = 22.sp,
modifier = Modifier.fillMaxWidth(),
textAlign = TextAlign.Center,
textDecoration = TextDecoration.Underline)
androidx.compose.material3.Text(text = "1.Bentley Bentayga",
fontSize = 15.sp)
androidx.compose.material3.Text(text = "2.Ferrari 812 GTS",
fontSize = 15.sp)
androidx.compose.material3.Text(text = "3.Mercedes G Wagon",
fontSize = 15.sp)
Spacer(modifier = Modifier.height(16.dp))
Divider()
//Centering an image
Box(modifier = Modifier.fillMaxWidth(),
contentAlignment = Alignment.Center) {
Image(painter = painterResource(id = R.drawable.mansory10) ,
contentDescription ="Mansory" ,
modifier = Modifier
.size(100.dp)
.clip(shape = CircleShape),
contentScale = ContentScale.Crop)
}
Spacer(modifier = Modifier.height(16.dp))
Button(
onClick = {
mContext.startActivity(Intent(mContext,Layoutactivity::class.java))
},
shape = RoundedCornerShape(5.dp),
colors = ButtonDefaults.buttonColors(Color.Black),
modifier = Modifier
.fillMaxWidth()
.padding(start = 30.dp, end = 30.dp)
) {
androidx.compose.material3.Text(text = "Next")
}
}
}
@Preview(showBackground = true)
@Composable
fun TextPreview(){
Text()
} | KCB-Android/app/src/main/java/com/example/kcb/MainActivity.kt | 3400743049 |
package com.example.kcb
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.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.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
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.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.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.kcb.ui.theme.KCBTheme
import com.example.kcb.ui.theme.Pink
class ChooseActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
Choose()
}
}
}
@Composable
fun Choose(){
Column(modifier = Modifier
.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
val mContext = LocalContext.current
Box(modifier = Modifier.fillMaxWidth(),
contentAlignment = Alignment.Center) {
Image(painter = painterResource(id = R.drawable.shopping2) ,
contentDescription ="shopping" ,
modifier = Modifier
.size(300.dp)
.clip(shape = CircleShape),
contentScale = ContentScale.Crop)
}
Spacer(modifier = Modifier.height(20.dp))
androidx.compose.material3.Text(text = "Choose Your products",
fontSize = 22.sp,
modifier = Modifier.fillMaxWidth(),
textAlign = TextAlign.Center,
fontWeight = FontWeight.ExtraBold
)
Spacer(modifier = Modifier.height(20.dp))
androidx.compose.material3.Text(text = "We provide variety of items be selected from by customers.Choose any that please you and place your order ",
fontSize = 18.sp,
modifier = Modifier.fillMaxWidth(),
textAlign = TextAlign.Center,
)
Spacer(modifier = Modifier.height(10.dp))
androidx.compose.material3.Text(text = "...",
fontSize = 32.sp,
modifier = Modifier.fillMaxWidth(),
textAlign = TextAlign.Center,
fontWeight = FontWeight.ExtraBold,
color = Color.DarkGray
)
Spacer(modifier = Modifier.height(30.dp))
Button(
onClick = {
mContext.startActivity(Intent(mContext,AddActivity::class.java))
},
shape = RoundedCornerShape(22.dp),
colors = ButtonDefaults.buttonColors(Pink),
modifier = Modifier
.fillMaxWidth()
.padding(start = 30.dp, end = 30.dp)
) {
Text(text = "Next ",
fontSize = 22.sp)
Spacer(modifier = Modifier)
}
}
}
@Preview(showBackground = true, showSystemUi = true)
@Composable
fun ChoosePreview(){
Choose()
}
| KCB-Android/app/src/main/java/com/example/kcb/ChooseActivity.kt | 2723225973 |
package com.example.kcb
import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Arrangement
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.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.paint
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.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
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.airbnb.lottie.compose.LottieAnimation
import com.airbnb.lottie.compose.LottieCompositionSpec
import com.airbnb.lottie.compose.animateLottieCompositionAsState
import com.airbnb.lottie.compose.rememberLottieComposition
import com.example.kcb.ui.theme.KCBTheme
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
class SplashScreenActivity : ComponentActivity() {
@SuppressLint("CoroutineCreationDuringComposition")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
Splash()
val mContext = LocalContext.current
val coroutineScope = rememberCoroutineScope()
coroutineScope.launch {
delay(1000)
mContext.startActivity(Intent(mContext,ChooseActivity::class.java))
finish()
}
}
}
}
@Composable
fun Splash(){
Column(
modifier = Modifier
.fillMaxSize()
.paint(
painterResource(id = R.drawable.background),
contentScale = ContentScale.Crop
),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
val mContext = LocalContext.current
//Lottie Animation
val composition by rememberLottieComposition(spec = LottieCompositionSpec.RawRes(R.raw.music))
val progress by animateLottieCompositionAsState(composition)
LottieAnimation(composition, progress,
modifier = Modifier.size(300.dp)
)
Spacer(modifier = Modifier.height(20.dp))
androidx.compose.material3.Text(
text = "Choose your favourite genre...",
fontWeight = FontWeight.Bold,
fontSize = 18.sp,
modifier = Modifier.fillMaxWidth(),
textAlign = TextAlign.Center,
fontFamily = FontFamily.Monospace,
color = Color.White
)
Spacer(modifier = Modifier.height(20.dp))
Spacer(modifier = Modifier.height(30.dp))
Button(
onClick = {
mContext.startActivity(Intent(mContext,ChooseActivity::class.java))
},
shape = RoundedCornerShape(22.dp),
colors = ButtonDefaults.buttonColors(Color.Black),
modifier = Modifier
.fillMaxWidth()
.padding(start = 30.dp, end = 30.dp)
) {
Text(text = "Continue ",
fontSize = 22.sp)
Spacer(modifier = Modifier)
}
}
}
@Preview(showBackground = true)
@Composable
fun SplashReview(){
Splash()
}
| KCB-Android/app/src/main/java/com/example/kcb/SplashScreenActivity.kt | 3099475381 |
package com.example.kcb
import android.content.Intent
import android.media.audiofx.BassBoost
import android.os.Bundle
import android.provider.Settings
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
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.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.ArrowForward
import androidx.compose.material.icons.filled.Menu
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material.icons.filled.Share
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarColors
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.paint
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.font.FontWeight
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.kcb.ui.theme.KCBTheme
class Layoutactivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
Layout()
}
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun Layout(){
Column(modifier = Modifier
.fillMaxSize()
.paint(painterResource(id = R.drawable.background),
contentScale = ContentScale.FillBounds)) {
val mContext = LocalContext.current
//TopAppBar
TopAppBar(title = { androidx.compose.material3.Text(text = "Home", color = Color.Gray) },
colors = TopAppBarDefaults.mediumTopAppBarColors(Color.Black),
navigationIcon = {
IconButton(onClick = { /*TODO*/ }) {
Icon(imageVector = Icons.Default.Menu,
contentDescription = "Menu" ,
tint = Color.DarkGray)
}
},
actions = {
IconButton(onClick = {
val shareIntent=Intent(Intent.ACTION_SEND)
shareIntent.type="text/plain"
shareIntent.putExtra(Intent.EXTRA_TEXT, "Check out this is a cool content")
mContext.startActivity(Intent.createChooser(shareIntent, "Share"))
}) {
Icon(imageVector = Icons.Default.Share,
contentDescription = "share",
tint = Color.White)
}
IconButton(onClick = {
val settingsIntent = Intent(Settings.ACTION_SETTINGS)
mContext.startActivity(settingsIntent)
}) {
Icon(imageVector = Icons.Default.Settings,
contentDescription = "settings",
tint = Color.White)
}
})
//End of TopAppBar
Spacer(modifier = Modifier.height(5.dp))
androidx.compose.material3.Text(text = "Cars on sale",
color = Color.White,
fontWeight = FontWeight.ExtraBold,
modifier = Modifier.fillMaxWidth(),
textAlign = TextAlign.Center,
fontSize = 26.sp
)
Spacer(modifier = Modifier.height(15.dp))
Row {
Image(painter = painterResource(id = R.drawable.mansory3),
contentDescription ="car" ,
modifier = Modifier.size(width = 250.dp, height = 150.dp))
Spacer(modifier = Modifier.width(20.dp))
Column {
androidx.compose.material3.Text(text = "Mercedes G-Wagon",
fontSize = 20.sp,
color = Color.White)
androidx.compose.material3.Text(text = "Most exquisite type of Mercedes for trips",
color = Color.White)
}
}
//End of row1
Spacer(modifier = Modifier.height(15.dp))
Row {
Image(painter = painterResource(id = R.drawable.mansory10),
contentDescription ="car" ,
modifier = Modifier.size(width = 250.dp, height = 150.dp))
Spacer(modifier = Modifier.width(20.dp))
Column {
androidx.compose.material3.Text(text = " Bentley Continental GT",
fontSize = 20.sp,
color = Color.White)
androidx.compose.material3.Text(text = "Can either be luxurious or sporty",
color = Color.White)
}
}
//End of row2
Spacer(modifier = Modifier.height(15.dp))
Row {
Image(painter = painterResource(id = R.drawable.mansory1),
contentDescription ="car" ,
modifier = Modifier.size(width = 250.dp, height = 150.dp))
Spacer(modifier = Modifier.width(20.dp))
Column {
androidx.compose.material3.Text(text = "Mc Laren",
fontSize = 20.sp,
color = Color.White)
androidx.compose.material3.Text(text = "An upgraded sports car ",
color = Color.White)
}
}
Spacer(modifier = Modifier.height(32.dp))
Row {
Spacer(modifier = Modifier.width(56.dp))
Button(
onClick = {
mContext.startActivity(Intent(mContext,MainActivity::class.java))
},
shape = RoundedCornerShape(5.dp),
colors = ButtonDefaults.buttonColors(Color.DarkGray),
) {
Icon(imageVector = Icons.Default.ArrowBack, contentDescription = "arrowbar", tint = Color.Black)
androidx.compose.material3.Text(text = "Back",
color = Color.Black)
}
Spacer(modifier = Modifier.width(42.dp))
Button(
onClick = {
mContext.startActivity(Intent(mContext,IntentActivity::class.java))
},
shape = RoundedCornerShape(5.dp),
colors = ButtonDefaults.buttonColors(Color.DarkGray),
) {
Icon(imageVector = Icons.Default.ArrowForward, contentDescription = "arrowbar", tint = Color.Black)
androidx.compose.material3.Text(text = "Next",
color = Color.Black)
}
}
}
}
@Preview(showBackground = true)
@Composable
fun LayoutPreview(){
Layout()
} | KCB-Android/app/src/main/java/com/example/kcb/layoutactivity.kt | 428648190 |
package com.example.kcb
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.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.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
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.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.font.FontWeight
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.kcb.ui.theme.KCBTheme
import com.example.kcb.ui.theme.Pink
class PayActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
Pay()
}
}
}
@Composable
fun Pay(){
Column(modifier = Modifier
.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
val mContext = LocalContext.current
Spacer(modifier = Modifier.height(10.dp))
Box(modifier = Modifier.fillMaxWidth(),
contentAlignment = Alignment.Center) {
Image(painter = painterResource(id = R.drawable.shopping2) ,
contentDescription ="shopping" ,
modifier = Modifier
.size(300.dp)
.clip(shape = CircleShape),
contentScale = ContentScale.Crop)
}
Spacer(modifier = Modifier.height(20.dp))
Text(text = "Pay by Cart",
fontSize = 22.sp,
modifier = Modifier.fillMaxWidth(),
textAlign = TextAlign.Center,
fontWeight = FontWeight.ExtraBold
)
Spacer(modifier = Modifier.height(20.dp))
Text(text = "We provide a variety of items to be selected from by customers.Choose any that please you and place your order ",
fontSize = 18.sp,
modifier = Modifier.fillMaxWidth(),
textAlign = TextAlign.Center,
fontWeight = FontWeight.Normal
)
Spacer(modifier = Modifier.height(10.dp))
Text(text = "...",
fontSize = 32.sp,
modifier = Modifier.fillMaxWidth(),
textAlign = TextAlign.Center,
fontWeight = FontWeight.ExtraBold,
color = Color.DarkGray
)
Spacer(modifier = Modifier.height(30.dp))
Button(
onClick = {
mContext.startActivity(Intent(mContext,PayActivity::class.java))
},
shape = RoundedCornerShape(22.dp),
colors = ButtonDefaults.buttonColors(Pink),
modifier = Modifier
.fillMaxWidth()
.padding(start = 30.dp, end = 30.dp)
) {
Text(text = "Next ",
fontSize = 22.sp)
Spacer(modifier = Modifier)
}
}
}
@Preview(showBackground = true)
@Composable
fun PayPreview(){
Pay()
}
| KCB-Android/app/src/main/java/com/example/kcb/PayActivity.kt | 1671500224 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.