path
stringlengths 4
297
| contentHash
stringlengths 1
10
| content
stringlengths 0
13M
|
---|---|---|
Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/shared/ViewModel.kt | 443947927 | package tanoshi.multiplatform.shared
expect open class ViewModel() |
Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/shared/util/ApplicationActivity.kt | 3126102306 | package tanoshi.multiplatform.shared.util
expect open class ApplicationActivity {
fun <applicationActivity:ApplicationActivity> changeActivity(
applicationActivityName : Class<applicationActivity> ,
vararg objects : Any
)
} |
Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/shared/SharedApplicationData.kt | 2438729163 | package tanoshi.multiplatform.shared
import tanoshi.multiplatform.common.util.logger.Logger
import tanoshi.multiplatform.shared.extension.ExtensionManager
expect class SharedApplicationData {
val appStartUpTime : String
val logFileName : String
val extensionManager : ExtensionManager
val logger : Logger
val portrait : Boolean
} |
Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/common/extension/ViewableExtension.kt | 449393322 | package tanoshi.multiplatform.common.extension
import tanoshi.multiplatform.common.extension.interfaces.Extension
import tanoshi.multiplatform.common.util.SelectableMenu
interface ViewableExtension : Extension {
val name : String
val domainsList : SelectableMenu<String>
val language : String
fun search( name : String , index : Int ) : List<ViewableEntry>
fun fetchDetail( entry : ViewableEntry )
fun fetchPlayableContentList( entry : ViewableEntry )
fun fetchPlayableMedia( entry : ViewableContent ) : List<ViewableMedia>
} |
Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/common/extension/PlayableEntry.kt | 2572590830 | package tanoshi.multiplatform.common.extension
data class PlayableEntry(
var name : String? = null ,
var language : String? = null ,
var content : List<PlayableContent>? = null ,
var otherData : HashMap<String,String>? = null ,
var coverArt : String? = null ,
var url : String? = null
) |
Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/common/extension/ReadableExtension.kt | 4110173184 | package tanoshi.multiplatform.common.extension
import tanoshi.multiplatform.common.extension.interfaces.Extension
import tanoshi.multiplatform.common.util.SelectableMenu
interface ReadableExtension : Extension {
val name : String
val domainsList : SelectableMenu<String>
val language : String
fun search( name : String , index : Int ) : List<ReadableEntry>
fun fetchDetail( entry : ReadableEntry )
fun fetchPlayableContentList( entry : ReadableEntry )
fun fetchPlayableMedia( entry : ReadableContent ) : List<ReadableMedia>
} |
Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/common/extension/PlayableExtension.kt | 2299838097 | package tanoshi.multiplatform.common.extension
import tanoshi.multiplatform.common.extension.interfaces.Extension
import tanoshi.multiplatform.common.util.SelectableMenu
interface PlayableExtension : Extension {
val name : String
val domainsList : SelectableMenu<String>
val language : String
fun search( name : String , index : Int ) : List<PlayableEntry>
fun fetchDetail( entry : PlayableEntry )
fun fetchPlayableContentList( entry : PlayableEntry )
fun fetchPlayableMedia( entry : PlayableContent ) : List<PlayableMedia>
} |
Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/common/extension/ViewableMedia.kt | 3295507763 | package tanoshi.multiplatform.common.extension
data class ReadableMedia(
var content : String
) |
Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/common/extension/enum/ExtensionCategory.kt | 1748328503 | package tanoshi.multiplatform.common.extension.enum
enum class ExtensionCategory {
WATCHABLE ,
VIEWABLE ,
READABLE
} |
Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/common/extension/ReadableMedia.kt | 3958100157 | package tanoshi.multiplatform.common.extension
data class ViewableMedia(
var url : String
) |
Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/common/extension/PlayableContent.kt | 2207608528 | package tanoshi.multiplatform.common.extension
data class PlayableContent(
var name : String? = null ,
var url : String? = null ,
val lanuage : String? = null
) |
Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/common/extension/annotations/MUTABLEFILED.kt | 2580233381 | package tanoshi.multiplatform.common.extension.annotations
@Target( AnnotationTarget.FIELD )
@Retention( AnnotationRetention.RUNTIME )
// this is annoation is used to look for changing field
// present in an extension class
// acts as customization button for that class
annotation class MUTABLEFILED(
val fieldName : String
) |
Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/common/extension/annotations/GROUPMEMBER.kt | 3153538579 | package tanoshi.multiplatform.common.extension.annotations
@Target( AnnotationTarget.FIELD )
@Retention( AnnotationRetention.RUNTIME )
// filed marked with this annotation are loaded at runtime
// to make changes to them
// so when a function is invoked they can use these modified fields
// these are grouped using groupId
annotation class GROUPMEMBER(
vararg val groupId : String
) |
Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/common/extension/annotations/TAB.kt | 2695948593 | package tanoshi.multiplatform.common.extension.annotations
@Target( AnnotationTarget.FUNCTION )
@Retention( AnnotationRetention.RUNTIME )
// marked funtion will be loaded at runtime
annotation class TAB(
val fieldName : String
) |
Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/common/extension/annotations/GROUPHOLDER.kt | 380862241 | package tanoshi.multiplatform.common.extension.annotations
@Target( AnnotationTarget.FUNCTION )
@Retention( AnnotationRetention.RUNTIME )
// This annotation is used to filter out various filed that are not relevant to function
// so those which are relevent can be changed at runtime before function is invoked
// these are grouped using groupId
annotation class GROUPHOLDER(
vararg val groupId : String
) |
Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/common/extension/PlayableMedia.kt | 2695366321 | package tanoshi.multiplatform.common.extension
data class PlayableMedia(
var mediaUrl : String? = null ,
var mediaLang : String? = null ,
var subtitleUrl : String? = null ,
var subtitleLang : String? = null ,
var quality : String? = null ,
) |
Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/common/extension/helper/okhttp.kt | 2496568525 | package tanoshi.multiplatform.common.extension.helper
import com.squareup.okhttp.Request
import com.squareup.okhttp.Request.Builder
val String.request : Request
get() = Request.Builder()
.url( this )
.build()
infix fun String.request( builderScope : Builder.() -> Unit ): Request = Request.Builder()
.url( this )
.apply(builderScope)
.build()
val defaultArg : Builder.() -> Unit = {
addHeader( "User-Agent" , "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36" )
} |
Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/common/extension/ReadableContent.kt | 1770159981 | package tanoshi.multiplatform.common.extension
data class ReadableContent(
var name : String? = null ,
var url : String? = null ,
val lanuage : String? = null
) |
Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/common/extension/ApplicationAccess.kt | 1462113469 | package tanoshi.multiplatform.common.extension
import tanoshi.multiplatform.common.util.logger.Logger
open class ApplicationAccess {
var logger : Logger? = null
} |
Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/common/extension/ReadableEntry.kt | 2944792977 | package tanoshi.multiplatform.common.extension
data class ReadableEntry(
var name : String? = null ,
var language : String? = null ,
var content : List<ReadableContent>? = null ,
var otherData : HashMap<String,String>? = null ,
var url : String? = null
) |
Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/common/extension/ViewableContent.kt | 909748087 | package tanoshi.multiplatform.common.extension
data class ViewableContent(
var name : String? = null ,
var url : String? = null ,
val lanuage : String? = null
) |
Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/common/extension/interfaces/Extension.kt | 2690332857 | package tanoshi.multiplatform.common.extension.interfaces
interface Extension |
Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/common/extension/ViewableEntry.kt | 3460544523 | package tanoshi.multiplatform.common.extension
data class ViewableEntry(
var name : String? = null ,
var language : String? = null ,
var content : List<ViewableContent>? = null ,
var otherData : HashMap<String,String>? = null ,
var url : String? = null
) |
Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/common/util/logger/LogScope.kt | 4211375810 | package tanoshi.multiplatform.common.util.logger
import tanoshi.multiplatform.common.exception.logger.AnotherTagIsAlreadyInUseException
class LogScope {
private var tag : Tag = Tag.NOTSPECIFIED
val WARN : Unit
get() {
if ( tag != Tag.NOTSPECIFIED ) throw AnotherTagIsAlreadyInUseException( tag.toString() )
tag = Tag.WARN
}
val ERROR : Unit
get() {
if ( tag != Tag.NOTSPECIFIED ) throw AnotherTagIsAlreadyInUseException( tag.toString() )
tag = Tag.ERROR
}
val DEBUG : Unit
get() {
if ( tag != Tag.NOTSPECIFIED ) throw AnotherTagIsAlreadyInUseException( tag.toString() )
tag = Tag.DEBUG
}
override fun toString(): String = tag.toString()
enum class Tag( name : String ) {
WARN( "WARNING" ) ,
ERROR( "ERROR" ) ,
DEBUG( "DEBUG" ) ,
NOTSPECIFIED( "NOTSPECIFIED" ) ;
override fun toString(): String = name
}
} |
Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/common/util/logger/Logger.kt | 2515396478 | package tanoshi.multiplatform.common.util.logger
import tanoshi.multiplatform.common.exception.logger.LogFileAlreadyExist
import java.io.File
import java.lang.Exception
class Logger {
private val log : ArrayList<Pair<String,String>> = ArrayList()
fun saveLog( file : File , overwrite : Boolean = false ) {
if ( log.isEmpty() ) return
try {
if ( file.isFile && !overwrite ) throw LogFileAlreadyExist( file.name )
file.outputStream().bufferedWriter().use { logFile ->
logFile.write( toString() )
}
} catch ( _ : Exception ) {}
}
val read : String
get() = toString()
val list : List<Pair<String,String>>
get() = log
infix fun log(logScope : LogScope.() -> String ) = LogScope().run {
val message = logScope()
val tag = toString()
log.add(
Pair( tag , message )
)
}
override fun toString(): String {
val buffer = StringBuilder()
for ( ( tag , message ) in log ) buffer.append( "$tag : $message" )
return buffer.toString()
}
} |
Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/common/util/SelectableMenu.kt | 1938386783 | package tanoshi.multiplatform.common.util
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import tanoshi.multiplatform.common.exception.SelectableMenuIsImmutableException
import tanoshi.multiplatform.common.exception.SelectableMenuEntryNotFoundException
class SelectableMenu < T > (
initialEntry : T , vararg entries : T
) {
private val selectedElement : MutableState<T> = mutableStateOf( initialEntry )
val activeElement : MutableState<T>
get() = selectedElement
val activeElementValue : T
get() = selectedElement.value
private var list : ArrayList<T> = ArrayList()
private var isImmutable : Boolean = false
init {
add( initialEntry )
entries.forEach { entry ->
add( entry )
}
}
val changeMutability : Boolean
get() {
isImmutable = !isImmutable
return isImmutable
}
fun entries() : List<T> = list
fun add( entry : T ) {
if ( isImmutable ) throw SelectableMenuIsImmutableException( this )
if ( ! list.contains( entry ) )list.add( entry )
}
fun remove( entry : T ) {
if ( isImmutable ) throw SelectableMenuIsImmutableException( this )
if ( list.contains( entry ) ) list.remove( entry )
}
fun select( entry : T ) {
if ( ! list.contains( entry ) ) throw SelectableMenuEntryNotFoundException( entry.toString() )
selectedElement.value = entry
}
override fun toString(): String {
return """
|object hash : ${this.hashCode()}
|active value : ${selectedElement.value}
|list : ${list.toString().let {
it.substring( 1 , it.length-1 )
}}
""".trimMargin( "|" )
}
} |
Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/common/util/functions.kt | 74205228 | package tanoshi.multiplatform.common.util
import tanoshi.multiplatform.common.util.logger.Logger
import java.io.File
import java.text.SimpleDateFormat
import java.util.Calendar
val currentDateTime : String
get() = Calendar.getInstance().time.let { date ->
SimpleDateFormat( "yyyy-MM-dd-HH-mm-ss" ).let { formatter ->
formatter.format( date )
}
}
val String.toFile : File
get() = File( this )
fun logger() : Logger = Logger()
fun <T> selectableMenu(
initialValue : T , vararg entries : T
) : SelectableMenu<T> = SelectableMenu<T>(
initialValue , *entries
) |
Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/common/util/RestrictedClasses.kt | 1160311545 | package tanoshi.multiplatform.common.util
import java.io.File
val restrictedClasses : HashSet<String> = hashSetOf(
File::class.java.name
) |
Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/common/navigation/NavigationController.kt | 3074669592 | package tanoshi.multiplatform.common.navigation
import androidx.compose.runtime.*
// keep the current screen information and backstack
class NavigationController(
private val startScreen : String ,
stack : MutableSet<String> = mutableSetOf()
) {
var currentScreen by mutableStateOf( startScreen )
private var screenBackstack = stack
infix fun navigateTo( nextScreen : String ) {
if ( currentScreen == nextScreen ) return
if ( screenBackstack.contains( currentScreen ) ) screenBackstack.remove( currentScreen )
if ( nextScreen == startScreen ) screenBackstack = mutableSetOf()
else screenBackstack.add( currentScreen )
currentScreen = nextScreen
}
// back lambda stack it contains all that task that need to be done before invoking
// screen back function
val backLambdaStackObject = BackLambdaStack.backLambdaStack()
// back function
fun back() {
backLambdaStackObject.peek()?.run {
if ( invoke(backLambdaStackObject) != backLambdaStackObject.keepAfterInvocation ) backLambdaStackObject.pop()
return@back
}
if ( screenBackstack.isEmpty() ) return
currentScreen = screenBackstack.last()
screenBackstack.remove( currentScreen )
}
} |
Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/common/navigation/Components.kt | 3557703331 | package tanoshi.multiplatform.common.navigation
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import kotlin.reflect.KProperty
// This Component file is made so
// That all the function that are needed to make navigation stack
// can be imported by one import statement
// i.e import tanoshi.multiplatform.shared.naviagtion.*
// All the Nav Controller Component
fun navController(
startScreen: String ,
stack : MutableSet<String> = mutableSetOf()
) : NavigationController = NavigationController( startScreen , stack )
@Composable
fun NavController (
startScreen : String ,
stack : MutableSet<String> = mutableSetOf()
) : MutableState<NavigationController> = rememberSaveable {
mutableStateOf( NavigationController( startScreen, stack ) )
}
operator fun NavigationController.getValue( thisObj : Any? , kProperty: KProperty<*>) : NavigationController = this
infix fun NavigationController.backStackLambdaPush( lambda : BackLambdaStack.() -> Any ) = backLambdaStackObject.push(lambda)
fun NavigationController.backStackLambdPeek() = backLambdaStackObject.peek()
fun NavigationController.backStackLambdaPop() = backLambdaStackObject.pop()
val NavigationController.back : Unit
get() {
back()
}
// All The Navigation Host Component
@Composable
fun CreateScreenCatalog(
navigationController: NavigationController ,
screen : @Composable NavigationHost.NavigationGraphBuilder.() -> Unit
) = NavigationHost( navigationController , screen ).also { it.renderView() }
@Composable
fun NavigationHost.NavigationGraphBuilder.Screen(
route: String,
content: @Composable () -> Unit
) {
if (navigationController.currentScreen == route) content()
} |
Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/common/navigation/BackLambdaStack.kt | 2566634375 | package tanoshi.multiplatform.common.navigation
// why create this class because we are gonna perform stack operation
// and linked constant time for retrieval and addition
// lambda was extension of this class instead of simple lambda so it
// user can return status without any issue
class BackLambdaStack {
val keepAfterInvocation : WorkStatus = WorkStatus.KeepAfterInvocation
val removeAfterInvocation : WorkStatus = WorkStatus.RemoveAfterInvocation
enum class WorkStatus {
KeepAfterInvocation ,
RemoveAfterInvocation
}
private data class LambdaFunctionNode (
val lamda : BackLambdaStack.() -> Any ,
var prev : LambdaFunctionNode? = null
)
private var tail : LambdaFunctionNode? = null
fun push( backLambda : BackLambdaStack.() -> Any ) = backLambda.let { lockedValue ->
tail = LambdaFunctionNode( lockedValue , tail )
}
fun pop() = tail?.let {
tail = it.prev
}
fun peek() = tail?.let {
it.lamda
}
companion object {
fun backLambdaStack() : BackLambdaStack = BackLambdaStack()
}
} |
Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/common/navigation/NavigationHost.kt | 1775324647 | package tanoshi.multiplatform.common.navigation
import androidx.compose.runtime.Composable
class NavigationHost(
val navigationController: NavigationController ,
val content : @Composable NavigationGraphBuilder.() -> Unit
) {
@Composable
fun renderView() {
NavigationGraphBuilder().renderScreen()
}
inner class NavigationGraphBuilder(
val navigationController: NavigationController = [email protected]
) {
@Composable
fun renderScreen() {
[email protected](this)
}
}
} |
Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/common/screens/LogScreen.kt | 2162481347 | package tanoshi.multiplatform.common.screens
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import tanoshi.multiplatform.common.util.logger.Logger
@Composable
fun LogScreen(
logger : Logger
) {
// val scrollState = rememberLazyListState()
// val coroutineScope = rememberCoroutineScope()
LazyColumn (
modifier = Modifier
// .draggable(
// orientation = Orientation.Horizontal,
// state = rememberDraggableState { delta ->
// coroutineScope.launch {
// scrollState.scrollBy(-delta)
// }},
// )
.fillMaxSize()
.background( Color.White )
.padding( 10.dp )
.clip( RoundedCornerShape( 10.dp ) )
.background( Color.LightGray )
.padding( 10.dp )
){
for ( ( tag , message ) in logger.list ) {
item {
Column {
Text(
text = tag ,
modifier = Modifier
.fillMaxWidth()
.clip( RoundedCornerShape( 5.dp ) )
.background( tag.color )
.padding( horizontal = 10.dp ) ,
color = Color.Black ,
)
Text(
text = message ,
color = Color.Black
)
Spacer( Modifier.height( 10.dp ) )
}
}
}
// item {
// Text(
// text = log ,
// modifier = Modifier
// .fillMaxSize() ,
// color = Color.Black
// )
// }
}
}
private val String.color : Color
get() = when ( this ) {
"ERROR" -> Color.Red
"WARNING" -> Color.Yellow
"DEBUG" -> Color.Green
else -> Color.Black
} |
Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/common/screens/BrowseScreen.kt | 4206210974 | package tanoshi.multiplatform.common.screens
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import tanoshi.multiplatform.shared.SharedApplicationData
@Composable
fun BrowseScreen(
sharedData : SharedApplicationData
) {
Box( Modifier.fillMaxSize() , contentAlignment = Alignment.Center ) {
Text( "Browse Screen" )
}
} |
Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/common/screens/MainScreen.kt | 3572582064 | package tanoshi.multiplatform.common.screens
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.onClick
import androidx.compose.material.Icon
import androidx.compose.material.Scaffold
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Home
import androidx.compose.material.icons.filled.List
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.unit.dp
import tanoshi.multiplatform.common.model.MainScreenViewModel
import tanoshi.multiplatform.common.navigation.CreateScreenCatalog
import tanoshi.multiplatform.common.navigation.Screen
import tanoshi.multiplatform.shared.SharedApplicationData
@Composable
fun MainScreen(
sharedAppData : SharedApplicationData ,
viewModel : MainScreenViewModel
) = sharedAppData.run {
if ( portrait ) PortraitMainScreen( viewModel )
else LandscapeMainScreen( viewModel )
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun SharedApplicationData.PortraitMainScreen(
viewModel : MainScreenViewModel
) {
Scaffold(
bottomBar = {
Row(
modifier = Modifier
.fillMaxWidth()
.wrapContentHeight()
.padding( 5.dp ) ,
horizontalArrangement = Arrangement.SpaceEvenly ,
verticalAlignment = Alignment.CenterVertically
) {
MainScreen.entries.forEach { screen ->
Row(
Modifier.onClick {
viewModel.navController navigateTo screen.name
} ,
verticalAlignment = Alignment.CenterVertically
) {
Icon(
screen.icon ,
screen.label
)
AnimatedVisibility(
viewModel.navController.currentScreen == screen.name
) {
Text(
" ${screen.label}" ,
modifier = Modifier
.align(Alignment.CenterVertically)
)
}
}
}
}
}
) {
Box( Modifier.fillMaxSize().padding( it ) , contentAlignment = Alignment.Center ) {
MainScreenCatalog( viewModel = viewModel )
}
}
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun SharedApplicationData.LandscapeMainScreen( viewModel: MainScreenViewModel ) {
Row (
modifier = Modifier
.fillMaxSize()
) {
Column(
modifier = Modifier
.fillMaxHeight()
.wrapContentWidth()
.padding( 5.dp ) ,
horizontalAlignment = Alignment.CenterHorizontally ,
verticalArrangement = Arrangement.SpaceEvenly
) {
MainScreen.entries.forEach { screen ->
Column(
modifier = Modifier
.onClick {
viewModel.navController navigateTo screen.name
}
) {
Icon(
screen.icon ,
screen.label
)
// AnimatedVisibility(
// viewModel.navController.currentScreen == screen.label
// ) {
// Text( screen.label ,
// modifier = Modifier
// .align(Alignment.CenterHorizontally)
// )
// }
}
}
}
MainScreenCatalog( viewModel )
}
}
enum class MainScreen(
val label : String ,
val icon : ImageVector
) {
BrowseScreen(
"Browse Screen" ,
Icons.Filled.Home
) ,
LogScreen(
"Log Screen" ,
Icons.Filled.List
)
}
@Composable
private fun SharedApplicationData.MainScreenCatalog(
viewModel : MainScreenViewModel
) {
CreateScreenCatalog( viewModel.navController ) {
Screen( MainScreen.BrowseScreen.name ) {
BrowseScreen( this@MainScreenCatalog )
}
Screen( MainScreen.LogScreen.name ) {
LogScreen( logger )
}
}
} |
Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/common/model/MainScreenViewModel.kt | 3363067731 | package tanoshi.multiplatform.common.model
import tanoshi.multiplatform.common.navigation.NavigationController
import tanoshi.multiplatform.common.navigation.navController
import tanoshi.multiplatform.common.screens.MainScreen
import tanoshi.multiplatform.shared.ViewModel
class MainScreenViewModel : ViewModel() {
val navController : NavigationController = navController( startScreen = MainScreen.BrowseScreen.name )
} |
Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/common/exception/logger/LogFileAlreadyExist.kt | 3242429320 | package tanoshi.multiplatform.common.exception.logger
class LogFileAlreadyExist( filePath : String ) : Exception( "File : $filePath" ) |
Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/common/exception/logger/AnotherTagIsAlreadyInUseException.kt | 1509776942 | package tanoshi.multiplatform.common.exception.logger
class AnotherTagIsAlreadyInUseException( tag : String) : Exception(
"\nOnly one tag can be specified for a log scope block\nFirst One is Considered\nCurrently \"$tag\" is in active"
) |
Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/common/exception/SelectableMenuEntryNotFoundException.kt | 3407618291 | package tanoshi.multiplatform.common.exception
class SelectableMenuEntryNotFoundException( entry : String ) : Exception(
"Entry \"$entry\" Not Found In List"
) |
Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/common/exception/SelectableMenuIsImmutableException.kt | 2008946636 | package tanoshi.multiplatform.common.exception
import tanoshi.multiplatform.common.util.SelectableMenu
class SelectableMenuIsImmutableException( selectableMenuObj : SelectableMenu<*> ) : Exception(
"SelectableMenu object ${selectableMenuObj.hashCode()} is immutable"
) |
Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/common/exception/extensionManager/IllegalDependenciesFoundException.kt | 3307275293 | package tanoshi.multiplatform.common.exception.extensionManager
import java.lang.Exception
class IllegalDependenciesFoundException( msg : String ) : Exception( msg ) |
Tanoshi-Multiplatform/composeApp/src/desktopMain/kotlin/tanoshi/multiplatform/desktop/App.kt | 3312205442 | package tanoshi.multiplatform.desktop
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import tanoshi.multiplatform.common.model.MainScreenViewModel
import tanoshi.multiplatform.common.screens.MainScreen
import tanoshi.multiplatform.shared.util.ApplicationActivity
class App : ApplicationActivity() {
@Composable
override fun onCreate() {
val mainScreenViewModel by remember { mutableStateOf( MainScreenViewModel() ) }
MainScreen(
applicationData ,
mainScreenViewModel
)
}
} |
Tanoshi-Multiplatform/composeApp/src/desktopMain/kotlin/tanoshi/multiplatform/desktop/MyApplication.kt | 2215549171 | @file: JvmName( "MyApplication" )
package tanoshi.multiplatform.desktop
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Settings
import androidx.compose.ui.graphics.vector.rememberVectorPainter
import androidx.compose.ui.window.Window
import androidx.compose.ui.window.application
import tanoshi.multiplatform.common.screens.LogScreen
import tanoshi.multiplatform.desktop.util.WindowStack
import tanoshi.multiplatform.desktop.util.customApplication
import tanoshi.multiplatform.shared.SharedApplicationData
fun main() : Unit = SharedApplicationData().run {
logger log {
"App Started At $appStartUpTime"
}
val windowStack = WindowStack( App() , this )
customApplication( this ) {
Window( onCloseRequest = ::exitApplication ) {
windowStack.render()
}
}
error?.let {
application( false ) {
Window( onCloseRequest = ::exitApplication , title = "App Log" ,
icon = rememberVectorPainter(
Icons.Filled.Settings
)
) {
LogScreen( logger )
}
}
}
}
|
Tanoshi-Multiplatform/composeApp/src/desktopMain/kotlin/tanoshi/multiplatform/desktop/util/WindowStack.kt | 1759843490 | package tanoshi.multiplatform.desktop.util
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import tanoshi.multiplatform.shared.SharedApplicationData
import tanoshi.multiplatform.shared.util.ApplicationActivity
class WindowStack(
startActivity : ApplicationActivity ,
private val sharedApplicationData : SharedApplicationData
) {
private var _activeWindow : MutableState<ApplicationActivity> = mutableStateOf( startActivity )
val activeWindow : ApplicationActivity
get() = _activeWindow.value
init {
startActivity.windowStack = this
startActivity.applicationData = sharedApplicationData
}
private var stack : ArrayList<ApplicationActivity> = arrayListOf(
startActivity
)
fun add( activity : ApplicationActivity ) {
activity.windowStack = this
activity.applicationData = sharedApplicationData
stack.add( activity )
_activeWindow.value = activity
}
fun addAll( vararg activities : ApplicationActivity ) {
activities.forEach { activity ->
add( activity )
}
_activeWindow.value = stack.last()
}
fun remove( activity: ApplicationActivity ) {
stack.remove( activity )
_activeWindow.value = stack.last()
}
fun removeAll( vararg activities : ApplicationActivity ) {
stack.removeAll(activities.toSet())
_activeWindow.value = stack.last()
}
@Composable
fun render() {
_activeWindow.value.onCreate()
}
} |
Tanoshi-Multiplatform/composeApp/src/desktopMain/kotlin/tanoshi/multiplatform/desktop/util/component.kt | 2008485969 | package tanoshi.multiplatform.desktop.util
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.window.*
import tanoshi.multiplatform.shared.SharedApplicationData
import java.awt.event.WindowEvent
@OptIn(ExperimentalComposeUiApi::class)
@Composable
private fun ApplicationScope.redirectErrors(
sharedApplicationData : SharedApplicationData ,
content : @Composable () -> Unit
) = sharedApplicationData.run {
CompositionLocalProvider(
LocalWindowExceptionHandlerFactory provides WindowExceptionHandlerFactory { window ->
WindowExceptionHandler {
logger log {
ERROR
"Uncaught Exception\n${it.stackTraceToString()}"
}
error = it
window.dispatchEvent(WindowEvent(window, WindowEvent.WINDOW_CLOSING))
}
} ,
content = content
)
}
fun customApplication(
sharedApplicationData : SharedApplicationData,
content: @Composable ApplicationScope.() -> Unit
) = application(
exitProcessOnExit = false
) {
sharedApplicationData.applicationScope = this
redirectErrors( sharedApplicationData ) {
content()
}
}
|
Tanoshi-Multiplatform/composeApp/src/desktopMain/kotlin/tanoshi/multiplatform/shared/extension/ExtensionManager.desktop.kt | 1801407074 | package tanoshi.multiplatform.shared.extension
import tanoshi.multiplatform.common.exception.extensionManager.IllegalDependenciesFoundException
import tanoshi.multiplatform.common.util.restrictedClasses
import java.io.File
import java.io.FileInputStream
import java.util.zip.ZipFile
actual class ExtensionManager {
var dir : File = File( System.getProperty( "user.dir" ) )
actual val extensionLoader: ExtensionLoader = ExtensionLoader()
var mappedRestrictedDependencies = HashMap<String,HashSet<String>>()
private val String.isRestricted : Boolean
get() = restrictedClasses.contains( this )
private fun checkExtensionForRestrictedDepencies(
extension : String
) = ZipFile( extension ).use { zip ->
zip.entries().asSequence().forEach { zipEntry ->
if ( zipEntry.name.endsWith( ".class" ) ) {
val classBuffer = zip.getInputStream( zipEntry ).bufferedReader().use{ it.readText() }
checkRestrictedDependencies( zipEntry.name.replace( "/" , "." ) , classBuffer )
}
}
}
private fun checkRestrictedDependencies( parentClass : String , classBuffer : String ) = Regex( "L[0-9a-zA-Z/]*;" ).findAll( classBuffer )
.map { it.value.replace( "/" , "." ).replace( ";" , "" ).substring( 1 ) }
.let { dependencyClasses ->
dependencyClasses.forEach { dependencyName ->
if ( dependencyName.isRestricted ) {
mappedRestrictedDependencies[parentClass]?.add( dependencyName ) ?: run {
mappedRestrictedDependencies[parentClass] = hashSetOf( dependencyName )
}
}
}
}
actual fun install(extensionId: String, file: File) {
install( extensionId, file.inputStream() ) ;
}
actual fun install(extensionId: String, fileInputStream: FileInputStream) {
mappedRestrictedDependencies = HashMap()
// clean up
File( dir , "temp" ).deleteRecursively()
// write to temporary directory
val extensionFile = File( dir , "temp/$extensionId/extension.jar" )
extensionFile.absoluteFile.parentFile.let {
if ( !it.isDirectory ) it.mkdirs()
}
extensionFile.outputStream().use { extension ->
val buffer : ByteArray = ByteArray( 1024 )
var len : Int
while ( fileInputStream.read( buffer ).also { len = it } > 0 ) {
extension.write( buffer , 0 , len )
}
}
// inspect file for certain dependency
checkExtensionForRestrictedDepencies( extensionFile.absolutePath )
if ( mappedRestrictedDependencies.isNotEmpty() ) {
val buffer = StringBuilder()
for ( ( className , dependencies ) in mappedRestrictedDependencies ) buffer.append(
"""
|class : $className
|Restricted Dependencies : $dependencies
|
""".trimMargin()
)
throw IllegalDependenciesFoundException( buffer.toString() )
}
extensionFile.absoluteFile.parentFile.renameTo(
File( dir , extensionId )
)
}
actual fun uninstall(extensionId: String) {
File( dir , extensionId ).deleteRecursively()
}
} |
Tanoshi-Multiplatform/composeApp/src/desktopMain/kotlin/tanoshi/multiplatform/shared/extension/ExtensionLoader.desktop.kt | 409654829 | package tanoshi.multiplatform.shared.extension
import java.io.File
import java.net.URL
import java.net.URLClassLoader
import java.util.zip.ZipFile
import tanoshi.multiplatform.common.extension.interfaces.Extension
actual class ExtensionLoader {
actual val loadedExtensionClasses : HashMap< String , Extension > = HashMap()
actual fun loadTanoshiExtension( vararg tanoshiExtensionFile : String ) = tanoshiExtensionFile.forEach { extensionFile ->
try {
loadExtension( extensionFile )
} catch ( _ : Exception ) {
} catch ( _ : Error ){
}
}
private fun loadExtension(tanoshiExtensionFile : String ) {
val classLoader = URLClassLoader(
arrayOf( tanoshiExtensionFile.url ) ,
this.javaClass.classLoader
)
val classNameList : ArrayList<String> = ArrayList()
ZipFile( tanoshiExtensionFile ).use { zip ->
zip.entries().asSequence().forEach { zipEntry ->
if ( zipEntry.name.endsWith( ".class" ) ) classNameList.add( zipEntry.name.replace( "/" , "." ).removeSuffix( ".class" ) )
}
}
classNameList.forEach { name ->
try {
val loadedClass : Class<*> = classLoader.loadClass(name)
val obj : Any = loadedClass.getDeclaredConstructor().newInstance()
if ( obj is Extension ) loadedExtensionClasses[ name ] = obj
} catch ( _ : Exception ) {
} catch ( _ : Error ) {
}
}
}
private val String.url : URL
get() = File( this ).toURI().toURL()
} |
Tanoshi-Multiplatform/composeApp/src/desktopMain/kotlin/tanoshi/multiplatform/shared/util/ApplicationActivity.desktop.kt | 63343516 | package tanoshi.multiplatform.shared.util
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import tanoshi.multiplatform.desktop.util.WindowStack
import tanoshi.multiplatform.shared.SharedApplicationData
actual open class ApplicationActivity {
lateinit var applicationData : SharedApplicationData
lateinit var windowStack : WindowStack
@Composable
open fun onCreate() {
Box( Modifier.fillMaxSize() , contentAlignment = Alignment.Center ) {
Text( "Extend This Class For Creating Activities" )
}
}
open fun onPause() {
}
open fun onResume() {}
actual fun <applicationActivity:ApplicationActivity> changeActivity(
applicationActivityName : Class<applicationActivity> ,
vararg objects : Any
) = windowStack.add( applicationActivityName.getDeclaredConstructor().newInstance() )
} |
Tanoshi-Multiplatform/composeApp/src/desktopMain/kotlin/tanoshi/multiplatform/shared/SharedApplicationData.desktop.kt | 1781008161 | package tanoshi.multiplatform.shared
import androidx.compose.ui.window.ApplicationScope
import androidx.compose.ui.window.WindowState
import tanoshi.multiplatform.common.util.currentDateTime
import tanoshi.multiplatform.common.util.logger
import tanoshi.multiplatform.common.util.logger.Logger
import tanoshi.multiplatform.shared.extension.ExtensionManager
actual open class SharedApplicationData(
actual val appStartUpTime : String = currentDateTime,
actual val logFileName : String = "$appStartUpTime.log.txt",
actual val extensionManager : ExtensionManager = ExtensionManager(),
actual val logger : Logger = logger(),
val windowState: WindowState = WindowState() ,
) {
lateinit var applicationScope: ApplicationScope
var error : Throwable? = null
actual val portrait : Boolean
get() = windowState.size.height > windowState.size.width
} |
Tanoshi-Multiplatform/composeApp/src/desktopMain/kotlin/tanoshi/multiplatform/shared/ViewModel.desktop.kt | 3563830934 | package tanoshi.multiplatform.shared
actual open class ViewModel actual constructor() |
Tanoshi-Multiplatform/composeApp/src/androidMain/kotlin/tanoshi/multiplatform/proxy/onClick.kt | 2121464154 | package androidx.compose.foundation
import androidx.compose.ui.Modifier
fun Modifier.onClick(
enabled: Boolean = true ,
onClick : () -> Unit
) : Modifier = clickable(
enabled = enabled ,
onClick = onClick
) |
Tanoshi-Multiplatform/composeApp/src/androidMain/kotlin/tanoshi/multiplatform/shared/ViewModel.android.kt | 2474998959 | package tanoshi.multiplatform.shared
import androidx.lifecycle.ViewModel
actual open class ViewModel actual constructor() : ViewModel() |
Tanoshi-Multiplatform/composeApp/src/androidMain/kotlin/tanoshi/multiplatform/shared/SharedApplicationData.android.kt | 798331718 | package tanoshi.multiplatform.shared
import android.app.Application
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import tanoshi.multiplatform.common.util.currentDateTime
import tanoshi.multiplatform.common.util.logger
import tanoshi.multiplatform.common.util.logger.Logger
import tanoshi.multiplatform.shared.extension.ExtensionManager
actual open class SharedApplicationData(
actual val appStartUpTime : String = currentDateTime,
actual val logFileName : String = "$appStartUpTime.log.txt",
actual val extensionManager : ExtensionManager = ExtensionManager(),
actual val logger : Logger = logger() ,
var startCrashActivity : () -> Unit = {}
) : Application() {
var _portrait : Boolean by mutableStateOf( true )
actual val portrait : Boolean
get() = _portrait
} |
Tanoshi-Multiplatform/composeApp/src/androidMain/kotlin/tanoshi/multiplatform/shared/extension/ExtensionManager.android.kt | 790933708 | package tanoshi.multiplatform.shared.extension
import android.content.Context
import tanoshi.multiplatform.common.exception.extensionManager.IllegalDependenciesFoundException
import tanoshi.multiplatform.common.util.restrictedClasses
import java.io.File
import java.io.FileInputStream
import java.util.zip.ZipFile
actual class ExtensionManager {
private lateinit var _applicationContext : Context
actual val extensionLoader: ExtensionLoader = ExtensionLoader()
var applicationContext : Context
get() = _applicationContext
set(value) {
extensionLoader.applicationContext = value
_applicationContext = value
}
var mappedRestrictedDependencies = HashMap<String,HashSet<String>>()
private val String.isRestricted : Boolean
get() = restrictedClasses.contains( this )
private fun checkExtensionForRestrictedDepencies(
pathToDex : File
) = checkRestrictedDependencies( pathToDex.toString() , pathToDex.readText() )
private fun checkRestrictedDependencies( parentClass : String , classBuffer : String ) = Regex( "L[0-9a-zA-Z/]*;" ).findAll( classBuffer )
.map { it.value.replace( "/" , "." ).replace( ";" , "" ).substring( 1 ) }
.let { dependencyClasses ->
dependencyClasses.forEach { dependencyName ->
if ( dependencyName.isRestricted ) {
mappedRestrictedDependencies[parentClass]?.add( dependencyName ) ?: run {
mappedRestrictedDependencies[parentClass] = hashSetOf( dependencyName )
}
}
}
}
actual fun install( extensionId: String , file: File ) {
install( extensionId , file.inputStream() )
}
actual fun install(extensionId: String, fileInputStream: FileInputStream) : Unit = _applicationContext.run {
// clean up
mappedRestrictedDependencies = HashMap()
getDir( "extension/temp" , Context.MODE_PRIVATE ).deleteRecursively()
// extract extension in temporary directory
val extensionDir = getDir( "extension/temp/$extensionId" , Context.MODE_PRIVATE ).also {
if ( !it.isDirectory ) it.mkdirs()
}
val extensionFile = File( extensionDir , "extension.tanoshi" )
extensionFile.outputStream().use { output ->
fileInputStream.use { input ->
val buffer = ByteArray( 1024 )
var len = 0
while ( input.read( buffer ).also { len = it } > 0 ) {
output.write( buffer , 0 , len )
}
}
}
ZipFile( extensionFile ).use { extension ->
extension.entries().asSequence().forEach { entry ->
val name = entry.name
if ( name.endsWith( ".dex" ) ) {
extension.getInputStream( entry ).use { input ->
File(
extensionDir ,
if ( name.contains( "/" ) ) name.substring( name.lastIndexOf( "/" )+1 )
else name
).outputStream().use { output ->
val buffer = ByteArray( 1024 )
var len = 0
while ( input.read( buffer ).also { len = it } > 0 ) {
output.write( buffer , 0 , len )
}
}
}
}
}
}
// check for restricted dependency
extensionDir.listFiles().forEach {
if ( it.name.endsWith( ".dex" ) ) {
checkExtensionForRestrictedDepencies( it )
}
}
if ( mappedRestrictedDependencies.isNotEmpty() ) {
val buffer = StringBuilder()
for ( ( className , dependencies ) in mappedRestrictedDependencies ) buffer.append(
"""
|class : $className
|Restricted Dependencies : $dependencies
|
""".trimMargin()
)
throw IllegalDependenciesFoundException( "$buffer" )
}
// installed
extensionDir.renameTo(
getDir(
"extension/$extensionId" , Context.MODE_PRIVATE
)
)
}
actual fun uninstall(extensionId: String) : Unit = _applicationContext.run {
getDir( "extension/$extensionId" , Context.MODE_PRIVATE ).deleteRecursively()
}
} |
Tanoshi-Multiplatform/composeApp/src/androidMain/kotlin/tanoshi/multiplatform/shared/extension/ExtensionLoader.android.kt | 4127710791 | package tanoshi.multiplatform.shared.extension
import android.content.Context
import tanoshi.multiplatform.common.extension.interfaces.Extension
import java.io.File
import java.lang.Exception
import dalvik.system.PathClassLoader
actual class ExtensionLoader {
lateinit var applicationContext : Context
actual val loadedExtensionClasses : HashMap< String , Extension > = HashMap()
actual fun loadTanoshiExtension( vararg tanoshiExtensionFile : String ) {
if ( !::applicationContext.isInitialized ) throw UninitializedPropertyAccessException( "application context not initialised" )
tanoshiExtensionFile.forEach { tanoshiFile ->
loadTanoshiFile( tanoshiFile )
}
}
private fun loadTanoshiFile( tanoshiExtensionFile: String ) = applicationContext.run {
val dexFiles : List<String> = getDir( "extension/$tanoshiExtensionFile" , Context.MODE_PRIVATE ).listFiles().run {
val listOfDexFile = ArrayList<String>()
forEach { file ->
val fileString = file.toString()
if ( fileString.endsWith( ".dex" ) ) listOfDexFile.add(
if ( fileString.contains( "/" ) ) fileString.substring( fileString.lastIndexOf( "/" )+1 )
else fileString
)
}
listOfDexFile
}
dexFiles.forEach { dexName ->
try {
loadDexFile( tanoshiExtensionFile , dexName )
} catch ( _ : Exception ) {
} catch ( _ : Error ) { }
}
}
private fun loadDexFile( tanoshiExtensionFile: String , dexFileName : String ) = applicationContext.run {
val file = File( getDir( "extension/$tanoshiExtensionFile" , Context.MODE_PRIVATE ) , dexFileName )
val classLoader = PathClassLoader( file.absolutePath , classLoader )
val classNameList : List<String> = Regex( "L[a-zA-Z0-9/]*;" ).findAll( file.readText() ).run {
val nameList = ArrayList<String>( count() )
forEach { lClassPath ->
nameList.add(
lClassPath.value.substring( 1 , lClassPath.value.length-1 ).replace( "/" , "." )
)
}
nameList
}
classNameList.forEach { className ->
try {
val loadedClass : Class<*> = classLoader.loadClass( className )
val obj : Any = loadedClass.getDeclaredConstructor().newInstance()
if ( obj is Extension ) loadedExtensionClasses[className] = obj as Extension
} catch ( _ : Exception ) {
} catch ( _ : Error ) {
}
}
}
} |
Tanoshi-Multiplatform/composeApp/src/androidMain/kotlin/tanoshi/multiplatform/shared/util/ApplicationActivity.android.kt | 3328069876 | package tanoshi.multiplatform.shared.util
import android.content.Intent
import android.content.res.Configuration
import android.os.Bundle
import androidx.activity.ComponentActivity
import tanoshi.multiplatform.shared.SharedApplicationData
actual open class ApplicationActivity : ComponentActivity() {
lateinit var sharedApplicationData : SharedApplicationData
lateinit var saved : () -> Unit
override fun onCreate(savedInstanceState: Bundle? ) {
sharedApplicationData = application as SharedApplicationData
sharedApplicationData._portrait = resources.configuration.orientation == 1
sharedApplicationData.startCrashActivity = {}
super.onCreate(savedInstanceState)
}
override fun onConfigurationChanged(newConfig: Configuration) {
sharedApplicationData._portrait = newConfig.orientation == 1
super.onConfigurationChanged(newConfig)
}
override fun onResume() {
super.onResume()
sharedApplicationData.startCrashActivity = saved
}
actual fun <applicationActivity:ApplicationActivity> changeActivity(
applicationActivityName : Class<applicationActivity> ,
vararg objects : Any
) {
val intent = Intent( this@ApplicationActivity , applicationActivityName )
startActivity( intent )
}
}
var ApplicationActivity.setCrashActivity : Class<*>
get() = "This Variable is Used to assign Crash Activity" as Class<*>
set(value) {
sharedApplicationData.startCrashActivity = {
finish()
startActivity( Intent( this , value ) )
}.also {
saved = it
}
sharedApplicationData.logger log {
DEBUG
"Attached Crash Handling Activity : ${this@setCrashActivity::class.java} -> ${value.canonicalName}".replace( "class" , "" )
}
}
|
Tanoshi-Multiplatform/composeApp/src/androidMain/kotlin/tanoshi/multiplatform/android/MyApplication.kt | 40489778 | package tanoshi.multiplatform.android
import android.widget.Toast
import tanoshi.multiplatform.shared.SharedApplicationData
class MyApplication : SharedApplicationData() {
override fun onCreate() {
super.onCreate()
logger log {
DEBUG
"App Started At $appStartUpTime"
}
extensionManager.apply {
applicationContext = [email protected]
}
// set uncaught exception thread
Thread.setDefaultUncaughtExceptionHandler { thread, throwable ->
handleUncaughtException( thread , throwable )
}
}
private fun handleUncaughtException( thread : Thread , throwable : Throwable ) {
logger log {
ERROR
throwable.stackTraceToString()
}
startCrashActivity()
}
} |
Tanoshi-Multiplatform/composeApp/src/androidMain/kotlin/tanoshi/multiplatform/android/activities/MainActivity.kt | 3742233989 | package tanoshi.multiplatform.android.activities
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.activity.viewModels
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import tanoshi.multiplatform.shared.util.ApplicationActivity
import tanoshi.multiplatform.shared.util.setCrashActivity
import tanoshi.multiplatform.common.model.MainScreenViewModel
import tanoshi.multiplatform.common.screens.MainScreen
class MainActivity : ApplicationActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setCrashActivity = CrashActivity::class.java
val mainScreenViewModel by viewModels<MainScreenViewModel>()
setContent {
Column {
Spacer( Modifier.height( 20.dp ) )
MainScreen(
sharedApplicationData ,
mainScreenViewModel
)
}
}
}
}
@Preview
@Composable
fun AppAndroidPreview() {} |
Tanoshi-Multiplatform/composeApp/src/androidMain/kotlin/tanoshi/multiplatform/android/activities/SecondActivity.kt | 1785667683 | package tanoshi.multiplatform.android.activities
import android.content.Intent
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.ui.Modifier
import tanoshi.multiplatform.shared.util.ApplicationActivity
import tanoshi.multiplatform.shared.util.setCrashActivity
class SecondActivity : ApplicationActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setCrashActivity = CrashActivity::class.java
setContent {
Column( verticalArrangement = Arrangement.Center , modifier = Modifier.fillMaxSize() ) {
Text( "Second Acitivity" )
Button( {
throw Exception( "\n\n\n\nWhatever" )
} ) {
Text( "Portrait : ${sharedApplicationData?.portrait}" )
}
Button( {
val i = Intent( this@SecondActivity , MainActivity::class.java )
startActivity( i )
} ) {
Text( "Change Activity" )
}
}
}
}
} |
Tanoshi-Multiplatform/composeApp/src/androidMain/kotlin/tanoshi/multiplatform/android/activities/CrashActivity.kt | 3029788796 | package tanoshi.multiplatform.android.activities
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import tanoshi.multiplatform.common.screens.LogScreen
import tanoshi.multiplatform.shared.SharedApplicationData
class CrashActivity : ComponentActivity() {
lateinit var sharedApplicaData : SharedApplicationData
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
sharedApplicaData = application as SharedApplicationData
setContent {
Column( Modifier.fillMaxSize() ) {
Spacer( Modifier.height( 20.dp ) )
LogScreen(
sharedApplicaData.logger
)
}
}
}
} |
Tanoshi-Multiplatform/extensions/src/commonMain/kotlin/tanoshi/extensions/anime/Gogoanime.kt | 3140014520 | package tanoshi.extensions.anime
import com.squareup.okhttp.OkHttpClient
import com.squareup.okhttp.Request
import org.jsoup.Jsoup
import tanoshi.multiplatform.common.extension.*
import tanoshi.multiplatform.common.extension.helper.defaultArg
import tanoshi.multiplatform.common.extension.helper.request
import tanoshi.multiplatform.common.util.SelectableMenu
class Gogoanime : PlayableExtension , ApplicationAccess() {
override val name: String = "Gogoanime"
override val domainsList: SelectableMenu<String> = SelectableMenu( "https://ww2.gogoanimes.fi/" )
override val language: String = "English"
override fun search(name: String, index: Int): List<PlayableEntry> {
val list = ArrayList<PlayableEntry>()
val searchQuery = "https://ww2.gogoanimes.fi/search.html?keyword=${
name.trimStart().trimEnd().replace( " " , " " ).replace( " " , "%20" )
}&page=$index"
val client = OkHttpClient()
val request = Request.Builder()
.url( searchQuery )
.get()
.build()
val response = client.newCall( request ).execute()
Jsoup.parse( response.body().string() )
.select( "ul.items>li" )
.forEach {
try {
list.add(
PlayableEntry(
name = it.select( "div>a" ).attr( "title" ) ,
url = domainsList.activeElementValue + it.select( "p.name>a" ).attr("href").substring(1) ,
coverArt = it.select( "div.img > a > img" ).attr( "src" )
)
)
} catch ( _ : Exception ) {}
}
return list
}
override fun fetchDetail(entry: PlayableEntry) {
TODO("Not yet implemented")
}
override fun fetchPlayableContentList(entry: PlayableEntry) {
TODO("Not yet implemented")
}
override fun fetchPlayableMedia(entry: PlayableContent): List<PlayableMedia> {
TODO("Not yet implemented")
}
}
fun main() {
Gogoanime().search( "One Piece" , 1 ).forEach {
println( it.name )
println( it.url )
println( it.coverArt )
}
} |
Peduli-Pangan-Android/app/src/androidTest/java/com/alvintio/pedulipangan/ExampleInstrumentedTest.kt | 3239401735 | package com.alvintio.pedulipangan
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.alvintio.pedulipangan", appContext.packageName)
}
} |
Peduli-Pangan-Android/app/src/test/java/com/alvintio/pedulipangan/ExampleUnitTest.kt | 3101854946 | package com.alvintio.pedulipangan
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)
}
} |
Peduli-Pangan-Android/app/src/main/java/com/alvintio/pedulipangan/viewmodel/AuthenticationViewModel.kt | 711081266 | package com.alvintio.pedulipangan.viewmodel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.alvintio.pedulipangan.model.User
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.UserProfileChangeRequest
import com.google.firebase.firestore.FirebaseFirestore
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.tasks.await
class AuthenticationViewModel : ViewModel() {
private val auth: FirebaseAuth = FirebaseAuth.getInstance()
private val firestore: FirebaseFirestore = FirebaseFirestore.getInstance()
private val _loginState = MutableLiveData<LoginState>()
val loginState: LiveData<LoginState>
get() = _loginState
private val _userInfo = MutableLiveData<User>()
val userInfo: LiveData<User>
get() = _userInfo
sealed class LoginState {
object Success : LoginState()
class Error(val message: String) : LoginState()
}
fun register(name: String, email: String, password: String) {
viewModelScope.launch(Dispatchers.IO) {
try {
val authResult = auth.createUserWithEmailAndPassword(email, password).await()
authResult.user?.updateProfile(UserProfileChangeRequest.Builder().setDisplayName(name).build())?.await()
val user = User(name, email, authResult.user?.uid ?: "")
_userInfo.postValue(user)
firestore.collection("users")
.document(authResult.user?.uid ?: "")
.set(user)
.await()
_loginState.postValue(LoginState.Success)
} catch (e: Exception) {
_loginState.postValue(LoginState.Error(e.message ?: "Registration error"))
}
}
}
fun login(email: String, password: String) {
viewModelScope.launch(Dispatchers.IO) {
try {
val authResult = auth.signInWithEmailAndPassword(email, password).await()
val user = User(
authResult.user?.displayName ?: "",
authResult.user?.email ?: "",
authResult.user?.uid ?: ""
)
_userInfo.postValue(user)
_loginState.postValue(LoginState.Success)
} catch (e: Exception) {
_loginState.postValue(LoginState.Error(e.message ?: "Login error"))
}
}
}
}
|
Peduli-Pangan-Android/app/src/main/java/com/alvintio/pedulipangan/viewmodel/NotificationsViewModel.kt | 1436033325 | package com.alvintio.pedulipangan.viewmodel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.alvintio.pedulipangan.model.Notification
class NotificationsViewModel : ViewModel() {
private val _notifications = MutableLiveData<List<Notification>>()
val notifications: LiveData<List<Notification>> get() = _notifications
fun addNotification(notification: Notification) {
_notifications.value = _notifications.value.orEmpty() + listOf(notification)
}
}
|
Peduli-Pangan-Android/app/src/main/java/com/alvintio/pedulipangan/viewmodel/SharedViewModel.kt | 3543494089 | package com.alvintio.pedulipangan.viewmodel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
class SharedViewModel : ViewModel() {
private val _searchQuery = MutableLiveData<String>()
val searchQuery: LiveData<String> get() = _searchQuery
fun setSearchQuery(query: String) {
_searchQuery.value = query
}
} |
Peduli-Pangan-Android/app/src/main/java/com/alvintio/pedulipangan/ui/settings/SettingsFragment.kt | 1739983190 | package com.alvintio.pedulipangan.ui.settings
import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.ViewModelProvider
import com.alvintio.pedulipangan.databinding.FragmentSettingsBinding
import com.alvintio.pedulipangan.view.WelcomeActivity
import com.google.firebase.auth.FirebaseAuth
class SettingsFragment : Fragment() {
private lateinit var auth: FirebaseAuth
private var _binding: FragmentSettingsBinding? = null
private val binding get() = _binding!!
private lateinit var settingsViewModel: SettingsViewModel
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
settingsViewModel = ViewModelProvider(this).get(SettingsViewModel::class.java)
auth = FirebaseAuth.getInstance()
_binding = FragmentSettingsBinding.inflate(inflater, container, false)
val root: View = binding.root
binding.btnLogout.setOnClickListener {
settingsViewModel.logout()
val intent = Intent(requireContext(), WelcomeActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK
startActivity(intent)
requireActivity().finish()
}
return root
}
override fun onResume() {
super.onResume()
val currentUser = auth.currentUser
if (currentUser != null) {
settingsViewModel.getUserData(currentUser.uid)
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
settingsViewModel.userData.observe(viewLifecycleOwner) { userData ->
binding.tvUserName.text = userData.name
binding.tvUserEmail.text = userData.email
}
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
|
Peduli-Pangan-Android/app/src/main/java/com/alvintio/pedulipangan/ui/settings/SettingsViewModel.kt | 2695807145 | package com.alvintio.pedulipangan.ui.settings
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.alvintio.pedulipangan.model.User
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.firestore.DocumentReference
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.firestore.ListenerRegistration
class SettingsViewModel : ViewModel() {
private val firestore: FirebaseFirestore = FirebaseFirestore.getInstance()
private val _userData = MutableLiveData<User>()
val userData: LiveData<User>
get() = _userData
private var userDataListener: ListenerRegistration? = null
fun logout() {
FirebaseAuth.getInstance().signOut()
}
fun getUserData(uid: String) {
val userRef: DocumentReference = firestore.collection("users").document(uid)
userDataListener?.remove()
userDataListener = userRef.addSnapshotListener { documentSnapshot, _ ->
if (documentSnapshot != null && documentSnapshot.exists()) {
val user = documentSnapshot.toObject(User::class.java)
if (user != null) {
_userData.value = user
} else {
}
}
}
}
override fun onCleared() {
userDataListener?.remove()
super.onCleared()
}
} |
Peduli-Pangan-Android/app/src/main/java/com/alvintio/pedulipangan/ui/home/HomeViewModel.kt | 1341390846 | package com.alvintio.pedulipangan.ui.home
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
class HomeViewModel : ViewModel() {
private val _text = MutableLiveData<String>().apply {
value = "This is home Fragment"
}
val text: LiveData<String> = _text
} |
Peduli-Pangan-Android/app/src/main/java/com/alvintio/pedulipangan/ui/home/HomeFragment.kt | 1909359315 | package com.alvintio.pedulipangan.ui.home
import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.content.pm.PackageManager
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import com.alvintio.pedulipangan.adapter.FoodAdapter
import com.alvintio.pedulipangan.data.remote.ApiConfig
import com.alvintio.pedulipangan.databinding.FragmentHomeBinding
import com.alvintio.pedulipangan.model.Food
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.firestore.FirebaseFirestore
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
class HomeFragment : Fragment() {
private var _binding: FragmentHomeBinding? = null
private val binding get() = _binding!!
private val locationManager by lazy {
requireContext().getSystemService(Context.LOCATION_SERVICE) as LocationManager
}
private val locationPermissionCode = 123
private var userLatitude: Double = 0.0
private var userLongitude: Double = 0.0
private var userLocation: Location? = null
private lateinit var auth: FirebaseAuth
private lateinit var firestore: FirebaseFirestore
@SuppressLint("SetTextI18n")
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = FragmentHomeBinding.inflate(inflater, container, false)
val view = binding.root
auth = FirebaseAuth.getInstance()
firestore = FirebaseFirestore.getInstance()
val userId = auth.currentUser?.uid
userId?.let {
firestore.collection("users").document(it).get()
.addOnSuccessListener { document ->
if (document != null) {
val username = document.getString("name")
binding.tvTitle.text = "Selamat Datang, $username!"
} else {
Log.d("HomeFragment", "Dokumen tidak ditemukan.")
}
}
.addOnFailureListener { exception ->
Log.d("HomeFragment", "Gagal membaca data: $exception")
}
}
getUserLocation()
getProducts()
if (hasLocationPermission()) {
getNearestRestaurants()
} else {
requestLocationPermission()
}
return view
}
private fun hasLocationPermission(): Boolean {
return ActivityCompat.checkSelfPermission(
requireContext(),
Manifest.permission.ACCESS_FINE_LOCATION
) == PackageManager.PERMISSION_GRANTED
}
private fun requestLocationPermission() {
ActivityCompat.requestPermissions(
requireActivity(),
arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
locationPermissionCode
)
}
@Deprecated("Deprecated in Java")
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == locationPermissionCode) {
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
getProducts()
getNearestRestaurants()
} else {
Toast.makeText(
requireContext(),
"Location permission denied",
Toast.LENGTH_SHORT
).show()
}
}
}
private fun getUserLocation() {
if (hasLocationPermission()) {
try {
val locationListener = object : LocationListener {
override fun onLocationChanged(location: Location) {
userLatitude = location.latitude
userLongitude = location.longitude
Log.d("UserLocation", "Latitude: $userLatitude, Longitude: $userLongitude")
}
override fun onStatusChanged(provider: String?, status: Int, extras: Bundle?) {}
override fun onProviderEnabled(provider: String) {}
override fun onProviderDisabled(provider: String) {}
}
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
1000,
1f,
locationListener
)
val lastKnownLocation: Location? =
locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER)
?: locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER)
lastKnownLocation?.let {
userLatitude = it.latitude
userLongitude = it.longitude
userLocation = it
Log.d("UserLocation", "Latitude: $userLatitude, Longitude: $userLongitude")
}
} catch (e: SecurityException) {
Toast.makeText(
requireContext(),
"Location permission is required",
Toast.LENGTH_SHORT
).show()
}
}
}
private fun getNearestRestaurants() {
if (hasLocationPermission()) {
val apiService = ApiConfig.getApiService()
try {
val lastKnownLocation: Location? =
locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER)
?: locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER)
lastKnownLocation?.let { location ->
apiService.getProducts()
.enqueue(object : Callback<List<Food>> {
override fun onResponse(
call: Call<List<Food>>,
response: Response<List<Food>>
) {
if (response.isSuccessful) {
val restaurantList = response.body()
restaurantList?.let {
val nearestRestaurants = filterRestaurantsByDistance(
it,
location.latitude,
location.longitude,
15.0 // Jarak maksimal dalam kilometer
)
Log.d("Restaurants", nearestRestaurants.toString())
setupNearestRestaurantRecyclerView(nearestRestaurants)
}
} else {
Toast.makeText(
requireContext(),
"Failed to get nearest restaurants",
Toast.LENGTH_SHORT
).show()
}
}
override fun onFailure(call: Call<List<Food>>, t: Throwable) {
Toast.makeText(
requireContext(),
"Error: ${t.message}",
Toast.LENGTH_SHORT
).show()
}
})
}
} catch (e: SecurityException) {
Toast.makeText(
requireContext(),
"Location permission is required",
Toast.LENGTH_SHORT
).show()
}
}
}
private fun filterRestaurantsByDistance(
restaurants: List<Food>,
userLatitude: Double,
userLongitude: Double,
maxDistance: Double
): List<Food> {
val filteredRestaurants = mutableListOf<Food>()
userLocation?.let { userLoc ->
for (restaurant in restaurants) {
val restaurantLocation = Location("RestaurantLocation")
restaurantLocation.latitude = restaurant.latitude
restaurantLocation.longitude = restaurant.longitude
val distance = userLoc.distanceTo(restaurantLocation) / 1000
if (distance <= maxDistance) {
filteredRestaurants.add(restaurant)
}
}
}
return filteredRestaurants
}
private fun setupNearestRestaurantRecyclerView(restaurantList: List<Food>) {
val foodAdapter = FoodAdapter(restaurantList)
foodAdapter.setUserLocation(userLatitude, userLongitude)
val layoutManager = LinearLayoutManager(requireContext(), LinearLayoutManager.HORIZONTAL, false)
binding.recyclerViewNearestRestaurant.layoutManager = layoutManager
binding.recyclerViewNearestRestaurant.adapter = foodAdapter
}
private fun getProducts() {
val apiService = ApiConfig.getApiService()
apiService.getProducts().enqueue(object : Callback<List<Food>> {
override fun onResponse(call: Call<List<Food>>, response: Response<List<Food>>) {
if (response.isSuccessful) {
val productList = response.body()
productList?.let {
val randomProducts = it.shuffled().take(5)
setupRecyclerView(randomProducts)
}
} else {
Toast.makeText(
requireContext(),
"Failed to get products",
Toast.LENGTH_SHORT
).show()
}
}
override fun onFailure(call: Call<List<Food>>, t: Throwable) {
Toast.makeText(requireContext(), "Error: ${t.message}", Toast.LENGTH_SHORT).show()
}
})
}
private fun setupRecyclerView(productList: List<Food>) {
val foodAdapter = FoodAdapter(productList)
val layoutManager =
LinearLayoutManager(requireContext(), LinearLayoutManager.HORIZONTAL, false)
binding.recyclerView.layoutManager = layoutManager
binding.recyclerView.adapter = foodAdapter
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
|
Peduli-Pangan-Android/app/src/main/java/com/alvintio/pedulipangan/ui/dashboard/DashboardFragment.kt | 2510694492 | package com.alvintio.pedulipangan.ui.dashboard
import android.annotation.SuppressLint
import android.os.Bundle
import android.util.Log
import android.view.*
import android.widget.SearchView
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.viewpager2.widget.ViewPager2
import com.alvintio.pedulipangan.R
import com.alvintio.pedulipangan.databinding.FragmentDashboardBinding
import com.alvintio.pedulipangan.viewmodel.SharedViewModel
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
class DashboardFragment : Fragment() {
private var _binding: FragmentDashboardBinding? = null
private val binding get() = _binding!!
private lateinit var sharedViewModel: SharedViewModel
@SuppressLint("UseCompatLoadingForColorStateLists")
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
sharedViewModel = ViewModelProvider(requireActivity()).get(SharedViewModel::class.java)
_binding = FragmentDashboardBinding.inflate(inflater, container, false)
val root: View = binding.root
val viewPager: ViewPager2 = root.findViewById(R.id.viewPager)
val adapter = DashboardPagerAdapter(requireActivity())
viewPager.adapter = adapter
viewPager.isUserInputEnabled = false
val searchView = binding.searchView
searchView.isFocusable = true
searchView.isFocusableInTouchMode = true
searchView.isClickable = true
searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(query: String?): Boolean {
return true
}
override fun onQueryTextChange(newText: String?): Boolean {
sharedViewModel.setSearchQuery(newText.orEmpty())
return true
}
})
val tabLayout: TabLayout = root.findViewById(R.id.tabLayout)
tabLayout.setBackgroundColor(resources.getColor(R.color.dark_green))
tabLayout.tabTextColors = resources.getColorStateList(R.color.black)
TabLayoutMediator(tabLayout, viewPager) { tab, position ->
tab.text = when (position) {
0 -> getString(R.string.list_dashboard)
1 -> getString(R.string.map_dashboard)
else -> throw IllegalArgumentException("Invalid position")
}
}.attach()
return root
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
|
Peduli-Pangan-Android/app/src/main/java/com/alvintio/pedulipangan/ui/dashboard/DashboardPagerAdapter.kt | 1589452372 | package com.alvintio.pedulipangan.ui.dashboard
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.alvintio.pedulipangan.ui.list.ListFragment
import com.alvintio.pedulipangan.ui.map.MapsFragment
class DashboardPagerAdapter(fragmentActivity: FragmentActivity) :
FragmentStateAdapter(fragmentActivity) {
override fun getItemCount(): Int {
return 2
}
override fun createFragment(position: Int): Fragment {
return when (position) {
0 -> ListFragment()
1 -> MapsFragment()
else -> throw IllegalArgumentException("Invalid position")
}
}
}
|
Peduli-Pangan-Android/app/src/main/java/com/alvintio/pedulipangan/ui/dashboard/DashboardViewModel.kt | 3991809968 | package com.alvintio.pedulipangan.ui.dashboard
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.alvintio.pedulipangan.data.remote.ApiConfig
import com.alvintio.pedulipangan.model.Food
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
class DashboardViewModel : ViewModel() {
private val _foodList = MutableLiveData<List<Food>>()
val foodList: LiveData<List<Food>> get() = _foodList
private val _searchQuery = MutableLiveData<String>()
val searchQuery: LiveData<String> get() = _searchQuery
private var originalFoodList: List<Food> = emptyList()
fun fetchFoods() {
val apiService = ApiConfig.getApiService()
apiService.getProducts().enqueue(object : Callback<List<Food>> {
override fun onResponse(call: Call<List<Food>>, response: Response<List<Food>>) {
if (response.isSuccessful) {
originalFoodList = response.body() ?: emptyList()
_foodList.value = originalFoodList
}
}
override fun onFailure(call: Call<List<Food>>, t: Throwable) {
}
})
}
fun setSearchQuery(query: String) {
_searchQuery.value = query
}
private fun performManualSearch() {
val query = _searchQuery.value.orEmpty().toLowerCase()
val searchResults = if (query.isNotEmpty()) {
originalFoodList.filter { food ->
food.name.toLowerCase().contains(query.toLowerCase())
}
} else {
originalFoodList
}
_foodList.value = searchResults
}
}
|
Peduli-Pangan-Android/app/src/main/java/com/alvintio/pedulipangan/ui/map/MapsFragment.kt | 2835352333 | package com.alvintio.pedulipangan.ui.map
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.alvintio.pedulipangan.R
import com.alvintio.pedulipangan.data.remote.ApiConfig
import com.alvintio.pedulipangan.model.Food
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.MapView
import com.google.android.gms.maps.OnMapReadyCallback
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.MarkerOptions
import retrofit2.Call
import retrofit2.Response
class MapsFragment : Fragment(), OnMapReadyCallback {
private lateinit var mMap: GoogleMap
private lateinit var mapView: MapView
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val rootView = inflater.inflate(R.layout.fragment_maps, container, false)
mapView = rootView.findViewById(R.id.mapView)
mapView.onCreate(savedInstanceState)
mapView.onResume()
mapView.getMapAsync(this)
return rootView
}
override fun onMapReady(googleMap: GoogleMap) {
mMap = googleMap
val apiService = ApiConfig.getApiService()
apiService.getProducts().enqueue(object : retrofit2.Callback<List<Food>> {
override fun onResponse(call: Call<List<Food>>, response: Response<List<Food>>) {
if (response.isSuccessful) {
val foodList = response.body()
foodList?.let {
updateMarkers(it)
}
} else {
}
}
override fun onFailure(call: Call<List<Food>>, t: Throwable) {
}
})
}
private fun updateMarkers(foodList: List<Food>) {
activity?.runOnUiThread {
mMap.clear()
foodList.forEach { food ->
val location = LatLng(food.latitude, food.longitude)
mMap.addMarker(MarkerOptions().position(location).title(food.name))
}
if (foodList.isNotEmpty()) {
val initialLocation = LatLng(foodList[0].latitude, foodList[0].longitude)
mMap.moveCamera(CameraUpdateFactory.newLatLng(initialLocation))
}
}
}
override fun onResume() {
super.onResume()
mapView.onResume()
}
override fun onPause() {
super.onPause()
mapView.onPause()
}
override fun onDestroy() {
super.onDestroy()
mapView.onDestroy()
}
override fun onLowMemory() {
super.onLowMemory()
mapView.onLowMemory()
}
}
|
Peduli-Pangan-Android/app/src/main/java/com/alvintio/pedulipangan/ui/list/ListFragment.kt | 1434510012 | package com.alvintio.pedulipangan.ui.list
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alvintio.pedulipangan.R
import com.alvintio.pedulipangan.adapter.FoodAdapter
import com.alvintio.pedulipangan.data.remote.ApiConfig
import com.alvintio.pedulipangan.model.Food
import com.alvintio.pedulipangan.ui.dashboard.DashboardViewModel
import com.alvintio.pedulipangan.viewmodel.SharedViewModel
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
class ListFragment : Fragment() {
private lateinit var foodAdapter: FoodAdapter
private var allFoodList: List<Food> = emptyList()
private lateinit var sharedViewModel: SharedViewModel
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.fragment_list, container, false)
val recyclerView: RecyclerView = view.findViewById(R.id.recyclerView)
sharedViewModel = ViewModelProvider(requireActivity()).get(SharedViewModel::class.java)
foodAdapter = FoodAdapter(emptyList())
recyclerView.layoutManager = LinearLayoutManager(requireContext())
recyclerView.adapter = foodAdapter
getFoodList()
sharedViewModel.searchQuery.observe(viewLifecycleOwner) { query ->
Log.d("ListFragment", "Received search query: $query")
performLocalSearch(query)
}
return view
}
private fun getFoodList() {
val apiService = ApiConfig.getApiService()
apiService.getProducts().enqueue(object : Callback<List<Food>> {
override fun onResponse(call: Call<List<Food>>, response: Response<List<Food>>) {
if (response.isSuccessful) {
val foodList = response.body()
foodList?.let {
foodAdapter.updateData(it)
allFoodList = it
}
}
}
override fun onFailure(call: Call<List<Food>>, t: Throwable) {
}
})
}
private fun performLocalSearch(query: String) {
Log.d("ListFragment", "Performing local search: $query")
val searchResults = allFoodList.filter { food ->
food.name.contains(query, ignoreCase = true)
}
foodAdapter.updateData(searchResults)
}
} |
Peduli-Pangan-Android/app/src/main/java/com/alvintio/pedulipangan/ui/notifications/NotificationsFragment.kt | 13113707 | package com.alvintio.pedulipangan.ui.notifications
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alvintio.pedulipangan.adapter.NotificationsAdapter
import com.alvintio.pedulipangan.databinding.FragmentNotificationsBinding
import com.alvintio.pedulipangan.model.Notification
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.firestore.FirebaseFirestore
class NotificationsFragment : Fragment() {
private var _binding: FragmentNotificationsBinding? = null
private val binding get() = _binding!!
private val auth = FirebaseAuth.getInstance()
private val firestore = FirebaseFirestore.getInstance()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentNotificationsBinding.inflate(inflater, container, false)
val root: View = binding.root
val notificationsRecyclerView: RecyclerView = binding.recyclerView
notificationsRecyclerView.layoutManager = LinearLayoutManager(requireContext())
val currentUserUid = auth.currentUser?.uid
firestore.collection("notifications")
.get()
.addOnSuccessListener { result ->
val notifications = mutableListOf<Notification>()
for (document in result) {
val uid = document.getString("uid")
val date = document.getString("date")
val message = document.getString("message")
uid?.let {
if (it == currentUserUid && date != null && message != null) {
notifications.add(Notification(it, date, message))
}
}
}
val adapter = NotificationsAdapter(notifications)
notificationsRecyclerView.adapter = adapter
}
.addOnFailureListener { exception ->
}
return root
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
|
Peduli-Pangan-Android/app/src/main/java/com/alvintio/pedulipangan/MainActivity.kt | 3597844563 | package com.alvintio.pedulipangan
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.navigation.findNavController
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.setupActionBarWithNavController
import androidx.navigation.ui.setupWithNavController
import com.alvintio.pedulipangan.databinding.ActivityMainBinding
import com.alvintio.pedulipangan.util.ViewUtils
import com.google.android.material.bottomnavigation.BottomNavigationView
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
val navView: BottomNavigationView = binding.navView
val navController = findNavController(R.id.nav_host_fragment_activity_main)
val appBarConfiguration = AppBarConfiguration(
setOf(
R.id.navigation_home, R.id.navigation_dashboard, R.id.navigation_expired_check, R.id.navigation_notifications, R.id.navigation_settings
)
)
setupActionBarWithNavController(navController, appBarConfiguration)
navView.setupWithNavController(navController)
ViewUtils.setupFullScreen(this)
}
} |
Peduli-Pangan-Android/app/src/main/java/com/alvintio/pedulipangan/util/ViewUtils.kt | 1511245531 | package com.alvintio.pedulipangan.util
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.view.WindowInsets
import android.view.WindowManager
import androidx.appcompat.app.AppCompatActivity
object ViewUtils {
fun setupFullScreen(activity: AppCompatActivity) {
@Suppress("DEPRECATION")
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
activity.window.insetsController?.hide(WindowInsets.Type.statusBars())
} else {
activity.window.setFlags(
WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN
)
}
activity.supportActionBar?.hide()
}
fun moveActivity(context: Context, target: Class<*>, data: String? = null, optionsBundle: Bundle? = null) {
val moveIntent = Intent(context, target)
data.let { moveIntent.putExtra("data", data) }
if (optionsBundle != null) {
context.startActivity(moveIntent, optionsBundle)
} else {
context.startActivity(moveIntent)
}
}
fun moveActivityNoHistory(context: Context, target: Class<*>, data: String? = null, optionsBundle: Bundle? = null) {
val moveIntent = Intent(context, target)
moveIntent.flags = Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK
data.let { moveIntent.putExtra("data", data) }
if (optionsBundle != null) {
context.startActivity(moveIntent, optionsBundle)
} else {
context.startActivity(moveIntent)
}
}
} |
Peduli-Pangan-Android/app/src/main/java/com/alvintio/pedulipangan/adapter/RestaurantAdapter.kt | 4085238153 | package com.alvintio.pedulipangan.adapter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.alvintio.pedulipangan.R
class RestaurantAdapter(private var restaurantList: List<String>) :
RecyclerView.Adapter<RestaurantAdapter.RestaurantViewHolder>() {
fun updateData(newList: List<String>) {
restaurantList = newList
notifyDataSetChanged()
}
class RestaurantViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val restaurantName: TextView = itemView.findViewById(R.id.tv_restaurant)
val restaurantPhoto: ImageView = itemView.findViewById(R.id.iv_restaurant)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RestaurantViewHolder {
val itemView = LayoutInflater.from(parent.context)
.inflate(R.layout.restaurant_list, parent, false)
return RestaurantViewHolder(itemView)
}
override fun onBindViewHolder(holder: RestaurantViewHolder, position: Int) {
val currentRestaurant = restaurantList[position]
holder.restaurantName.text = currentRestaurant
holder.restaurantPhoto.setImageResource(R.drawable.ic_launcher_background)
}
override fun getItemCount(): Int {
return restaurantList.size
}
fun getRestaurantName(position: Int): String {
return restaurantList[position]
}
}
|
Peduli-Pangan-Android/app/src/main/java/com/alvintio/pedulipangan/adapter/FoodAdapter.kt | 758345149 | package com.alvintio.pedulipangan.adapter
import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.alvintio.pedulipangan.R
import com.alvintio.pedulipangan.model.Food
import com.alvintio.pedulipangan.view.DetailListActivity
import com.bumptech.glide.Glide
class FoodAdapter(private var foodList: List<Food>) : RecyclerView.Adapter<FoodAdapter.ViewHolder>() {
private var userLatitude: Double? = null
private var userLongitude: Double? = null
fun updateData(newFoodList: List<Food>) {
foodList = newFoodList
notifyDataSetChanged()
}
fun setUserLocation(latitude: Double, longitude: Double) {
userLatitude = latitude
userLongitude = longitude
notifyDataSetChanged()
}
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val foodName: TextView = itemView.findViewById(R.id.tv_restaurant_food)
val foodPrice: TextView = itemView.findViewById(R.id.tv_price)
val foodImage: ImageView = itemView.findViewById(R.id.iv_restaurant_food)
init {
itemView.setOnClickListener {
val position = adapterPosition
if (position != RecyclerView.NO_POSITION) {
val selectedFood = foodList[position]
val context = itemView.context
val intent = Intent(context, DetailListActivity::class.java).apply {
putExtra(DetailListActivity.EXTRA_PRODUCT_ID, selectedFood.id)
putExtra(DetailListActivity.EXTRA_PRODUCT_NAME, selectedFood.name)
putExtra(DetailListActivity.EXTRA_PRODUCT_PRICE, selectedFood.price)
putExtra(DetailListActivity.EXTRA_PRODUCT_DESCRIPTION, selectedFood.detail)
putExtra(DetailListActivity.EXTRA_PRODUCT_IMAGE, selectedFood.attachment)
}
context.startActivity(intent)
}
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.food_list, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val currentFood = foodList[position]
holder.foodName.text = currentFood.name
holder.foodPrice.text = "Rp${String.format("%,.0f", currentFood.price)}"
Glide.with(holder.foodImage.context)
.load(currentFood.attachment)
.placeholder(R.drawable.ic_launcher_background)
.error(R.drawable.ic_launcher_background)
.into(holder.foodImage)
}
override fun getItemCount(): Int {
return foodList.size
}
}
|
Peduli-Pangan-Android/app/src/main/java/com/alvintio/pedulipangan/adapter/NotificationsAdapter.kt | 701463894 | package com.alvintio.pedulipangan.adapter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.alvintio.pedulipangan.R
import com.alvintio.pedulipangan.model.Notification
class NotificationsAdapter(private val notifications: List<Notification>) :
RecyclerView.Adapter<NotificationsAdapter.NotificationViewHolder>() {
class NotificationViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val dateTextView: TextView = itemView.findViewById(R.id.tv_date)
val messageTextView: TextView = itemView.findViewById(R.id.tv_notification)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NotificationViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.notification_list, parent, false)
return NotificationViewHolder(view)
}
override fun onBindViewHolder(holder: NotificationViewHolder, position: Int) {
val notification = notifications[position]
holder.dateTextView.text = notification.date
holder.messageTextView.text = notification.message
}
override fun getItemCount(): Int {
return notifications.size
}
}
|
Peduli-Pangan-Android/app/src/main/java/com/alvintio/pedulipangan/model/RegisterResponse.kt | 2540757040 | package com.alvintio.pedulipangan.model
import com.google.gson.annotations.SerializedName
data class RegisterResponse(
@field:SerializedName("error")
val error: Boolean? = null,
@field:SerializedName("message")
val message: String? = null
) |
Peduli-Pangan-Android/app/src/main/java/com/alvintio/pedulipangan/model/Food.kt | 3355254946 | package com.alvintio.pedulipangan.model
data class Food(
val id: String,
val name: String,
val price: Double,
val attachment: String,
val detail: String,
val latitude: Double,
val longitude: Double
)
|
Peduli-Pangan-Android/app/src/main/java/com/alvintio/pedulipangan/model/User.kt | 1685186505 | package com.alvintio.pedulipangan.model
import com.google.gson.annotations.SerializedName
data class User(
@SerializedName("name") val name: String = "",
@SerializedName("email") val email: String = "",
@SerializedName("userId") val userId: String = ""
)
|
Peduli-Pangan-Android/app/src/main/java/com/alvintio/pedulipangan/model/LoginResponse.kt | 2939766474 | package com.alvintio.pedulipangan.model
import com.google.gson.annotations.SerializedName
data class LoginResponse(
@field:SerializedName("loginResult")
val loginResult: LoginResult? = null,
@field:SerializedName("error")
val error: Boolean? = null,
@field:SerializedName("message")
val message: String? = null
) |
Peduli-Pangan-Android/app/src/main/java/com/alvintio/pedulipangan/model/Notification.kt | 1866553157 | package com.alvintio.pedulipangan.model
import com.google.firebase.firestore.FieldValue
data class Notification(
val uid: String,
val date: String,
val message: String
) {
fun toMap(): Map<String, Any> {
return mapOf(
"uid" to uid,
"date" to date,
"message" to message,
"timestamp" to FieldValue.serverTimestamp()
)
}
}
|
Peduli-Pangan-Android/app/src/main/java/com/alvintio/pedulipangan/model/LoginResult.kt | 4176800059 | package com.alvintio.pedulipangan.model
import com.google.gson.annotations.SerializedName
data class LoginResult(
@field:SerializedName("name")
val name: String? = null,
@field:SerializedName("userId")
val userId: String? = null,
@field:SerializedName("token")
val token: String? = null
) |
Peduli-Pangan-Android/app/src/main/java/com/alvintio/pedulipangan/view/WelcomeActivity.kt | 6988513 | package com.alvintio.pedulipangan.view
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.airbnb.lottie.LottieAnimationView
import com.alvintio.pedulipangan.R
import com.alvintio.pedulipangan.databinding.ActivityWelcomeBinding
import com.alvintio.pedulipangan.util.ViewUtils
class WelcomeActivity : AppCompatActivity() {
private lateinit var binding: ActivityWelcomeBinding
private lateinit var appIcon: LottieAnimationView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityWelcomeBinding.inflate(layoutInflater)
setContentView(binding.root)
appIcon = findViewById(R.id.iv_welcome_image)
appIcon.setAnimation(R.raw.app_logo)
appIcon.playAnimation()
ViewUtils.setupFullScreen(this)
setupAction()
}
private fun setupAction() {
binding.btnLogin.setOnClickListener {
ViewUtils.moveActivity(this, LoginActivity::class.java)
}
binding.btnRegister.setOnClickListener {
ViewUtils.moveActivity(this, RegisterActivity::class.java)
}
}
} |
Peduli-Pangan-Android/app/src/main/java/com/alvintio/pedulipangan/view/RegisterActivity.kt | 589859235 | package com.alvintio.pedulipangan.view
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.preferencesDataStore
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.ViewModelProvider
import com.alvintio.pedulipangan.MainActivity
import com.alvintio.pedulipangan.R
import com.alvintio.pedulipangan.databinding.ActivityRegisterBinding
import com.alvintio.pedulipangan.util.ViewUtils
import com.alvintio.pedulipangan.viewmodel.AuthenticationViewModel
import com.google.firebase.Firebase
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.auth
import com.google.firebase.firestore.auth.User
import com.google.firebase.firestore.firestore
class RegisterActivity : AppCompatActivity() {
private lateinit var binding: ActivityRegisterBinding
private lateinit var auth: FirebaseAuth
private lateinit var viewModel: AuthenticationViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityRegisterBinding.inflate(layoutInflater)
setContentView(binding.root)
auth = Firebase.auth
viewModel = ViewModelProvider(this).get(AuthenticationViewModel::class.java)
ViewUtils.setupFullScreen(this)
setupRegister()
}
private fun setupRegister() {
binding.progressBar.visibility = View.GONE
binding.btnRegister.setOnClickListener {
val name = binding.edRegisterName.text.toString()
val email = binding.edRegisterEmail.text.toString()
val password = binding.edRegisterPassword.text.toString()
if (name.isEmpty()) {
binding.edRegisterName.error = getString(R.string.input_name)
return@setOnClickListener
}
if (email.isEmpty()) {
binding.edRegisterEmail.error = getString(R.string.input_email)
return@setOnClickListener
}
if (password.isEmpty()) {
binding.edRegisterPassword.error = getString(R.string.input_password)
return@setOnClickListener
}
binding.progressBar.visibility = View.VISIBLE
viewModel.register(name, email, password)
registerWithEmailAndPassword(name, email, password)
}
}
private fun saveUserDataToFirestore(userId: String, name: String, email: String) {
val db = Firebase.firestore
val usersCollection = db.collection("users")
val user = com.alvintio.pedulipangan.model.User(name, email, userId)
usersCollection.document(userId)
.set(user)
.addOnSuccessListener {
Log.d("Firestore", "Data telah tersimpan di Firestore!")
}
.addOnFailureListener { e ->
Log.w("Firestore", "Data belum tersimpan di Firestore!", e)
}
}
private fun registerWithEmailAndPassword(name: String, email: String, password: String) {
auth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this) { task ->
binding.progressBar.visibility = View.GONE
if (task.isSuccessful) {
val user = task.result?.user
if (user != null) {
Log.d("Register", "User created successfully")
saveUserDataToFirestore(user.uid, name, email)
Toast.makeText(
this,
"Registrasi berhasil!",
Toast.LENGTH_SHORT
).show()
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
finish()
}
} else {
Toast.makeText(
this,
"Registrasi gagal, tolong ulang kembali!!",
Toast.LENGTH_SHORT
).show()
}
}
}
} |
Peduli-Pangan-Android/app/src/main/java/com/alvintio/pedulipangan/view/DetailListActivity.kt | 700108554 | package com.alvintio.pedulipangan.view
import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.alvintio.pedulipangan.R
import com.alvintio.pedulipangan.databinding.ActivityDetailListBinding
import com.alvintio.pedulipangan.model.Food
import com.alvintio.pedulipangan.util.ViewUtils
import com.bumptech.glide.Glide
class DetailListActivity : AppCompatActivity() {
private lateinit var binding: ActivityDetailListBinding
private var quantity = 1
@SuppressLint("SetTextI18n")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityDetailListBinding.inflate(layoutInflater)
setContentView(binding.root)
val productName = intent.getStringExtra(EXTRA_PRODUCT_NAME)
val productPrice = intent.getDoubleExtra(EXTRA_PRODUCT_PRICE, 0.0)
val productDescription = intent.getStringExtra(EXTRA_PRODUCT_DESCRIPTION)
val productImage = intent.getStringExtra(EXTRA_PRODUCT_IMAGE)
binding.tvProductNameDetail.text = productName ?: ""
binding.tvProductPriceDetail.text = "Rp${String.format("%,.0f", productPrice)}"
binding.tvProductDescriptionDetail.text = productDescription ?: ""
binding.btnDecreaseQuantity.setOnClickListener {
updateQuantity(-1)
}
binding.btnIncreaseQuantity.setOnClickListener {
updateQuantity(1)
}
binding.btnReserveProducts.setOnClickListener {
val intent = Intent(this, ReserveActivity::class.java).apply {
putExtra(ReserveActivity.EXTRA_PRODUCT_NAME, productName)
putExtra(ReserveActivity.EXTRA_PRODUCT_PRICE, productPrice)
putExtra(ReserveActivity.EXTRA_PRODUCT_QUANTITY, quantity)
}
startActivity(intent)
}
Glide.with(this)
.load(productImage)
.placeholder(R.drawable.placeholder)
.error(R.drawable.ic_launcher_background)
.into(binding.ivDetailList)
ViewUtils.setupFullScreen(this)
}
private fun updateQuantity(change: Int) {
val newQuantity = quantity + change
if (newQuantity >= 1) {
quantity = newQuantity
binding.tvQuantity.text = quantity.toString()
}
}
companion object {
const val EXTRA_PRODUCT_ID = "extra_product_id"
const val EXTRA_PRODUCT_NAME = "extra_product_name"
const val EXTRA_PRODUCT_PRICE = "extra_product_price"
const val EXTRA_PRODUCT_DESCRIPTION = "extra_product_description"
const val EXTRA_PRODUCT_IMAGE = "extra_product_image"
}
}
|
Peduli-Pangan-Android/app/src/main/java/com/alvintio/pedulipangan/view/OnboardingActivity.kt | 4262322407 | package com.alvintio.pedulipangan.view
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.alvintio.pedulipangan.databinding.ActivityOnboardingBinding
import com.alvintio.pedulipangan.util.ViewUtils
class OnboardingActivity : AppCompatActivity() {
private lateinit var binding: ActivityOnboardingBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityOnboardingBinding.inflate(layoutInflater)
setContentView(binding.root)
ViewUtils.setupFullScreen(this)
binding.btnSkip.setOnClickListener {
ViewUtils.moveActivityNoHistory(this, WelcomeActivity::class.java)
}
binding.btnStart.setOnClickListener {
ViewUtils.moveActivityNoHistory(this, WelcomeActivity::class.java)
}
}
} |
Peduli-Pangan-Android/app/src/main/java/com/alvintio/pedulipangan/view/ReserveActivity.kt | 3292314806 | package com.alvintio.pedulipangan.view
import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import com.alvintio.pedulipangan.MainActivity
import com.alvintio.pedulipangan.R
import com.alvintio.pedulipangan.databinding.ActivityReserveBinding
import com.alvintio.pedulipangan.model.Notification
import com.alvintio.pedulipangan.util.ViewUtils
import com.alvintio.pedulipangan.viewmodel.NotificationsViewModel
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.firestore.FirebaseFirestore
import java.text.NumberFormat
import java.text.SimpleDateFormat
import java.util.*
class ReserveActivity : AppCompatActivity() {
private lateinit var binding: ActivityReserveBinding
private val notificationsViewModel by viewModels<NotificationsViewModel>()
private val firestore = FirebaseFirestore.getInstance()
@SuppressLint("SimpleDateFormat")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityReserveBinding.inflate(layoutInflater)
setContentView(binding.root)
val productPrice = intent.getDoubleExtra(EXTRA_PRODUCT_PRICE, 0.0)
val productQuantity = intent.getIntExtra(EXTRA_PRODUCT_QUANTITY, 0)
val auth = FirebaseAuth.getInstance()
val currentUser = auth.currentUser
var timeZone = TimeZone.getTimeZone("Asia/Jakarta")
val currentDateTime = SimpleDateFormat("dd MMM yyyy, HH:mm", Locale.getDefault()).apply {
timeZone = timeZone
}.format(Date())
binding.dateReserve.text = getString(R.string.date_reserve, currentDateTime)
val totalPrice = productPrice * productQuantity
val formattedPrice = NumberFormat.getCurrencyInstance(Locale("id", "ID")).format(totalPrice)
binding.priceReserve.text = getString(R.string.price_reserve, formattedPrice)
val notificationMessage = "Selamat, pembelian anda sebesar $formattedPrice telah berhasil"
val notification = Notification(currentUser.toString(), currentDateTime, notificationMessage)
if (currentUser != null) {
val uid = currentUser.uid
val notification = Notification(uid, currentDateTime, notificationMessage)
firestore.collection("notifications")
.add(notification.toMap())
.addOnSuccessListener {
notificationsViewModel.addNotification(notification)
}
.addOnFailureListener { e ->
}
}
binding.btnBack.setOnClickListener {
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
finish()
}
ViewUtils.setupFullScreen(this)
}
companion object {
const val EXTRA_PRODUCT_NAME = "extra_product_name"
const val EXTRA_PRODUCT_PRICE = "extra_product_price"
const val EXTRA_PRODUCT_QUANTITY = "extra_product_quantity"
}
}
|
Peduli-Pangan-Android/app/src/main/java/com/alvintio/pedulipangan/view/customviews/CustomEditText.kt | 739373505 | package com.alvintio.pedulipangan.view.customviews
import android.content.Context
import android.text.Editable
import android.text.TextWatcher
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatEditText
import com.alvintio.pedulipangan.R
class CustomEditText : AppCompatEditText {
private fun isValidEmail(email: String): Boolean {
return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()
}
constructor(context: Context) : super(context) {
init()
}
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
init()
}
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int): super(context, attrs, defStyleAttr) {
init()
}
private fun init() {
when (id) {
R.id.ed_register_password, R.id.ed_login_password -> {
addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
//Do Nothing
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
if (s.toString().length < 8) {
setError(context.getString(R.string.pass_less_than_8_char), null)
} else {
error = null
}
}
override fun afterTextChanged(s: Editable?) {
}
})
}
R.id.ed_register_email, R.id.ed_login_email -> {
addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
if (!isValidEmail(s.toString())) {
setError(context.getString(R.string.invalid_email), null)
} else {
error = null
}
}
override fun afterTextChanged(s: Editable?) {
}
})
}
}
}
} |
Peduli-Pangan-Android/app/src/main/java/com/alvintio/pedulipangan/view/ExpirationCheckerActivity.kt | 3476991376 | package com.alvintio.pedulipangan.view
import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Matrix
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.provider.SyncStateContract.Helpers
import android.view.Surface
import android.view.View
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.camera.core.CameraSelector
import androidx.camera.core.Preview
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import androidx.core.util.Consumer
import androidx.exifinterface.media.ExifInterface
import com.alvintio.pedulipangan.databinding.ActivityExpirationCheckerBinding
import com.alvintio.pedulipangan.util.ViewUtils
import java.io.File
import java.io.FileOutputStream
import java.text.SimpleDateFormat
import java.util.Locale
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
class ExpirationCheckerActivity : AppCompatActivity() {
companion object {
private val REQUIRED_CAMERA_PERMISS = arrayOf(Manifest.permission.CAMERA)
private const val REQUEST_CODE_PERMISS = 101
}
private lateinit var binding: ActivityExpirationCheckerBinding
private var pathImg: String = ""
private val galleryLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
if (it.resultCode == RESULT_OK) {
val selectedImageUri: Uri? = it.data?.data
selectedImageUri?.let {
binding.ivProductImage.setImageURI(it)
}
}
}
private val cameraLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
if (it.resultCode == RESULT_OK) {
val file = File(pathImg)
file.let { image ->
val bitmap = BitmapFactory.decodeFile(image.path)
rotateImage(bitmap, pathImg).compress(
Bitmap.CompressFormat.JPEG,
100,
FileOutputStream(image)
)
binding.ivProductImage.setImageBitmap(rotateImage(bitmap, pathImg))
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityExpirationCheckerBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.apply {
btnCamera.setOnClickListener {
if (!checkImagePermission()) {
ActivityCompat.requestPermissions(
this@ExpirationCheckerActivity,
REQUIRED_CAMERA_PERMISS,
REQUEST_CODE_PERMISS
)
} else {
startCamera()
}
}
btnGallery.setOnClickListener {
openGallery()
}
}
ViewUtils.setupFullScreen(this)
}
private fun rotateImage(bitmap: Bitmap, path: String): Bitmap {
val orientation = ExifInterface(path).getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_UNDEFINED
)
val matrix = Matrix()
when (orientation) {
ExifInterface.ORIENTATION_ROTATE_90 -> matrix.setRotate(90f)
ExifInterface.ORIENTATION_ROTATE_180 -> matrix.setRotate(180f)
}
return Bitmap.createBitmap(
bitmap,
0,
0,
bitmap.width,
bitmap.height,
matrix,
true
)
}
private fun startCamera() {
val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
intent.resolveActivity(packageManager)
val storageDir: File? = getExternalFilesDir(Environment.DIRECTORY_PICTURES)
val customTempFile = File.createTempFile(
SimpleDateFormat(
"dd-MMM-yyyy",
Locale.US
).format(System.currentTimeMillis()), ".jpg", storageDir
)
customTempFile.also {
pathImg = it.absolutePath
intent.putExtra(
MediaStore.EXTRA_OUTPUT, FileProvider.getUriForFile(
this@ExpirationCheckerActivity,
"com.alvintio.pedulipangan.fileprovider",
it
)
)
cameraLauncher.launch(intent)
}
}
private fun openGallery() {
val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
galleryLauncher.launch(intent)
}
private fun checkImagePermission() = REQUIRED_CAMERA_PERMISS.all {
ContextCompat.checkSelfPermission(baseContext, it) == PackageManager.PERMISSION_GRANTED
}
}
|
Peduli-Pangan-Android/app/src/main/java/com/alvintio/pedulipangan/view/LoginActivity.kt | 1668379503 | package com.alvintio.pedulipangan.view
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import com.alvintio.pedulipangan.MainActivity
import com.alvintio.pedulipangan.R
import com.alvintio.pedulipangan.databinding.ActivityLoginBinding
import com.alvintio.pedulipangan.util.ViewUtils
import com.alvintio.pedulipangan.viewmodel.AuthenticationViewModel
import com.google.firebase.Firebase
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.auth
class LoginActivity : AppCompatActivity() {
private lateinit var binding: ActivityLoginBinding
private lateinit var auth: FirebaseAuth
private lateinit var viewModel: AuthenticationViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityLoginBinding.inflate(layoutInflater)
setContentView(binding.root)
auth = Firebase.auth
ViewUtils.setupFullScreen(this)
setupLogin()
viewModel = ViewModelProvider(this).get(AuthenticationViewModel::class.java)
viewModel.loginState.observe(this) { loginState ->
when (loginState) {
is AuthenticationViewModel.LoginState.Success -> {
moveToMainActivity()
}
is AuthenticationViewModel.LoginState.Error -> {
binding.progressBar.visibility = View.GONE
handleError(Exception(loginState.message))
}
}
}
}
private fun setupLogin() {
binding.progressBar.visibility = View.GONE
binding.btnLogin.setOnClickListener {
val email = binding.edLoginEmail.text.toString()
val password = binding.edLoginPassword.text.toString()
if (email.isEmpty()) {
binding.edLoginEmail.error = getString(R.string.input_email)
return@setOnClickListener
}
if (password.isEmpty()) {
binding.edLoginPassword.error = getString(R.string.input_password)
return@setOnClickListener
}
binding.progressBar.visibility = View.VISIBLE
viewModel.login(email, password)
}
}
private fun moveToMainActivity() {
ViewUtils.moveActivityNoHistory(this@LoginActivity, MainActivity::class.java)
finish()
}
private fun handleError(exception: Exception?) {
AlertDialog.Builder(this).apply {
setTitle(getString(R.string.error))
setMessage(exception?.localizedMessage ?: getString(R.string.error))
setPositiveButton(getString(R.string.continue_on)) { _, _ -> }
create()
show()
}
}
} |
Peduli-Pangan-Android/app/src/main/java/com/alvintio/pedulipangan/view/SplashActivity.kt | 3053700870 | package com.alvintio.pedulipangan.view
import android.annotation.SuppressLint
import android.content.Context
import android.os.Build
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.preferencesDataStore
import androidx.lifecycle.lifecycleScope
import com.airbnb.lottie.LottieAnimationView
import com.alvintio.pedulipangan.MainActivity
import com.alvintio.pedulipangan.R
import com.google.firebase.auth.FirebaseAuth
import com.alvintio.pedulipangan.util.ViewUtils
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "user_prefs")
@SuppressLint("CustomSplashScreen")
class SplashActivity : AppCompatActivity() {
private lateinit var appIcon: LottieAnimationView
private lateinit var auth: FirebaseAuth
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_splash)
appIcon = findViewById(R.id.img_icon)
appIcon.setAnimation(R.raw.app_logo)
appIcon.playAnimation()
ViewUtils.setupFullScreen(this)
val content = findViewById<View>(android.R.id.content)
@Suppress("UNUSED_EXPRESSION")
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
content.viewTreeObserver.addOnDrawListener { false }
}
auth = FirebaseAuth.getInstance()
lifecycleScope.launch {
delay(6000.toLong())
val user = auth.currentUser
if (user != null) {
ViewUtils.moveActivityNoHistory(this@SplashActivity, MainActivity::class.java)
} else {
ViewUtils.moveActivityNoHistory(this@SplashActivity, OnboardingActivity::class.java)
}
}
}
}
|
Peduli-Pangan-Android/app/src/main/java/com/alvintio/pedulipangan/data/repo/Result.kt | 727348530 | package com.alvintio.pedulipangan.data.repo
sealed class Result<out R> private constructor() {
data class Success<out T>(val data: T) : Result<T>()
data class Error(val error:String) : Result<Nothing>()
object Loading : Result<Nothing>()
} |
Peduli-Pangan-Android/app/src/main/java/com/alvintio/pedulipangan/data/remote/ApiConfig.kt | 3804138355 | package com.alvintio.pedulipangan.data.remote
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
class ApiConfig {
companion object{
fun getApiService(): ApiService {
val loggingInterceptor = if(com.airbnb.lottie.BuildConfig.DEBUG) {
HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)
} else {
HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)
}
val client = OkHttpClient.Builder()
.addInterceptor(loggingInterceptor)
.build()
val retrofit = Retrofit.Builder()
.baseUrl("https://backend-dot-peduli-pangan-project.et.r.appspot.com/")
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build()
return retrofit.create(ApiService::class.java)
}
}
} |
Peduli-Pangan-Android/app/src/main/java/com/alvintio/pedulipangan/data/remote/ApiService.kt | 852553121 | package com.alvintio.pedulipangan.data.remote
import com.alvintio.pedulipangan.model.Food
import retrofit2.Call
import retrofit2.http.*
interface ApiService {
@GET("/getproducts")
fun getProducts(): Call<List<Food>>
@GET("/getproduct/{id}")
fun getProductById(@Path("id") productId: String): Call<Food>
} |
MindSharpener_S65463_LabTest/app/src/androidTest/java/com/example/mindsharpener/ExampleInstrumentedTest.kt | 1889564967 | package com.example.mindsharpener
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.mindsharpener", appContext.packageName)
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.