content
stringlengths
0
13M
path
stringlengths
4
263
contentHash
stringlengths
1
10
package app.xlei.vipexam.feature.wordlist import android.content.Context import android.content.Intent import androidx.core.content.FileProvider import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import app.xlei.vipexam.core.data.repository.Repository import app.xlei.vipexam.core.database.module.Word import app.xlei.vipexam.core.network.module.EudicRemoteDatasource import app.xlei.vipexam.feature.wordlist.constant.SortMethod import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import org.apache.commons.csv.CSVFormat import org.apache.commons.csv.CSVPrinter import java.io.File import java.io.PrintWriter import javax.inject.Inject @HiltViewModel class WordListViewModel @Inject constructor( private val repository: Repository<Word>, ) : ViewModel() { private val _wordList = MutableStateFlow(emptyList<Word>()) private val _syncState = MutableStateFlow<SyncState<Nothing>>(SyncState.Default) val wordList get() = _wordList.asStateFlow() val syncState get() = _syncState.asStateFlow() var sortMethod = MutableStateFlow(SortMethod.OLD_TO_NEW) init { getWordList() } private fun getWordList() { viewModelScope.launch { repository.getAll() .flowOn(Dispatchers.IO) .collect { wordList: List<Word> -> _wordList.update { wordList } } } } fun addWord(word: Word) { viewModelScope.launch(Dispatchers.IO) { repository.add(word) } } fun removeWord(word: Word) { viewModelScope.launch(Dispatchers.IO) { repository.remove(word) } } fun setSortMethod(sortMethod: SortMethod) { this.sortMethod.value = sortMethod viewModelScope.launch { repository.getAll() .flowOn(Dispatchers.IO) .map { words -> when (sortMethod) { SortMethod.OLD_TO_NEW -> words.sortedBy { it.created } SortMethod.NEW_TO_OLD -> words.sortedByDescending { it.created } SortMethod.A_TO_Z -> words.sortedBy { it.word } SortMethod.Z_TO_A -> words.sortedByDescending { it.word } } } .collect { sortedWordList: List<Word> -> _wordList.update { sortedWordList } } } } fun exportWordsToCSV(context: Context) { viewModelScope.launch(Dispatchers.IO) { val words = repository.getAll().first() val csvFile = File(context.cacheDir, "words-${System.currentTimeMillis()}.csv") CSVPrinter( PrintWriter(csvFile), CSVFormat.DEFAULT.withHeader("id", "word", "created") ).use { printer -> words.forEach { word -> printer.printRecord(word.id, word.word, word.created) } } withContext(Dispatchers.Main) { shareCSVFile(context, csvFile) } } } private fun shareCSVFile(context: Context, file: File) { val contentUri = FileProvider.getUriForFile(context, "${context.packageName}.provider", file) val shareIntent = Intent().apply { action = Intent.ACTION_SEND putExtra(Intent.EXTRA_STREAM, contentUri) type = "text/csv" } context.startActivity(Intent.createChooser(shareIntent, "Save file...")) } fun syncToEudic(apiKey: String) { apiKey.takeIf { it != "" }?.let { _syncState.update { SyncState.Syncing } viewModelScope.launch { EudicRemoteDatasource.api = it if (EudicRemoteDatasource.sync(_wordList.value.map { it.word })) _syncState.update { SyncState.Success } else _syncState.update { SyncState.Error } } } } fun resetSyncState() { _syncState.update { SyncState.Default } } } sealed class SyncState<out T> { data object Default : SyncState<Nothing>() data object Success : SyncState<Nothing>() data object Syncing : SyncState<Nothing>() data object Error : SyncState<Nothing>() }
vipexam/feature/wordlist/src/main/java/app/xlei/vipexam/feature/wordlist/WordListViewModel.kt
849720985
package app.xlei.vipexam.feature.wordlist import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.background import androidx.compose.foundation.combinedClickable import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.statusBarsPadding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyRow import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.KeyboardArrowDown import androidx.compose.material.icons.filled.KeyboardArrowUp import androidx.compose.material.icons.filled.Share import androidx.compose.material3.AssistChip import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.FilterChip import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.LargeTopAppBar import androidx.compose.material3.ListItem import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.material3.TopAppBarDefaults import androidx.compose.material3.rememberTopAppBarState import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.input.nestedscroll.nestedScroll import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.hilt.navigation.compose.hiltViewModel import app.xlei.vipexam.core.ui.DateText import app.xlei.vipexam.feature.wordlist.components.CopyToClipboardButton import app.xlei.vipexam.feature.wordlist.components.TranslationSheet import app.xlei.vipexam.feature.wordlist.constant.SortMethod import app.xlei.vipexam.preference.EudicApiKey import app.xlei.vipexam.preference.LocalEudicApiKey import compose.icons.FeatherIcons import compose.icons.feathericons.Check import compose.icons.feathericons.Menu import compose.icons.feathericons.RefreshCcw import compose.icons.feathericons.RefreshCw import compose.icons.feathericons.X import kotlinx.coroutines.delay @OptIn( ExperimentalFoundationApi::class, ExperimentalMaterial3Api::class, ) @Composable fun WordListScreen( modifier: Modifier = Modifier, initSortMethod: SortMethod = SortMethod.OLD_TO_NEW, viewModel: WordListViewModel = hiltViewModel(), openDrawer: () -> Unit, ) { val wordListState by viewModel.wordList.collectAsState() val syncState by viewModel.syncState.collectAsState() val scrollBehavior = TopAppBarDefaults.exitUntilCollapsedScrollBehavior( rememberTopAppBarState() ) var textToTranslate by remember { mutableStateOf("") } var showTranslationSheet by remember { mutableStateOf(false) } var showSortMethods by rememberSaveable { mutableStateOf(false) } LaunchedEffect(Unit) { viewModel.setSortMethod(initSortMethod) } val sortMethod = viewModel.sortMethod.collectAsState() val context = LocalContext.current val eudicApiKey = LocalEudicApiKey.current LaunchedEffect(syncState) { if (syncState == SyncState.Success || syncState == SyncState.Error) { delay(2000) viewModel.resetSyncState() } } Scaffold( topBar = { LargeTopAppBar( actions = { IconButton( onClick = { viewModel.syncToEudic(eudicApiKey.value) }, enabled = eudicApiKey is EudicApiKey.Some ) { when (syncState) { SyncState.Default -> { Icon( imageVector = FeatherIcons.RefreshCw, contentDescription = null ) } SyncState.Error -> { Icon(imageVector = FeatherIcons.X, contentDescription = null) } SyncState.Success -> { Icon(imageVector = FeatherIcons.Check, contentDescription = null) } SyncState.Syncing -> { Icon( imageVector = FeatherIcons.RefreshCcw, contentDescription = null ) } } } IconButton(onClick = { viewModel.exportWordsToCSV(context) }) { Icon(imageVector = Icons.Default.Share, contentDescription = null) } }, title = { Text( stringResource(R.string.words) ) }, navigationIcon = { IconButton( onClick = openDrawer ) { Icon( imageVector = FeatherIcons.Menu, contentDescription = null, ) } }, scrollBehavior = scrollBehavior ) }, modifier = modifier .background(MaterialTheme.colorScheme.background) .statusBarsPadding() .nestedScroll(scrollBehavior.nestedScrollConnection), ) { paddingValues -> Column( modifier = Modifier .padding(paddingValues) ) { LazyColumn { stickyHeader { Column( modifier = Modifier .fillMaxWidth() .background(MaterialTheme.colorScheme.background) ) { LazyRow { item { AssistChip( onClick = { showSortMethods = !showSortMethods }, label = { Text(text = stringResource(id = R.string.sort)) }, trailingIcon = { Icon( imageVector = if (showSortMethods) { Icons.Default.KeyboardArrowUp } else { Icons.Default.KeyboardArrowDown }, contentDescription = null, ) }, modifier = Modifier .padding(horizontal = 8.dp) ) } } LazyRow { if (showSortMethods) SortMethod.entries.forEach { item { FilterChip( onClick = { viewModel.setSortMethod(it) }, label = { Text(text = stringResource(id = it.method)) }, selected = it == sortMethod.value, modifier = Modifier .padding(horizontal = 8.dp) ) } } } } } items(wordListState.size) { index -> ListItem( headlineContent = { Text(wordListState[index].word) }, supportingContent = { DateText(wordListState[index].created) }, trailingContent = { CopyToClipboardButton(text = wordListState[index].word) }, modifier = Modifier .combinedClickable( onClick = { textToTranslate = wordListState[index].word showTranslationSheet = true }, onLongClick = { viewModel.removeWord(wordListState[index]) } ) ) } item { if (wordListState.isEmpty()) Text( text = stringResource(R.string.empty_wordlist_tips), textAlign = TextAlign.Center, modifier = Modifier .fillMaxSize() ) } } if (showTranslationSheet) TranslationSheet( textToTranslate ) { showTranslationSheet = !showTranslationSheet } } } }
vipexam/feature/wordlist/src/main/java/app/xlei/vipexam/feature/wordlist/WordListScreen.kt
3452517232
package app.xlei.vipexam.feature.wordlist.components.viewmodel import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import androidx.paging.PagingData import androidx.paging.cachedIn import app.xlei.vipexam.core.data.paging.MomoLookUpApi import app.xlei.vipexam.core.data.paging.MomoLookUpRepository import app.xlei.vipexam.core.network.module.momoLookUp.Phrase import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Job import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class TranslationSheetViewModel @Inject constructor( private val momoLookUpRepository: MomoLookUpRepository ) : ViewModel() { private val _phrases: MutableStateFlow<PagingData<Phrase>> = MutableStateFlow(PagingData.empty()) val phrases = _phrases private var searchJob: Job? = null suspend fun search(keyword: String) { MomoLookUpApi.keyword = keyword searchJob?.cancel() searchJob = viewModelScope.launch { momoLookUpRepository.search().distinctUntilChanged() .cachedIn(viewModelScope) .collect { _phrases.value = it } } } fun clean() { searchJob?.cancel() _phrases.value = PagingData.empty() } suspend fun refresh(keyword: String) = search(keyword) }
vipexam/feature/wordlist/src/main/java/app/xlei/vipexam/feature/wordlist/components/viewmodel/TranslationSheetViewModel.kt
423331269
package app.xlei.vipexam.feature.wordlist.components import android.widget.Toast import androidx.compose.animation.AnimatedVisibility import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.ExperimentalLayoutApi import androidx.compose.foundation.layout.FlowRow import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.text.selection.SelectionContainer import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.FilterChip import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.Icon import androidx.compose.material3.ListItem import androidx.compose.material3.ModalBottomSheet import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalTextToolbar import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.hilt.navigation.compose.hiltViewModel import androidx.paging.compose.collectAsLazyPagingItems import app.xlei.vipexam.core.data.paging.MomoLookUpApi import app.xlei.vipexam.core.data.paging.Source import app.xlei.vipexam.core.network.module.NetWorkRepository import app.xlei.vipexam.core.ui.EmptyTextToolbar import app.xlei.vipexam.core.ui.TranslateDialog import app.xlei.vipexam.feature.wordlist.components.viewmodel.TranslationSheetViewModel import compose.icons.FeatherIcons import compose.icons.feathericons.Loader import kotlinx.coroutines.launch @OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class) @Composable fun TranslationSheet( text: String, viewModel: TranslationSheetViewModel = hiltViewModel(), toggleBottomSheet: () -> Unit, ) { val phrases = viewModel.phrases.collectAsLazyPagingItems() var translation by remember { mutableStateOf( app.xlei.vipexam.core.network.module.TranslationResponse( code = 200, id = "", data = "", emptyList() ) ) } val context = LocalContext.current val coroutine = rememberCoroutineScope() var showTranslationDialog by remember { mutableStateOf(false) } var selectedSource by remember { mutableStateOf(Source.ALL) } DisposableEffect(Unit) { coroutine.launch { val res = NetWorkRepository.translateToZH(text) res.onSuccess { translation = it } res.onFailure { toggleBottomSheet() Toast.makeText(context, it.toString(), Toast.LENGTH_SHORT).show() } viewModel.search(text) } onDispose { viewModel.clean() } } ModalBottomSheet( onDismissRequest = toggleBottomSheet, ) { Column( modifier = Modifier .run { if (phrases.itemCount == 0) this.padding(bottom = 120.dp) else this } ) { Column( modifier = Modifier .padding(horizontal = 24.dp) ) { Text( text = text, fontWeight = FontWeight.Bold, ) HorizontalDivider() Text( text = translation.data, fontSize = 24.sp, ) LazyRow { if (translation.alternatives.isEmpty() && translation.data == "") { item { Icon( imageVector = FeatherIcons.Loader, contentDescription = null, ) } } else { items(translation.alternatives.size) { Text( text = translation.alternatives[it], modifier = Modifier .padding(end = 12.dp) ) } } } } AnimatedVisibility(visible = phrases.itemCount > 0) { FlowRow( modifier = Modifier.padding(4.dp) ) { Source.entries.forEach { FilterChip( selected = selectedSource == it, onClick = { selectedSource = it MomoLookUpApi.source = it coroutine.launch { viewModel.refresh(text) } }, label = { Text(text = it.displayName) }, modifier = Modifier.padding(start = 4.dp) ) } } } LazyColumn { items(phrases.itemCount) { CompositionLocalProvider( value = LocalTextToolbar provides EmptyTextToolbar { showTranslationDialog = true } ) { SelectionContainer { phrases[it]?.let { phrase -> ListItem( headlineContent = { Text( text = "${it + 1}. ${ phrase.context.phrase.removeSuffix( "//" ) }" ) }, supportingContent = { Column { Text( text = phrase.context.options.joinToString( separator = "\n" ) { option -> option.option + ". " + option.phrase }) Text(text = phrase.source) } } ) } } } } } } if (showTranslationDialog) TranslateDialog( onDismissRequest = { showTranslationDialog = false }, dismissButton = {} ) } }
vipexam/feature/wordlist/src/main/java/app/xlei/vipexam/feature/wordlist/components/TranslationSheet.kt
4277944015
package app.xlei.vipexam.feature.wordlist.components import android.annotation.SuppressLint import android.content.ClipData import android.content.ClipboardManager import android.content.Context import android.widget.Toast import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import app.xlei.vipexam.feature.wordlist.R import compose.icons.FeatherIcons import compose.icons.feathericons.Clipboard @Composable fun CopyToClipboardButton( modifier: Modifier = Modifier, text: String, ) { val context = LocalContext.current val string = stringResource(R.string.CopyToClipboardSuccess) fun copyToClipboard(word: String) { context.copyToClipboard(word) } IconButton( onClick = { copyToClipboard(text) Toast.makeText(context, "$text $string", Toast.LENGTH_LONG).show() }, modifier = modifier, ) { Icon( imageVector = FeatherIcons.Clipboard, contentDescription = null, ) } } @SuppressLint("ServiceCast") fun Context.copyToClipboard(text: CharSequence) { val clipboard = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager val clip = ClipData.newPlainText("label", text) clipboard.setPrimaryClip(clip) }
vipexam/feature/wordlist/src/main/java/app/xlei/vipexam/feature/wordlist/components/CopyToClipBoardButton.kt
1384371937
package app.xlei.vipexam.feature.wordlist.constant import app.xlei.vipexam.feature.wordlist.R enum class SortMethod(val method: Int) { OLD_TO_NEW(R.string.sort_by_old_to_new), NEW_TO_OLD(R.string.sort_by_new_to_old), A_TO_Z(R.string.sort_by_a_z), Z_TO_A(R.string.sort_by_z_a), }
vipexam/feature/wordlist/src/main/java/app/xlei/vipexam/feature/wordlist/constant/SortMethod.kt
1903604796
package app.xlei.vipexam.feature.bookmarks 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("app.xlei.vipexam.feature.bookmarks.test", appContext.packageName) } }
vipexam/feature/bookmarks/src/androidTest/java/app/xlei/vipexam/feature/bookmarks/ExampleInstrumentedTest.kt
1652261363
package app.xlei.vipexam.feature.bookmarks 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) } }
vipexam/feature/bookmarks/src/test/java/app/xlei/vipexam/feature/bookmarks/ExampleUnitTest.kt
2285093559
package app.xlei.vipexam.feature.bookmarks import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import app.xlei.vipexam.core.data.repository.BookmarkRepository import app.xlei.vipexam.core.database.module.Bookmark import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class BookmarksViewModel @Inject constructor( private val bookmarkRepository: BookmarkRepository ) : ViewModel() { private val _bookmarks = MutableStateFlow(emptyList<Bookmark>()) val bookmarks = _bookmarks.asStateFlow() private var _filter = MutableStateFlow("") val filter = _filter.asStateFlow() init { getBookmarks() } private fun getBookmarks() { viewModelScope.launch { bookmarkRepository .getAllBookmarks() .flowOn(Dispatchers.IO) .collect { bookmark: List<Bookmark> -> _bookmarks.update { if (_filter.value == "") bookmark else bookmark.filter { it.question == _filter.value } } } } } fun setFilter(question: String? = null) { _filter.update { question ?: "" } getBookmarks() } fun delete(index: Int) { viewModelScope.launch(Dispatchers.IO) { bookmarkRepository.deleteBookmark( _bookmarks.value[index] ) } } }
vipexam/feature/bookmarks/src/main/java/app/xlei/vipexam/feature/bookmarks/BookmarksViewModel.kt
3736653888
package app.xlei.vipexam.feature.bookmarks import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.background import androidx.compose.foundation.combinedClickable import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.statusBarsPadding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyRow import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.KeyboardArrowDown import androidx.compose.material.icons.filled.KeyboardArrowUp import androidx.compose.material3.AssistChip import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.FilterChip import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.LargeTopAppBar import androidx.compose.material3.ListItem import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.material3.TopAppBarDefaults import androidx.compose.material3.rememberTopAppBarState import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.input.nestedscroll.nestedScroll import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.hilt.navigation.compose.hiltViewModel import app.xlei.vipexam.core.ui.DateText import app.xlei.vipexam.core.ui.LoginAlert import compose.icons.FeatherIcons import compose.icons.feathericons.Menu @OptIn( ExperimentalMaterial3Api::class, ExperimentalFoundationApi::class, ) @Composable fun BookmarksScreen( modifier: Modifier = Modifier, viewModel: BookmarksViewModel = hiltViewModel(), openDrawer: () -> Unit, onBookmarkClick: (String,String) -> Boolean, ) { val bookmarksState by viewModel.bookmarks.collectAsState() val filter by viewModel.filter.collectAsState() val scrollBehavior = TopAppBarDefaults.exitUntilCollapsedScrollBehavior( rememberTopAppBarState() ) var showFilter by rememberSaveable { mutableStateOf(false) } var showLoginAlert by remember { mutableStateOf(false) } val questions = bookmarksState.map { it.question }.toSet() Scaffold( topBar = { LargeTopAppBar( title = { Text( stringResource(R.string.bookmarks) ) }, navigationIcon = { IconButton( onClick = openDrawer ) { Icon( imageVector = FeatherIcons.Menu, contentDescription = null, ) } }, scrollBehavior = scrollBehavior ) }, modifier = Modifier .background(MaterialTheme.colorScheme.background) .statusBarsPadding() .nestedScroll(scrollBehavior.nestedScrollConnection), ) { paddingValues -> Column( modifier = Modifier .padding(paddingValues) ) { LazyColumn { stickyHeader { Column( modifier = Modifier .fillMaxWidth() .background(MaterialTheme.colorScheme.background) ) { LazyRow { item { AssistChip( onClick = { showFilter = !showFilter }, label = { Text(text = stringResource(id = R.string.question)) }, trailingIcon = { Icon( imageVector = if (showFilter) { Icons.Default.KeyboardArrowUp } else { Icons.Default.KeyboardArrowDown }, contentDescription = null, ) }, modifier = Modifier .padding(horizontal = 8.dp) ) } } LazyRow { if (showFilter) questions.forEach { item { FilterChip( onClick = { when (filter) { it -> viewModel.setFilter() else -> viewModel.setFilter(it) } }, label = { Text(text = it) }, selected = it == filter, modifier = Modifier .padding(horizontal = 8.dp) ) } } } } } items(bookmarksState.size) { index -> ListItem( headlineContent = { Text(bookmarksState[index].question) }, supportingContent = { Text( text = bookmarksState[index].examName, style = MaterialTheme.typography.bodySmall, ) }, trailingContent = { DateText(bookmarksState[index].created) }, modifier = Modifier .combinedClickable( onClick = { showLoginAlert = onBookmarkClick .invoke( bookmarksState[index].examId, bookmarksState[index].question ).not() }, onLongClick = { viewModel.delete(index) } ) ) } item { if (bookmarksState.isEmpty()) Text( text = stringResource(R.string.empty_bookmarks_tips), textAlign = TextAlign.Center, modifier = Modifier .fillMaxSize() ) } } if (showLoginAlert) LoginAlert { showLoginAlert = false } } } }
vipexam/feature/bookmarks/src/main/java/app/xlei/vipexam/feature/bookmarks/BookmarksScreen.kt
26919229
package app.xlei.vipexam.feature.history 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("app.xlei.vipexam.feature.history.test", appContext.packageName) } }
vipexam/feature/history/src/androidTest/java/app/xlei/vipexam/feature/history/ExampleInstrumentedTest.kt
2012098225
package app.xlei.vipexam.feature.history 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) } }
vipexam/feature/history/src/test/java/app/xlei/vipexam/feature/history/ExampleUnitTest.kt
1693953276
package app.xlei.vipexam.feature.history import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.background import androidx.compose.foundation.combinedClickable import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.statusBarsPadding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.LargeTopAppBar import androidx.compose.material3.ListItem import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.material3.TopAppBarDefaults import androidx.compose.material3.rememberTopAppBarState import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.input.nestedscroll.nestedScroll import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextAlign import androidx.hilt.navigation.compose.hiltViewModel import app.xlei.vipexam.core.ui.DateText import app.xlei.vipexam.core.ui.LoginAlert import compose.icons.FeatherIcons import compose.icons.feathericons.Menu import compose.icons.feathericons.Trash2 @OptIn( ExperimentalMaterial3Api::class, ExperimentalFoundationApi::class, ) @Composable fun HistoryScreen( modifier: Modifier = Modifier, viewModel: HistoryViewModel = hiltViewModel(), openDrawer: () -> Unit, onHistoryClick: (String) -> Boolean, ) { val examHistoryState by viewModel.examHistory.collectAsState() val scrollBehavior = TopAppBarDefaults.exitUntilCollapsedScrollBehavior( rememberTopAppBarState() ) var showLoginAlert by remember { mutableStateOf(false) } Scaffold( topBar = { LargeTopAppBar( title = { Text( stringResource(R.string.history) ) }, navigationIcon = { IconButton( onClick = openDrawer ) { Icon( imageVector = FeatherIcons.Menu, contentDescription = null, ) } }, actions = { IconButton( onClick = { viewModel.cleanHistory() }, enabled = examHistoryState.isNotEmpty() ) { Icon(imageVector = FeatherIcons.Trash2, contentDescription = null) } }, scrollBehavior = scrollBehavior ) }, modifier = Modifier .background(MaterialTheme.colorScheme.background) .statusBarsPadding() .nestedScroll(scrollBehavior.nestedScrollConnection), ) { paddingValues -> Column( modifier = Modifier .padding(paddingValues) ) { LazyColumn { items(examHistoryState.size) { index -> ListItem( headlineContent = { Text(examHistoryState[index].examName) }, supportingContent = { DateText(examHistoryState[index].lastOpen) }, modifier = Modifier .combinedClickable( onClick = { showLoginAlert = onHistoryClick.invoke(examHistoryState[index].examId).not() }, onLongClick = { viewModel.delete(index) } ) ) } item { if (examHistoryState.isEmpty()) Text( text = stringResource(R.string.empty_history_tips), textAlign = TextAlign.Center, modifier = Modifier .fillMaxSize() ) } } if (showLoginAlert) LoginAlert { showLoginAlert = false } } } }
vipexam/feature/history/src/main/java/app/xlei/vipexam/feature/history/HistoryScreen.kt
657954324
package app.xlei.vipexam.feature.history import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import app.xlei.vipexam.core.data.repository.ExamHistoryRepository import app.xlei.vipexam.core.database.module.ExamHistory import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class HistoryViewModel @Inject constructor( private val examHistoryRepository: ExamHistoryRepository ) : ViewModel() { private val _examHistory = MutableStateFlow(emptyList<ExamHistory>()) val examHistory = _examHistory.asStateFlow() init { getExamHistory() } private fun getExamHistory() { viewModelScope.launch { examHistoryRepository .getAllExamHistory() .flowOn(Dispatchers.IO) .collect { examHistory: List<ExamHistory> -> _examHistory.update { examHistory } } } } fun cleanHistory() { viewModelScope.launch(Dispatchers.IO) { examHistoryRepository .removeAllHistory() } } fun delete(index: Int) { viewModelScope.launch(Dispatchers.IO) { examHistoryRepository .removeHistory(_examHistory.value[index]) } } }
vipexam/feature/history/src/main/java/app/xlei/vipexam/feature/history/HistoryViewModel.kt
1118662323
package com.project.seaBattle 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.project.seaBattle", appContext.packageName) } }
sea-battle/app/src/androidTest/java/com/project/seaBattle/ExampleInstrumentedTest.kt
835518946
package com.project.seaBattle 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) } }
sea-battle/app/src/test/java/com/project/seaBattle/ExampleUnitTest.kt
3711427116
package com.project.seaBattle.utils import android.content.Context import android.widget.Toast fun showToast( message: String, context: Context, ) { Toast.makeText(context, message, Toast.LENGTH_SHORT).show() }
sea-battle/app/src/main/java/com/project/seaBattle/utils/showToast.kt
1651745712
package com.project.seaBattle.utils import androidx.activity.OnBackPressedDispatcherOwner import androidx.activity.addCallback fun OnBackPressedDispatcherOwner.setupOnBackPressedCallback(onBackPressedAction: () -> Unit) { onBackPressedDispatcher.addCallback(this) { onBackPressedAction.invoke() } }
sea-battle/app/src/main/java/com/project/seaBattle/utils/setupOnBackPressedCallback.kt
2489669220
package com.project.seaBattle.logics.battle import android.annotation.SuppressLint import android.content.Context import android.graphics.Bitmap import android.graphics.BitmapFactory import android.graphics.Canvas import android.graphics.Rect import android.util.AttributeSet import android.view.MotionEvent import android.view.View import com.project.seaBattle.R import com.project.seaBattle.logics.board.BoardSide import com.project.seaBattle.logics.board.Cell import com.project.seaBattle.logics.board.GameBoard import com.project.seaBattle.logics.ship.Ship class BattleEditor(context: Context, attrs: AttributeSet?) : View(context, attrs) { var leftShips: MutableList<Ship>? = null var rightShips: MutableList<Ship>? = null private var rightBoard: GameBoard? = null private var leftBoard: GameBoard? = null private var currentGameBoard: GameBoard? = null private var currentShipsForCheck: MutableList<Ship>? = null private var lastDamagedShip: Ship? = null private var currentPlayerBitmap: Bitmap? = null private var currentPlayerImgRect: Rect? = null private var onGameOver: ((loser: BoardSide) -> Unit)? = null private val pressedCells: MutableList<Cell> = mutableListOf() override fun onDraw(canvas: Canvas) { super.onDraw(canvas) for (cell in pressedCells) { cell.drawClick(canvas) } currentPlayerBitmap?.let { currentPlayerImgRect?.let { rect -> canvas.drawBitmap(it, null, rect, null) } } } fun setLeftBoard(board: GameBoard) { leftBoard = board } fun setRightBoard(board: GameBoard) { rightBoard = board currentGameBoard = rightBoard currentShipsForCheck = rightShips initializeCurrentPlayerImg() } private fun initializeCurrentPlayerImg() { currentPlayerBitmap = BitmapFactory.decodeResource(context.resources, R.drawable.right_plays) currentGameBoard?.setBoardLimits(context) val cellSize = currentGameBoard?.cellSize val rightForRect = (rightBoard?.leftLimit!! - cellSize!!).toInt() val topForRect = ((currentGameBoard?.bottomLimit!! / 2) - (currentGameBoard?.topLimit!! / 2)).toInt() val leftForRect = rightForRect.minus(cellSize) val bottomForRect = topForRect.plus(2 * cellSize) currentPlayerImgRect = Rect(leftForRect, topForRect, rightForRect, bottomForRect) } private fun setCurrentBoard() { if (currentGameBoard == rightBoard) { currentGameBoard = leftBoard currentShipsForCheck = leftShips currentPlayerBitmap = BitmapFactory.decodeResource(context.resources, R.drawable.left_plays) } else { currentGameBoard = rightBoard currentShipsForCheck = rightShips currentPlayerBitmap = BitmapFactory.decodeResource(context.resources, R.drawable.right_plays) } } private fun checkHits(imgRect: Rect): Boolean { for (ship in currentShipsForCheck!!) { if (ship.checkHits(imgRect)) { lastDamagedShip = ship return true } } return false } private fun getCellImageRect( x: Float, y: Float, ): Rect { return Rect( x.toInt(), y.toInt(), (x + currentGameBoard!!.cellSize).toInt(), (y + currentGameBoard!!.cellSize).toInt(), ) } private fun addSurroundingCell(newCell: Cell) { val hasCellWithSameImgRect = pressedCells.any { it.imageRect.intersect(newCell.imageRect) } if (!hasCellWithSameImgRect) { pressedCells.add(newCell) } } private fun determineTheLoser() { currentGameBoard?.let { onGameOver?.invoke(it.side) } } fun setOnGameOver(listener: (winner: BoardSide) -> Unit) { onGameOver = listener } @SuppressLint("ClickableViewAccessibility") override fun onTouchEvent(event: MotionEvent): Boolean { when (event.action) { MotionEvent.ACTION_DOWN -> handleActionDown(event.x, event.y) } return true } private fun handleActionDown( x: Float, y: Float, ) { if (currentGameBoard!!.checkPressureWithinBoard(x, y)) { val xCord = currentGameBoard!!.getXCellCordForShip(x) val yCord = currentGameBoard!!.getYCellCordForShip(y) val cellImageRect = getCellImageRect(xCord!!, yCord!!) processCellClick(cellImageRect) } } private fun processCellClick(cellImageRect: Rect) { val isCellPressed = pressedCells.any { it.imageRect.intersect(cellImageRect) } if (!isCellPressed) { val isHit = checkHits(cellImageRect) pressedCells.add(Cell(cellImageRect, isHit, context)) if (isHit) { handleHit() } else { setCurrentBoard() } invalidate() } } private fun handleHit() { if (lastDamagedShip!!.checkDestruction()) { handleShipDestruction() } } private fun handleShipDestruction() { val surroundingCells = lastDamagedShip!!.getSurroundingCells() for (surroundingCellImageRect in surroundingCells) { if (currentGameBoard!!.checkImgRectWithinBoard(surroundingCellImageRect)) { addSurroundingCell(Cell(surroundingCellImageRect, false, context)) } } currentShipsForCheck?.remove(lastDamagedShip!!) val shipsList = if (currentGameBoard == rightBoard) rightShips else leftShips shipsList?.remove(lastDamagedShip!!) if (rightShips?.isEmpty() == true || leftShips?.isEmpty() == true) { determineTheLoser() } } }
sea-battle/app/src/main/java/com/project/seaBattle/logics/battle/BattleEditor.kt
2642921899
package com.project.seaBattle.logics.board import android.content.Context import android.graphics.Bitmap import android.graphics.BitmapFactory import android.graphics.Canvas import android.graphics.Paint import android.graphics.Rect import com.project.seaBattle.R import com.project.seaBattle.logics.ship.ShipOrientation class GameBoard(val side: BoardSide) { var leftLimit: Float = 0.0f var topLimit: Float = 0.0f var cellSize: Int = 0 var bottomLimit: Float = 0.0f var startXForPlacementShips: Int? = 0 private var rightLimit: Float = 0.0f private var screenHeight: Float? = 0f private var lettersBitmap: Bitmap? = null private var numbersBitmap: Bitmap? = null private var lettersImgRect: Rect? = null private var numbersImgRect: Rect? = null private val verticalLines = mutableListOf<Float>() private val horizontalLines = mutableListOf<Float>() private val cellsNumberInRow: Int = 10 fun setBoardLimits(context: Context) { val displayMetrics = context.resources.displayMetrics val screenWidth = displayMetrics.widthPixels.toFloat() val centerInWidth = screenWidth / 2 screenHeight = displayMetrics.heightPixels.toFloat() val boardSize = calculateBoardSize(screenHeight!!) lettersBitmap = BitmapFactory.decodeResource(context.resources, R.drawable.letters) numbersBitmap = BitmapFactory.decodeResource(context.resources, R.drawable.numbers) setLimitsAndStartX(centerInWidth, boardSize, screenWidth) cellSize = calculateCellSize() setImgRectForImages() createLinesForBoard() } private fun calculateBoardSize(screenHeight: Float): Float { val indentFromTopPercentage = 0.1f val bottomBoardIndentFromTopPercentage = 0.8f return screenHeight * bottomBoardIndentFromTopPercentage - screenHeight * indentFromTopPercentage } private fun setLimitsAndStartX( centerInWidth: Float, boardSize: Float, screenWidth: Float, ) { val indentBoardFromCenterPercentage = 0.05f if (side == BoardSide.RIGHT) { leftLimit = centerInWidth + screenWidth * indentBoardFromCenterPercentage startXForPlacementShips = (centerInWidth - screenWidth * indentBoardFromCenterPercentage - boardSize).toInt() } else { leftLimit = centerInWidth - screenWidth * indentBoardFromCenterPercentage - boardSize startXForPlacementShips = (centerInWidth + screenWidth * indentBoardFromCenterPercentage).toInt() } topLimit = screenHeight!! / 2 - boardSize / cellsNumberInRow - boardSize / 2 rightLimit = leftLimit + boardSize bottomLimit = topLimit + boardSize } private fun calculateCellSize(): Int { return ((rightLimit - leftLimit) / cellsNumberInRow).toInt() } private fun setImgRectForImages() { val imgDisplacementCf = 1.2f val leftForLettersImgRect = (leftLimit - imgDisplacementCf * cellSize).toInt() val topForNumbersImgRect = (topLimit - imgDisplacementCf * cellSize).toInt() lettersImgRect = Rect(leftForLettersImgRect, topLimit.toInt(), leftForLettersImgRect + cellSize, bottomLimit.toInt()) numbersImgRect = Rect(leftLimit.toInt(), topForNumbersImgRect, rightLimit.toInt(), topForNumbersImgRect + cellSize) } private fun createLinesForBoard() { val lineCountInOnePlane = 9 val boardWidth = rightLimit - leftLimit val colsSize = boardWidth / cellsNumberInRow var verticalLineStartX = leftLimit var horizontalLineStartY = topLimit for (i in 0..lineCountInOnePlane) { verticalLines.add(verticalLineStartX) horizontalLines.add(horizontalLineStartY) verticalLineStartX += colsSize horizontalLineStartY += colsSize } verticalLines.add(rightLimit) horizontalLines.add(bottomLimit) } fun checkPressureWithinBoard( x: Float, y: Float, ): Boolean { return (x in leftLimit..rightLimit && y in topLimit..bottomLimit) } fun checkImgRectWithinBoard(cellImgRect: Rect): Boolean { val boardRect = Rect(leftLimit.toInt(), topLimit.toInt(), rightLimit.toInt(), bottomLimit.toInt()) return cellImgRect.intersect((boardRect)) } fun drawBoard( canvas: Canvas, paint: Paint, ) { for (line in verticalLines) canvas.drawLine(line, topLimit, line, bottomLimit, paint) for (line in horizontalLines) canvas.drawLine(leftLimit, line, rightLimit, line, paint) lettersBitmap?.let { lettersImgRect?.let { rect -> canvas.drawBitmap(it, null, rect, null) } } numbersBitmap?.let { numbersImgRect?.let { rect -> canvas.drawBitmap(it, null, rect, null) } } } fun getXCellCordForShip(x: Float): Float? { val rightVerticalLineOfCell = verticalLines.find { it > x } return rightVerticalLineOfCell?.minus(cellSize) } fun getYCellCordForShip(y: Float): Float? { val lowerHorizontalLineOfCell = horizontalLines.find { it > y } return lowerHorizontalLineOfCell?.minus(cellSize) } fun getShipDisplacement( x: Float, y: Float, shipLength: Int, shipPosition: ShipOrientation, ): Float { val permissibleLine: Float var shipDisplacement = 0f val linesForCheck = if (shipPosition == ShipOrientation.HORIZONTAL) verticalLines else horizontalLines val numberPermissibleLine = linesForCheck.size - shipLength permissibleLine = linesForCheck[numberPermissibleLine] val cellCord = if (shipPosition == ShipOrientation.HORIZONTAL) getXCellCordForShip(x) else getYCellCordForShip(y) if (cellCord!! - permissibleLine > 0) shipDisplacement = cellCord - permissibleLine + cellSize return shipDisplacement } }
sea-battle/app/src/main/java/com/project/seaBattle/logics/board/GameBoard.kt
127135960
package com.project.seaBattle.logics.board enum class BoardSide { RIGHT, LEFT, }
sea-battle/app/src/main/java/com/project/seaBattle/logics/board/BoardSide.kt
704683384
package com.project.seaBattle.logics.board import android.content.Context import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.util.AttributeSet import android.view.View class DrawingBoard(context: Context, attrs: AttributeSet?) : View(context, attrs) { private val paint = Paint() private var rightBoard: GameBoard? = null private var leftBoard: GameBoard? = null init { paint.color = Color.BLACK paint.strokeWidth = 10f paint.style = Paint.Style.STROKE paint.isAntiAlias = true } fun setBoard(board: GameBoard) { if (board.side == BoardSide.RIGHT) { rightBoard = board } else { leftBoard = board } } override fun onDraw(canvas: Canvas) { super.onDraw(canvas) if (rightBoard != null) { rightBoard?.setBoardLimits(context) rightBoard?.drawBoard(canvas, paint) } if (leftBoard != null) { leftBoard?.setBoardLimits(context) leftBoard?.drawBoard(canvas, paint) } } }
sea-battle/app/src/main/java/com/project/seaBattle/logics/board/DrawingBoard.kt
1296736199
package com.project.seaBattle.logics.board import android.content.Context import android.graphics.Bitmap import android.graphics.BitmapFactory import android.graphics.Canvas import android.graphics.Rect import com.project.seaBattle.R class Cell(val imageRect: Rect, private val isHit: Boolean, context: Context) { private var bitmapMiss: Bitmap? = null private var bitmapHit: Bitmap? = null init { bitmapMiss = BitmapFactory.decodeResource(context.resources, R.drawable.miss) bitmapHit = BitmapFactory.decodeResource(context.resources, R.drawable.hit) } private fun drawMiss(canvas: Canvas) { bitmapMiss?.let { imageRect.let { rect -> canvas.drawBitmap(it, null, rect, null) } } } private fun drawHit(canvas: Canvas) { bitmapHit?.let { imageRect.let { rect -> canvas.drawBitmap(it, null, rect, null) } } } fun drawClick(canvas: Canvas) { if (isHit) { drawHit(canvas) } else { drawMiss(canvas) } } }
sea-battle/app/src/main/java/com/project/seaBattle/logics/board/Cell.kt
1857626112
package com.project.seaBattle.logics.ship import android.content.Context import android.graphics.Bitmap import android.graphics.BitmapFactory import android.graphics.Canvas import android.graphics.Matrix import android.graphics.Rect import com.project.seaBattle.R class Ship(private val context: Context, resourceId: Int, private val cellSize: Int) { var currentX: Int = 0 var currentY: Int = 0 var startX: Int = 0 var startY: Int = 0 var imageRect: Rect? = null var shipLength: Int = 0 var shipPosition: ShipOrientation = ShipOrientation.HORIZONTAL private var bitmap: Bitmap? = null private var constantForShipSize: Float = 0.0f private var remainingCells: Int = 0 init { bitmap = BitmapFactory.decodeResource(context.resources, resourceId) setConstants() setStartPosition() } private fun setConstants() { val smallestShip = BitmapFactory.decodeResource(context.resources, R.drawable.ship_single) constantForShipSize = smallestShip.width.toFloat() shipLength = (bitmap!!.width / constantForShipSize).toInt() remainingCells = shipLength } fun draw(canvas: Canvas) { bitmap?.let { imageRect?.let { rect -> canvas.drawBitmap(it, null, rect, null) } } } fun setStartPosition() { if (shipPosition == ShipOrientation.VERTICAL) setShipHorizontal() val width = cellSize * shipLength imageRect = Rect( startX, startY, startX + width, startY + cellSize, ) } private fun setShipVertical() { shipPosition = ShipOrientation.VERTICAL bitmap?.let { val matrix = Matrix() matrix.postRotate(90f) bitmap = Bitmap.createBitmap(it, 0, 0, it.width, it.height, matrix, true) } } private fun setShipHorizontal() { shipPosition = ShipOrientation.HORIZONTAL bitmap?.let { val matrix = Matrix() matrix.postRotate(-90f) bitmap = Bitmap.createBitmap(it, 0, 0, it.width, it.height, matrix, true) } } fun toggleShipOrientation() { if (shipPosition == ShipOrientation.HORIZONTAL) { setShipVertical() } else { setShipHorizontal() } } private fun getUnavailableSpace(): Rect { return Rect( imageRect!!.left - cellSize / 2, imageRect!!.top - cellSize / 2, imageRect!!.right + cellSize, imageRect!!.bottom + cellSize, ) } fun checkNeighborhoods(shipSpace: Rect): Boolean { return shipSpace.intersect(getUnavailableSpace()) } fun checkHits(cellImgRect: Rect): Boolean { val isHit = cellImgRect.intersect(imageRect!!) if (isHit) remainingCells-- return isHit } fun checkDestruction(): Boolean { return remainingCells == 0 } fun moveShipTo( x: Int, y: Int, ) { currentX = x currentY = y } private fun calculateOutermostCells(): Pair<Rect, Rect> { val width = shipLength * cellSize return if (shipPosition == ShipOrientation.HORIZONTAL) { Pair( Rect(currentX - cellSize, currentY, currentX, currentY + cellSize), Rect(currentX + width, currentY, currentX + width + cellSize, currentY + cellSize), ) } else { Pair( Rect(currentX, currentY - cellSize, currentX + cellSize, currentY), Rect(currentX, currentY + width, currentX + cellSize, currentY + width + cellSize), ) } } private fun addCellsToList( cellsList: MutableList<Rect>, firstOutermostCell: Rect, secondOutermostCell: Rect, ) { cellsList.add(firstOutermostCell) cellsList.add(secondOutermostCell) } private fun addSurroundingCells( cellsList: MutableList<Rect>, outermostCell: Rect, isHorizontal: Boolean, ) { val left = outermostCell.left val right = outermostCell.right val top = outermostCell.top val bottom = outermostCell.bottom for (cell in 0 until shipLength + 2) { val leftOffset = left + cell * cellSize val rightOffset = right + cell * cellSize val topOffset = top + cell * cellSize val bottomOffset = bottom + cell * cellSize if (isHorizontal) { cellsList.add(Rect(leftOffset, currentY - cellSize, rightOffset, currentY)) cellsList.add(Rect(leftOffset, currentY + cellSize, rightOffset, currentY + 2 * cellSize)) } else { cellsList.add(Rect(currentX - cellSize, topOffset, currentX, bottomOffset)) cellsList.add(Rect(currentX + cellSize, topOffset, currentX + 2 * cellSize, bottomOffset)) } } } fun getSurroundingCells(): MutableList<Rect> { val surroundingCells = mutableListOf<Rect>() val (firstOutermostCell, secondOutermostCell) = calculateOutermostCells() addCellsToList(surroundingCells, firstOutermostCell, secondOutermostCell) addSurroundingCells(surroundingCells, firstOutermostCell, shipPosition == ShipOrientation.HORIZONTAL) return surroundingCells } }
sea-battle/app/src/main/java/com/project/seaBattle/logics/ship/Ship.kt
3342669311
package com.project.seaBattle.logics.ship enum class ShipOrientation { HORIZONTAL, VERTICAL, }
sea-battle/app/src/main/java/com/project/seaBattle/logics/ship/ShipOrientation.kt
1845722267
package com.project.seaBattle.logics.shipsSetting import android.annotation.SuppressLint import android.content.Context import android.graphics.Canvas import android.util.AttributeSet import android.view.MotionEvent import android.view.View import com.project.seaBattle.R import com.project.seaBattle.logics.board.GameBoard import com.project.seaBattle.logics.ship.Ship import com.project.seaBattle.logics.ship.ShipOrientation class ShipsSetter(context: Context, attrs: AttributeSet?) : View(context, attrs) { var gameBoard: GameBoard? = null val ships = mutableListOf<Ship>() private var movingShip: Ship? = null private var touchX = 0f private var touchY = 0f private var cellSize: Int = 0 private var shipCapsizes: Boolean = false private var xUntilMoving = 0 private var yUntilMoving = 0 fun initializeShips() { gameBoard?.setBoardLimits(context) cellSize = gameBoard?.cellSize!! addShips(R.drawable.ship_single, 4, cellSize) addShips(R.drawable.ship_double, 3, cellSize) addShips(R.drawable.ship_triple, 2, cellSize) addShips(R.drawable.ship_fourfold, 1, cellSize) } private fun addShips( resourceId: Int, count: Int, cellSize: Int, ) { val yIndentFromBoardTop = 50f val startY = (gameBoard?.topLimit!! + yIndentFromBoardTop).toInt() val startX = gameBoard?.startXForPlacementShips var distanceMultiplier = 0 repeat(count) { val newShip = Ship(context, resourceId, cellSize) val shipTypesNumber = 4 newShip.currentY = startY + ((shipTypesNumber - count) * cellSize * 2) val xDistanceBetweenShips = 7 - count if (startX != null) newShip.currentX = startX + distanceMultiplier * cellSize * xDistanceBetweenShips newShip.startX = newShip.currentX newShip.startY = newShip.currentY newShip.setStartPosition() ships.add(newShip) distanceMultiplier++ } } private fun checkPossibilityInstallingShip(): Boolean { var falseCount = 0 for (ship in ships) { movingShip?.imageRect?.let { if (ship.checkNeighborhoods(it)) { falseCount++ if (falseCount == 2) return false } } } return true } fun areAllShipsInstalled(): Boolean { for (ship in ships) { if (ship.imageRect?.let { gameBoard?.checkImgRectWithinBoard(it) } != true) { return false } } return true } private fun handleShipMovement( ship: Ship, touchX: Float, touchY: Float, ) { val displacement = gameBoard?.getShipDisplacement(touchX, touchY, ship.shipLength, ship.shipPosition) ship.currentX = gameBoard?.getXCellCordForShip(touchX)?.toInt()!! ship.currentY = gameBoard?.getYCellCordForShip(touchY)?.toInt()!! if (ship.shipPosition == ShipOrientation.HORIZONTAL) { ship.currentX -= displacement!!.toInt() } else { ship.currentY -= displacement!!.toInt() } } private fun updateImageRect(ship: Ship) { val width = if (ship.shipPosition == ShipOrientation.HORIZONTAL) cellSize * ship.shipLength else cellSize val height = if (ship.shipPosition == ShipOrientation.HORIZONTAL) cellSize else cellSize * ship.shipLength ship.imageRect?.set(ship.currentX, ship.currentY, ship.currentX + width, ship.currentY + height) } override fun onDraw(canvas: Canvas) { super.onDraw(canvas) for (ship in ships) { ship.draw(canvas) } } @SuppressLint("ClickableViewAccessibility") override fun onTouchEvent(event: MotionEvent): Boolean { touchX = event.x touchY = event.y when (event.action) { MotionEvent.ACTION_DOWN -> { shipCapsizes = true for (ship in ships) { if (ship.imageRect!!.contains(touchX.toInt(), touchY.toInt())) { movingShip = ship movingShip?.let { xUntilMoving = it.currentX yUntilMoving = it.currentY it.currentX = touchX.toInt() it.currentY = touchY.toInt() } } } } MotionEvent.ACTION_MOVE -> { shipCapsizes = false movingShip?.let { val deltaX = touchX.toInt() - it.currentX val deltaY = touchY.toInt() - it.currentY val width = if (it.shipPosition == ShipOrientation.HORIZONTAL) cellSize * it.shipLength else cellSize val height = if (it.shipPosition == ShipOrientation.HORIZONTAL) cellSize else cellSize * it.shipLength it.currentX += deltaX it.currentY += deltaY it.imageRect!!.set( it.currentX, it.currentY, it.currentX + width, it.currentY + height, ) } invalidate() } MotionEvent.ACTION_UP -> { if (gameBoard!!.checkPressureWithinBoard(touchX, touchY)) { movingShip?.let { if (!checkPossibilityInstallingShip()) { it.moveShipTo(xUntilMoving, yUntilMoving) } else { if (gameBoard?.checkPressureWithinBoard(touchX, touchY) == true) { handleShipMovement(it, touchX, touchY) if (shipCapsizes) { it.toggleShipOrientation() handleShipMovement(it, touchX, touchY) } updateImageRect(it) if (!checkPossibilityInstallingShip()) { if (shipCapsizes) it.toggleShipOrientation() it.moveShipTo(xUntilMoving, yUntilMoving) } } } updateImageRect(it) } } else { movingShip?.setStartPosition() } invalidate() } } return true } }
sea-battle/app/src/main/java/com/project/seaBattle/logics/shipsSetting/ShipsSetter.kt
3023537595
package com.project.seaBattle.logics.shipsSetting import com.project.seaBattle.logics.board.BoardSide import com.project.seaBattle.logics.ship.Ship class GameInfoManager private constructor() { var rightPlayerName: String? = null var winnerName: String? = null val rightShips: MutableList<Ship> = mutableListOf() val leftShips: MutableList<Ship> = mutableListOf() var leftPlayerName: String? = null fun addShips( ships: MutableList<Ship>, side: BoardSide, ) { if (side == BoardSide.RIGHT) { rightShips.addAll(ships) } else { leftShips.addAll(ships) } } fun setPlayerName( name: String, side: BoardSide, ) { if (side == BoardSide.RIGHT) { rightPlayerName = name } else { leftPlayerName = name } } fun resetAllInfo() { rightShips.clear() leftShips.clear() leftPlayerName = null rightPlayerName = null winnerName = null } companion object { private var instance: GameInfoManager? = null fun getInstance(): GameInfoManager { if (instance == null) { instance = GameInfoManager() } return instance!! } } }
sea-battle/app/src/main/java/com/project/seaBattle/logics/shipsSetting/GameInfoManager.kt
783446715
package com.project.seaBattle.dialogs import android.app.Dialog import android.content.Intent import android.graphics.Color import android.graphics.drawable.ColorDrawable import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.Window import androidx.fragment.app.DialogFragment import com.project.seaBattle.activities.StartActivity import com.project.seaBattle.databinding.DialogWinnerLayoutBinding class ShowingWinnerDialog(private val winnerName: String) : DialogFragment() { @Suppress("ktlint:standard:property-naming") private var _binding: DialogWinnerLayoutBinding? = null private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?, ): View { _binding = DialogWinnerLayoutBinding.inflate(inflater, container, false) val view = binding.root binding.winner.text = winnerName binding.returnStartActivity.setOnClickListener { val intent = Intent(context, StartActivity::class.java) startActivity(intent) } return view } override fun onDestroyView() { super.onDestroyView() _binding = null } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val dialog = super.onCreateDialog(savedInstanceState) dialog.requestWindowFeature(Window.FEATURE_NO_TITLE) dialog.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT)) return dialog } }
sea-battle/app/src/main/java/com/project/seaBattle/dialogs/ShowingWinnerDialog.kt
1461186359
package com.project.seaBattle.dialogs import android.app.Dialog import android.graphics.Color import android.graphics.drawable.ColorDrawable import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.Window import androidx.fragment.app.DialogFragment import com.project.seaBattle.databinding.DialogPlayerNameLayoutBinding class PlayerNameDialog : DialogFragment() { @Suppress("ktlint:standard:property-naming") private var _binding: DialogPlayerNameLayoutBinding? = null private var onNameEntered: ((name: String) -> Unit)? = null private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?, ): View { _binding = DialogPlayerNameLayoutBinding.inflate(inflater, container, false) val view = binding.root binding.saveName.setOnClickListener { onNameEntered?.invoke(binding.enterName.text.toString()) dismiss() } return view } override fun onDestroyView() { super.onDestroyView() _binding = null } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val dialog = super.onCreateDialog(savedInstanceState) dialog.requestWindowFeature(Window.FEATURE_NO_TITLE) dialog.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT)) return dialog } fun setOnNameEntered(listener: (name: String) -> Unit) { onNameEntered = listener } }
sea-battle/app/src/main/java/com/project/seaBattle/dialogs/PlayerNameDialog.kt
137357977
package com.project.seaBattle.activities import android.content.Intent import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.project.seaBattle.databinding.ActivityMainBinding import com.project.seaBattle.logics.board.BoardSide import com.project.seaBattle.logics.shipsSetting.GameInfoManager import com.project.seaBattle.utils.showToast class StartActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) val view = binding.root setContentView(view) val gameInfoManager = GameInfoManager.getInstance() binding.player1Button.setOnClickListener { if (gameInfoManager.leftShips.isNotEmpty()) { showToast("The ships for the first player are already installed", this) } else { val intent = Intent(this, SetShipsActivity::class.java) intent.putExtra("SIDE", BoardSide.LEFT.name) startActivity(intent) } } binding.player2Button.setOnClickListener { if (gameInfoManager.rightShips.isNotEmpty()) { showToast("The ships for the second player are already installed", this) } else { val intent = Intent(this, SetShipsActivity::class.java) intent.putExtra("SIDE", BoardSide.RIGHT.name) startActivity(intent) } } binding.startButton.setOnClickListener { if (gameInfoManager.leftShips.isNotEmpty() && gameInfoManager.rightShips.isNotEmpty()) { val intent = Intent(this, BattleActivity::class.java) startActivity(intent) } else { showToast("Ships are not installed for all players", this) } } binding.resetInfo.setOnClickListener { gameInfoManager.resetAllInfo() } } }
sea-battle/app/src/main/java/com/project/seaBattle/activities/StartActivity.kt
2180414811
package com.project.seaBattle.activities import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.project.seaBattle.databinding.ActivityBattleBinding import com.project.seaBattle.dialogs.ShowingWinnerDialog import com.project.seaBattle.logics.board.BoardSide import com.project.seaBattle.logics.board.GameBoard import com.project.seaBattle.logics.shipsSetting.GameInfoManager import com.project.seaBattle.utils.setupOnBackPressedCallback import com.project.seaBattle.utils.showToast class BattleActivity : AppCompatActivity() { private lateinit var binding: ActivityBattleBinding private val leftGameBoard = GameBoard(BoardSide.LEFT) private val rightGameBoard = GameBoard(BoardSide.RIGHT) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityBattleBinding.inflate(layoutInflater) val view = binding.root setContentView(view) setupGame() setupOnBackPressedCallback { showToast("This button does not work in the game", this) } } private fun setupGame() { val gameInfoManager = GameInfoManager.getInstance() binding.drawingBoard.setBoard(rightGameBoard) binding.drawingBoard.setBoard(leftGameBoard) binding.firstPlayerName.text = gameInfoManager.leftPlayerName binding.secondPlayerName.text = gameInfoManager.rightPlayerName binding.battleEditor.leftShips = gameInfoManager.leftShips binding.battleEditor.rightShips = gameInfoManager.rightShips binding.battleEditor.setRightBoard(rightGameBoard) binding.battleEditor.setLeftBoard(leftGameBoard) binding.battleEditor.setOnGameOver { loser -> gameInfoManager.winnerName = if (loser == BoardSide.RIGHT) gameInfoManager.leftPlayerName else gameInfoManager.rightPlayerName gameInfoManager.winnerName?.let { val showingWinnerDialog = ShowingWinnerDialog(it) showingWinnerDialog.show(supportFragmentManager, "ShowingWinnerDialog") } gameInfoManager.resetAllInfo() } } }
sea-battle/app/src/main/java/com/project/seaBattle/activities/BattleActivity.kt
994047204
package com.project.seaBattle.activities import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.project.seaBattle.databinding.ActivitySetShipsBinding import com.project.seaBattle.dialogs.PlayerNameDialog import com.project.seaBattle.logics.board.BoardSide import com.project.seaBattle.logics.board.GameBoard import com.project.seaBattle.logics.shipsSetting.GameInfoManager import com.project.seaBattle.utils.setupOnBackPressedCallback import com.project.seaBattle.utils.showToast class SetShipsActivity : AppCompatActivity() { private lateinit var binding: ActivitySetShipsBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivitySetShipsBinding.inflate(layoutInflater) val view = binding.root setContentView(view) val boardSideName = intent.getStringExtra("SIDE") val boardSide = boardSideName?.let { BoardSide.valueOf(it) } val gameBoard = boardSide?.let { GameBoard(it) } val gameInfoManager = GameInfoManager.getInstance() val playerNameDialog = PlayerNameDialog() playerNameDialog.show(supportFragmentManager, "PlayerNameDialog") playerNameDialog.setOnNameEntered { name -> gameInfoManager.setPlayerName(name, boardSide!!) } binding.drawingBoard.setBoard(gameBoard!!) binding.shipsSetter.gameBoard = gameBoard binding.shipsSetter.initializeShips() binding.shipsInstalled.setOnClickListener { if (binding.shipsSetter.areAllShipsInstalled()) { gameInfoManager.addShips(binding.shipsSetter.ships, boardSide) finish() } else { showToast("Not all ships are installed", this) } } setupOnBackPressedCallback { showToast("This button does not work in the game", this) } } }
sea-battle/app/src/main/java/com/project/seaBattle/activities/SetShipsActivity.kt
2197241071
package com.example.onelab_homework 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.onelab_homework", appContext.packageName) } }
One_Homework/app/src/androidTest/java/com/example/onelab_homework/ExampleInstrumentedTest.kt
591914039
package com.example.onelab_homework 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) } }
One_Homework/app/src/test/java/com/example/onelab_homework/ExampleUnitTest.kt
3046694333
package com.example.onelab_homework.database import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.ForeignKey import androidx.room.Index import androidx.room.PrimaryKey import com.example.homework.book.Book import java.util.PriorityQueue @Entity(tableName = "book") public class BookDbEntity( @PrimaryKey(autoGenerate = true) val id:Long, @ColumnInfo(name ="name") val name:String, @ColumnInfo(name ="description") var descr :String, @ColumnInfo(name ="price") var imageUrl:String , @ColumnInfo(name ="isFavorite") var isFavorite:Boolean ) { fun toBook(): Book { BookDbEntity return Book( id =id, name =name, descr =descr, imageUrl =imageUrl, isFavorite= isFavorite ) } companion object { fun toDbEntity(book: Book): BookDbEntity { return BookDbEntity( name = book.name, descr = book.descr, imageUrl = book.imageUrl, id = book.id, isFavorite = book.isFavorite ) } fun toBook(bookDbEntity: BookDbEntity): Book { return Book( id = bookDbEntity.id, name = bookDbEntity.name, descr = bookDbEntity.descr, imageUrl =bookDbEntity.imageUrl, isFavorite =bookDbEntity.isFavorite ) } } }
One_Homework/app/src/main/java/com/example/onelab_homework/database/BookDbEntity.kt
2870244021
package com.example.onelab_homework.database import androidx.room.Database import androidx.room.Index import androidx.room.RoomDatabase import androidx.room.TypeConverters @Database( version = 1, entities = [BookDbEntity::class ] ) //@TypeConverters(BookConverters::class ) abstract class AppDatabase:RoomDatabase() { abstract fun getBookDao():BookDao }
One_Homework/app/src/main/java/com/example/onelab_homework/database/AppDatabase.kt
3258453640
package com.example.onelab_homework.database import androidx.room.Dao import androidx.room.Insert import androidx.room.Query import com.example.homework.book.Book @Dao interface BookDao { @Query("Select * from book") suspend fun getAllBooks():List<BookDbEntity>? @Insert suspend fun addBook(books:BookDbEntity) @Query("Delete from book") suspend fun deleteAll() @Query("UPDATE book SET isFavorite =:isFavorite where name =:name") suspend fun changeFavorite(name:String ,isFavorite:Boolean) @Query("Select * from book where isFavorite =1") suspend fun getAllFavorites() :List<BookDbEntity>? }
One_Homework/app/src/main/java/com/example/onelab_homework/database/BookDao.kt
191117691
package com.example.onelab_homework.database import com.example.homework.book.Book import com.example.onelab_homework.book.Resource interface BooksRepository { suspend fun getBooks(text:String): Resource<List<Book>> suspend fun getBooksFromCache():List<Book>? suspend fun addBookToCache(books:List<Book>) suspend fun getFavoritesBook():List<Book> suspend fun addFavoriteBook(book: Book) suspend fun getAllBooks():List<Book> //clear cache suspend fun deleteAllBooks() suspend fun changeFavorite(name:String ,isFavorite:Boolean) suspend fun getAllFavorites():List<Book> }
One_Homework/app/src/main/java/com/example/onelab_homework/database/BooksRepository.kt
1752145813
package com.example.onelab_homework.database import android.util.Log import com.example.homework.book.Book import com.example.homework.book.BookApi import com.example.onelab_homework.book.Resource class BooksRepositoryImpl(val api: BookApi, val bookDao:BookDao): BooksRepository { override suspend fun getBooks(text:String): Resource<List<Book>> { val response = try { val ss =api.getBooksByQuery(text) val resp = mutableListOf<Book>() Log.d("12132321132","${ss.toString()} ") Log.d("12132321132","${ss.items.size} ") ss.items[0].volumeInfo.title ss.items[0].volumeInfo.description for(a in 0 until 8){ Log.d("12132321132" ,ss.items.get(a).volumeInfo.imageLinks.smallThumbnail) Log.d("12132321132" ,ss.items.get(a).volumeInfo.title) Log.d("12132321132" ,ss.items.get(a).volumeInfo.description ?: "No descr") val sub =ss.items.get(a).volumeInfo.imageLinks.smallThumbnail.substring(4) val s = Book(id = 0, imageUrl = "https${sub}", name =ss.items[a].volumeInfo.title, descr = ss.items[a].volumeInfo.description ?: "No description", isFavorite = false ) resp.add(s) } Log.d("12132321132","what") return Resource.Success(resp) } catch(e: Exception) { Log.d("12132321132" ,e.toString()) return Resource.Error("An unknown error occured.") } return Resource.Loading() // // // call.enqueue(object : Callback<BookResponse> { // override fun onResponse(call: Call<BookResponse>, response: Response<BookResponse>) { // if (response.isSuccessful) { // val bookResponse = response.body() // response // for(a in 0 until bookResponse!!.items.size){ // listOfBook.add(Book( // bookResponse.items.get(a).volumeInfo.imageLinks.thumbnail // ) // // ) // } // } else { // Log.d("LOGGING", "ERROR") // // Handle error // } // } // // override fun onFailure(call: Call<BookResponse>, t: Throwable) { // Log.d("LOGGING", "Failiare") // } // }) // return listOfBook } override suspend fun getBooksFromCache(): List<Book>? { val sss =bookDao.getAllBooks()!!.map { BookDbEntity -> BookDbEntity.toBook() } return sss TODO("Not yet implemented") } override suspend fun addBookToCache(books: List<Book>) { val bookDbEntities = mutableListOf<BookDbEntity>() for(a in 0 until books.size){ bookDbEntities.add(BookDbEntity.toDbEntity(books[a])) } for(b in 0 until books.size){ bookDao.addBook(bookDbEntities[b]) } Log.d("32132123", "books.added") } override suspend fun getFavoritesBook(): List<Book> { //return bookDao.getFavoritesBooks().map { BookDbEntity -> BookDbEntity.toBook() } return listOf() } override suspend fun addFavoriteBook(book: Book) { // bookDao.addFavorites(BookDbEntity(book.id ,book.name ,book.descr ,book.imageUrl)) } override suspend fun getAllBooks(): List<Book> { TODO("Not yet implemented") } override suspend fun deleteAllBooks() { bookDao.deleteAll() } override suspend fun changeFavorite(name:String ,isFavorite:Boolean) { bookDao.changeFavorite(name,isFavorite) } override suspend fun getAllFavorites(): List<Book> { val books =bookDao.getAllFavorites() if(books==null){ return listOf() } else{ return bookDao.getAllFavorites()!!.map { BookDbEntity -> BookDbEntity.toBook() } } } }
One_Homework/app/src/main/java/com/example/onelab_homework/database/BooksRepositoryImpl.kt
1348254774
package com.example.onelab_homework import android.Manifest import android.app.NotificationChannel import android.app.NotificationManager import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.os.Build import androidx.core.app.NotificationCompat import androidx.core.app.ActivityCompat import androidx.core.app.NotificationManagerCompat class MyReceiver : BroadcastReceiver() { override fun onReceive( context: Context, intent: Intent) { } }
One_Homework/app/src/main/java/com/example/onelab_homework/MyReceiver.kt
3207311045
package com.example.onelab_homework import android.app.NotificationChannel import android.app.NotificationManager import android.content.Context import android.os.Build import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import androidx.room.Room import com.example.homework.book.BookApi import com.example.onelab_homework.database.BooksRepository import com.example.onelab_homework.database.AppDatabase import com.example.onelab_homework.database.BooksRepositoryImpl import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory object App { lateinit var applicationContext: Context fun init(context:Context){ applicationContext =context } val retrofit = Retrofit.Builder() .baseUrl(BookApi.BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build() private val database1: AppDatabase by lazy<AppDatabase> { Room.databaseBuilder(applicationContext, AppDatabase::class.java, "database.db") // .createFromAsset("initial_database.db") .build() } private val bookApi = retrofit.create(BookApi::class.java) val booksRepository: BooksRepository by lazy{ BooksRepositoryImpl(bookApi, database1.getBookDao() ) } }
One_Homework/app/src/main/java/com/example/onelab_homework/App.kt
4144137228
package com.example.onelab_homework import android.content.Context import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.ViewGroup import android.widget.Toast import androidx.lifecycle.LifecycleCoroutineScope import androidx.navigation.NavController import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.example.homework.book.Book import com.example.onelab_homework.database.BooksRepository import com.example.onelab_homework.databinding.FragmentItemBinding import kotlinx.coroutines.launch class MyItemRecyclerViewAdapter( val navController: NavController, val context: Context, val booksRepository: BooksRepository, val lifecycleScope: LifecycleCoroutineScope ): RecyclerView.Adapter<MyItemRecyclerViewAdapter.SeedsViewHolder>() { var itemList =mutableListOf<Book>() set(newValue) { field= newValue notifyDataSetChanged() } fun assignist(listElement: MutableList<Book>){ Log.d("32132123","ASSigned") for(a in listElement){ Log.d("32132123",a.toString()) } itemList =listElement } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SeedsViewHolder { Log.d("32132123","create") val inflater =LayoutInflater.from(parent.context) val binding =FragmentItemBinding.inflate(inflater,parent,false) return SeedsViewHolder(binding) } override fun getItemCount()= itemList.size override fun onBindViewHolder(holder: SeedsViewHolder, position: Int) { val item =itemList[position] Log.d("32132123","${item.imageUrl} herehrehrherhehrher") Glide.with(context) .load(item.imageUrl) .into(holder.binding.itemImage) holder.binding.root.setOnClickListener{ val bundle =Bundle() //serilizable медленнее, но легче bundle.putSerializable("KEY" ,item) navController.navigate(R.id.action_itemFragment_to_elementDescriptionPage, bundle) } holder.binding.root.setOnLongClickListener{ lifecycleScope.launch { booksRepository.addFavoriteBook(item) Toast.makeText(context ,"Added!",Toast.LENGTH_SHORT).show() } true } } class SeedsViewHolder(val binding:FragmentItemBinding):RecyclerView.ViewHolder(binding.root){ } } data class MyListElement(var name:String ,var text:String )
One_Homework/app/src/main/java/com/example/onelab_homework/MyItemRecyclerViewAdapter.kt
291539860
package com.example.onelab_homework import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.navigation.NavController import androidx.navigation.Navigation import androidx.navigation.fragment.NavHostFragment import androidx.navigation.ui.NavigationUI import androidx.navigation.ui.NavigationUI.setupWithNavController import androidx.navigation.ui.setupActionBarWithNavController import com.example.onelab_homework.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { lateinit var binding :ActivityMainBinding private lateinit var navController : NavController override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding =ActivityMainBinding.inflate(layoutInflater) App.init(applicationContext) //setSupportActionBar(binding.toobarMainPage) setContentView(binding.root) } }
One_Homework/app/src/main/java/com/example/onelab_homework/MainActivity.kt
2347717480
package com.example.onelab_homework.fragments.placeholder import android.os.Bundle import android.util.Log import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.platform.ComposeView import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import coil.Coil import coil.compose.AsyncImage import com.example.homework.book.Book import com.example.onelab_homework.R import com.example.onelab_homework.databinding.FragmentFavoritesBinding // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private const val ARG_PARAM1 = "param1" private const val ARG_PARAM2 = "param2" /** * A simple [Fragment] subclass. * Use the [FavoritesFragment.newInstance] factory method to * create an instance of this fragment. */ class FavoritesFragment : Fragment() { // TODO: Rename and change types of parameters private var param1: String? = null private var param2: String? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.let { param1 = it.getString(ARG_PARAM1) param2 = it.getString(ARG_PARAM2) } } lateinit var binding:FragmentFavoritesBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding =FragmentFavoritesBinding.inflate(layoutInflater) val composeView = binding.composeView val favorites = mutableListOf<Book>() composeView.setContent { // Compose code here composeView.setContent { val books =(arguments?.getSerializable("MYKEY") ?: mutableListOf(Book(0,"123","123","123" ,false)) )as MutableList<Book> Log.d("1233312132312","$books") Greeting(books) } } // Inflate the layout for this fragment return binding.root } @Composable fun Greeting(favorites:MutableList<Book>) { LazyColumn(){ items(favorites.size){ ListElement(favorites[it]) } } } @Composable fun ListElement(item:Book){ Row(Modifier.height(100.dp).padding(bottom =10.dp ,end =10.dp)) { AsyncImage( modifier = Modifier.fillMaxHeight().width(100.dp), model = item.imageUrl, contentDescription = null ) Column(){ Text(item.name ,Modifier.padding(top =10.dp) ,fontWeight = FontWeight.Bold , fontSize =16.sp) Text(getFirst20Words(item.descr),Modifier.padding(top =10.dp)) } } } fun getFirst20Words(input: String): String { val words = input.trim().split("\\s+".toRegex()) // Split the string into words val first30Words = words.take(20) // Take the first 30 words return first30Words.joinToString(" ") // Join the first 30 words back into a single string } companion object { /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment FavoritesFragment. */ // TODO: Rename and change types and number of parameters @JvmStatic fun newInstance(param1: String, param2: String) = FavoritesFragment().apply { arguments = Bundle().apply { putString(ARG_PARAM1, param1) putString(ARG_PARAM2, param2) } } } }
One_Homework/app/src/main/java/com/example/onelab_homework/fragments/placeholder/FavoritesFragment.kt
3638578991
package com.example.onelab_homework import androidx.activity.ComponentActivity import androidx.activity.viewModels import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider typealias ViewModelCreator<VM> = () -> VM class ViewModelFactory<VM : ViewModel>( private val viewModelCreator: ViewModelCreator<VM> ) : ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>): T { return viewModelCreator() as T } } inline fun <reified VM : ViewModel> Fragment.viewModelCreator(noinline creator: ViewModelCreator<VM>): Lazy<VM> { return viewModels { ViewModelFactory(creator) } } inline fun <reified VM : ViewModel> ComponentActivity.viewModelCreator(noinline creator: ViewModelCreator<VM>): Lazy<VM> { return viewModels { ViewModelFactory(creator) } }
One_Homework/app/src/main/java/com/example/onelab_homework/ViewModelFactory.kt
3094574634
package com.example.onelab_homework import android.Manifest import android.app.NotificationChannel import android.app.NotificationManager import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.os.Build import android.util.Log import androidx.core.app.ActivityCompat import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.homework.book.Book import com.example.onelab_homework.database.BooksRepository import com.example.onelab_homework.book.Resource import kotlinx.coroutines.Deferred import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.async import kotlinx.coroutines.launch class ListViewModel(val repository: BooksRepository ,val context: Context): ViewModel() { var books = MutableLiveData<MutableList<Book>>() var favorites =MutableLiveData<MutableList<Book>>() fun getBooks(text:String){ viewModelScope.launch { val bookss = repository.getBooksFromCache()!! val comp = listOf<Book>() if (bookss.size!=0 ) { Log.d("32132123",bookss.size.toString()) books.value = bookss.toMutableList() } else { Log.d("32132123","HERE HH") val res = repository.getBooks(text) when (res) { is Resource.Success -> { Log.d("12132321132", res.data?.get(0)!!.imageUrl.toString()) books.value = res.data.toMutableList() repository.addBookToCache(res.data) } is Resource.Loading -> { Log.d("12132321132", "Loading") } is Resource.Error -> { Log.d("12132321132", "Errorrrr") } } } } } fun deleteAll() { viewModelScope.launch { repository.deleteAllBooks() } } suspend fun getAllFavorites() { Log.d("1233312132312" ,"WHAT") viewModelScope.launch { favorites.value = repository.getAllFavorites().toMutableList() } } }
One_Homework/app/src/main/java/com/example/onelab_homework/ListViewModel.kt
3496197212
package com.example.onelab_homework import android.app.NotificationChannel import android.app.NotificationManager import android.content.Context import android.os.Build import androidx.core.app.NotificationCompat import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.onelab_homework.database.BooksRepository import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch class ElementDescriptionViewModel(val repository: BooksRepository , val context: Context): ViewModel() { private val CHANNEL_ID = "channel_id" private val NOTIFICATION_ID = 123 var isFavorite= MutableLiveData<Boolean>() fun changeFavorite(name:String ,isFavorite:Boolean){ viewModelScope.launch { repository.changeFavorite(name ,isFavorite) } } fun sendMsg(bookName:String) { viewModelScope.launch(Dispatchers.IO) { val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val channel = NotificationChannel( CHANNEL_ID, "Channel Name", NotificationManager.IMPORTANCE_DEFAULT ) notificationManager.createNotificationChannel(channel) } val builder = NotificationCompat.Builder(context, CHANNEL_ID) .setSmallIcon(R.drawable.baseline_timer_24) .setContentTitle("Time to read!") .setContentText("You need to read ${bookName}") .setPriority(NotificationCompat.PRIORITY_DEFAULT) notificationManager.notify(NOTIFICATION_ID, builder.build()) } } }
One_Homework/app/src/main/java/com/example/onelab_homework/ElementDescriptionViewModel.kt
2104067655
package com.example.onelab_homework import android.R.menu import android.app.PendingIntent import android.content.Intent import android.os.Build import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.Menu import android.view.MenuInflater import android.view.MenuItem import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.core.view.MenuHost import androidx.core.view.MenuProvider import androidx.fragment.app.Fragment import androidx.lifecycle.lifecycleScope import androidx.navigation.fragment.findNavController import androidx.recyclerview.widget.GridLayoutManager import com.example.homework.book.Book import com.example.onelab_homework.databinding.FragmentItemListBinding import kotlinx.coroutines.launch import java.io.Serializable /** * A fragment representing a list of Items. */ class ItemFragment : Fragment() { val viewModel by viewModelCreator { ListViewModel( App.booksRepository, requireContext() ) } lateinit var binding : FragmentItemListBinding lateinit var adapter: MyItemRecyclerViewAdapter override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding =FragmentItemListBinding.inflate(layoutInflater) adapter = MyItemRecyclerViewAdapter(findNavController(), requireContext() ,App.booksRepository ,lifecycleScope) binding.list.adapter =adapter binding.list.layoutManager =GridLayoutManager(context, 2) // adapter.assignist(sss) viewModel.getBooks("night") // binding.toobarMainPage.menu viewModel.favorites.observe(viewLifecycleOwner){items -> val bundle =Bundle() bundle.putSerializable("MYKEY" ,items as Serializable) findNavController().navigate(R.id.action_itemFragment_to_favoritesFragment, bundle) } //viewModel.deleteAll() viewModel.books.observe(viewLifecycleOwner){ Log.d("32132123", "observer works") adapter.assignist(it) } // adapter.itemList = listOf{ // Book("123" ,) // } val toolbar =binding.toobarMainPage toolbar.inflateMenu(R.menu.menu_main_page); toolbar.title ="My App" toolbar.setOnMenuItemClickListener { when(it.itemId){ R.id.Favorites -> { lifecycleScope.launch { val s =viewModel.getAllFavorites() // chtoto(s.await()) } true } else -> { false } } } return binding.root } }
One_Homework/app/src/main/java/com/example/onelab_homework/ItemFragment.kt
1081666066
package com.example.homework.book import com.example.onelab_homework.book.SeriesInfo import java.io.Serializable data class Book(var id:Long ,var name:String ,var descr :String ,var imageUrl :String, var isFavorite:Boolean):Serializable
One_Homework/app/src/main/java/com/example/onelab_homework/book/Book.kt
3897329101
package com.example.onelab_homework.book data class IndustryIdentifier( val type: String, val identifier: String ) data class ReadingModes( val text: Boolean, val image: Boolean ) data class PanelizationSummary( val containsEpubBubbles: Boolean, val containsImageBubbles: Boolean ) data class ImageLinks( val smallThumbnail: String, val thumbnail: String ) data class SaleInfo( val country: String, val saleability: String, val isEbook: Boolean, val listPrice: Map<String, Any>? = null, val retailPrice: Map<String, Any>? = null, val buyLink: String? = null, val offers: List<Map<String, Any>>? = null ) data class Epub( val isAvailable: Boolean, val acsTokenLink: String ) data class Pdf( val isAvailable: Boolean, val acsTokenLink: String ) data class AccessInfo( val country: String, val viewability: String, val embeddable: Boolean, val publicDomain: Boolean, val textToSpeechPermission: String, val epub: Epub? = null, val pdf: Pdf? = null, val webReaderLink: String? = null, val accessViewStatus: String? = null, val quoteSharingAllowed: Boolean? = null ) data class VolumeInfo( val title: String, val subtitle: String? = null, val authors: List<String>, val publisher: String, val publishedDate: String, val description: String?, val industryIdentifiers: List<IndustryIdentifier>, val readingModes: ReadingModes, val pageCount: Int, val printType: String, val categories: List<String>, val maturityRating: String, val allowAnonLogging: Boolean, val contentVersion: String, val panelizationSummary: PanelizationSummary, val imageLinks: ImageLinks, val language: String, val previewLink: String, val infoLink: String, val canonicalVolumeLink: String, val seriesInfo: Map<String, Any>? = null ) data class SearchInfo( val textSnippet: String ) data class SeriesInfo( val kind: String, val bookDisplayNumber: String, val volumeSeries: List<Map<String, Any>> ) data class Volume( val kind: String, val id: String, val etag: String, val selfLink: String, val volumeInfo: VolumeInfo, val saleInfo: SaleInfo, val accessInfo: AccessInfo, val searchInfo: SearchInfo, val seriesInfo: SeriesInfo? = null ) data class BookResponse( val kind: String, val totalItems: Int, val items: List<Volume> )
One_Homework/app/src/main/java/com/example/onelab_homework/book/BookResponse.kt
2981277289
package com.example.onelab_homework.book sealed class Resource<T>(val data: T? = null, val message: String? = null) { class Success<T>(data: T) : Resource<T>(data) class Error<T>(message: String, data: T? = null) : Resource<T>(data, message) class Loading<T> : Resource<T>() }
One_Homework/app/src/main/java/com/example/onelab_homework/book/Resource.kt
1068643604
package com.example.homework.book import com.example.onelab_homework.book.BookResponse import retrofit2.http.GET import retrofit2.http.Query interface BookApi { companion object { const val BASE_URL = "https://www.googleapis.com/books/v1/" } @GET("volumes") suspend fun getBooksByQuery(@Query("q") query: String): BookResponse }
One_Homework/app/src/main/java/com/example/onelab_homework/book/BookApi.kt
2449676395
package com.example.onelab_homework import android.content.Context import android.content.Intent import androidx.work.Worker import androidx.work.WorkerParameters class MyWorker(val context: Context, workerParams: WorkerParameters) : Worker(context, workerParams) { override fun doWork(): Result { // Отправляем широковещательное сообщение val intent = Intent("com.example.MY_NOTIFICATION") context.sendBroadcast(intent) return Result.success() } }
One_Homework/app/src/main/java/com/example/onelab_homework/MyWorker.kt
4148928846
package com.example.onelab_homework import android.app.AlertDialog import android.graphics.drawable.ColorDrawable import android.os.Bundle import android.util.Log import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.Menu import android.view.MenuInflater import android.view.MenuItem import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.core.view.MenuHost import androidx.core.view.MenuProvider import androidx.lifecycle.lifecycleScope import androidx.work.PeriodicWorkRequest import androidx.work.WorkManager import com.bumptech.glide.Glide import com.example.homework.book.Book import com.example.onelab_homework.databinding.FragmentElementDescriptionPageBinding import com.example.onelab_homework.databinding.StartTimerBinding import java.util.concurrent.TimeUnit // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private const val ARG_PARAM1 = "param1" private const val ARG_PARAM2 = "param2" /** * A simple [Fragment] subclass. * Use the [ElementDescriptionPage.newInstance] factory method to * create an instance of this fragment. */ class ElementDescriptionPage : Fragment() { lateinit var binding:FragmentElementDescriptionPageBinding lateinit var name:String val viewModel by viewModelCreator { ElementDescriptionViewModel( App.booksRepository, requireContext() ) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding =FragmentElementDescriptionPageBinding.inflate(layoutInflater) val book =(arguments?.getSerializable("KEY") ?: Book(0,"123","123","123" ,false) )as Book viewModel.isFavorite.value =book.isFavorite name =book.name // if(book.isFavorite){ // val s =binding.toobarDescr.menu.findItem(R.id.addToFavorite) // Log.d("asdjkljdsajkdlsajlkads" ,s.toString()) // } Log.d("What" , book.imageUrl) Glide.with(this) .load(book.imageUrl) .into(binding.imageView) binding.descriptionItem.text =book.descr binding.nameItemm.text =book.name val toolbar =binding.toobarDescr toolbar.inflateMenu(R.menu.menu_descriprion); toolbar.setOnMenuItemClickListener { when (it.itemId) { R.id.addToFavorite -> { Log.d("123123","2312231312213123") //it.setIcon(R.drawable.baseline_favorite_24) viewModel.isFavorite.value =!viewModel.isFavorite.value!! true } R.id.addTimer -> { val builder = AlertDialog.Builder(context) var binding = StartTimerBinding.inflate(layoutInflater) builder.setView(binding.root) val alertDialog =builder.create() binding.button.setOnClickListener{ viewModel.sendMsg(name) } if(alertDialog.window!=null){ alertDialog.window!!.setBackgroundDrawable(ColorDrawable(0)) } alertDialog.show() true } else -> { true } } } toolbar.title ="My Descr" viewModel.isFavorite.observe(viewLifecycleOwner){ Log.d("123123",it.toString()) val s = binding.toobarDescr.menu.findItem(R.id.addToFavorite) if(it) { Log.d("123123","trueasd") s.setIcon(R.drawable.baseline_favorite_24) viewModel.changeFavorite(name ,isFavorite =it ) } else { Log.d("123123","falseasd") s.setIcon(R.drawable.baseline_not_favorite) viewModel.changeFavorite(name ,isFavorite =it ) } } return binding.root } companion object { /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment ElementDescriptionPage. */ // TODO: Rename and change types and number of parameters @JvmStatic fun newInstance(param1: String, param2: String) = ElementDescriptionPage().apply { arguments = Bundle().apply { putString(ARG_PARAM1, param1) putString(ARG_PARAM2, param2) } } } }
One_Homework/app/src/main/java/com/example/onelab_homework/ElementDescriptionPage.kt
2366294254
package com.example.demo.app import javafx.scene.text.FontWeight import tornadofx.Stylesheet import tornadofx.box import tornadofx.cssclass import tornadofx.px class Styles : Stylesheet() { companion object { val heading by cssclass() } init { label { padding = box(10.px) fontSize = 20.px fontWeight = FontWeight.BOLD } heading { fontSize = 45.px fontWeight = FontWeight.EXTRA_BOLD } } }
kotlin-chat/src/main/kotlin/com/example/demo/app/Styles.kt
781067901
package com.example.demo.app import com.example.demo.view.MainView import tornadofx.App class MyApp: App(MainView::class, Styles::class) { }
kotlin-chat/src/main/kotlin/com/example/demo/app/MyApp.kt
3054394858
package com.example.demo.view import com.example.demo.app.Styles import javafx.beans.property.SimpleListProperty import javafx.beans.property.SimpleObjectProperty import javafx.collections.FXCollections import javafx.geometry.Pos import tornadofx.* class MessageAndAuthor(val authorId: String, val message: String); class ChatDescription(val name: String, val id: String, var messages: List<MessageAndAuthor>) class MainView : View("Kotekpsotek Chat") { var displayChatContent = SimpleObjectProperty<ChatDescription?>(null); val messagesChannel = listOf( MessageAndAuthor(authorId = "1", message = "Txt1") ); val chatList = listOf<ChatDescription?>(ChatDescription(name = "Test Name", id = "123", messages = messagesChannel)) override val root = vbox { label("Chat App") { addClass(Styles.heading) style { textFill = c("black") } } vbox { // TODO: Download from websocket server if (chatList.size != 0) { style { padding = box(0.px, 10.px, 0.px, 10.px) } for (chat in chatList) { button(chat?.name ?: "") { setPrefSize(400.0, 50.0) this.alignment = Pos.BASELINE_LEFT style { padding = box(5.px) fontFamily = "Inter; sans-serif" } // Switch to chat action { displayChatContent.value = chat } } } } else { this.alignment = Pos.CENTER label(text = "No chats are here ❌") { style { fontSize = 15.px padding = box(50.px) textFill = c("red") } } } } } }
kotlin-chat/src/main/kotlin/com/example/demo/view/MainView.kt
3817313966
/* 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.makeitso.model.service.module 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 com.google.firebase.Firebase import dagger.Module import dagger.Provides import dagger.hilt.components.SingletonComponent import dagger.hilt.testing.TestInstallIn @Module @TestInstallIn(components = [SingletonComponent::class], replaces = [FirebaseModule::class]) object TestFirebaseModule { private const val HOST = "10.0.2.2" private const val AUTH_PORT = 9099 private const val FIRESTORE_PORT = 8080 @Provides fun auth(): FirebaseAuth = Firebase.auth.also { it.useEmulator(HOST, AUTH_PORT) } @Provides fun firestore(): FirebaseFirestore = Firebase.firestore.also { it.useEmulator(HOST, FIRESTORE_PORT) } }
Make-It-So/start/app/src/androidTest/java/com/example/makeitso/model/service/module/TestFirebaseModule.kt
1759721996
/* 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.makeitso import android.app.Application import android.content.Context import androidx.test.runner.AndroidJUnitRunner import dagger.hilt.android.testing.HiltTestApplication class MakeItSoTestRunner : AndroidJUnitRunner() { override fun newApplication( cl: ClassLoader?, className: String?, context: Context? ): Application { return super.newApplication(cl, HiltTestApplication::class.java.name, context) } }
Make-It-So/start/app/src/androidTest/java/com/example/makeitso/MakeItSoTestRunner.kt
1215355492
/* 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.makeitso import com.example.makeitso.model.Task import com.example.makeitso.model.service.StorageService import com.google.common.truth.Truth.assertThat import com.google.firebase.firestore.FirebaseFirestore import dagger.hilt.android.testing.HiltAndroidRule import dagger.hilt.android.testing.HiltAndroidTest import javax.inject.Inject import kotlinx.coroutines.flow.first import kotlinx.coroutines.runBlocking import kotlinx.coroutines.tasks.await import kotlinx.coroutines.test.runTest import org.junit.Before import org.junit.Rule import org.junit.Test @HiltAndroidTest class AwesomeTest { @get:Rule val hilt = HiltAndroidRule(this) @Inject lateinit var storage: StorageService @Inject lateinit var firestore: FirebaseFirestore @Before fun setup() { hilt.inject() runBlocking { firestore.clearPersistence().await() } } @Test fun test() = runTest { val newId = storage.save(Task(title = "Testing")) val result = storage.tasks.first() assertThat(result).containsExactly(Task(id = newId, title = "Testing")) } }
Make-It-So/start/app/src/androidTest/java/com/example/makeitso/AwesomeTest.kt
2336400148
package com.example.makeitso import android.app.NotificationChannel import android.app.NotificationManager import android.app.NotificationManager.IMPORTANCE_DEFAULT import android.app.PendingIntent import android.app.PendingIntent.FLAG_IMMUTABLE import android.content.Intent import android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP import android.os.Build import android.util.Log import androidx.compose.material.ExperimentalMaterialApi import androidx.core.app.NotificationCompat import com.google.firebase.messaging.FirebaseMessagingService import com.google.firebase.messaging.RemoteMessage import kotlin.random.Random class MakeItSoMessagingService : FirebaseMessagingService() { private val random = Random override fun onMessageReceived(remoteMessage: RemoteMessage) { remoteMessage.notification?.let { message -> sendNotification(message) } } @OptIn(ExperimentalMaterialApi::class) private fun sendNotification(message: RemoteMessage.Notification) { // If you want the notifications to appear when your app is in foreground val intent = Intent(this, MakeItSoActivity::class.java).apply { addFlags(FLAG_ACTIVITY_CLEAR_TOP) } val pendingIntent = PendingIntent.getActivity( this, 0, intent, FLAG_IMMUTABLE ) val channelId = this.getString(R.string.default_notification_channel_id) val notificationBuilder = NotificationCompat.Builder(this, channelId) .setContentTitle(message.title) .setContentText(message.body) .setSmallIcon(R.mipmap.ic_launcher) .setAutoCancel(true) .setContentIntent(pendingIntent) val manager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val channel = NotificationChannel(channelId, CHANNEL_NAME, IMPORTANCE_DEFAULT) manager.createNotificationChannel(channel) } manager.notify(random.nextInt(), notificationBuilder.build()) } override fun onNewToken(token: String) { // If you want to send messages to this application instance or // manage this apps subscriptions on the server side, send the // FCM registration token to your app server. Log.d("FCM","New token: $token") } companion object { const val CHANNEL_NAME = "FCM notification channel" } }
Make-It-So/start/app/src/main/java/com/example/makeitso/MakeItSoMessagingService.kt
106336736
/* 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.makeitso const val SPLASH_SCREEN = "SplashScreen" const val SETTINGS_SCREEN = "SettingsScreen" const val LOGIN_SCREEN = "LoginScreen" const val SIGN_UP_SCREEN = "SignUpScreen" const val TASKS_SCREEN = "TasksScreen" const val EDIT_TASK_SCREEN = "EditTaskScreen" const val TASK_ID = "taskId" const val TASK_ID_ARG = "?$TASK_ID={$TASK_ID}"
Make-It-So/start/app/src/main/java/com/example/makeitso/MakeItSoRoutes.kt
3028692133
/* 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.makeitso import android.app.Application import dagger.hilt.android.HiltAndroidApp @HiltAndroidApp class MakeItSoHiltApp : Application() {}
Make-It-So/start/app/src/main/java/com/example/makeitso/MakeItSoHiltApp.kt
1704438359
/* 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.makeitso.screens.settings data class SettingsUiState(val isAnonymousAccount: Boolean = true)
Make-It-So/start/app/src/main/java/com/example/makeitso/screens/settings/SettingsUiState.kt
1797455976
/* 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.makeitso.screens.settings import androidx.compose.foundation.layout.* import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material.* 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.makeitso.R.drawable as AppIcon import com.example.makeitso.R.string as AppText import com.example.makeitso.common.composable.* import com.example.makeitso.common.ext.card import com.example.makeitso.common.ext.spacer import com.example.makeitso.theme.MakeItSoTheme @ExperimentalMaterialApi @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) } ) } @ExperimentalMaterialApi @Composable fun SettingsScreenContent( modifier: Modifier = Modifier, uiState: SettingsUiState, onLoginClick: () -> Unit, onSignUpClick: () -> Unit, onSignOutClick: () -> Unit, onDeleteMyAccountClick: () -> Unit ) { Column( modifier = modifier.fillMaxWidth().fillMaxHeight().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() } } } } @ExperimentalMaterialApi @Composable private fun SignOutCard(signOut: () -> Unit) { var showWarningDialog by remember { mutableStateOf(false) } RegularCardEditor(AppText.sign_out, AppIcon.ic_exit, "", Modifier.card()) { showWarningDialog = true } if (showWarningDialog) { AlertDialog( title = { Text(stringResource(AppText.sign_out_title)) }, text = { Text(stringResource(AppText.sign_out_description)) }, dismissButton = { DialogCancelButton(AppText.cancel) { showWarningDialog = false } }, confirmButton = { DialogConfirmButton(AppText.sign_out) { signOut() showWarningDialog = false } }, onDismissRequest = { showWarningDialog = false } ) } } @ExperimentalMaterialApi @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( title = { Text(stringResource(AppText.delete_account_title)) }, text = { Text(stringResource(AppText.delete_account_description)) }, dismissButton = { DialogCancelButton(AppText.cancel) { showWarningDialog = false } }, confirmButton = { DialogConfirmButton(AppText.delete_my_account) { deleteMyAccount() showWarningDialog = false } }, onDismissRequest = { showWarningDialog = false } ) } } @Preview(showBackground = true) @ExperimentalMaterialApi @Composable fun SettingsScreenPreview() { val uiState = SettingsUiState(isAnonymousAccount = false) MakeItSoTheme { SettingsScreenContent( uiState = uiState, onLoginClick = { }, onSignUpClick = { }, onSignOutClick = { }, onDeleteMyAccountClick = { } ) } }
Make-It-So/start/app/src/main/java/com/example/makeitso/screens/settings/SettingsScreen.kt
3538698155
/* 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.makeitso.screens.settings import com.example.makeitso.LOGIN_SCREEN import com.example.makeitso.SIGN_UP_SCREEN import com.example.makeitso.SPLASH_SCREEN import com.example.makeitso.model.service.AccountService import com.example.makeitso.model.service.LogService import com.example.makeitso.model.service.StorageService import com.example.makeitso.screens.MakeItSoViewModel import dagger.hilt.android.lifecycle.HiltViewModel import javax.inject.Inject import kotlinx.coroutines.flow.map @HiltViewModel class SettingsViewModel @Inject constructor( logService: LogService, private val accountService: AccountService, private val storageService: StorageService ) : MakeItSoViewModel(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) } } }
Make-It-So/start/app/src/main/java/com/example/makeitso/screens/settings/SettingsViewModel.kt
2551449822
/* 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.makeitso.screens import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.makeitso.common.snackbar.SnackbarManager import com.example.makeitso.common.snackbar.SnackbarMessage.Companion.toSnackbarMessage import com.example.makeitso.model.service.LogService import kotlinx.coroutines.CoroutineExceptionHandler import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch open class MakeItSoViewModel(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 ) }
Make-It-So/start/app/src/main/java/com/example/makeitso/screens/MakeItSoViewModel.kt
2622876676
/* 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.makeitso.screens.splash import androidx.compose.runtime.mutableStateOf import com.example.makeitso.SPLASH_SCREEN import com.example.makeitso.TASKS_SCREEN import com.example.makeitso.model.service.AccountService import com.example.makeitso.model.service.ConfigurationService import com.example.makeitso.model.service.LogService import com.example.makeitso.screens.MakeItSoViewModel 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 ) : MakeItSoViewModel(logService) { val showError = mutableStateOf(false) init { launchCatching { configurationService.fetchConfiguration() } } fun onAppStart(openAndPopUp: (String, String) -> Unit) { showError.value = false if (accountService.hasUser) openAndPopUp(TASKS_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(TASKS_SCREEN, SPLASH_SCREEN) } } }
Make-It-So/start/app/src/main/java/com/example/makeitso/screens/splash/SplashViewModel.kt
1055890139
/* 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.makeitso.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.material.CircularProgressIndicator import androidx.compose.material.MaterialTheme import androidx.compose.material.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.makeitso.R.string as AppText import com.example.makeitso.common.composable.BasicButton import com.example.makeitso.common.ext.basicButton import com.example.makeitso.theme.MakeItSoTheme 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.colors.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.colors.onBackground) } } LaunchedEffect(true) { delay(SPLASH_TIMEOUT) onAppStart() } } @Preview(showBackground = true) @Composable fun SplashScreenPreview() { MakeItSoTheme { SplashScreenContent( onAppStart = { }, shouldShowError = true ) } }
Make-It-So/start/app/src/main/java/com/example/makeitso/screens/splash/SplashScreen.kt
3162787655
/* 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.makeitso.screens.tasks enum class TaskActionOption(val title: String) { EditTask("Edit task"), ToggleFlag("Toggle flag"), DeleteTask("Delete task"); companion object { fun getByTitle(title: String): TaskActionOption { values().forEach { action -> if (title == action.title) return action } return EditTask } fun getOptions(hasEditOption: Boolean): List<String> { val options = mutableListOf<String>() values().forEach { taskAction -> if (hasEditOption || taskAction != EditTask) { options.add(taskAction.title) } } return options } } }
Make-It-So/start/app/src/main/java/com/example/makeitso/screens/tasks/TaskActionOption.kt
3225833856
/* 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.makeitso.screens.tasks import androidx.compose.runtime.mutableStateOf import com.example.makeitso.EDIT_TASK_SCREEN import com.example.makeitso.SETTINGS_SCREEN import com.example.makeitso.TASK_ID import com.example.makeitso.model.Task import com.example.makeitso.model.service.ConfigurationService import com.example.makeitso.model.service.LogService import com.example.makeitso.model.service.StorageService import com.example.makeitso.screens.MakeItSoViewModel import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.emptyFlow import javax.inject.Inject @HiltViewModel class TasksViewModel @Inject constructor( logService: LogService, private val storageService: StorageService, private val configurationService: ConfigurationService ) : MakeItSoViewModel(logService) { val options = mutableStateOf<List<String>>(listOf()) val tasks = storageService.tasks fun loadTaskOptions() { val hasEditOption = configurationService.isShowTaskEditButtonConfig options.value = TaskActionOption.getOptions(hasEditOption) } fun onTaskCheckChange(task: Task) { launchCatching { storageService.update(task.copy(completed = !task.completed)) } } fun onAddClick(openScreen: (String) -> Unit) = openScreen(EDIT_TASK_SCREEN) fun onSettingsClick(openScreen: (String) -> Unit) = openScreen(SETTINGS_SCREEN) fun onTaskActionClick(openScreen: (String) -> Unit, task: Task, action: String) { when (TaskActionOption.getByTitle(action)) { TaskActionOption.EditTask -> openScreen("$EDIT_TASK_SCREEN?$TASK_ID={${task.id}}") TaskActionOption.ToggleFlag -> onFlagTaskClick(task) TaskActionOption.DeleteTask -> onDeleteTaskClick(task) } } private fun onFlagTaskClick(task: Task) { launchCatching { storageService.update(task.copy(flag = !task.flag)) } } private fun onDeleteTaskClick(task: Task) { launchCatching { storageService.delete(task.id) } } }
Make-It-So/start/app/src/main/java/com/example/makeitso/screens/tasks/TasksViewModel.kt
607458925
/* 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.makeitso.screens.tasks import androidx.compose.foundation.layout.* import androidx.compose.material.* import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.example.makeitso.R.drawable as AppIcon import com.example.makeitso.common.composable.DropdownContextMenu import com.example.makeitso.common.ext.contextMenu import com.example.makeitso.common.ext.hasDueDate import com.example.makeitso.common.ext.hasDueTime import com.example.makeitso.model.Task import com.example.makeitso.theme.DarkOrange import java.lang.StringBuilder @Composable @ExperimentalMaterialApi fun TaskItem( task: Task, options: List<String>, onCheckChange: () -> Unit, onActionClick: (String) -> Unit ) { Card( backgroundColor = MaterialTheme.colors.background, modifier = Modifier.padding(8.dp, 0.dp, 8.dp, 8.dp), ) { Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth(), ) { Checkbox( checked = task.completed, onCheckedChange = { onCheckChange() }, modifier = Modifier.padding(8.dp, 0.dp) ) Column(modifier = Modifier.weight(1f)) { Text(text = task.title, style = MaterialTheme.typography.subtitle2) CompositionLocalProvider(LocalContentAlpha provides ContentAlpha.medium) { Text(text = getDueDateAndTime(task), fontSize = 12.sp) } } if (task.flag) { Icon( painter = painterResource(AppIcon.ic_flag), tint = DarkOrange, contentDescription = "Flag" ) } DropdownContextMenu(options, Modifier.contextMenu(), onActionClick) } } } private fun getDueDateAndTime(task: Task): String { val stringBuilder = StringBuilder("") if (task.hasDueDate()) { stringBuilder.append(task.dueDate) stringBuilder.append(" ") } if (task.hasDueTime()) { stringBuilder.append("at ") stringBuilder.append(task.dueTime) } return stringBuilder.toString() }
Make-It-So/start/app/src/main/java/com/example/makeitso/screens/tasks/TaskItem.kt
2498837044
/* 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.makeitso.screens.tasks import android.annotation.SuppressLint import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material.* import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Add import androidx.compose.runtime.* 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 androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.viewmodel.compose.viewModel import com.example.makeitso.R.drawable as AppIcon import com.example.makeitso.R.string as AppText import com.example.makeitso.common.composable.ActionToolbar import com.example.makeitso.common.ext.smallSpacer import com.example.makeitso.common.ext.toolbarActions import com.example.makeitso.model.Task import com.example.makeitso.theme.MakeItSoTheme @Composable @ExperimentalMaterialApi fun TasksScreen( openScreen: (String) -> Unit, viewModel: TasksViewModel = hiltViewModel() ) { TasksScreenContent( onAddClick = viewModel::onAddClick, onSettingsClick = viewModel::onSettingsClick, onTaskCheckChange = viewModel::onTaskCheckChange, onTaskActionClick = viewModel::onTaskActionClick, openScreen = openScreen, viewModel = viewModel ) LaunchedEffect(viewModel) { viewModel.loadTaskOptions() } } @SuppressLint("UnusedMaterialScaffoldPaddingParameter") @Composable @ExperimentalMaterialApi fun TasksScreenContent( modifier: Modifier = Modifier, onAddClick: ((String) -> Unit) -> Unit, onSettingsClick: ((String) -> Unit) -> Unit, onTaskCheckChange: (Task) -> Unit, onTaskActionClick: ((String) -> Unit, Task, String) -> Unit, openScreen: (String) -> Unit, viewModel: TasksViewModel = hiltViewModel() ) { val tasks = viewModel .tasks .collectAsStateWithLifecycle(emptyList()) Scaffold( floatingActionButton = { FloatingActionButton( onClick = { onAddClick(openScreen) }, backgroundColor = MaterialTheme.colors.primary, contentColor = MaterialTheme.colors.onPrimary, modifier = modifier.padding(16.dp) ) { Icon(Icons.Filled.Add, "Add") } } ) { Column(modifier = Modifier .fillMaxWidth() .fillMaxHeight()) { ActionToolbar( title = AppText.tasks, modifier = Modifier.toolbarActions(), endActionIcon = AppIcon.ic_settings, endAction = { onSettingsClick(openScreen) } ) Spacer(modifier = Modifier.smallSpacer()) LazyColumn { val options by viewModel.options items(tasks.value, key = { it.id }) { taskItem -> TaskItem( task = taskItem, //options = listOf(), options = options, onCheckChange = { onTaskCheckChange(taskItem) }, onActionClick = { action -> onTaskActionClick(openScreen, taskItem, action) } ) } } } } } @Preview(showBackground = true) @ExperimentalMaterialApi @Composable fun TasksScreenPreview() { MakeItSoTheme { TasksScreenContent( onAddClick = { }, onSettingsClick = { }, onTaskCheckChange = { }, onTaskActionClick = { _, _, _ -> }, openScreen = { } ) } }
Make-It-So/start/app/src/main/java/com/example/makeitso/screens/tasks/TasksScreen.kt
2455749173
/* 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.makeitso.screens.edit_task import androidx.compose.runtime.mutableStateOf import androidx.lifecycle.SavedStateHandle import com.example.makeitso.TASK_ID import com.example.makeitso.common.ext.idFromParameter import com.example.makeitso.model.Task import com.example.makeitso.model.service.LogService import com.example.makeitso.model.service.StorageService import com.example.makeitso.screens.MakeItSoViewModel import dagger.hilt.android.lifecycle.HiltViewModel import java.text.SimpleDateFormat import java.util.* import javax.inject.Inject @HiltViewModel class EditTaskViewModel @Inject constructor( savedStateHandle: SavedStateHandle, logService: LogService, private val storageService: StorageService, ) : MakeItSoViewModel(logService) { val task = mutableStateOf(Task()) init { val taskId = savedStateHandle.get<String>(TASK_ID) if (taskId != null) { launchCatching { task.value = storageService.getTask(taskId.idFromParameter()) ?: Task() } } } fun onTitleChange(newValue: String) { task.value = task.value.copy(title = newValue) } fun onDescriptionChange(newValue: String) { task.value = task.value.copy(description = newValue) } fun onUrlChange(newValue: String) { task.value = task.value.copy(url = newValue) } fun onDateChange(newValue: Long) { val calendar = Calendar.getInstance(TimeZone.getTimeZone(UTC)) calendar.timeInMillis = newValue val newDueDate = SimpleDateFormat(DATE_FORMAT, Locale.ENGLISH).format(calendar.time) task.value = task.value.copy(dueDate = newDueDate) } fun onTimeChange(hour: Int, minute: Int) { val newDueTime = "${hour.toClockPattern()}:${minute.toClockPattern()}" task.value = task.value.copy(dueTime = newDueTime) } fun onFlagToggle(newValue: String) { val newFlagOption = EditFlagOption.getBooleanValue(newValue) task.value = task.value.copy(flag = newFlagOption) } fun onPriorityChange(newValue: String) { task.value = task.value.copy(priority = newValue) } fun onDoneClick(popUpScreen: () -> Unit) { launchCatching { val editedTask = task.value if (editedTask.id.isBlank()) { storageService.save(editedTask) } else { storageService.update(editedTask) } popUpScreen() } } private fun Int.toClockPattern(): String { return if (this < 10) "0$this" else "$this" } companion object { private const val UTC = "UTC" private const val DATE_FORMAT = "EEE, d MMM yyyy" } }
Make-It-So/start/app/src/main/java/com/example/makeitso/screens/edit_task/EditTaskViewModel.kt
838724084
/* 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.makeitso.screens.edit_task import androidx.appcompat.app.AppCompatActivity import androidx.compose.foundation.layout.* import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material.ExperimentalMaterialApi import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.tooling.preview.Preview import androidx.hilt.navigation.compose.hiltViewModel import com.example.makeitso.R.drawable as AppIcon import com.example.makeitso.R.string as AppText import com.example.makeitso.common.composable.* import com.example.makeitso.common.ext.card import com.example.makeitso.common.ext.fieldModifier import com.example.makeitso.common.ext.spacer import com.example.makeitso.common.ext.toolbarActions import com.example.makeitso.model.Priority import com.example.makeitso.model.Task import com.example.makeitso.theme.MakeItSoTheme import com.google.android.material.datepicker.MaterialDatePicker import com.google.android.material.timepicker.MaterialTimePicker import com.google.android.material.timepicker.TimeFormat @Composable @ExperimentalMaterialApi fun EditTaskScreen( popUpScreen: () -> Unit, viewModel: EditTaskViewModel = hiltViewModel() ) { val task by viewModel.task val activity = LocalContext.current as AppCompatActivity EditTaskScreenContent( task = task, onDoneClick = { viewModel.onDoneClick(popUpScreen) }, onTitleChange = viewModel::onTitleChange, onDescriptionChange = viewModel::onDescriptionChange, onUrlChange = viewModel::onUrlChange, onDateChange = viewModel::onDateChange, onTimeChange = viewModel::onTimeChange, onPriorityChange = viewModel::onPriorityChange, onFlagToggle = viewModel::onFlagToggle, activity = activity ) } @Composable @ExperimentalMaterialApi fun EditTaskScreenContent( modifier: Modifier = Modifier, task: Task, onDoneClick: () -> Unit, onTitleChange: (String) -> Unit, onDescriptionChange: (String) -> Unit, onUrlChange: (String) -> Unit, onDateChange: (Long) -> Unit, onTimeChange: (Int, Int) -> Unit, onPriorityChange: (String) -> Unit, onFlagToggle: (String) -> Unit, activity: AppCompatActivity? ) { Column( modifier = modifier.fillMaxWidth().fillMaxHeight().verticalScroll(rememberScrollState()), horizontalAlignment = Alignment.CenterHorizontally ) { ActionToolbar( title = AppText.edit_task, modifier = Modifier.toolbarActions(), endActionIcon = AppIcon.ic_check, endAction = { onDoneClick() } ) Spacer(modifier = Modifier.spacer()) val fieldModifier = Modifier.fieldModifier() BasicField(AppText.title, task.title, onTitleChange, fieldModifier) BasicField(AppText.description, task.description, onDescriptionChange, fieldModifier) BasicField(AppText.url, task.url, onUrlChange, fieldModifier) Spacer(modifier = Modifier.spacer()) CardEditors(task, onDateChange, onTimeChange, activity) CardSelectors(task, onPriorityChange, onFlagToggle) Spacer(modifier = Modifier.spacer()) } } @ExperimentalMaterialApi @Composable private fun CardEditors( task: Task, onDateChange: (Long) -> Unit, onTimeChange: (Int, Int) -> Unit, activity: AppCompatActivity? ) { RegularCardEditor(AppText.date, AppIcon.ic_calendar, task.dueDate, Modifier.card()) { showDatePicker(activity, onDateChange) } RegularCardEditor(AppText.time, AppIcon.ic_clock, task.dueTime, Modifier.card()) { showTimePicker(activity, onTimeChange) } } @Composable @ExperimentalMaterialApi private fun CardSelectors( task: Task, onPriorityChange: (String) -> Unit, onFlagToggle: (String) -> Unit ) { val prioritySelection = Priority.getByName(task.priority).name CardSelector(AppText.priority, Priority.getOptions(), prioritySelection, Modifier.card()) { newValue -> onPriorityChange(newValue) } val flagSelection = EditFlagOption.getByCheckedState(task.flag).name CardSelector(AppText.flag, EditFlagOption.getOptions(), flagSelection, Modifier.card()) { newValue -> onFlagToggle(newValue) } } private fun showDatePicker(activity: AppCompatActivity?, onDateChange: (Long) -> Unit) { val picker = MaterialDatePicker.Builder.datePicker().build() activity?.let { picker.show(it.supportFragmentManager, picker.toString()) picker.addOnPositiveButtonClickListener { timeInMillis -> onDateChange(timeInMillis) } } } private fun showTimePicker(activity: AppCompatActivity?, onTimeChange: (Int, Int) -> Unit) { val picker = MaterialTimePicker.Builder().setTimeFormat(TimeFormat.CLOCK_24H).build() activity?.let { picker.show(it.supportFragmentManager, picker.toString()) picker.addOnPositiveButtonClickListener { onTimeChange(picker.hour, picker.minute) } } } @Preview(showBackground = true) @ExperimentalMaterialApi @Composable fun EditTaskScreenPreview() { val task = Task( title = "Task title", description = "Task description", flag = true ) MakeItSoTheme { EditTaskScreenContent( task = task, onDoneClick = { }, onTitleChange = { }, onDescriptionChange = { }, onUrlChange = { }, onDateChange = { }, onTimeChange = { _, _ -> }, onPriorityChange = { }, onFlagToggle = { }, activity = null ) } }
Make-It-So/start/app/src/main/java/com/example/makeitso/screens/edit_task/EditTaskScreen.kt
4191085042
/* 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.makeitso.screens.edit_task enum class EditFlagOption { On, Off; companion object { fun getByCheckedState(checkedState: Boolean?): EditFlagOption { val hasFlag = checkedState ?: false return if (hasFlag) On else Off } fun getBooleanValue(flagOption: String): Boolean { return flagOption == On.name } fun getOptions(): List<String> { val options = mutableListOf<String>() values().forEach { flagOption -> options.add(flagOption.name) } return options } } }
Make-It-So/start/app/src/main/java/com/example/makeitso/screens/edit_task/EditFlagOption.kt
625423710
/* 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.makeitso.screens.sign_up 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.makeitso.R.string as AppText import com.example.makeitso.common.composable.* import com.example.makeitso.common.ext.basicButton import com.example.makeitso.common.ext.fieldModifier import com.example.makeitso.theme.MakeItSoTheme @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]" ) MakeItSoTheme { SignUpScreenContent( uiState = uiState, onEmailChange = { }, onPasswordChange = { }, onRepeatPasswordChange = { }, onSignUpClick = { } ) } }
Make-It-So/start/app/src/main/java/com/example/makeitso/screens/sign_up/SignUpScreen.kt
1358001008
/* 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.makeitso.screens.sign_up import androidx.compose.runtime.mutableStateOf import com.example.makeitso.R.string as AppText import com.example.makeitso.SETTINGS_SCREEN import com.example.makeitso.SIGN_UP_SCREEN import com.example.makeitso.common.ext.isValidEmail import com.example.makeitso.common.ext.isValidPassword import com.example.makeitso.common.ext.passwordMatches import com.example.makeitso.common.snackbar.SnackbarManager import com.example.makeitso.model.service.AccountService import com.example.makeitso.model.service.LogService import com.example.makeitso.screens.MakeItSoViewModel import dagger.hilt.android.lifecycle.HiltViewModel import javax.inject.Inject @HiltViewModel class SignUpViewModel @Inject constructor( private val accountService: AccountService, logService: LogService ) : MakeItSoViewModel(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) } } }
Make-It-So/start/app/src/main/java/com/example/makeitso/screens/sign_up/SignUpViewModel.kt
2706619517
/* 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.makeitso.screens.sign_up data class SignUpUiState( val email: String = "", val password: String = "", val repeatPassword: String = "" )
Make-It-So/start/app/src/main/java/com/example/makeitso/screens/sign_up/SignUpUiState.kt
1737242844
/* 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.makeitso.screens.login import androidx.compose.runtime.mutableStateOf import com.example.makeitso.LOGIN_SCREEN import com.example.makeitso.R.string as AppText import com.example.makeitso.SETTINGS_SCREEN import com.example.makeitso.common.ext.isValidEmail import com.example.makeitso.common.snackbar.SnackbarManager import com.example.makeitso.model.service.AccountService import com.example.makeitso.model.service.LogService import com.example.makeitso.screens.MakeItSoViewModel import dagger.hilt.android.lifecycle.HiltViewModel import javax.inject.Inject @HiltViewModel class LoginViewModel @Inject constructor( private val accountService: AccountService, logService: LogService ) : MakeItSoViewModel(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) } } }
Make-It-So/start/app/src/main/java/com/example/makeitso/screens/login/LoginViewModel.kt
4239581162
/* 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.makeitso.screens.login data class LoginUiState( val email: String = "", val password: String = "" )
Make-It-So/start/app/src/main/java/com/example/makeitso/screens/login/LoginUiState.kt
3622176427
/* 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.makeitso.screens.login import androidx.compose.foundation.layout.* 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.makeitso.R.string as AppText import com.example.makeitso.common.composable.* import com.example.makeitso.common.ext.basicButton import com.example.makeitso.common.ext.fieldModifier import com.example.makeitso.common.ext.textButton import com.example.makeitso.theme.MakeItSoTheme @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]" ) MakeItSoTheme { LoginScreenContent( uiState = uiState, onEmailChange = { }, onPasswordChange = { }, onSignInClick = { }, onForgotPasswordClick = { } ) } }
Make-It-So/start/app/src/main/java/com/example/makeitso/screens/login/LoginScreen.kt
2163535745
/* 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.makeitso.common.snackbar import android.content.res.Resources import androidx.annotation.StringRes import com.example.makeitso.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) } } }
Make-It-So/start/app/src/main/java/com/example/makeitso/common/snackbar/SnackbarMessage.kt
1730361887
/* 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.makeitso.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 } }
Make-It-So/start/app/src/main/java/com/example/makeitso/common/snackbar/SnackbarManager.kt
368510474
/* 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.makeitso.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) }
Make-It-So/start/app/src/main/java/com/example/makeitso/common/ext/StringExt.kt
2117289206
/* 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.makeitso.common.ext import com.example.makeitso.model.Task fun Task?.hasDueDate(): Boolean { return this?.dueDate.orEmpty().isNotBlank() } fun Task?.hasDueTime(): Boolean { return this?.dueTime.orEmpty().isNotBlank() }
Make-It-So/start/app/src/main/java/com/example/makeitso/common/ext/TaskExt.kt
1189228462
/* 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.makeitso.common.ext import androidx.compose.foundation.layout.* 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.card(): Modifier { return this.padding(16.dp, 0.dp, 16.dp, 8.dp) } fun Modifier.contextMenu(): Modifier { return this.wrapContentWidth() } fun Modifier.alertDialog(): Modifier { return this.wrapContentWidth().wrapContentHeight() } fun Modifier.dropdownSelector(): Modifier { return this.fillMaxWidth() } fun Modifier.fieldModifier(): Modifier { return this.fillMaxWidth().padding(16.dp, 4.dp) } fun Modifier.toolbarActions(): Modifier { return this.wrapContentSize(Alignment.TopEnd) } fun Modifier.spacer(): Modifier { return this.fillMaxWidth().padding(12.dp) } fun Modifier.smallSpacer(): Modifier { return this.fillMaxWidth().height(8.dp) }
Make-It-So/start/app/src/main/java/com/example/makeitso/common/ext/ModifierExt.kt
1490560864
/* 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.makeitso.common.composable import androidx.annotation.StringRes import androidx.compose.foundation.layout.* import androidx.compose.material.* import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.MoreVert import androidx.compose.runtime.* import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp @Composable @ExperimentalMaterialApi fun DropdownContextMenu( options: List<String>, modifier: Modifier, onActionClick: (String) -> Unit ) { var isExpanded by remember { mutableStateOf(false) } ExposedDropdownMenuBox( expanded = isExpanded, modifier = modifier, onExpandedChange = { isExpanded = !isExpanded } ) { Icon( modifier = Modifier.padding(8.dp, 0.dp), imageVector = Icons.Default.MoreVert, contentDescription = "More" ) ExposedDropdownMenu( modifier = Modifier.width(180.dp), expanded = isExpanded, onDismissRequest = { isExpanded = false } ) { options.forEach { selectionOption -> DropdownMenuItem( onClick = { isExpanded = false onActionClick(selectionOption) } ) { Text(text = selectionOption) } } } } } @Composable @ExperimentalMaterialApi 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( onClick = { onNewValue(selectionOption) isExpanded = false } ) { Text(text = selectionOption) } } } } } @Composable @ExperimentalMaterialApi private fun dropdownColors(): TextFieldColors { return ExposedDropdownMenuDefaults.textFieldColors( backgroundColor = MaterialTheme.colors.onPrimary, focusedIndicatorColor = Color.Transparent, unfocusedIndicatorColor = Color.Transparent, trailingIconColor = MaterialTheme.colors.onSurface, focusedTrailingIconColor = MaterialTheme.colors.onSurface, focusedLabelColor = MaterialTheme.colors.primary, unfocusedLabelColor = MaterialTheme.colors.primary ) }
Make-It-So/start/app/src/main/java/com/example/makeitso/common/composable/DropdownComposable.kt
2214167780
/* 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.makeitso.common.composable import androidx.annotation.DrawableRes import androidx.annotation.StringRes import androidx.compose.foundation.layout.* import androidx.compose.material.* import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import com.example.makeitso.common.ext.dropdownSelector @ExperimentalMaterialApi @Composable fun DangerousCardEditor( @StringRes title: Int, @DrawableRes icon: Int, content: String, modifier: Modifier, onEditClick: () -> Unit ) { CardEditor(title, icon, content, onEditClick, MaterialTheme.colors.primary, modifier) } @ExperimentalMaterialApi @Composable fun RegularCardEditor( @StringRes title: Int, @DrawableRes icon: Int, content: String, modifier: Modifier, onEditClick: () -> Unit ) { CardEditor(title, icon, content, onEditClick, MaterialTheme.colors.onSurface, modifier) } @ExperimentalMaterialApi @Composable private fun CardEditor( @StringRes title: Int, @DrawableRes icon: Int, content: String, onEditClick: () -> Unit, highlightColor: Color, modifier: Modifier ) { Card( backgroundColor = MaterialTheme.colors.onPrimary, 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 @ExperimentalMaterialApi fun CardSelector( @StringRes label: Int, options: List<String>, selection: String, modifier: Modifier, onNewValue: (String) -> Unit ) { Card(backgroundColor = MaterialTheme.colors.onPrimary, modifier = modifier) { DropdownSelector(label, options, selection, Modifier.dropdownSelector(), onNewValue) } }
Make-It-So/start/app/src/main/java/com/example/makeitso/common/composable/CardComposable.kt
2132506523
/* 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.makeitso.common.composable import androidx.annotation.DrawableRes import androidx.annotation.StringRes import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.foundation.layout.Box import androidx.compose.material.* import androidx.compose.runtime.* import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource @Composable fun BasicToolbar(@StringRes title: Int) { TopAppBar(title = { Text(stringResource(title)) }, backgroundColor = toolbarColor()) } @Composable fun ActionToolbar( @StringRes title: Int, @DrawableRes endActionIcon: Int, modifier: Modifier, endAction: () -> Unit ) { TopAppBar( title = { Text(stringResource(title)) }, backgroundColor = toolbarColor(), actions = { Box(modifier) { IconButton(onClick = endAction) { Icon(painter = painterResource(endActionIcon), contentDescription = "Action") } } } ) } @Composable private fun toolbarColor(darkTheme: Boolean = isSystemInDarkTheme()): Color { return if (darkTheme) MaterialTheme.colors.secondary else MaterialTheme.colors.primaryVariant }
Make-It-So/start/app/src/main/java/com/example/makeitso/common/composable/ToolbarComposable.kt
210640367
package com.example.makeitso.common.composable import androidx.compose.material.AlertDialog import androidx.compose.material.ButtonDefaults import androidx.compose.material.Text import androidx.compose.material.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.stringResource import com.example.makeitso.common.ext.alertDialog import com.example.makeitso.common.ext.textButton import com.example.makeitso.theme.BrightOrange import com.example.makeitso.R.string as AppText @Composable fun PermissionDialog(onRequestPermission: () -> Unit) { var showWarningDialog by remember { mutableStateOf(true) } if (showWarningDialog) { AlertDialog( modifier = Modifier.alertDialog(), title = { Text(stringResource(id = AppText.notification_permission_title)) }, text = { Text(stringResource(id = AppText.notification_permission_description)) }, confirmButton = { TextButton( onClick = { onRequestPermission() showWarningDialog = false }, modifier = Modifier.textButton(), colors = ButtonDefaults.buttonColors( backgroundColor = BrightOrange, contentColor = Color.White ) ) { Text(text = stringResource(AppText.request_notification_permission)) } }, onDismissRequest = { } ) } } @Composable fun RationaleDialog() { var showWarningDialog by remember { mutableStateOf(true) } if (showWarningDialog) { AlertDialog( modifier = Modifier.alertDialog(), title = { Text(stringResource(id = AppText.notification_permission_title)) }, text = { Text(stringResource(id = AppText.notification_permission_settings)) }, confirmButton = { TextButton( onClick = { showWarningDialog = false }, modifier = Modifier.textButton(), colors = ButtonDefaults.buttonColors( backgroundColor = BrightOrange, contentColor = Color.White ) ) { Text(text = stringResource(AppText.ok)) } }, onDismissRequest = { showWarningDialog = false } ) } }
Make-It-So/start/app/src/main/java/com/example/makeitso/common/composable/PermissionDialogComposable.kt
809064112
/* 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.makeitso.common.composable import androidx.annotation.StringRes import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.* import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Email import androidx.compose.material.icons.filled.Lock 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.makeitso.R.drawable as AppIcon import com.example.makeitso.R.string as AppText @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( singleLine = true, modifier = modifier, value = value, onValueChange = { onNewValue(it) }, 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( modifier = modifier, value = value, onValueChange = { onNewValue(it) }, 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 ) }
Make-It-So/start/app/src/main/java/com/example/makeitso/common/composable/TextFieldComposable.kt
1385818777
/* 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.makeitso.common.composable import androidx.annotation.StringRes import androidx.compose.material.* 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( backgroundColor = MaterialTheme.colors.primary, contentColor = MaterialTheme.colors.onPrimary ) ) { Text(text = stringResource(text), fontSize = 16.sp) } } @Composable fun DialogConfirmButton(@StringRes text: Int, action: () -> Unit) { Button( onClick = action, colors = ButtonDefaults.buttonColors( backgroundColor = MaterialTheme.colors.primary, contentColor = MaterialTheme.colors.onPrimary ) ) { Text(text = stringResource(text)) } } @Composable fun DialogCancelButton(@StringRes text: Int, action: () -> Unit) { Button( onClick = action, colors = ButtonDefaults.buttonColors( backgroundColor = MaterialTheme.colors.onPrimary, contentColor = MaterialTheme.colors.primary ) ) { Text(text = stringResource(text)) } }
Make-It-So/start/app/src/main/java/com/example/makeitso/common/composable/ButtonComposable.kt
2259013003
/* 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.makeitso import android.content.res.Resources import androidx.compose.material.ScaffoldState import androidx.compose.runtime.Stable import androidx.navigation.NavHostController import com.example.makeitso.common.snackbar.SnackbarManager import com.example.makeitso.common.snackbar.SnackbarMessage.Companion.toMessage import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.flow.filterNotNull import kotlinx.coroutines.launch @Stable class MakeItSoAppState( val scaffoldState: ScaffoldState, 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) scaffoldState.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 } } } }
Make-It-So/start/app/src/main/java/com/example/makeitso/MakeItSoAppState.kt
950698670
/* 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.makeitso.theme import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Shapes import androidx.compose.ui.unit.dp val Shapes = Shapes( small = RoundedCornerShape(4.dp), medium = RoundedCornerShape(4.dp), large = RoundedCornerShape(0.dp) )
Make-It-So/start/app/src/main/java/com/example/makeitso/theme/Shape.kt
4147254942
/* 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.makeitso.theme import androidx.compose.ui.graphics.Color val BrightOrange = Color(0xFFFF8A65) val MediumOrange = Color(0xFFFFA000) val DarkOrange = Color(0xFFF57C00)
Make-It-So/start/app/src/main/java/com/example/makeitso/theme/Color.kt
853761130
/* 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.makeitso.theme import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material.MaterialTheme import androidx.compose.material.darkColors import androidx.compose.material.lightColors import androidx.compose.runtime.Composable private val DarkColorPalette = darkColors(primary = BrightOrange, primaryVariant = MediumOrange, secondary = DarkOrange) private val LightColorPalette = lightColors(primary = BrightOrange, primaryVariant = MediumOrange, secondary = DarkOrange) @Composable fun MakeItSoTheme(darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable() () -> Unit) { val colors = if (darkTheme) DarkColorPalette else LightColorPalette MaterialTheme(colors = colors, typography = Typography, shapes = Shapes, content = content) }
Make-It-So/start/app/src/main/java/com/example/makeitso/theme/Theme.kt
1102309055
/* 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.makeitso.theme import androidx.compose.material.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp val Typography = Typography( body1 = TextStyle(fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp) )
Make-It-So/start/app/src/main/java/com/example/makeitso/theme/Type.kt
2137908583
/* 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.makeitso import android.Manifest import android.content.res.Resources import android.os.Build import androidx.annotation.RequiresApi import androidx.compose.foundation.layout.padding import androidx.compose.material.* 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.compose.ui.platform.LocalConfiguration import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.unit.dp import androidx.navigation.NavGraphBuilder import androidx.navigation.NavHostController import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.rememberNavController import androidx.navigation.navArgument import com.example.makeitso.common.composable.PermissionDialog import com.example.makeitso.common.composable.RationaleDialog import com.example.makeitso.common.snackbar.SnackbarManager import com.example.makeitso.screens.edit_task.EditTaskScreen import com.example.makeitso.screens.login.LoginScreen import com.example.makeitso.screens.settings.SettingsScreen import com.example.makeitso.screens.sign_up.SignUpScreen import com.example.makeitso.screens.splash.SplashScreen import com.example.makeitso.screens.tasks.TasksScreen import com.example.makeitso.theme.MakeItSoTheme import com.google.accompanist.permissions.ExperimentalPermissionsApi import com.google.accompanist.permissions.isGranted import com.google.accompanist.permissions.rememberPermissionState import com.google.accompanist.permissions.shouldShowRationale import kotlinx.coroutines.CoroutineScope @Composable @ExperimentalMaterialApi fun MakeItSoApp() { MakeItSoTheme { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { RequestNotificationPermissionDialog() } Surface(color = MaterialTheme.colors.background) { val appState = rememberAppState() Scaffold( snackbarHost = { SnackbarHost( hostState = it, modifier = Modifier.padding(8.dp), snackbar = { snackbarData -> Snackbar(snackbarData, contentColor = MaterialTheme.colors.onPrimary) } ) }, scaffoldState = appState.scaffoldState ) { innerPaddingModifier -> NavHost( navController = appState.navController, startDestination = SPLASH_SCREEN, modifier = Modifier.padding(innerPaddingModifier) ) { makeItSoGraph(appState) } } } } } @RequiresApi(Build.VERSION_CODES.TIRAMISU) @OptIn(ExperimentalPermissionsApi::class) @Composable fun RequestNotificationPermissionDialog() { val permissionState = rememberPermissionState(permission = Manifest.permission.POST_NOTIFICATIONS) if (!permissionState.status.isGranted) { if (permissionState.status.shouldShowRationale) RationaleDialog() else PermissionDialog { permissionState.launchPermissionRequest() } } } @Composable fun rememberAppState( scaffoldState: ScaffoldState = rememberScaffoldState(), navController: NavHostController = rememberNavController(), snackbarManager: SnackbarManager = SnackbarManager, resources: Resources = resources(), coroutineScope: CoroutineScope = rememberCoroutineScope() ) = remember(scaffoldState, navController, snackbarManager, resources, coroutineScope) { MakeItSoAppState(scaffoldState, navController, snackbarManager, resources, coroutineScope) } @Composable @ReadOnlyComposable fun resources(): Resources { LocalConfiguration.current return LocalContext.current.resources } @ExperimentalMaterialApi fun NavGraphBuilder.makeItSoGraph(appState: MakeItSoAppState) { 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(TASKS_SCREEN) { TasksScreen(openScreen = { route -> appState.navigate(route) }) } composable( route = "$EDIT_TASK_SCREEN$TASK_ID_ARG", arguments = listOf(navArgument(TASK_ID) { nullable = true defaultValue = null }) ) { EditTaskScreen( popUpScreen = { appState.popUp() } ) } }
Make-It-So/start/app/src/main/java/com/example/makeitso/MakeItSoApp.kt
1440630700
/* 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.makeitso import android.os.Bundle import androidx.activity.compose.setContent import androidx.appcompat.app.AppCompatActivity import androidx.compose.material.ExperimentalMaterialApi import dagger.hilt.android.AndroidEntryPoint // MakeItSoActivity starts the first composable, which uses material cards that are still experimental. // TODO: Update material dependency and experimental annotations once the API stabilizes. @AndroidEntryPoint @ExperimentalMaterialApi class MakeItSoActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { MakeItSoApp() } } }
Make-It-So/start/app/src/main/java/com/example/makeitso/MakeItSoActivity.kt
1430978422