content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
package com.mataecheverry.exerciciguerrers.ui.theme import androidx.compose.ui.graphics.Color val Purple80 = Color(0xFFD0BCFF) val PurpleGrey80 = Color(0xFFCCC2DC) val Pink80 = Color(0xFFEFB8C8) val Purple40 = Color(0xFF6650a4) val PurpleGrey40 = Color(0xFF625b71) val Pink40 = Color(0xFF7D5260)
ExerciciGuerrers/app/src/main/java/com/mataecheverry/exerciciguerrers/ui/theme/Color.kt
3873553204
package com.mataecheverry.exerciciguerrers.ui.theme import android.app.Activity import android.os.Build import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import androidx.core.view.WindowCompat private val DarkColorScheme = darkColorScheme( primary = Purple80, secondary = PurpleGrey80, tertiary = Pink80 ) private val LightColorScheme = lightColorScheme( primary = Purple40, secondary = PurpleGrey40, tertiary = Pink40 /* Other default colors to override background = Color(0xFFFFFBFE), surface = Color(0xFFFFFBFE), onPrimary = Color.White, onSecondary = Color.White, onTertiary = Color.White, onBackground = Color(0xFF1C1B1F), onSurface = Color(0xFF1C1B1F), */ ) @Composable fun ExerciciGuerrersTheme( darkTheme: Boolean = isSystemInDarkTheme(), // Dynamic color is available on Android 12+ dynamicColor: Boolean = true, content: @Composable () -> Unit ) { val colorScheme = when { dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { val context = LocalContext.current if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) } darkTheme -> DarkColorScheme else -> LightColorScheme } val view = LocalView.current if (!view.isInEditMode) { SideEffect { val window = (view.context as Activity).window window.statusBarColor = colorScheme.primary.toArgb() WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme } } MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content ) }
ExerciciGuerrers/app/src/main/java/com/mataecheverry/exerciciguerrers/ui/theme/Theme.kt
3500954626
package com.mataecheverry.exerciciguerrers.ui.theme import androidx.compose.material3.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp // Set of Material typography styles to start with val Typography = Typography( bodyLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp, lineHeight = 24.sp, letterSpacing = 0.5.sp ) /* Other default text styles to override titleLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 22.sp, lineHeight = 28.sp, letterSpacing = 0.sp ), labelSmall = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Medium, fontSize = 11.sp, lineHeight = 16.sp, letterSpacing = 0.5.sp ) */ )
ExerciciGuerrers/app/src/main/java/com/mataecheverry/exerciciguerrers/ui/theme/Type.kt
3736321457
package com.mataecheverry.exerciciguerrers.ui.pantallas import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material.icons.filled.Menu import androidx.compose.material3.Divider import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import coil.compose.AsyncImage import coil.request.ImageRequest import com.mataecheverry.exerciciguerrers.R import com.mataecheverry.exerciciguerrers.dades.Guerrers @OptIn(ExperimentalMaterial3Api::class) @Composable fun PantallaGuerrerDetall(id: String, onPopUpToClick: () -> Unit){ val num = id.toInt() Scaffold( topBar = { TopAppBar( colors = TopAppBarDefaults.smallTopAppBarColors( containerColor = MaterialTheme.colorScheme.primaryContainer, titleContentColor = MaterialTheme.colorScheme.onPrimaryContainer ), title = { Text("Detalls de ${Guerrers.dades[num].nom}") }, navigationIcon = { IconButton(onClick = onPopUpToClick) { Icon( imageVector = Icons.Default.ArrowBack, contentDescription = "Vista detallada" ) } } ) } ) { Column(modifier = Modifier .fillMaxWidth() .padding(it) .padding(10.dp) .background(MaterialTheme.colorScheme.background), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally) { AsyncImage(model = ImageRequest.Builder(LocalContext.current) .data("https://www.loremflickr.com/300/300/guerrer?lock=${Guerrers.dades[num].id}") .crossfade(true) .build(), placeholder=painterResource(id = R.drawable.ic_launcher_foreground), contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier .weight(0.3F) .clip(CircleShape) .padding(10.dp) ) Text(text = "Nom: ${Guerrers.dades[num].nom}, ${Guerrers.dades[num].edat}", fontSize = 25.sp, fontWeight = FontWeight.Bold, modifier = Modifier .weight(0.3F), ) Divider(thickness = 2.dp, color = MaterialTheme.colorScheme.onBackground) Text(text = "Força: ${Guerrers.dades[num].forsa}\n" + "Resistencia: ${Guerrers.dades[num].resistencia}\nAtac: ${Guerrers.dades[num].atac}\nDefensa: ${Guerrers.dades[num].defensa}", fontSize = 20.sp, fontWeight = FontWeight.Medium, modifier = Modifier .weight(0.3F)) } } }
ExerciciGuerrers/app/src/main/java/com/mataecheverry/exerciciguerrers/ui/pantallas/PantallaGuerrerDetall.kt
730226655
package com.mataecheverry.exerciciguerrers.ui.pantallas import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Add import androidx.compose.material.icons.filled.Check import androidx.compose.material.icons.filled.Edit import androidx.compose.material.icons.filled.Face import androidx.compose.material.icons.filled.Menu import androidx.compose.material3.AlertDialogDefaults.titleContentColor import androidx.compose.material3.BottomAppBar import androidx.compose.material3.BottomAppBarDefaults import androidx.compose.material3.BottomAppBarDefaults.containerColor import androidx.compose.material3.Button import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.FloatingActionButton import androidx.compose.material3.FloatingActionButtonDefaults import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.sp import com.mataecheverry.exerciciguerrers.R @OptIn(ExperimentalMaterial3Api::class) @Composable fun PantallaPrincipal(onLlistaDeGuerrersClick: () -> Unit, onLlistaDePlantesClick: () -> Unit, onLlistaArmesClick: () -> Unit) { Scaffold( topBar = { TopAppBar( colors = TopAppBarDefaults.smallTopAppBarColors( containerColor = MaterialTheme.colorScheme.primaryContainer, titleContentColor = MaterialTheme.colorScheme.onPrimaryContainer ), title = { Text("Menú de llistes") }, navigationIcon = { IconButton(onClick = {}) { Icon( imageVector = Icons.Default.Face, contentDescription = "Vista detallada" ) } } ) }, bottomBar = { BottomAppBar ( containerColor = MaterialTheme.colorScheme.primaryContainer, contentColor = MaterialTheme.colorScheme.onPrimaryContainer, ) { Image( painter = painterResource(id= R.drawable.calendario), contentDescription = "Imatge", ) } } ) { Column( verticalArrangement = Arrangement.SpaceEvenly, modifier = Modifier .fillMaxSize() .padding(it) ) { Box( modifier = Modifier .fillMaxWidth() .weight(1F) ) { Button(modifier = Modifier .align(Alignment.Center), onClick = { onLlistaArmesClick()}) { Text("Llista d'Armes", fontSize = 25.sp,) } } Box( modifier = Modifier .fillMaxWidth() .weight(1F) ) { Button(modifier = Modifier .align(Alignment.Center), onClick = { onLlistaDePlantesClick()}) { Text("Llista de Plantes", fontSize = 25.sp,) } } Box( modifier = Modifier .fillMaxWidth() .weight(1F) ) { Button(modifier = Modifier .align(Alignment.Center), onClick = { onLlistaDeGuerrersClick() }) { Text("Llista de Guerrers", fontSize = 25.sp,) } } } } }
ExerciciGuerrers/app/src/main/java/com/mataecheverry/exerciciguerrers/ui/pantallas/PantallaPrincipal.kt
2244140487
package com.mataecheverry.exerciciguerrers.ui.pantallas import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material3.Divider import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import coil.compose.AsyncImage import coil.request.ImageRequest import com.mataecheverry.exerciciguerrers.R import com.mataecheverry.exerciciguerrers.dades.Guerrers import com.mataecheverry.exerciciguerrers.dades.Plantes @OptIn(ExperimentalMaterial3Api::class) @Composable fun PantallaPlantaDetall(id: String, onPopUpToClick: () -> Unit){ val num = id.toInt() Scaffold( topBar = { TopAppBar( colors = TopAppBarDefaults.smallTopAppBarColors( containerColor = MaterialTheme.colorScheme.primaryContainer, titleContentColor = MaterialTheme.colorScheme.onPrimaryContainer ), title = { Text("Detalls de ${Plantes.dadesPlanta[num].nom}") }, navigationIcon = { IconButton(onClick = onPopUpToClick) { Icon( imageVector = Icons.Default.ArrowBack, contentDescription = "Vista detallada" ) } } ) } ) { Column(modifier = Modifier .fillMaxWidth() .padding(it) .padding(10.dp) .background(MaterialTheme.colorScheme.background), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally) { AsyncImage(model = ImageRequest.Builder(LocalContext.current) .data("https://www.loremflickr.com/300/300/indoorplants?lock=${Plantes.dadesPlanta[num].id}") .crossfade(true) .build(), placeholder= painterResource(id = R.drawable.ic_launcher_foreground), contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier .weight(0.3F) .clip(CircleShape) .padding(10.dp) ) Text(text = "Nom: ${Plantes.dadesPlanta[num].nom}, ${Plantes.dadesPlanta[num].id}", fontSize = 25.sp, fontWeight = FontWeight.Bold, modifier = Modifier .weight(0.3F), ) Divider(thickness = 2.dp, color = MaterialTheme.colorScheme.onBackground) Text(text = "Llum: ${Plantes.dadesPlanta[num].llum}\n" + "Humitat: ${Plantes.dadesPlanta[num].nivellHumitat}\n" + "Rec: ${Plantes.dadesPlanta[num].rec}\n" + "Mida: ${Plantes.dadesPlanta[num].mida}\n"+ "Temperatura: ${Plantes.dadesPlanta[num].temperatura}\n"+ "Fertilitzant: ${Plantes.dadesPlanta[num].fertilitzant}", fontSize = 20.sp, fontWeight = FontWeight.Medium, modifier = Modifier .weight(0.3F)) } } }
ExerciciGuerrers/app/src/main/java/com/mataecheverry/exerciciguerrers/ui/pantallas/PantallaPlantaDetall.kt
1802288755
package com.mataecheverry.exerciciguerrers.ui.pantallas import com.mataecheverry.exerciciguerrers.dades.Arma import com.mataecheverry.exerciciguerrers.dades.Armes import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material.icons.filled.Menu import androidx.compose.material3.CardDefaults import androidx.compose.material3.ElevatedCard import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.ListItem import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import coil.compose.AsyncImage import coil.request.ImageRequest import com.mataecheverry.exerciciguerrers.R @OptIn(ExperimentalMaterial3Api::class) @Composable fun PantallaLlistaDArmes(arma: String, onArmaClick: (String) -> Unit, onPopUpToClick: () -> Unit) { Scaffold( topBar = { TopAppBar( colors = TopAppBarDefaults.smallTopAppBarColors( containerColor = Color(0XFFffdad3), titleContentColor = Color(0XFF3e0400) ), title = { Text("Llista d'Armes") }, navigationIcon = { IconButton(onClick = onPopUpToClick) { Icon( imageVector = Icons.Default.ArrowBack, contentDescription = "Llista d'Armes" ) } } ) } ) { LazyColumn(modifier = Modifier .padding(it) .fillMaxSize()) { item{ Text(arma, fontSize = 25.sp) } items(Armes.dadesArmes){ arma -> ItemArma(arma = arma) { onArmaClick(arma.id) } } } } } @OptIn(ExperimentalMaterial3Api::class) @Composable fun ItemArma(arma: Arma, onArmaClick: (String)-> Unit) { ElevatedCard(elevation = CardDefaults.cardElevation(6.dp), modifier = Modifier .padding(10.dp) .background(Color(0XFFffdad3)) .clickable { onArmaClick(arma.id)}) { ListItem( leadingContent = { AsyncImage(model = ImageRequest.Builder(LocalContext.current) .data("https://www.loremflickr.com/300/300/weapons?lock=${arma.id}") .crossfade(true) .build(), placeholder= painterResource(id = R.drawable.ic_launcher_foreground), contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier .size(100.dp) .clip(CircleShape) .padding(10.dp), ) }, headlineText = { Text("${arma.nom}, ${arma.id}") }, supportingText = { Text("Cadència de foc: ${arma.cadencia}\n" + "Tipus de projectil: ${arma.projectil}") } ) } }
ExerciciGuerrers/app/src/main/java/com/mataecheverry/exerciciguerrers/ui/pantallas/PantallaLlistaArmes.kt
2137707178
package com.mataecheverry.exerciciguerrers.ui.pantallas import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.sp @Composable fun PantallaMinimMaxim(minim: Int, maxim: Int) { Column(modifier = Modifier.fillMaxSize()) { Box(modifier = Modifier.fillMaxWidth().weight(1F)){ Text(text = minim.toString(), fontSize = 88.sp, modifier = Modifier .align(Alignment.Center)) } Box(modifier = Modifier.fillMaxWidth().weight(1F)){ Text(text = maxim.toString(), fontSize = 88.sp, modifier = Modifier .align(Alignment.Center)) } } }
ExerciciGuerrers/app/src/main/java/com/mataecheverry/exerciciguerrers/ui/pantallas/PantallaMinMax.kt
3533327035
package com.mataecheverry.exerciciguerrers.ui.pantallas import android.util.Log import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material.icons.filled.Menu import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.ElevatedCard import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.ListItem import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import coil.compose.AsyncImage import coil.request.ImageRequest import com.mataecheverry.exerciciguerrers.R import com.mataecheverry.exerciciguerrers.dades.Guerrer import com.mataecheverry.exerciciguerrers.dades.Guerrers import java.util.ArrayList @OptIn(ExperimentalMaterial3Api::class) @Composable fun PantallaLlistaDeGuerrers(titol: String, onGuerrerClick: (String) -> Unit, onPopUpToClick: () -> Unit) { Scaffold( topBar = { TopAppBar( colors = TopAppBarDefaults.smallTopAppBarColors( containerColor = Color(0XFFffdad3), titleContentColor = Color(0XFF3e0400) ), title = { Text("Llista de Guerrers") }, navigationIcon = { IconButton(onClick = onPopUpToClick) { Icon( imageVector = Icons.Default.ArrowBack, contentDescription = "Llista de guerrers" ) } } ) } ) { LazyColumn(modifier = Modifier .padding(it) .fillMaxSize()) { item{ Text(titol, fontSize = 25.sp) } items(Guerrers.dades){guerrer -> ItemGuerrer(guerrer = guerrer) { onGuerrerClick(guerrer.id) } } } } } @OptIn(ExperimentalMaterial3Api::class) @Composable fun ItemGuerrer(guerrer: Guerrer, onGuerrerClick: (String)-> Unit) { ElevatedCard(elevation = CardDefaults.cardElevation(6.dp), modifier = Modifier .padding(10.dp) .background(Color(0XFFffdad3)) .clickable { onGuerrerClick(guerrer.id)}) { ListItem( leadingContent = { AsyncImage(model = ImageRequest.Builder(LocalContext.current) .data("https://www.loremflickr.com/300/300/guerrer?lock=${guerrer.id}") .crossfade(true) .build(), placeholder=painterResource(id = R.drawable.ic_launcher_foreground), contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier .size(100.dp) .clip(CircleShape) .padding(10.dp), ) }, headlineText = {Text("${guerrer.nom}, ${guerrer.edat}")}, supportingText = {Text("ATK = ${guerrer.atac}, DEF = ${guerrer.defensa}")} ) } }
ExerciciGuerrers/app/src/main/java/com/mataecheverry/exerciciguerrers/ui/pantallas/PantallaLlistaDeGuerrers.kt
3335299608
package com.mataecheverry.exerciciguerrers.ui.pantallas import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material.icons.filled.Menu import androidx.compose.material3.Divider import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import coil.compose.AsyncImage import coil.request.ImageRequest import com.mataecheverry.exerciciguerrers.R import com.mataecheverry.exerciciguerrers.dades.Armes import com.mataecheverry.exerciciguerrers.dades.Guerrers import com.mataecheverry.exerciciguerrers.dades.Plantes @OptIn(ExperimentalMaterial3Api::class) @Composable fun PantallaArmaDetall(id: String, onPopUpToClick: () -> Unit){ val num = id.toInt() Scaffold( topBar = { TopAppBar( colors = TopAppBarDefaults.smallTopAppBarColors( containerColor = MaterialTheme.colorScheme.primaryContainer, titleContentColor = MaterialTheme.colorScheme.onPrimaryContainer ), title = { Text("Detalls de ${Armes.dadesArmes[num].nom}") }, navigationIcon = { IconButton(onClick = onPopUpToClick) { Icon( imageVector = Icons.Default.ArrowBack, contentDescription = "Vista detallada" ) } } ) } ) { Column(modifier = Modifier .fillMaxWidth() .padding(it) .padding(10.dp) .background(MaterialTheme.colorScheme.background), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally) { AsyncImage(model = ImageRequest.Builder(LocalContext.current) .data("https://www.loremflickr.com/300/300/weapons?lock=${Armes.dadesArmes[num].id}") .crossfade(true) .build(), placeholder= painterResource(id = R.drawable.ic_launcher_foreground), contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier .weight(0.3F) .clip(CircleShape) .padding(10.dp) ) Text(text = "Nom: ${Armes.dadesArmes[num].nom}, ${Armes.dadesArmes[num].id}", fontSize = 25.sp, fontWeight = FontWeight.Bold, modifier = Modifier .weight(0.3F), ) Divider(thickness = 2.dp, color = MaterialTheme.colorScheme.onBackground) Text(text = "Nom: ${Armes.dadesArmes[num].nom}\n" + "Cadència de foc: ${Armes.dadesArmes[num].cadencia}\n" + "Descripcio: ${Armes.dadesArmes[num].projectil}\n" + "Història: ${Armes.dadesArmes[num].historia}", fontSize = 20.sp, fontWeight = FontWeight.Medium, modifier = Modifier .weight(0.3F)) } } }
ExerciciGuerrers/app/src/main/java/com/mataecheverry/exerciciguerrers/ui/pantallas/PantallaArmaDetall.kt
2932162708
package com.mataecheverry.exerciciguerrers.ui.pantallas import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material.icons.filled.Menu import androidx.compose.material3.CardDefaults import androidx.compose.material3.ElevatedCard import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.ListItem import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import coil.compose.AsyncImage import coil.request.ImageRequest import com.mataecheverry.exerciciguerrers.R import com.mataecheverry.exerciciguerrers.dades.Planta import com.mataecheverry.exerciciguerrers.dades.Plantes @OptIn(ExperimentalMaterial3Api::class) @Composable fun PantallaLlistaDePlantes(planta: String, onPlantaClick: (String) -> Unit, onPopUpToClick: () -> Unit) { Scaffold( topBar = { TopAppBar( colors = TopAppBarDefaults.smallTopAppBarColors( containerColor = Color(0XFFffdad3), titleContentColor = Color(0XFF3e0400) ), title = { Text("Llista de Plantes") }, navigationIcon = { IconButton(onClick = onPopUpToClick) { Icon( imageVector = Icons.Default.ArrowBack, contentDescription = "Llista de Plantes" ) } } ) } ) { LazyColumn(modifier = Modifier .padding(it) .fillMaxSize()) { item{ Text(planta, fontSize = 25.sp) } items(Plantes.dadesPlanta){ planta -> ItemPlanta(planta = planta) { onPlantaClick(planta.id) } } } } } @OptIn(ExperimentalMaterial3Api::class) @Composable fun ItemPlanta(planta: Planta, onPlantaClick: (String)-> Unit) { ElevatedCard(elevation = CardDefaults.cardElevation(6.dp), modifier = Modifier .padding(10.dp) .background(Color(0XFFffdad3)) .clickable { onPlantaClick(planta.id)}) { ListItem( leadingContent = { AsyncImage(model = ImageRequest.Builder(LocalContext.current) .data("https://www.loremflickr.com/300/300/indoorplants?lock=${planta.id}") .crossfade(true) .build(), placeholder= painterResource(id = R.drawable.ic_launcher_foreground), contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier .size(100.dp) .clip(CircleShape) .padding(10.dp), ) }, headlineText = { Text("${planta.nom}, ${planta.id}") }, supportingText = { Text("ATK = ${planta.llum}, DEF = ${planta.nivellHumitat}") } ) } }
ExerciciGuerrers/app/src/main/java/com/mataecheverry/exerciciguerrers/ui/pantallas/PantallaLlistaDePlantes.kt
1261822684
package com.mataecheverry.exerciciguerrers import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import com.mataecheverry.exerciciguerrers.navegacio.GrafDeNavegacio import com.mataecheverry.exerciciguerrers.ui.theme.ExerciciGuerrersTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { ExerciciGuerrersTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { GrafDeNavegacio() } } } } } @Preview(showBackground = true) @Composable fun GreetingPreview() { ExerciciGuerrersTheme { GrafDeNavegacio() } }
ExerciciGuerrers/app/src/main/java/com/mataecheverry/exerciciguerrers/MainActivity.kt
2539554545
package com.mataecheverry.exerciciguerrers.dades import androidx.compose.ui.graphics.Color import kotlin.random.Random data class Guerrer( val id: String, val nom: String, val foto: String, val color: Color, val edat: Int, val forsa: Int, val resistencia: Int, val atac: Int, val defensa: Int ) class Guerrers{ companion object { private fun generaGuerrer(id: Int): Guerrer { return Guerrer( id = id.toString(), nom = nomRandom(), foto = "https://loremflickr.com/300/300/warriors?lock=$id", color = Color(Random.nextInt(256), Random.nextInt(256), Random.nextInt(256)), edat = Random.nextInt(67), forsa = Random.nextInt(300), resistencia = Random.nextInt(300), atac = Random.nextInt(300), defensa = Random.nextInt(300) ) } val dades = (0..100).toList().map { generaGuerrer(it) }; } } fun nomRandom(): String { val noms = listOf( "Ares", "Kratos", "Athena", "Odin", "Thor", "Freya", "Ezio", "Altair", "Leonidas", "Cassandra", "Raiden", "Sonya", "Scorpion", "Morrigan", "Arthas", "Illidan", "Sylvanas", "Sauron", "Aragorn", "Legolas", "Geralt", "Ciri", "Triss", "Ezreal", "Fiora", "Lancelot", "Guinevere", "Perseus", "Atalanta", "Hercules", "Achilles", "Xena", "Gabrielle", "Beowulf", "Valkyrie", "Dante", "Nero", "Cassandra", "Thane", "Marauder", "Tyrael", "Leona", "Ashe", "Darius" ) var nom = noms.random() return nom }
ExerciciGuerrers/app/src/main/java/com/mataecheverry/exerciciguerrers/dades/Guerrer.kt
1626493988
package com.mataecheverry.exerciciguerrers.dades import kotlin.random.Random data class Arma( val id: String, val nom: String, val foto: String, val cadencia: Int, val projectil: Int, val historia: String, ) class Armes{ companion object { private fun generaArma(id: Int): Arma { return Arma( id = id.toString(), nom = armaRandom(), foto = "https://loremflickr.com/300/300/plants?lock=$id", cadencia = Random.nextInt(100), projectil = Random.nextInt(100), historia= "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." ) } val dadesArmes = (0..100).toList().map { generaArma(it) }; } } fun armaRandom(): String { val arma = listOf( "Glock-18", "USP-S", "P2000", "Dual Berettas", "P250", "Five-SeveN", "CZ75-Auto", "Tec-9", "Desert Eagle", "Nova", "XM1014", "Sawed-Off", "Mag-7", "MP9", "MP7", "UMP-45", "P90", "MAC-10", "AK-47", "M4A4", "M4A1-S", "SG 553", "AUG", "AWP", "SSG 08", "G3SG1", "SCAR-20", "M249", "Negev" ) var nom = arma.random() return nom }
ExerciciGuerrers/app/src/main/java/com/mataecheverry/exerciciguerrers/dades/Arma.kt
2264524552
package com.mataecheverry.exerciciguerrers.dades import kotlin.random.Random data class Planta( val id: String, val nom: String, val foto: String, val nivellHumitat: Int, val llum: String, val temperatura: String, val mida: String, val rec: String, val fertilitzant: String ) class Plantes{ companion object { private fun generaPlanta(id: Int): Planta { return Planta( id = id.toString(), nom = plantaRandom(), foto = "https://loremflickr.com/300/300/plants?lock=$id", nivellHumitat = Random.nextInt(100), llum = "Llum clara i indirecta", temperatura = "15-38ºC", mida = "Alta", rec = "Un cop per setmana", fertilitzant = "Fertilitzant líquid cada dos setmanes.", ) } val dadesPlanta = (0..100).toList().map { generaPlanta(it) }; } } fun plantaRandom(): String { val planta = listOf( "Snake Plant (Sansevieria trifasciata)", "Spider Plant (Chlorophytum comosum)", "Peace Lily (Spathiphyllum)", "Fiddle Leaf Fig (Ficus lyrata)", "ZZ Plant (Zamioculcas zamiifolia)", "Rubber Plant (Ficus elastica)", "Pothos (Epipremnum aureum)", "Monstera Deliciosa", "Aloe Vera (Aloe barbadensis miller)", "Succulents (Various species)", "Chinese Evergreen (Aglaonema)", "Philodendron (Various species)", "Boston Fern (Nephrolepis exaltata)", "Parlor Palm (Chamaedorea elegans)", "Calathea (Various species)", "Jade Plant (Crassula ovata)", "African Violet (Saintpaulia)", "Bamboo Palm (Chamaedorea seifrizii)", "Cast Iron Plant (Aspidistra elatior)", "Devil's Ivy (Epipremnum aureum)", "Areca Palm (Dypsis lutescens)", "String of Pearls (Senecio rowleyanus)", "Bird of Paradise (Strelitzia reginae)", "ZZ Raven Plant (Zamioculcas zamiifolia 'Raven')", "Swiss Cheese Plant (Monstera adansonii)", "Spiderette Plant (Chlorophytum comosum 'Bonnie')", "Nerve Plant (Fittonia)", "Lucky Bamboo (Dracaena sanderiana)", "Majesty Palm (Ravenea rivularis)", "String of Hearts (Ceropegia woodii)", "Golden Pothos (Epipremnum aureum 'Marble Queen')", "Yucca Plant (Yucca elephantipes)", "Cactus (Various species)", "Elephant Ear Plant (Alocasia)", "Lipstick Plant (Aeschynanthus radicans)", "Pilea Peperomioides", "Begonia (Various species)", "Fern Arum (Nephrolepis exaltata 'Bostoniensis')", "Dieffenbachia (Dieffenbachia seguine)" ) var nom = planta.random() return nom }
ExerciciGuerrers/app/src/main/java/com/mataecheverry/exerciciguerrers/dades/Planta.kt
1653615029
package com.mataecheverry.exerciciguerrers.navegacio import androidx.navigation.NamedNavArgument import androidx.navigation.NavType import androidx.navigation.navArgument sealed class Destinacio ( val rutaBase: String, //3 //98 val argumentsDeNaveacio: List<ArgumentDeNavegacio> = emptyList())//Primera pantalla = "principal"; Segona = MinMax/{min}/{max}; tercera: llistaDeGuerres/{titol} { //ruta amb paràmetres: val rutaGenerica = run{ //Tenim un allista d'arguments, cada argument té una clau i un tipus. Ens referim a argumentDeNavegacio.clau val claus = argumentsDeNaveacio.map { "{${it.clau}}" } listOf(rutaBase) .plus(claus) .joinToString("/") } //map: per cada element de la llista, aplica el que es demana. val navArgs = argumentsDeNaveacio.map{it.toNavArgument()} //Definim les destinacions, és a dir, les pantalles: object Principal: Destinacio("Principal") object LlistaDeGuerrers: Destinacio("LlistaDeGerrers", listOf(ArgumentDeNavegacio.Titol) ) { fun creaRutaEspecifica(titol: String)= "$rutaBase/$titol" } object DetallGuerrer : Destinacio("DetallGuerrer", listOf(ArgumentDeNavegacio.Detall)) { fun creaRutaEspecifica(id: String) = "$rutaBase/$id" } object LlistaDePlantes: Destinacio("LlistaDePlantes", listOf(ArgumentDeNavegacio.Planta)) { fun creaRutaEspecifica(planta: String) = "$rutaBase/$planta" } object DetallPlanta: Destinacio("DetallPlanta", listOf(ArgumentDeNavegacio.DetallPlanta)) { fun creaRutaEspecifica(id: String)= "$rutaBase/$id" } object LlistaDArmes: Destinacio ("LlistaDArmes", listOf(ArgumentDeNavegacio.Arma)) { fun creaRutaEspecifica(arma: String) = "$rutaBase/$arma" } object DetallArma: Destinacio("DetallArma", listOf(ArgumentDeNavegacio.DetallArma)) { fun creaRutaEspecifica(id: String)= "$rutaBase/$id" } } //Definim tots els arguments que hi ha. Hem de poder dir quins arguments i tipus té. enum class ArgumentDeNavegacio ( val clau: String, val tipus: NavType<*> ) { Titol("Titol", NavType.StringType), Planta("PlantaTitol", NavType.StringType), Arma("ArmaTitol", NavType.StringType), Detall("Detall", NavType.StringType), DetallPlanta("DetallPlanta", NavType.StringType), DetallArma("DetallArma", NavType.StringType); //Format navArgs o argument de navegació per fer conversions: fun toNavArgument(): NamedNavArgument{ return navArgument(clau){tipus} } }
ExerciciGuerrers/app/src/main/java/com/mataecheverry/exerciciguerrers/navegacio/Destinacio.kt
1309607193
package com.mataecheverry.exerciciguerrers.navegacio import android.util.Log import androidx.compose.runtime.Composable import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.rememberNavController import com.mataecheverry.exerciciguerrers.ui.pantallas.PantallaArmaDetall import com.mataecheverry.exerciciguerrers.ui.pantallas.PantallaGuerrerDetall import com.mataecheverry.exerciciguerrers.ui.pantallas.PantallaLlistaDArmes import com.mataecheverry.exerciciguerrers.ui.pantallas.PantallaLlistaDeGuerrers import com.mataecheverry.exerciciguerrers.ui.pantallas.PantallaLlistaDePlantes import com.mataecheverry.exerciciguerrers.ui.pantallas.PantallaMinimMaxim import com.mataecheverry.exerciciguerrers.ui.pantallas.PantallaPlantaDetall import com.mataecheverry.exerciciguerrers.ui.pantallas.PantallaPrincipal @Composable fun GrafDeNavegacio(){ val controladorDeNavegacio = rememberNavController() NavHost(navController = controladorDeNavegacio , startDestination = Destinacio.Principal.rutaGenerica) { composable( route=Destinacio.Principal.rutaGenerica ){ PantallaPrincipal( //Els botons que ajuden a navegar: onLlistaDePlantesClick = { controladorDeNavegacio.navigate(Destinacio.LlistaDePlantes.rutaGenerica) }, onLlistaDeGuerrersClick = { controladorDeNavegacio.navigate(Destinacio.LlistaDeGuerrers.rutaGenerica) }, onLlistaArmesClick = { controladorDeNavegacio.navigate(Destinacio.LlistaDArmes.rutaGenerica) } ) } //region guerrers composable( route=Destinacio.LlistaDeGuerrers.rutaGenerica, arguments = Destinacio.LlistaDeGuerrers.navArgs ){ //Recuperem els paràmetres: val titol = it.arguments?.getString(ArgumentDeNavegacio.Titol.clau) requireNotNull(titol) PantallaLlistaDeGuerrers(titol, onGuerrerClick = {guerrerId: String -> controladorDeNavegacio.navigate(Destinacio.DetallGuerrer.creaRutaEspecifica(guerrerId))}, onPopUpToClick={controladorDeNavegacio.navigateUp()}) } composable( route=Destinacio.DetallGuerrer.rutaGenerica, arguments = Destinacio.DetallGuerrer.navArgs){ val id = it.arguments?.getString(ArgumentDeNavegacio.Detall.clau) requireNotNull(id) PantallaGuerrerDetall(id, onPopUpToClick = {controladorDeNavegacio.navigateUp()}) } //endregion //region plantes composable ( route=Destinacio.LlistaDePlantes.rutaGenerica, arguments = Destinacio.LlistaDePlantes.navArgs){ val planta = it.arguments?.getString(ArgumentDeNavegacio.Planta.clau) requireNotNull(planta) PantallaLlistaDePlantes(planta, onPlantaClick={plantaId: String -> controladorDeNavegacio.navigate(Destinacio.DetallPlanta.creaRutaEspecifica(plantaId))}, onPopUpToClick={controladorDeNavegacio.navigateUp()}) } composable( route=Destinacio.DetallPlanta.rutaGenerica, arguments = Destinacio.DetallPlanta.navArgs){ val id = it.arguments?.getString(ArgumentDeNavegacio.DetallPlanta.clau) requireNotNull(id) PantallaPlantaDetall(id, onPopUpToClick = {controladorDeNavegacio.navigateUp()}) } //endregion //region armes composable ( route=Destinacio.LlistaDArmes.rutaGenerica, arguments = Destinacio.LlistaDArmes.navArgs){ val arma = it.arguments?.getString(ArgumentDeNavegacio.Arma.clau) requireNotNull(arma) PantallaLlistaDArmes(arma, onArmaClick={ armaId: String -> controladorDeNavegacio.navigate(Destinacio.DetallArma.creaRutaEspecifica(armaId))}, onPopUpToClick={controladorDeNavegacio.navigateUp()}) } composable( route=Destinacio.DetallArma.rutaGenerica, arguments = Destinacio.DetallArma.navArgs){ val id = it.arguments?.getString(ArgumentDeNavegacio.DetallArma.clau) requireNotNull(id) PantallaArmaDetall(id, onPopUpToClick = {controladorDeNavegacio.navigateUp()}) } //endregion } }
ExerciciGuerrers/app/src/main/java/com/mataecheverry/exerciciguerrers/navegacio/GraphNavegacio.kt
2278643353
package io.github.tomatsch87.ui import io.github.tomatsch87.actions.SettingsAction import io.github.tomatsch87.actions.ToolWindowClearAction import io.github.tomatsch87.actions.ToolWindowRequestFeedbackAction import io.github.tomatsch87.actions.ToolWindowSearchAction import io.github.tomatsch87.services.PluginSettings import com.intellij.icons.AllIcons import com.intellij.openapi.actionSystem.* import com.intellij.openapi.actionSystem.impl.ActionButtonWithText import com.intellij.ui.JBColor import com.intellij.ui.OnePixelSplitter import com.intellij.ui.components.JBLabel import com.intellij.ui.components.panels.NonOpaquePanel import java.awt.* import java.awt.event.FocusAdapter import java.awt.event.FocusEvent import javax.swing.BoxLayout import javax.swing.JPanel import javax.swing.JTextField class ToolWindowActionsPanel(searchAction: ToolWindowSearchAction, clearAction: ToolWindowClearAction, requestFeedbackAction: ToolWindowRequestFeedbackAction) : NonOpaquePanel() { // Store the filter text fields private val filterTextFields: MutableList<JTextField> = mutableListOf() init { // Set the layout of the panel this.layout = BorderLayout() // Create a panel for the login status val loginStatusPanel = JPanel() // Create a label for the login status icon val loginStatusLabel = JBLabel() if (PluginSettings.instance.state.accessToken == "") { loginStatusLabel.text = "No Connection" loginStatusLabel.icon = AllIcons.Debugger.Db_set_breakpoint } else { loginStatusLabel.text = "Connected" loginStatusLabel.icon = AllIcons.General.InspectionsOK } // Add the label to the login status panel loginStatusPanel.add(loginStatusLabel) loginLabels.add(loginStatusLabel) // Create a panel for the action buttons val actionButtonsPanel = JPanel() actionButtonsPanel.layout = BorderLayout() val helperPanel = JPanel() helperPanel.layout = FlowLayout(FlowLayout.LEFT) // Add an action button for the search action to the panel val searchPresentation = Presentation("Search") searchPresentation.icon = AllIcons.Actions.Search helperPanel.add(ActionButtonWithText( searchAction, searchPresentation, ActionPlaces.TOOLWINDOW_CONTENT, Dimension(75, 30) )) // Add an action button for the clear results action to the panel val clearPresentation = Presentation("Clear results") clearPresentation.icon = AllIcons.Actions.Refresh helperPanel.add(ActionButtonWithText( clearAction, clearPresentation, ActionPlaces.TOOLWINDOW_CONTENT, Dimension(75, 30) )) // Add an action button for the settings action to the panel val settingsPresentation = Presentation("Settings") settingsPresentation.icon = AllIcons.General.Settings helperPanel.add(ActionButtonWithText( SettingsAction(), settingsPresentation, ActionPlaces.TOOLWINDOW_CONTENT, Dimension(75, 30) )) // Add an action button for the settings action to the panel val feedbackPresentation = Presentation("Feedback") feedbackPresentation.icon = AllIcons.General.ContextHelp helperPanel.add(ActionButtonWithText( requestFeedbackAction, feedbackPresentation, ActionPlaces.TOOLWINDOW_CONTENT, Dimension(75, 30) )) actionButtonsPanel.add(helperPanel, BorderLayout.WEST) actionButtonsPanel.add(loginStatusPanel, BorderLayout.EAST) // Create a panel for the filter val filterPanel = JPanel() filterPanel.layout = BoxLayout(filterPanel, BoxLayout.X_AXIS) // Path filter val pathFilter = JTextField(18) pathFilter.foreground = JBColor.GRAY val pathFilterText = "Enter path filter" pathFilter.text = pathFilterText pathFilter.addFocusListener(object : FocusAdapter() { override fun focusGained(e: FocusEvent) { if (pathFilter.text == pathFilterText) { pathFilter.foreground = JBColor.BLACK pathFilter.text = "" } } override fun focusLost(e: FocusEvent) { if (pathFilter.text.isEmpty()) { pathFilter.foreground = JBColor.GRAY pathFilter.text = pathFilterText } } }) filterTextFields.add(pathFilter) // Include filter val includeFilter = JTextField(18) includeFilter.foreground = JBColor.GRAY val includeFilterText = "Enter keywords to include" includeFilter.text = includeFilterText includeFilter.addFocusListener(object : FocusAdapter() { override fun focusGained(e: FocusEvent) { if (includeFilter.text == includeFilterText) { includeFilter.foreground = JBColor.BLACK includeFilter.text = "" } } override fun focusLost(e: FocusEvent) { if (includeFilter.text.isEmpty()) { includeFilter.foreground = JBColor.GRAY includeFilter.text = includeFilterText } } }) filterTextFields.add(includeFilter) // Exclude filter val excludeFilter = JTextField(18) excludeFilter.foreground = JBColor.GRAY val excludeFilterText = "Enter keywords to exclude" excludeFilter.text = excludeFilterText excludeFilter.addFocusListener(object : FocusAdapter() { override fun focusGained(e: FocusEvent) { if (excludeFilter.text == excludeFilterText) { excludeFilter.foreground = JBColor.BLACK excludeFilter.text = "" } } override fun focusLost(e: FocusEvent) { if (excludeFilter.text.isEmpty()) { excludeFilter.foreground = JBColor.GRAY excludeFilter.text = excludeFilterText } } }) filterTextFields.add(excludeFilter) // Add the filter text fields to the filter panel filterPanel.add(pathFilter) filterPanel.add(includeFilter) filterPanel.add(excludeFilter) // Create a new OnePixelSplitter instance to split the action buttons panel and the filter panel val horizontalSplitter = OnePixelSplitter(true, 0.0f) horizontalSplitter.setResizeEnabled(false) // Add the action buttons panel and the filter panel to the OnePixelSplitter horizontalSplitter.firstComponent = actionButtonsPanel horizontalSplitter.secondComponent = filterPanel // Add the action buttons panel to the main panel on the left side this.add(horizontalSplitter, BorderLayout.WEST) } // This method is used to refresh the buttons of the panel fun refreshButtons() { // Perform the necessary refresh operations on the buttons for (component in this.components) { if (component is ActionButtonWithText) { component.update() } } } // This method is used to get the text from all filter text fields fun getFilterText(): List<String> { val texts = filterTextFields.map { it.text }.toMutableList() if (texts[0] == "Enter path filter") { texts[0] = "" } if (texts[1] == "Enter keywords to include") { texts[1] = "" } if (texts[2] == "Enter keywords to exclude") { texts[2] = "" } return texts } companion object { // Store the login status labels val loginLabels: MutableList<JBLabel> = mutableListOf() // This method is used change the login status of the panel fun updateLoginStatusPanel() { loginLabels.forEach { if (PluginSettings.instance.state.accessToken == "") { it.text = "No Connection" it.icon = AllIcons.Debugger.Db_set_breakpoint } else { it.text = "Connected" it.icon = AllIcons.General.InspectionsOK } } } } }
copilot-toolwindow-plugin/src/main/kotlin/io/github/tomatsch87/ui/ToolWindowActionsPanel.kt
3867177552
package io.github.tomatsch87.ui import io.github.tomatsch87.actions.ToolWindowResultFeedbackAction import io.github.tomatsch87.actions.ToolWindowSearchAction import com.intellij.openapi.actionSystem.* import com.intellij.openapi.actionSystem.impl.ActionButton import com.intellij.ui.JBColor import com.intellij.ui.components.JBLabel import com.intellij.ui.components.panels.NonOpaquePanel import org.jdesktop.swingx.geom.Star2D import java.awt.* import javax.swing.BoxLayout import javax.swing.JButton import kotlin.math.min // This class defines the feedback panel at the bottom of each Editor panel class ToolWindowFeedbackPanel(panelNumber: Int, private val searchAction: ToolWindowSearchAction) : NonOpaquePanel() { private val id = panelNumber private var star1: Star private var star2: Star private var star3: Star private var star4: Star private var star5: Star private var star = 0 private var label: JBLabel class Star : JButton() { init { setContentAreaFilled(true) setCursor(Cursor(Cursor.HAND_CURSOR)) border = null isOpaque = false } override fun paint(g: Graphics?) { super.paint(g) val g2 = g?.create() as Graphics2D g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) val width = width val height = height val size = min(width, height) / 2 val x = width / 2 val y = height / 2 val s = Star2D(x.toDouble(), y.toDouble() * 1.1, ((size / 2).toDouble()) * 0.9, size.toDouble() * 0.9, 5) g2.color = JBColor.GRAY g2.fill(s) if (isSelected) { g2.color = JBColor(0xFFF700, 0xFFF700) g2.fill(s) } g2.dispose() } override fun getPreferredSize(): Dimension { return Dimension(40, 40) } } init { // Set the layout of the panel this.layout = BorderLayout() val starPanel = NonOpaquePanel() starPanel.layout = BoxLayout(starPanel, BoxLayout.X_AXIS) // Add the 5 stars to the panel this.star1 = Star() this.star1.toolTipText = "Irrelevant: The snippet has nothing to do with my search." this.star1.addActionListener{ this.star = 0 this.star1ActionPerformed() } starPanel.add(star1) this.star2 = Star() this.star2.toolTipText = "Related: The snippet seems related to my search but does not answer it." this.star2.addActionListener{ this.star = 1 this.star2ActionPerformed() } starPanel.add(star2) this.star3 = Star() this.star3.toolTipText = "Remotely relevant: The snippet provides some information relevant to my search, which may be minimal." this.star3.addActionListener{ this.star = 2 this.star3ActionPerformed() } starPanel.add(star3) this.star4 = Star() this.star4.toolTipText = "Relevant: The snippet has some answer for my search, but may need substantial modification." this.star4.addActionListener{ this.star = 3 this.star4ActionPerformed() } starPanel.add(star4) this.star5 = Star() this.star5.toolTipText = "Highly relevant: The snippet is dedicated to my search and can be used with minimal modification." this.star5.addActionListener{ this.star = 4 this.star5ActionPerformed() } starPanel.add(star5) this.add(starPanel, BorderLayout.WEST) this.label = JBLabel("Select a star to provide feedback") this.label.foreground = JBColor.GRAY this.label.setAllowAutoWrapping(true) this.add(this.label, BorderLayout.EAST) } // This method is used to refresh the buttons of the panel fun refreshButtons() { // Perform the necessary refresh operations on the buttons for (component in this.components) { if (component is ActionButton) { component.update() } } } // This method is used to reset the feedback panel fun reset() { this.star1.setSelected(false) this.star2.setSelected(false) this.star3.setSelected(false) this.star4.setSelected(false) this.star5.setSelected(false) this.label.text = "Select a star to provide feedback" } private fun star1ActionPerformed() { star1.setSelected(true) star2.setSelected(false) star3.setSelected(false) star4.setSelected(false) star5.setSelected(false) this.label.text = "Irrelevant" val event = AnActionEvent(null, DataContext.EMPTY_CONTEXT, ActionPlaces.TOOLWINDOW_POPUP, Presentation(), ActionManager.getInstance(), 0) ToolWindowResultFeedbackAction(panelNumber = this.id, 0, searchAction).actionPerformed(event) } private fun star2ActionPerformed() { star1.setSelected(true) star2.setSelected(true) star3.setSelected(false) star4.setSelected(false) star5.setSelected(false) this.label.text = "Related" val event = AnActionEvent(null, DataContext.EMPTY_CONTEXT, ActionPlaces.TOOLWINDOW_POPUP, Presentation(), ActionManager.getInstance(), 0) ToolWindowResultFeedbackAction(panelNumber = this.id, 1, searchAction).actionPerformed(event) } private fun star3ActionPerformed() { star1.setSelected(true) star2.setSelected(true) star3.setSelected(true) star4.setSelected(false) star5.setSelected(false) this.label.text = "Remotely relevant" val event = AnActionEvent(null, DataContext.EMPTY_CONTEXT, ActionPlaces.TOOLWINDOW_POPUP, Presentation(), ActionManager.getInstance(), 0) ToolWindowResultFeedbackAction(panelNumber = this.id, 2, searchAction).actionPerformed(event) } private fun star4ActionPerformed() { star1.setSelected(true) star2.setSelected(true) star3.setSelected(true) star4.setSelected(true) star5.setSelected(false) this.label.text = "Relevant" val event = AnActionEvent(null, DataContext.EMPTY_CONTEXT, ActionPlaces.TOOLWINDOW_POPUP, Presentation(), ActionManager.getInstance(), 0) ToolWindowResultFeedbackAction(panelNumber = this.id, 3, searchAction).actionPerformed(event) } private fun star5ActionPerformed() { star1.setSelected(true) star2.setSelected(true) star3.setSelected(true) star4.setSelected(true) star5.setSelected(true) this.label.text = "Highly relevant" val event = AnActionEvent(null, DataContext.EMPTY_CONTEXT, ActionPlaces.TOOLWINDOW_POPUP, Presentation(), ActionManager.getInstance(), 0) ToolWindowResultFeedbackAction(panelNumber = this.id, 4, searchAction).actionPerformed(event) } }
copilot-toolwindow-plugin/src/main/kotlin/io/github/tomatsch87/ui/ToolWindowFeedbackPanel.kt
506945633
package io.github.tomatsch87.ui import io.github.tomatsch87.actions.ToolWindowSearchAction import io.github.tomatsch87.domain.ToolWindowEditor import com.intellij.openapi.application.ApplicationInfo import com.intellij.openapi.editor.EditorFactory import com.intellij.openapi.fileTypes.FileType import com.intellij.openapi.fileTypes.FileTypeManager import com.intellij.openapi.wm.ToolWindow import com.intellij.openapi.wm.WindowManager import com.intellij.ui.components.JBScrollPane import com.intellij.ui.components.panels.NonOpaquePanel import com.intellij.ui.EditorTextField import com.intellij.ui.OnePixelSplitter import com.intellij.ui.components.JBLabel import com.intellij.util.asSafely import java.awt.BorderLayout import java.awt.Dimension import java.awt.event.ComponentAdapter import java.awt.event.ComponentEvent import javax.swing.* // This class defines the editor panel which is the main panel of the ToolWindow with 10 editor text fields class ToolWindowEditorPanel(private val toolWindow: ToolWindow, searchAction: ToolWindowSearchAction) : NonOpaquePanel() { // The content panel which contains the 10 editor panels private val content = JPanel() // Get intellij window height private val windowHeight = WindowManager.getInstance().getFrame(toolWindow.project)?.height ?: 0 // List of the editor panels private val editorPanels: MutableList<JPanel> = mutableListOf() // List of the editor text fields private val editorTextFields: MutableList<EditorTextField> = mutableListOf() // List of the editor file path labels private val editorFilePathLabels: MutableList<JBLabel> = mutableListOf() // List of the feedback panel instances private val feedbackInstance: MutableList<ToolWindowFeedbackPanel> = mutableListOf() init { // Set the layout of the content panel to vertical box layout content.layout = BoxLayout(content, BoxLayout.Y_AXIS) // variable to store the language of the file var extension = "unknown" // Get the application name val app = ApplicationInfo.getInstance().fullApplicationName // Set the language of the file based on the application when { app.contains("IntelliJ") -> { extension = "java" } app.contains("PyCharm") -> { extension = "py" } app.contains("WebStorm") -> { extension = "js" } } // Add 10 editor panels to the content panel for (i in 0 until 10) { // Create a new ToolWindowFeedbackPanel instance to display the like and dislike buttons val feedbackPanel = ToolWindowFeedbackPanel(i, searchAction) feedbackInstance.add(feedbackPanel) // Create a new ToolWindowEditorPanel instance to display the editor text field val editorPanel = createEditorPanel(extension) // Create a new JBLabel instance to display the file path of the editor val editorLabel = JBLabel("") // Set the border of the editor label editorLabel.border = BorderFactory.createEmptyBorder(3, 5, 3, 5) // Add the editor label to the list of editor labels in the companion object editorFilePathLabels.add(editorLabel) // Add the editor label to the editor panel editorPanel.add(editorLabel, BorderLayout.NORTH) // Add the editor panel to the list of editor panels in the companion object editorPanels.add(editorPanel) // Create a new OnePixelSplitter instance to split the feedback panel and the editor panel val verticalSplitter = OnePixelSplitter(true, 0.95f) verticalSplitter.setResizeEnabled(false) // Add the feedback panel and the editor panel to the OnePixelSplitter verticalSplitter.firstComponent = editorPanel verticalSplitter.secondComponent = feedbackPanel // Add the OnePixelSplitter to the content of the editor panel content.add(verticalSplitter) // Add a horizontal line after every vertical splitter content.add(Box.createRigidArea(Dimension(0, 2))) } // Wrap content panel in a scroll pane for vertical scrolling val scrollPane = JBScrollPane(content) scrollPane.horizontalScrollBarPolicy = JScrollPane.HORIZONTAL_SCROLLBAR_NEVER scrollPane.verticalScrollBarPolicy = JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED // Add the scroll pane to the main panel layout = BorderLayout() add(scrollPane, BorderLayout.CENTER) } // This function creates an editor panel with a single editor text field private fun createEditorPanel(extension: String): JPanel { // Create the editor text field val editorTextField = createEditorTextField(extension) // Add the editor text field to the list of editor text fields in the companion object editorTextFields.add(editorTextField) // Create the editor panel val editorPanel = JPanel() // Set the layout of the editor panel to border layout editorPanel.layout = BorderLayout() // Set the maximum size of the editor panel editorPanel.maximumSize = Dimension(Int.MAX_VALUE, if (windowHeight > 0) windowHeight / 2 else 600) // Add an empty WEST component with a BoxLayout to enforce a minimum height val westPanel = JPanel() westPanel.layout = BoxLayout(westPanel, BoxLayout.Y_AXIS) westPanel.add(Box.createVerticalGlue()) editorPanel.add(westPanel, BorderLayout.WEST) // Add the editor text field in a scroll pane to the CENTER component val editorScrollPane = JBScrollPane(editorTextField) editorScrollPane.horizontalScrollBarPolicy = JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED editorScrollPane.verticalScrollBarPolicy = JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED editorPanel.add(editorScrollPane, BorderLayout.CENTER) // Add an empty EAST component with a BoxLayout to enforce a minimum height val eastPanel = JPanel() eastPanel.layout = BoxLayout(eastPanel, BoxLayout.Y_AXIS) eastPanel.add(Box.createVerticalGlue()) editorPanel.add(eastPanel, BorderLayout.EAST) // Add a ComponentListener to the editorTextField to listen for changes in its size editorTextField.addComponentListener(object : ComponentAdapter() { override fun componentResized(e: ComponentEvent?) { // Calculate the preferred height of the editorTextField based on its content val prefHeight = editorTextField.preferredSize.height // Calculate the height of the editorPanel val panelHeight = westPanel.preferredSize.height + prefHeight + eastPanel.preferredSize.height // Set the height of the editorPanel based on the calculated height editorPanel.preferredSize = Dimension(Int.MAX_VALUE, panelHeight.coerceIn(if (windowHeight > 0) windowHeight / 7 else 180, if (windowHeight > 0) windowHeight / 2 else 600)) // Revalidate and repaint the editorPanel to reflect the new size editorPanel.revalidate() editorPanel.repaint() } }) return editorPanel } // This function creates an editor text field private fun createEditorTextField(extension: String): EditorTextField { // Get the file type from the language and create the document for the editor val fileType: FileType = FileTypeManager.getInstance().getFileTypeByExtension(extension) val editorFactory = EditorFactory.getInstance() val document = editorFactory.createDocument("") // Create the editor text field val twEditor = ToolWindowEditor(toolWindow, document, toolWindow.project, fileType) // Set up the editor twEditor.createEditor() // Dispose the editor twEditor.dispose() return twEditor } // This method is used to reset all the feedback panels fun resetAllFeedbackPanels() { for (panel in feedbackInstance) { panel.reset() } } // This function updates the code of the editor text fields fun updateEditorTextFields(code: List<String>, before: List<Int>, after: List<Int>, filePaths: List<String>) { // Remove folding regions clearEditorTextFields() for (i in editorTextFields.indices) { if (i < code.size) { editorTextFields[i].text = code[i] editorFilePathLabels[i].text = "Result ${i+1} from " + filePaths[i] // Add folding regions for codeBefore and codeAfter val editor = editorTextFields[i].editor val foldingModel = editor?.foldingModel if (editor != null) { foldingModel?.runBatchFoldingOperation { val startBeforeOffset = editor.document.getLineStartOffset(0) val endBeforeOffset = if ((before[i] - 1) < 0) { editor.document.getLineEndOffset(0) } else { editor.document.getLineEndOffset(before[i] - 1) } val startAfterOffset = editor.document.getLineStartOffset(after[i]) val endAfterOffset = if ((editor.document.lineCount -1) < 0) { editor.document.getLineEndOffset(0) } else { editor.document.getLineEndOffset(editor.document.lineCount - 1) } val foldrBefore = foldingModel.addFoldRegion(startBeforeOffset, endBeforeOffset, "...") if (foldrBefore != null) { foldrBefore.isExpanded = false } val foldrAfter = foldingModel.addFoldRegion(startAfterOffset, endAfterOffset, "...") if (foldrAfter != null) { foldrAfter.isExpanded = false } } } editorPanels[i].revalidate() editorPanels[i].repaint() } else { break } } } // This function clears the text of the editor text fields fun clearEditorTextFields() { for (i in editorTextFields.indices) { editorTextFields[i].text = "" editorFilePathLabels[i].text = "" editorTextFields[i].asSafely<ToolWindowEditor>()?.resetFontSize() editorPanels[i].revalidate() editorPanels[i].repaint() } } }
copilot-toolwindow-plugin/src/main/kotlin/io/github/tomatsch87/ui/ToolWindowEditorPanel.kt
84007500
package io.github.tomatsch87.ui import io.github.tomatsch87.services.AuthenticationService import io.github.tomatsch87.services.PluginSettings import com.intellij.openapi.ui.DialogWrapper import java.awt.BorderLayout import java.awt.FlowLayout import javax.swing.* // Provides dialog to access the plugin settings from the toolbar settings item class SettingsDialogWrapper : DialogWrapper(true) { // Initialize text fields for userEmail and connectionUri private val firstName = JTextField(13) private val lastName = JTextField(13) private val userEmail = JTextField(30) private val connectionUri = JTextField(30) private val password = JPasswordField(30) init { // Call superclass constructor and set dialog title init() title = "Copilot Toolwindow Settings" // Get plugin settings state val state = PluginSettings.instance.state // Initialize text fields with saved state firstName.text = state.firstName lastName.text = state.lastName userEmail.text = state.userEmail connectionUri.text = state.connectionUri password.text = state.getPasswordFromSafe() } // Create the center panel of the dialog override fun createCenterPanel(): JComponent { // Create a new panel with a border layout val panel = JPanel(BorderLayout()) // Create a form panel with a box layout val formPanel = JPanel() formPanel.layout = BoxLayout(formPanel, BoxLayout.Y_AXIS) // Create a new labels and text fields val fn = JLabel("First Name:") val ln = JLabel("Last Name:") // Create a new panels with a border layout val namePanel = JPanel(BorderLayout()) val fnPanel = JPanel(BorderLayout()) val lnPanel = JPanel(BorderLayout()) // Layout for the name panel fnPanel.add(fn, BorderLayout.WEST) fnPanel.add(firstName, BorderLayout.EAST) lnPanel.add(ln, BorderLayout.WEST) lnPanel.add(lastName, BorderLayout.EAST) namePanel.add(fnPanel, BorderLayout.WEST) namePanel.add(lnPanel, BorderLayout.EAST) // Add text field panels to the form panel formPanel.add(namePanel) formPanel.add(createTextFieldPanel("User-Email:", userEmail)) formPanel.add(createTextFieldPanel("Password:", password)) formPanel.add(createTextFieldPanel("Connection-Address:", connectionUri)) // Add the form panel to the center of the main panel panel.add(formPanel, BorderLayout.CENTER) return panel } // Create the south panel with custom buttons override fun createSouthPanel(): JComponent { // Create a panel with a flow layout val panel = JPanel(FlowLayout(FlowLayout.RIGHT)) // Create the default "Cancel" and "OK" buttons val cancelButton = JButton(cancelAction) val okButton = JButton(okAction) // Create the custom "Register" button val registerButton = JButton("Register") registerButton.addActionListener { registerUserDialog() } // Create the custom "Login" button val loginButton = JButton("Login") loginButton.addActionListener { loginUserDialog() } // Add the buttons to the panel panel.add(registerButton) panel.add(loginButton) panel.add(cancelButton) panel.add(okButton) return panel } // Write settings to state and login user when "Login" button is pressed private fun loginUserDialog() { val state = PluginSettings.instance.state // Write current input from text fields to state state.firstName = firstName.text state.lastName = lastName.text state.userEmail = userEmail.text state.connectionUri = connectionUri.text state.setPasswordToSafe(String(password.password)) // Login user AuthenticationService().logoutUser() AuthenticationService().loginUser() } // Write settings to state and register user when "Register" button is pressed private fun registerUserDialog() { val state = PluginSettings.instance.state // Write current input from text fields to state state.firstName = firstName.text state.lastName = lastName.text state.userEmail = userEmail.text state.connectionUri = connectionUri.text state.setPasswordToSafe(String(password.password)) // Register user AuthenticationService().logoutUser() AuthenticationService().registerUser() AuthenticationService().loginUser() } // Save settings and close dialog when OK button is pressed override fun doOKAction() { val state = PluginSettings.instance.state // Write current input from text fields to state state.firstName = firstName.text state.lastName = lastName.text state.userEmail = userEmail.text state.connectionUri = connectionUri.text state.setPasswordToSafe(String(password.password)) this.close(OK_EXIT_CODE) } // Helper function to create a text field panel with a label private fun createTextFieldPanel(labelText: String, textField: JTextField): JPanel { // Create a new label with the given text val label = JLabel(labelText) // Create a new panel with a border layout val textFieldPanel = JPanel(BorderLayout()) // Add the label to the left of the text field textFieldPanel.add(label, BorderLayout.WEST) textFieldPanel.add(textField, BorderLayout.EAST) return textFieldPanel } }
copilot-toolwindow-plugin/src/main/kotlin/io/github/tomatsch87/ui/SettingsDialogWrapper.kt
409663600
package io.github.tomatsch87.ui import io.github.tomatsch87.services.AuthenticationService import io.github.tomatsch87.services.PluginSettings import com.intellij.openapi.options.Configurable import com.intellij.ui.components.JBLabel import com.intellij.util.ui.FormBuilder import javax.swing.* // Provides integration of the plugin settings into the system settings from intellij. class SettingsConfigurable : Configurable { private var panel: JPanel? private val registerButton = JButton("Register") private val loginButton = JButton("Login") // Initialize text fields for userEmail and connectionUri private val firstName = JTextField(15) private val lastName = JTextField(15) private val userEmail = JTextField(30) private val connectionUri = JTextField(30) private val password = JPasswordField(30) init { // Create the Swing form panel = FormBuilder.createFormBuilder() .addLabeledComponent(JBLabel("First Name: "), firstName, 1, false) .addComponent(firstName, 1) .addLabeledComponent(JBLabel("Last Name: "), lastName, 1, false) .addComponent(lastName, 1) .addLabeledComponent(JBLabel("User-Email: "), userEmail, 1, false) .addComponent(userEmail, 1) .addLabeledComponent(JBLabel("Password: "), password, 1, false) .addComponent(password, 1) .addLabeledComponent(JBLabel("Connection-Address: "), connectionUri, 1, false) .addComponent(connectionUri, 1) .addComponent(loginButton) .addComponent(registerButton) .addComponentFillVertically(JPanel(), 0) .panel // Add action listener to register button registerButton.addActionListener { registerUserDialog() } // Add action listener to login button loginButton.addActionListener { loginUserDialog() } } // Write settings to state and register user when "Register" button is pressed private fun registerUserDialog() { val state = PluginSettings.instance.state // Write current input from text fields to state state.firstName = firstName.text state.lastName = lastName.text state.userEmail = userEmail.text state.connectionUri = connectionUri.text state.setPasswordToSafe(String(password.password)) // Register user AuthenticationService().logoutUser() AuthenticationService().registerUser() AuthenticationService().loginUser() } // Write settings to state and login user when "Login" button is pressed private fun loginUserDialog() { val state = PluginSettings.instance.state // Write current input from text fields to state state.firstName = firstName.text state.lastName = lastName.text state.userEmail = userEmail.text state.connectionUri = connectionUri.text state.setPasswordToSafe(String(password.password)) // Login user AuthenticationService().logoutUser() AuthenticationService().loginUser() } // Returns the visible name of the configurable component override fun getDisplayName(): String { return "Copilot Toolwindow Settings" } // Returns Swing form that enables the user to configure settings override fun createComponent(): JComponent? { return panel } // Indicates whether the Swing form was modified or not override fun isModified(): Boolean { // Get plugin settings state val state = PluginSettings.instance.state return !firstName.text.equals(state.firstName) or !lastName.text.equals(state.lastName) or !userEmail.text.equals(state.userEmail) or !connectionUri.text.equals(state.connectionUri) or (String(password.password) != state.getPasswordFromSafe()) } // Write current input from text fields to state override fun apply() { val state = PluginSettings.instance.state // Write current input from text fields to state state.firstName = firstName.text state.lastName = lastName.text state.userEmail = userEmail.text state.connectionUri = connectionUri.text state.setPasswordToSafe(String(password.password)) // Apply changes from dialog AuthenticationService().logoutUser() AuthenticationService().loginUserNoPopup() } // Initialize text fields with saved state override fun reset() { val state = PluginSettings.instance.state firstName.text = state.firstName lastName.text = state.lastName userEmail.text = state.userEmail connectionUri.text = state.connectionUri password.text = state.getPasswordFromSafe() } // Notifies the configurable component that the Swing form will be closed override fun disposeUIResources() { panel = null } }
copilot-toolwindow-plugin/src/main/kotlin/io/github/tomatsch87/ui/SettingsConfigurable.kt
1053389874
package io.github.tomatsch87.ui import io.github.tomatsch87.actions.* import com.intellij.openapi.project.Project import com.intellij.openapi.ui.SimpleToolWindowPanel import com.intellij.openapi.wm.ToolWindow import com.intellij.ui.OnePixelSplitter import com.intellij.ui.content.ContentFactory import javax.swing.JComponent import javax.swing.JPanel // Defines a ToolWindowFactory that creates a CopilotToolWindow when the tool window is opened class CopilotToolWindowFactory : ToolWindowFactory { // Creates a content factory instance to create content for the CopilotToolWindow private val contentFactory = ContentFactory.getInstance() // This function is called when the tool window is created override fun createToolWindowContent(project: Project, toolWindow: ToolWindow) { val myToolWindow = CopilotToolWindow(toolWindow) val content = contentFactory.createContent(myToolWindow.getContent(), null, false) // Add the content to the tool window's content manager toolWindow.contentManager.addContent(content) } override fun shouldBeAvailable(project: Project) = true class CopilotToolWindow(toolWindow: ToolWindow) { // Create a new SimpleToolWindow instance to hold the content private val content: JPanel = SimpleToolWindowPanel(true, true) init { // Create all the actions and panels that are used in the CopilotToolWindow // use dependency injection to pass the actions to the panels val searchAction = ToolWindowSearchAction() val editorPanel = ToolWindowEditorPanel(toolWindow, searchAction) searchAction.setEditorPanel(editorPanel) val clearAction = ToolWindowClearAction(editorPanel, searchAction) val requestFeedbackAction = ToolWindowRequestFeedbackAction(searchAction) val actionsPanel = ToolWindowActionsPanel(searchAction, clearAction, requestFeedbackAction) searchAction.setActionsPanel(actionsPanel) // Create a new OnePixelSplitter instance to split the actions panel and the editor panel val horizontalSplitter = OnePixelSplitter(true, 0.0f) horizontalSplitter.setResizeEnabled(false) // Add the actions panel and the editor panel to the OnePixelSplitter horizontalSplitter.firstComponent = actionsPanel horizontalSplitter.secondComponent = editorPanel // Add the OnePixelSplitter to the content of the ToolWindow content.add(horizontalSplitter) } // This function returns the content of the ToolWindow, which is a JComponent fun getContent() : JComponent { return content } } }
copilot-toolwindow-plugin/src/main/kotlin/io/github/tomatsch87/ui/CopilotToolWindowFactory.kt
2415599570
package io.github.tomatsch87.ui import com.intellij.openapi.ui.DialogWrapper import com.intellij.ui.components.JBScrollPane import com.intellij.ui.components.JBTextArea import java.awt.BorderLayout import java.awt.event.FocusAdapter import java.awt.event.FocusEvent import javax.swing.* // Provides dialog for request feedback from the action bar feedback item class RequestFeedbackDialogWrapper(private val initMessage: String) : DialogWrapper(true) { private val feedbackField = JBTextArea(10, 25) init { title = "Provide Feedback" init() } override fun createCenterPanel(): JComponent { // Create a new panel with a border layout val panel = JPanel(BorderLayout()) // Create a form panel with a box layout val formPanel = JPanel() formPanel.layout = BoxLayout(formPanel, BoxLayout.Y_AXIS) formPanel.add(JLabel("Help us improve!"), BorderLayout.WEST) formPanel.add(JLabel("Please explain your motivation behind this request."), BorderLayout.WEST) formPanel.add(Box.createVerticalStrut(20), BorderLayout.WEST) val initialText = initMessage feedbackField.text = initialText feedbackField.addFocusListener(object : FocusAdapter() { override fun focusGained(e: FocusEvent) { if (feedbackField.text == "I wanted to find...") { feedbackField.text = "" } } override fun focusLost(e: FocusEvent) { if (feedbackField.text.isEmpty()) { feedbackField.text = initialText } } }) formPanel.add(JBScrollPane(feedbackField), BorderLayout.WEST) // Add the form panel to the center of the main panel panel.add(formPanel, BorderLayout.WEST) return panel } // Get feedback from the text field fun getFeedback(): String { return feedbackField.text } }
copilot-toolwindow-plugin/src/main/kotlin/io/github/tomatsch87/ui/RequestFeedbackDialogWrapper.kt
3373343613
package io.github.tomatsch87.actions import io.github.tomatsch87.services.AuthenticationService import io.github.tomatsch87.services.PluginSettings import com.google.gson.Gson import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import java.net.URI import java.net.http.HttpClient import java.net.http.HttpRequest import java.net.http.HttpResponse import javax.swing.JOptionPane // This is the action that is triggered when the user clicks on the star rating buttons in the tool window class ToolWindowResultFeedbackAction(private val panelNumber: Int, private val advancedFeedback: Int, private val searchAction: ToolWindowSearchAction) : AnAction() { override fun actionPerformed(event: AnActionEvent) { // Get the response instance from the ToolWindowSearchAction val responseInstance = searchAction.getResponseInstance() // Get the request instance from the ToolWindowSearchAction val requestInstance = searchAction.getRequestInstance() // If the response instance is empty, return if (responseInstance.results.isEmpty()) { return } if (PluginSettings.instance.state.accessToken == "") { AuthenticationService().loginUserNoPopup() if (PluginSettings.instance.state.accessToken == "") { JOptionPane.showMessageDialog( null, "Automatic login failed. Please login manually through the settings.", "Login required", JOptionPane.ERROR_MESSAGE ) return } } // Get the result from the response instance val result = responseInstance.results[panelNumber] // Create a map of the data to be sent val data = mapOf( "feedback" to mapOf( "result" to mapOf( "rank" to result.rank, "score" to result.score, "content" to mapOf( "code" to result.content.code, "language" to result.content.language, "contentType" to result.content.contentType, "repository" to result.content.repository, "repositoryUrl" to result.content.repositoryUrl, "filepath" to result.content.filepath, "filepathUrl" to result.content.filepathUrl, "codeBefore" to result.content.codeBefore, "codeAfter" to result.content.codeAfter, "startByte" to result.content.startByte, "startLine" to result.content.startLine, "endByte" to result.content.endByte, "endLine" to result.content.endLine, "contextStartLine" to result.content.contextStartLine, "contextEndLine" to result.content.contextEndLine ), ), "simple_feedback" to 0, "advanced_feedback" to advancedFeedback ), "request" to mapOf( "request_id" to responseInstance.requestId, "filepath" to requestInstance["filepath"], "indices" to requestInstance["indices"], "max_results" to requestInstance["max_results"], "position" to requestInstance["position"], "code" to requestInstance["code"] ) ) // convert data to json val json = Gson().toJson(data) println(json) val response : HttpResponse<String> try { // send data as post request val client = HttpClient.newHttpClient() val request = HttpRequest.newBuilder() .version(HttpClient.Version.HTTP_1_1) .uri(URI.create("${PluginSettings.instance.state.connectionUri}/search/feedback/result")) .header("accept", "application/json") .header("Authorization", "Bearer ${PluginSettings.instance.state.accessToken}") .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofString(json)) .build() // get response, if no response is found, return response = client.send(request, HttpResponse.BodyHandlers.ofString()) ?: return } catch (e: Exception) { AuthenticationService().logoutUser() return } println(response.body()) } }
copilot-toolwindow-plugin/src/main/kotlin/io/github/tomatsch87/actions/ToolWindowResultFeedbackAction.kt
1422645076
package io.github.tomatsch87.actions import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import java.awt.Toolkit import java.awt.datatransfer.StringSelection // This is the action that is triggered when the user clicks on the "Copy" button in the tool window class ToolWindowCopyAction(private val panelNumber: Int, private val searchAction: ToolWindowSearchAction) : AnAction() { override fun actionPerformed(event: AnActionEvent) { // Get the response instance from the ToolWindowSearchAction val responseInstance = searchAction.getResponseInstance() // If the response instance is empty, return if (responseInstance.results.isEmpty()) { return } // Get the result from the response instance val result = responseInstance.results[panelNumber] // Get the code from the result val code = result.content.code // Copy the code to the clipboard val selection = StringSelection(code) val clipboard = Toolkit.getDefaultToolkit().systemClipboard clipboard.setContents(selection, null) } }
copilot-toolwindow-plugin/src/main/kotlin/io/github/tomatsch87/actions/ToolWindowCopyAction.kt
385273268
package io.github.tomatsch87.actions import io.github.tomatsch87.domain.QueryResponse import io.github.tomatsch87.ui.ToolWindowEditorPanel import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent // This is the action that is triggered when the user clicks the "Clear" button in the tool window class ToolWindowClearAction(private val editorPanel: ToolWindowEditorPanel, private val searchAction: ToolWindowSearchAction) : AnAction() { override fun actionPerformed(e: AnActionEvent) { // Clear the text in the EditorTextFields of the ToolWindowEditorPanel editorPanel.clearEditorTextFields() // Clear the feedback panel editorPanel.resetAllFeedbackPanels() // Clear the response instance searchAction.setResponseInstance(QueryResponse()) } }
copilot-toolwindow-plugin/src/main/kotlin/io/github/tomatsch87/actions/ToolWindowClearAction.kt
507445367
package io.github.tomatsch87.actions import io.github.tomatsch87.domain.QueryResponse import io.github.tomatsch87.services.AuthenticationService import io.github.tomatsch87.services.PluginSettings import io.github.tomatsch87.ui.ToolWindowActionsPanel import io.github.tomatsch87.ui.ToolWindowEditorPanel import com.google.gson.Gson import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.psi.PsiDocumentManager import java.net.URI import java.net.http.HttpClient import java.net.http.HttpRequest import java.net.http.HttpResponse import javax.swing.JOptionPane // This is the action that is triggered when the user clicks on the "Search" button in the tool window class ToolWindowSearchAction : AnAction() { // Response and request instances are used to get a reference to search results from the tool window private var responseInstance: QueryResponse = QueryResponse() private var requestInstance = mapOf<String, Any?>() // The editor panel is used to update the editor text fields private var editorPanel: ToolWindowEditorPanel? = null // The actions panel is used to get the filters from the tool window private var actionsPanel: ToolWindowActionsPanel? = null override fun actionPerformed(event: AnActionEvent) { // Get the project context, if no project is found, return val project = event.project ?: return // Get the active editor from the project context, if no editor is found, return val fileEditorManager = FileEditorManager.getInstance(project) val editor = fileEditorManager.selectedTextEditor ?: return // Get the text from the editor val text = editor.document.text // Get the position of the caret val line = editor.caretModel.logicalPosition.line.plus(1) val column = editor.caretModel.logicalPosition.column.plus(1) // obtain the psiFile, if no psiFile is found, return val psiFile = PsiDocumentManager.getInstance(project).getPsiFile(editor.document) ?: return // obtain filepath from active editor file val filepath = psiFile.virtualFile.path if (PluginSettings.instance.state.accessToken == "") { AuthenticationService().loginUserNoPopup() if (PluginSettings.instance.state.accessToken == "") { JOptionPane.showMessageDialog( null, "Automatic login failed. Please login manually through the settings.", "Login required", JOptionPane.ERROR_MESSAGE ) return } } // create a map of the data to be sent val maxResults = 10 val data = mutableMapOf( "filepath" to filepath, "max_results" to maxResults, "position" to mapOf( "line" to line, "column" to column ), "code" to text, "filters" to null ) // get the filters from the tool window val filters = actionsPanel!!.getFilterText() if (filters[0].isNotBlank()) { data["filters"] = mapOf( "must" to listOf(mapOf("key" to "filepath", "match" to mapOf("text" to filters[0]))) ) } // Clear the feedback panel editorPanel?.resetAllFeedbackPanels() // store the request instance requestInstance = data // convert data to json val json = Gson().toJson(data) val response: HttpResponse<String> try { // send data as post request val client = HttpClient.newHttpClient() val request = HttpRequest.newBuilder() .version(HttpClient.Version.HTTP_1_1) .uri(URI.create("${PluginSettings.instance.state.connectionUri}/search")) .header("accept", "application/json") .header("Authorization", "Bearer ${PluginSettings.instance.state.accessToken}") .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofString(json)) .build() // get response, if no response is found, return response = client.send(request, HttpResponse.BodyHandlers.ofString()) ?: return } catch (e: Exception) { return } // parse the response responseInstance = Gson().fromJson(response.body(), QueryResponse::class.java) // create a list to store the results val results = mutableListOf<String>() // create a list to store file paths val filePaths = mutableListOf<String>() // Get number of lines number of the codeBefore and codeAfter parts val beforeLineNumber = mutableListOf<Int>() val afterLineNumber = mutableListOf<Int>() var tempNum: Int // add the results from each model from all languages to the results list responseInstance.results.forEach { results.add("${it.content.code}") beforeLineNumber.add(it.content.codeBefore) afterLineNumber.add(it.content.codeAfter) filePaths.add(it.content.filepath) } // update the editor text fields with the results editorPanel?.updateEditorTextFields(results, beforeLineNumber, afterLineNumber, filePaths) } // This function returns the request instance fun getRequestInstance(): Map<String, Any?> { return requestInstance } // This function returns the response instance fun getResponseInstance(): QueryResponse { return responseInstance } // This function sets the response instance fun setResponseInstance(response: QueryResponse) { responseInstance = response } // This function sets the editor panel fun setEditorPanel(editorPanel: ToolWindowEditorPanel) { this.editorPanel = editorPanel } // This function sets the actions panel fun setActionsPanel(actionsPanel: ToolWindowActionsPanel) { this.actionsPanel = actionsPanel } }
copilot-toolwindow-plugin/src/main/kotlin/io/github/tomatsch87/actions/ToolWindowSearchAction.kt
1227070032
package io.github.tomatsch87.actions import io.github.tomatsch87.services.AuthenticationService import io.github.tomatsch87.services.PluginSettings import io.github.tomatsch87.ui.RequestFeedbackDialogWrapper import com.google.gson.Gson import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import java.net.URI import java.net.http.HttpClient import java.net.http.HttpRequest import java.net.http.HttpResponse import javax.swing.JOptionPane // This is the action that is triggered when the user clicks on the "Feedback" button in the action bar class ToolWindowRequestFeedbackAction(private val searchAction: ToolWindowSearchAction) : AnAction() { override fun actionPerformed(event: AnActionEvent) { // Get the response instance from the ToolWindowSearchAction val responseInstance = searchAction.getResponseInstance() if (PluginSettings.instance.state.accessToken == "") { AuthenticationService().loginUserNoPopup() if (PluginSettings.instance.state.accessToken == "") { JOptionPane.showMessageDialog( null, "Automatic login failed. Please login manually through the settings.", "Login required", JOptionPane.ERROR_MESSAGE ) return } } // If the response instance is empty, return error if (responseInstance.results.isEmpty()) { JOptionPane.showMessageDialog( null, "Please search for code snippets first.", "Search request required", JOptionPane.ERROR_MESSAGE ) return } val feedbackMessage: String val getResponse : HttpResponse<String> try { // get feedback message from backend val client = HttpClient.newHttpClient() val getRequest = HttpRequest.newBuilder() .version(HttpClient.Version.HTTP_1_1) .uri(URI.create("${PluginSettings.instance.state.connectionUri}/search/requests/${responseInstance.requestId}/feedback")) .header("accept", "application/json") .header("Authorization", "Bearer ${PluginSettings.instance.state.accessToken}") .header("Content-Type", "application/json") .GET() .build() // get response, if no response is found, return getResponse = client.send(getRequest, HttpResponse.BodyHandlers.ofString()) ?: return } catch (e: Exception) { AuthenticationService().logoutUser() return } // convert response to json val getJson = Gson().fromJson(getResponse.body(), Map::class.java) val feedbackDialog: RequestFeedbackDialogWrapper = if (getJson["message"] == null) { RequestFeedbackDialogWrapper("I wanted to find...") } else { val initMessage = getJson["message"].toString() RequestFeedbackDialogWrapper(initMessage) } if (feedbackDialog.showAndGet()) { // Get the feedback message from the dialog feedbackMessage = feedbackDialog.getFeedback() } else { // If the user cancels the dialog, return return } // Create a map of the data to be sent val data : Map<String, Any> data = mapOf( "message" to feedbackMessage ) // convert data to json val json = Gson().toJson(data) println(json) val response : HttpResponse<String> if(getJson["message"] == null) { try { // send data as post request val client = HttpClient.newHttpClient() val request = HttpRequest.newBuilder() .version(HttpClient.Version.HTTP_1_1) .uri(URI.create("${PluginSettings.instance.state.connectionUri}/search/requests/${responseInstance.requestId}/feedback")) .header("accept", "application/json") .header("Authorization", "Bearer ${PluginSettings.instance.state.accessToken}") .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofString(json)) .build() // get response, if no response is found, return response = client.send(request, HttpResponse.BodyHandlers.ofString()) ?: return } catch (e: Exception) { AuthenticationService().logoutUser() return } println(response.body()) } else { try { // send data as put request val client = HttpClient.newHttpClient() val request = HttpRequest.newBuilder() .version(HttpClient.Version.HTTP_1_1) .uri(URI.create("${PluginSettings.instance.state.connectionUri}/search/requests/${responseInstance.requestId}/feedback")) .header("accept", "application/json") .header("Authorization", "Bearer ${PluginSettings.instance.state.accessToken}") .header("Content-Type", "application/json") .method("PATCH",HttpRequest.BodyPublishers.ofString(json)) .build() // get response, if no response is found, return response = client.send(request, HttpResponse.BodyHandlers.ofString()) ?: return } catch (e: Exception) { AuthenticationService().logoutUser() return } println(response.body()) } } }
copilot-toolwindow-plugin/src/main/kotlin/io/github/tomatsch87/actions/ToolWindowRequestFeedbackAction.kt
2996881610
package io.github.tomatsch87.actions import io.github.tomatsch87.ui.SettingsDialogWrapper import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent class SettingsAction : AnAction() { // This method is called when the action is triggered. override fun actionPerformed(e: AnActionEvent) { // Create a new instance of the SettingsDialogWrapper and display it to the user. SettingsDialogWrapper().showAndGet() } }
copilot-toolwindow-plugin/src/main/kotlin/io/github/tomatsch87/actions/SettingsAction.kt
3867218877
package io.github.tomatsch87.domain import com.google.gson.annotations.SerializedName // This data class is used to parse the response to the search query from the server data class QueryResponse( // The request id is used to identify the request @SerializedName("request_id") val requestId: String, // The models specified in the indices field of the request @SerializedName("results") val results: List<Results> ) { // Second constructor without parameters constructor() : this("", listOf<Results>()) // A results is a completion returned by the server data class Results( val rank: Int, val score: Double, val content: Content, val index: String ) // The content of a snippet data class Content( val code: String, val language: String, val contentType: Int, val repository: String, val repositoryUrl: String, val filepath: String, val filepathUrl: String, val codeBefore: Int, val codeAfter: Int, val startByte: Int?, val startLine: Int, val endByte: Int?, val endLine: Int, val contextStartLine: Int, val contextEndLine: Int ) }
copilot-toolwindow-plugin/src/main/kotlin/io/github/tomatsch87/domain/QueryResponse.kt
2822270985
package io.github.tomatsch87.domain import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.EditorFactory import com.intellij.openapi.editor.FoldRegion import com.intellij.openapi.editor.colors.EditorColorsManager import com.intellij.openapi.editor.ex.EditorEx import com.intellij.openapi.project.Project import com.intellij.openapi.fileTypes.FileType import com.intellij.ui.EditorTextField import com.intellij.openapi.editor.ex.FoldingListener import com.intellij.openapi.wm.ToolWindow // Class to define a custom editor text field for the toolWindow class ToolWindowEditor(private val toolWindow: ToolWindow, document: Document, project: Project, filetype: FileType) : EditorTextField(document, project, filetype) { // The editor instance private var editorInstance: EditorEx? = null // The folding model class MyFoldingListener(private val editorTextField: EditorTextField) : FoldingListener { override fun onFoldRegionStateChange(foldRegion: FoldRegion) { super.onFoldRegionStateChange(foldRegion) editorTextField.revalidate() editorTextField.repaint() } } // Customize the editor public override fun createEditor() : EditorEx { // Create a new editor val editor = super.createEditor() editorInstance = editor // Enable line numbers editor.settings.isLineNumbersShown = true // Enable folding outline editor.settings.isFoldingOutlineShown = true // Add a folding listener editor.foldingModel.addListener(MyFoldingListener(this), toolWindow.disposable) // Allow multiple lines this.isOneLineMode = false // Change font size to default font size from the IDE this.setFontInheritedFromLAF(false) // Set the editor to read-only this.isViewer = true // Set the editor to not focusable this.isFocusable = false // Add MouseWheelListener for font scaling editor.contentComponent.addMouseWheelListener { e -> if (e.isControlDown) { val fontSize = editor.colorsScheme.editorFontSize val direction = if (e.wheelRotation < 0) 1 else -1 val newFontSize = fontSize + direction if (newFontSize > 0) { editor.colorsScheme.editorFontSize = newFontSize } } else { editor.contentComponent.parent.dispatchEvent(e) } } return editor } // Function to reset the font size to the IDE's current setting fun resetFontSize() { editorInstance?.let { editor -> val globalFontSize = EditorColorsManager.getInstance().globalScheme.editorFontSize editor.colorsScheme.editorFontSize = globalFontSize } } // Dispose the editor fun dispose() { editorInstance?.let { EditorFactory.getInstance().releaseEditor(it) } editorInstance = null } }
copilot-toolwindow-plugin/src/main/kotlin/io/github/tomatsch87/domain/ToolWindowEditor.kt
22123101
package io.github.tomatsch87.services import io.github.tomatsch87.ui.ToolWindowActionsPanel import io.github.tomatsch87.ui.ToolWindowEditorPanel import io.github.tomatsch87.ui.ToolWindowFeedbackPanel import com.intellij.openapi.project.Project import com.intellij.openapi.startup.StartupActivity import com.intellij.openapi.ui.SimpleToolWindowPanel import com.intellij.openapi.wm.ToolWindowManager import com.intellij.ui.OnePixelSplitter import com.intellij.ui.components.JBScrollPane import java.awt.Component import java.awt.Container // This class is used to refresh the tool window when the project is opened class StartupToolWindow : StartupActivity { // This method is run when the project is opened override fun runActivity(project: Project) { // Log in user on startup AuthenticationService().loginUserNoPopup() // Get the tool window by its ID val toolWindowId = "Copilot Toolwindow" val toolWindowManager = ToolWindowManager.getInstance(project) val toolWindow = toolWindowManager.getToolWindow(toolWindowId) // Check if the tool window exists and is visible if (toolWindow != null && toolWindow.isVisible) { // Get the content of the tool window val contentManager = toolWindow.contentManager val content = contentManager.getContent(0) // Check if the content exists if (content != null) { // Get the component of the content val component = content.component // Check if the component is a SimpleToolWindowPanel if (component is SimpleToolWindowPanel) { // Get the content of the SimpleToolWindowPanel val contentComponent = component.getComponent(0) // Check if the content of the SimpleToolWindowPanel is a OnePixelSplitter if (contentComponent is OnePixelSplitter) { // Get the first component of the OnePixelSplitter val firstComponent = contentComponent.getComponent(1) // Check if the first component of the OnePixelSplitter is a ToolWindowActionsPanel if (firstComponent is ToolWindowActionsPanel) { // Refresh buttons of the ToolWindowActionsPanel firstComponent.refreshButtons() } // Get the second component of the OnePixelSplitter val secondComponent = contentComponent.getComponent(2) // Check if the second component of the OnePixelSplitter is a ToolWindowEditorPanel if (secondComponent is ToolWindowEditorPanel) { // Get the editor panel splitters of the ToolWindowEditorPanel val editorScrollPane = secondComponent.getComponent(0) if (editorScrollPane is JBScrollPane) { val vertSplitters = editorScrollPane.viewport.view // Create a list to store all components val componentsList = mutableListOf<Component>() // Check if the view is a container (such as JPanel, JComponent, etc.) if (vertSplitters is Container) { for (c in vertSplitters.components) { componentsList.add(c) } } componentsList.forEach { // Check if the editor panel splitter is a OnePixelSplitter if (it is OnePixelSplitter) { // Get the second component of the editor panel splitter val editorSecondComponent = it.getComponent(2) // Check if the second component of the editor panel splitter is a ToolWindowFeedbackPanel if (editorSecondComponent is ToolWindowFeedbackPanel) { // Refresh the buttons of the ToolWindowFeedbackPanel editorSecondComponent.refreshButtons() } } } } } } } } } } }
copilot-toolwindow-plugin/src/main/kotlin/io/github/tomatsch87/services/StartupToolWindow.kt
886333427
package io.github.tomatsch87.services import com.intellij.credentialStore.CredentialAttributes import com.intellij.ide.passwordSafe.PasswordSafe import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.* /** * This class is used to store and retrieve the settings for the Copilot Toolwindow Intellij-Plugin. * It is a PersistentStateComponent implementation storing the application settings in a persistent way. * * The {@link State} and {@link Storage} annotations define the name of the data and the file name where * these persistent application settings are stored. */ @State( name = "io.github.tomatsch87.services.PluginSettings", storages = [Storage("copilotToolwindowSettings.xml", roamingType = RoamingType.DISABLED)] ) class PluginSettings : PersistentStateComponent<PluginSettings.PluginState>{ private var currentPluginState = PluginState() data class PluginState(var userEmail: String = "", var connectionUri: String = "", var firstName: String = "", var lastName: String = "" , var passwordCredentialAttributes: CredentialAttributes = CredentialAttributes("io.github.tomatsch87.services.PluginSettings", userEmail) , var accessToken: String = "" ) { // This method is used to get the password from the password safe fun getPasswordFromSafe(): String { return PasswordSafe.instance.getPassword(passwordCredentialAttributes) ?: "" } // This method is used to store the password in the password safe fun setPasswordToSafe(password: String) { return PasswordSafe.instance.setPassword(passwordCredentialAttributes, password) } } // Called by IDEA to get the current state of this service, so that it can be saved to persistence override fun getState(): PluginState { return currentPluginState } // Called by IDEA when new component state is loaded override fun loadState(state: PluginState) { currentPluginState = state } companion object { // This companion object is used to get a reference to the single instance of this service. val instance: PluginSettings get() = ApplicationManager.getApplication().getService(PluginSettings::class.java) } }
copilot-toolwindow-plugin/src/main/kotlin/io/github/tomatsch87/services/PluginSettings.kt
2517241789
package io.github.tomatsch87.services import io.github.tomatsch87.ui.ToolWindowActionsPanel import com.google.gson.Gson import java.net.URI import java.net.URLEncoder import java.net.http.HttpClient import java.net.http.HttpRequest import java.net.http.HttpResponse import javax.swing.JOptionPane // Provides authentication service to register/login the user with the API class AuthenticationService { // Register the user with the API fun registerUser() { val state = PluginSettings.instance.state val data = mapOf( "email" to state.userEmail, "password" to state.getPasswordFromSafe(), "is_active" to true, "name" to "${state.firstName} ${state.lastName}" ) // convert data to json val json = Gson().toJson(data) // send data as post request val client = HttpClient.newHttpClient() val request = HttpRequest.newBuilder() .version(HttpClient.Version.HTTP_1_1) .uri(URI.create("${PluginSettings.instance.state.connectionUri}/auth/register")) .header("accept", "application/json") .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofString(json)) .build() // get response, if no response is found, return val response = client.send(request, HttpResponse.BodyHandlers.ofString()) ?: return // if response status code is not 201, show error message and return if (response.statusCode() != 201) { JOptionPane.showMessageDialog( null, "Registration failed ${response.statusCode()}: ${response.body()}", "Registration failed", JOptionPane.ERROR_MESSAGE ) } else { JOptionPane.showMessageDialog( null, "Registration successful", "Registration successful", JOptionPane.INFORMATION_MESSAGE ) } } // Login the user with the API without showing any popup fun loginUserNoPopup() { val state = PluginSettings.instance.state val grantType = "" val username = state.userEmail val password = state.getPasswordFromSafe() val scope = "" val clientId = "" val clientSecret = "" val encodedUser = URLEncoder.encode(username, "UTF-8") val encodedPassword = URLEncoder.encode(password, "UTF-8") val data = "grant_type=$grantType&username=$encodedUser&password=$encodedPassword&scope=$scope&client_id=$clientId&client_secret=$clientSecret" val response: HttpResponse<String> try { // send data as post request val client = HttpClient.newHttpClient() val request = HttpRequest.newBuilder() .version(HttpClient.Version.HTTP_1_1) .uri(URI.create("${PluginSettings.instance.state.connectionUri}/auth/jwt/login")) .header("accept", "application/json") .header("Content-Type", "application/x-www-form-urlencoded") .POST(HttpRequest.BodyPublishers.ofString(data)) .build() // get response, if no response is found, return response = client.send(request, HttpResponse.BodyHandlers.ofString()) ?: return } catch (e: Exception) { PluginSettings.instance.state.accessToken = "" ToolWindowActionsPanel.updateLoginStatusPanel() return } if (response.statusCode() == 200) { // Parse the JSON response val gson = Gson() val json = gson.fromJson(response.body(), Map::class.java) // Get the access_token value from the parsed JSON PluginSettings.instance.state.accessToken = json["access_token"].toString() // Show status in the actions panel ToolWindowActionsPanel.updateLoginStatusPanel() } } // Login the user with the API fun loginUser() { val state = PluginSettings.instance.state val grantType = "" val username = state.userEmail val password = state.getPasswordFromSafe() val scope = "" val clientId = "" val clientSecret = "" val encodedUser = URLEncoder.encode(username, "UTF-8") val encodedPassword = URLEncoder.encode(password, "UTF-8") val data = "grant_type=$grantType&username=$encodedUser&password=$encodedPassword&scope=$scope&client_id=$clientId&client_secret=$clientSecret" val response: HttpResponse<String> try { // send data as post request val client = HttpClient.newHttpClient() val request = HttpRequest.newBuilder() .version(HttpClient.Version.HTTP_1_1) .uri(URI.create("${PluginSettings.instance.state.connectionUri}/auth/jwt/login")) .header("accept", "application/json") .header("Content-Type", "application/x-www-form-urlencoded") .POST(HttpRequest.BodyPublishers.ofString(data)) .build() // get response, if no response is found, return response = client.send(request, HttpResponse.BodyHandlers.ofString()) ?: return } catch (e: Exception) { PluginSettings.instance.state.accessToken = "" ToolWindowActionsPanel.updateLoginStatusPanel() JOptionPane.showMessageDialog( null, "Login failed, please check your network connection", "Login required", JOptionPane.ERROR_MESSAGE ) return } if (response.statusCode() == 200) { // Parse the JSON response val gson = Gson() val json = gson.fromJson(response.body(), Map::class.java) // Get the access_token value from the parsed JSON PluginSettings.instance.state.accessToken = json["access_token"].toString() // Show status in the actions panel ToolWindowActionsPanel.updateLoginStatusPanel() JOptionPane.showMessageDialog( null, "Successfully logged in", "Login", JOptionPane.INFORMATION_MESSAGE ) } else { JOptionPane.showMessageDialog( null, "Login failed with code: ${response.statusCode()} \n ${response.body()}", "Login required", JOptionPane.ERROR_MESSAGE ) } } // Logout the user from the API fun logoutUser() { if (PluginSettings.instance.state.accessToken == "") { return } // Reset the access token PluginSettings.instance.state.accessToken = "" // Show status in the actions panel ToolWindowActionsPanel.updateLoginStatusPanel() } }
copilot-toolwindow-plugin/src/main/kotlin/io/github/tomatsch87/services/AuthenticationService.kt
664069270
package com.example.Buscador_Vuelos.ui.screens.search import com.example.Buscador_Vuelos.model.Airport import com.example.Buscador_Vuelos.model.Favorite data class SearchUiState( val searchQuery: String = "", val selectedCode: String = "", val airportList: List<Airport> = emptyList(), val favoriteList: List<Favorite> = emptyList(), )
Buscador_Vuelos/app/src/main/java/com/example/Buscador_Vuelos/ui/screens/search/SearchUiState.kt
2628381337
package com.example.Buscador_Vuelos.ui.screens.search import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import com.example.Buscador_Vuelos.model.Airport import com.example.Buscador_Vuelos.model.Favorite import com.example.Buscador_Vuelos.ui.screens.flight_screen.FlightRow @Composable fun FavoriteResult( modifier: Modifier = Modifier, airportList: List<Airport>, favoriteList: List<Favorite>, onFavoriteClick: (String, String) -> Unit ) { LazyColumn( modifier = modifier .padding(8.dp) .fillMaxWidth() ) { items(favoriteList, key = { it.id }) { item -> val departAirport = airportList.first { airport -> airport.code == item.departureCode } val destinationAirport = airportList.first { airport -> airport.code == item.destinationCode } FlightRow( isFavorite = true, departureAirportCode = departAirport.code, departureAirportName = departAirport.name, destinationAirportCode = destinationAirport.code, destinationAirportName = destinationAirport.name, onFavoriteClick = onFavoriteClick ) } } }
Buscador_Vuelos/app/src/main/java/com/example/Buscador_Vuelos/ui/screens/search/FavoriteResult.kt
9386180
package com.example.Buscador_Vuelos.ui.screens.search import androidx.compose.runtime.toMutableStateList import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.viewModelScope import androidx.lifecycle.viewmodel.initializer import androidx.lifecycle.viewmodel.viewModelFactory import com.example.Buscador_Vuelos.FlightApplication import com.example.Buscador_Vuelos.data.FlightRepository import com.example.Buscador_Vuelos.data.UserPreferencesRepository import com.example.Buscador_Vuelos.model.Airport import com.example.Buscador_Vuelos.model.Favorite import kotlinx.coroutines.Job import kotlinx.coroutines.flow.* import kotlinx.coroutines.launch class SearchViewModel( val flightRepository: FlightRepository, private val userPreferencesRepository: UserPreferencesRepository ) : ViewModel() { private val _uiState = MutableStateFlow(SearchUiState()) val uiState = _uiState.asStateFlow() private var deletedRecord: Favorite? = null private var getAirportsJob: Job? = null // private var getFavoritesJob: Job? = null // Airports from the Airport Table private var airportList = mutableListOf<Airport>()// MutableState<List<Favorite>>(emptyList()) // Favorites from the Favorite Table private var favoriteList = mutableListOf<Favorite>()// MutableState<List<Favorite>>(emptyList()) // Tmp List used to // var flightList = mutableListOf<Flight>()// MutableState<List<Favorite>>(emptyList()) init { viewModelScope.launch { userPreferencesRepository.userPreferencesFlow.collect { // _uiState.value = uiState.value.copy( // searchQuery = it.searchValue, // ) processSearchQueryFlow(it.searchValue) } } } fun onQueryChange(query: String) { //job?.cancel() //job = viewModelScope.launch { // appRepository.saveSearchQuery(query) //} processSearchQueryFlow(query) } private fun processSearchQueryFlow(query: String) { _uiState.update { it.copy(searchQuery = query) } if (query.isEmpty()) { viewModelScope.launch { airportList = flightRepository.getAllAirports().toMutableStateList() favoriteList= flightRepository.getAllFavoritesFlights().toMutableStateList() _uiState.update { uiState.value.copy( airportList = airportList, favoriteList = favoriteList ) } } } else { getAirportsJob?.cancel() getAirportsJob = flightRepository.getAllAirportsFlow(query) // on each emission .onEach { result -> _uiState.update { uiState.value.copy( airportList = result, ) } }.launchIn(viewModelScope) } } fun updateQuery(searchQuery: String) { _uiState.update { currentState -> currentState.copy( searchQuery = searchQuery, ) } updatePreferenceSearchValue(searchQuery) } fun updateSelectedCode(selectedCode: String) { _uiState.update { currentState -> currentState.copy( selectedCode = selectedCode, ) } } fun removeDbFavorite(record: Favorite) { viewModelScope.launch { deletedRecord = record flightRepository.deleteFavoriteFlight(record) // Cheating, I am forcing a Recomposition // I should be using Flow but am not sure how to atm //val play = flightRepository.getAllFavoritesFlights() val xx = uiState.value.favoriteList.toMutableStateList() //val index = xx.indexOf(record) xx.remove(record) _uiState.update { uiState.value.copy( favoriteList = xx, ) } } } // fun restoreDbRecord() { // viewModelScope.launch { // notesRepository.insertNote(deletedNote ?: return@launch) // deletedNote = null // } // } // _uiState.update { // uiState.value.copy( // searchQuery = "" // ) // } fun updatePreferenceSearchValue(newValue: String) { viewModelScope.launch { userPreferencesRepository.updateUserPreferences(searchValue = newValue) } } // Notes: Question: At moment this is chuck of code is repeated in two files // in QueryViewModel and in DetailsViewModel. // what can I do/ place it so as not to have repeat code? I tried but I got a bunch of errors /** * Factory for BookshelfViewModel] that takes BookshelfRepository] as a dependency */ companion object { val Factory: ViewModelProvider.Factory = viewModelFactory { initializer { val application = (this[ViewModelProvider.AndroidViewModelFactory.APPLICATION_KEY] as FlightApplication) val flightRepository = application.container.flightRepository val preferencesRepository = application.userPreferencesRepository SearchViewModel( flightRepository = flightRepository, userPreferencesRepository = preferencesRepository ) } } } }
Buscador_Vuelos/app/src/main/java/com/example/Buscador_Vuelos/ui/screens/search/SearchViewModel.kt
3594119134
package com.example.Buscador_Vuelos.ui.screens.search import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.text.KeyboardActions import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.Text import androidx.compose.material.TextField import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalFocusManager import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.unit.dp @Composable fun SearchTextField( query: String, onQueryChange: (String) -> Unit ) { val focusManager = LocalFocusManager.current TextField( value = query, onValueChange = { onQueryChange(it) }, placeholder = { Text(text = "Search here") }, singleLine = true, maxLines = 1, keyboardOptions = KeyboardOptions( keyboardType = KeyboardType.Text, imeAction = ImeAction.Done ), keyboardActions = KeyboardActions( onDone = { focusManager.clearFocus() //viewModel.updateSearchResult(uiState.query) } ), modifier = Modifier .padding(top= 16.dp) .fillMaxWidth(), ) }
Buscador_Vuelos/app/src/main/java/com/example/Buscador_Vuelos/ui/screens/search/SearchTextField.kt
2082760154
package com.example.Buscador_Vuelos.ui.screens.search import androidx.compose.foundation.layout.Column import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.ui.Modifier import androidx.lifecycle.viewmodel.compose.viewModel import com.example.Buscador_Vuelos.NavigationDestination import com.example.Buscador_Vuelos.R import com.example.Buscador_Vuelos.model.Favorite object SearchDestination : NavigationDestination { override val route = "home" override val titleRes = R.string.app_name } @Composable fun SearchScreen( modifier: Modifier = Modifier, onSelectCode: (String) -> Unit ) { val viewModel: SearchViewModel = viewModel(factory = SearchViewModel.Factory) val uiState = viewModel.uiState.collectAsState().value Column( modifier = modifier) { SearchTextField( uiState.searchQuery, onQueryChange = { viewModel.updateQuery(it) viewModel.updateSelectedCode("") viewModel.onQueryChange(it) } ) if (uiState.searchQuery.isEmpty()) { val favoriteList = uiState.favoriteList val airportList = uiState.airportList if (favoriteList.isNotEmpty()){ FavoriteResult( airportList = airportList, favoriteList = favoriteList, onFavoriteClick = { departureCode: String, destinationCode: String -> val tmp = Favorite( id = favoriteList.filter { xxx -> (xxx.departureCode == departureCode && xxx.destinationCode == destinationCode) }.first().id, departureCode = departureCode, destinationCode = destinationCode, ) viewModel.removeDbFavorite(tmp) }, ) } else { Text(text = "No Favorites yet") } } else { val airports = uiState.airportList SearchResults( airports = airports, onSelectCode = onSelectCode ) } } }
Buscador_Vuelos/app/src/main/java/com/example/Buscador_Vuelos/ui/screens/search/SearchScreen.kt
1370744567
package com.example.Buscador_Vuelos.ui.screens.search import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material.Card import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import com.example.Buscador_Vuelos.model.Airport @Composable fun SearchResults( modifier: Modifier = Modifier, airports: List<Airport>, onSelectCode: (String) -> Unit, ) { LazyColumn( modifier = modifier .padding(8.dp) .fillMaxWidth() ) { items( items = airports ) { Card( elevation = 8.dp, modifier = Modifier .fillMaxWidth() .padding(4.dp) ) { AirportRow( code = it.code, name = it.name, onSelectCode = onSelectCode, modifier = Modifier.padding(horizontal = 8.dp, vertical = 8.dp) ) } } } } //@Preview //@Composable //fun XPreview() { // val mockData = MockData.airports // SearchResults( // airports = mockData, // onSelectCode = {}, // ) //}
Buscador_Vuelos/app/src/main/java/com/example/Buscador_Vuelos/ui/screens/search/SearchResults.kt
1810688315
package com.example.Buscador_Vuelos.ui.screens.search import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.* import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp @Composable fun AirportRow( modifier: Modifier = Modifier, //airport: Airport, //airport: Air, code: String, name: String, onSelectCode: (String) -> Unit = { }, ) { Row( verticalAlignment = Alignment.CenterVertically, modifier = modifier .clickable( onClick = { if (code != "") { onSelectCode(code) } }, ) ) { Spacer( modifier = Modifier.width(24.dp) ) Text( text = code, fontWeight = FontWeight.Bold ) Spacer(modifier = Modifier.width(16.dp)) Text( text = name, maxLines = 1, overflow = TextOverflow.Ellipsis ) } } //@Preview //@Composable //fun AirportRowPreview() { // AirportRow( // airport = Airport(1, "JFK", "John F. Kennedy International Airport", 1111), // onSelectCode = {}, // ) //} //
Buscador_Vuelos/app/src/main/java/com/example/Buscador_Vuelos/ui/screens/search/AirportRow.kt
1911293178
package com.example.Buscador_Vuelos.ui.screens.flight_screen import androidx.compose.runtime.* import androidx.lifecycle.* import androidx.lifecycle.viewmodel.initializer import androidx.lifecycle.viewmodel.viewModelFactory import com.example.Buscador_Vuelos.FlightApplication import com.example.Buscador_Vuelos.data.FlightRepository import com.example.Buscador_Vuelos.model.Favorite import kotlinx.coroutines.flow.* import kotlinx.coroutines.launch class FlightViewModel( savedStateHandle: SavedStateHandle, val flightRepository: FlightRepository ): ViewModel() { private val _uiState = MutableStateFlow(FlightsUiState()) val uiState: StateFlow<FlightsUiState> = _uiState private val airportCode: String = savedStateHandle[FlightScreenDestination.codeArg] ?: "" var flightAdded: Boolean by mutableStateOf(false) // private var getFlightsJob: Job? = null init { viewModelScope.launch { processFlightList(airportCode) } } private fun processFlightList(airportCode: String) { viewModelScope.launch { val ff = flightRepository.getAllFavoritesFlights().toMutableStateList() val aa = flightRepository.getAllAirports().toMutableStateList() val departureAirport = aa.first { it.code == airportCode } _uiState.update { uiState.value.copy( code = airportCode, favoriteList = ff, destinationList = aa, departureAirport = departureAirport, ) } } } fun addFavoriteFlight(departureCode: String, destinationCode: String) { viewModelScope.launch { val favorite: Favorite = flightRepository.getSingleFavorite(departureCode, destinationCode) if (favorite == null) { val tmp = Favorite( departureCode = departureCode, destinationCode = destinationCode, ) flightAdded = true flightRepository.insertFavoriteFlight(tmp) } else { flightAdded = false flightRepository.deleteFavoriteFlight(favorite) } // Cheating, I am forcing a Recomposition // I should be using Flow but am not sure how to atm val play = flightRepository.getAllFavoritesFlights() _uiState.update { uiState.value.copy( favoriteList = play, ) } } } // Notes: Question: At moment this is chuck of code is repeated in two files // in QueryViewModel and in DetailsViewModel. // what can I do/ place it so as not to have repeat code? I tried but I got a bunch of errors /** * Factory for BookshelfViewModel] that takes BookshelfRepository] as a dependency */ companion object { val Factory: ViewModelProvider.Factory = viewModelFactory { initializer { val application = (this[ViewModelProvider.AndroidViewModelFactory.APPLICATION_KEY] as FlightApplication) val flightRepository = application.container.flightRepository FlightViewModel( this.createSavedStateHandle(), flightRepository = flightRepository ) } } } }
Buscador_Vuelos/app/src/main/java/com/example/Buscador_Vuelos/ui/screens/flight_screen/FlightViewModel.kt
2920945980
package com.example.Buscador_Vuelos.ui.screens.flight_screen import com.example.Buscador_Vuelos.model.Airport import com.example.Buscador_Vuelos.model.Favorite data class FlightsUiState( val code: String = "", val favoriteList: List<Favorite> = emptyList(), val destinationList: List<Airport> = emptyList(), val departureAirport: Airport = Airport(), )
Buscador_Vuelos/app/src/main/java/com/example/Buscador_Vuelos/ui/screens/flight_screen/FlightsUiState.kt
1888780541
package com.example.Buscador_Vuelos.ui.screens.flight_screen import androidx.compose.foundation.layout.* import androidx.compose.material.* import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Favorite import androidx.compose.material.icons.outlined.FavoriteBorder import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.example.Buscador_Vuelos.data.MockData import com.example.Buscador_Vuelos.ui.screens.search.AirportRow @Composable fun FlightRow( modifier: Modifier = Modifier, isFavorite: Boolean, departureAirportCode: String, departureAirportName: String, destinationAirportCode: String, destinationAirportName: String, onFavoriteClick: (String, String) -> Unit, ) { Card( elevation = 8.dp, modifier = Modifier .fillMaxWidth() .padding(4.dp) ) { Row { Column( modifier = modifier.weight(10f) ) { Column { Text( text = "Depart", style = MaterialTheme.typography.overline, modifier = Modifier.padding(start = 32.dp) ) AirportRow(code = departureAirportCode, name = departureAirportName) Text( text = "Arrival", style = MaterialTheme.typography.overline, modifier = Modifier.padding(start = 32.dp) ) AirportRow(code = destinationAirportCode, name = destinationAirportName) } } IconButton( onClick = { onFavoriteClick(departureAirportCode, destinationAirportCode) }, modifier = Modifier.align(Alignment.CenterVertically) ) { Icon( imageVector = if (isFavorite) Icons.Filled.Favorite else Icons.Outlined.FavoriteBorder, tint = if (isFavorite) Color.Red else Color.LightGray, contentDescription = null ) } } } } @Preview @Composable fun FlightRowPreview() { val mock = MockData FlightRow( isFavorite = true, departureAirportCode = mock.airports[1].code, departureAirportName = mock.airports[1].name, destinationAirportCode = mock.airports[2].code, destinationAirportName = mock.airports[2].name, onFavoriteClick = { _: String, _:String ->} ) }
Buscador_Vuelos/app/src/main/java/com/example/Buscador_Vuelos/ui/screens/flight_screen/FlightRow.kt
2734207662
package com.example.Buscador_Vuelos.ui.screens.flight_screen import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.example.Buscador_Vuelos.data.MockData import com.example.Buscador_Vuelos.model.Airport import com.example.Buscador_Vuelos.model.Favorite @Composable fun FlightResults( modifier: Modifier = Modifier, departureAirport: Airport, destinationList: List<Airport>, favoriteList: List<Favorite>, onFavoriteClick: (String, String) -> Unit ) { Column { //Text(text = uiState.value.play) LazyColumn( modifier = modifier .padding(8.dp) .fillMaxWidth() ) { items(destinationList, key = { it.id }) { item -> val isFavorite = favoriteList.find { f -> f.departureCode == departureAirport.code && f.destinationCode == item.code } FlightRow( isFavorite = isFavorite != null, departureAirportCode = departureAirport.code, departureAirportName = departureAirport.name, destinationAirportCode = item.code, destinationAirportName = item.name, onFavoriteClick = onFavoriteClick ) } } } } @Preview @Composable fun FlightResultsPreview() { val mockData = MockData.airports FlightResults( departureAirport = mockData[0], destinationList = mockData, favoriteList = emptyList(), onFavoriteClick = { _: String, _: String -> } ) }
Buscador_Vuelos/app/src/main/java/com/example/Buscador_Vuelos/ui/screens/flight_screen/FlightResults.kt
27164188
package com.example.Buscador_Vuelos.ui.screens.flight_screen import android.widget.Toast import androidx.compose.foundation.layout.Column import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.ui.platform.LocalContext import androidx.lifecycle.viewmodel.compose.viewModel import com.example.Buscador_Vuelos.R import com.example.Buscador_Vuelos.NavigationDestination object FlightScreenDestination : NavigationDestination { override val route = "flight_screen" override val titleRes = R.string.app_name const val codeArg = "code" val routeWithArgs = "$route/{$codeArg}" } @Composable fun FlightScreen() { val viewModel: FlightViewModel = viewModel(factory = FlightViewModel.Factory) val uiState = viewModel.uiState.collectAsState() val context = LocalContext.current // val scope = rememberCoroutineScope() Column { FlightResults( departureAirport = uiState.value.departureAirport, destinationList = uiState.value.destinationList, favoriteList = uiState.value.favoriteList, onFavoriteClick = { s1: String, s2: String -> viewModel.addFavoriteFlight(s1, s2) if(viewModel.flightAdded){ Toast.makeText(context,"ADDED", Toast.LENGTH_SHORT).show() }else{ Toast.makeText(context,"DELETED", Toast.LENGTH_SHORT).show() } } ) } }
Buscador_Vuelos/app/src/main/java/com/example/Buscador_Vuelos/ui/screens/flight_screen/FlightScreen.kt
1517895264
package com.example.Buscador_Vuelos import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Shapes import androidx.compose.ui.unit.dp val Shapes = Shapes( small = RoundedCornerShape(4.dp), medium = RoundedCornerShape(4.dp), large = RoundedCornerShape(0.dp) )
Buscador_Vuelos/app/src/main/java/com/example/Buscador_Vuelos/ui/theme/Shape.kt
2204320177
package com.example.Buscador_Vuelos import androidx.compose.ui.graphics.Color val Purple200 = Color(0xFFBB86FC) val Purple500 = Color(0xFF6200EE) val Purple700 = Color(0xFF3700B3) val Teal200 = Color(0xFF03DAC5)
Buscador_Vuelos/app/src/main/java/com/example/Buscador_Vuelos/ui/theme/Color.kt
3952420605
package com.example.Buscador_Vuelos import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material.MaterialTheme import androidx.compose.material.darkColors import androidx.compose.material.lightColors import androidx.compose.runtime.Composable import com.example.Buscador_Vuelos.ui.theme.Typography private val DarkColorPalette = darkColors( primary = Purple200, primaryVariant = Purple700, secondary = Teal200 ) private val LightColorPalette = lightColors( primary = Purple500, primaryVariant = Purple700, secondary = Teal200 ) @Composable fun FlightSearchTheme(darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable () -> Unit) { val colors = if (darkTheme) { DarkColorPalette } else { LightColorPalette } MaterialTheme( colors = colors, typography = Typography, shapes = Shapes, content = content ) }
Buscador_Vuelos/app/src/main/java/com/example/Buscador_Vuelos/ui/theme/Theme.kt
991611790
package com.example.Buscador_Vuelos.ui.theme import androidx.compose.material.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp val Typography = Typography( body1 = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp ) )
Buscador_Vuelos/app/src/main/java/com/example/Buscador_Vuelos/ui/theme/Type.kt
3784200756
package com.example.Buscador_Vuelos import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material.MaterialTheme import androidx.compose.material.Surface import androidx.compose.ui.Modifier class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { FlightSearchTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colors.background ) { FlightSearchApp() } } } } }
Buscador_Vuelos/app/src/main/java/com/example/Buscador_Vuelos/MainActivity.kt
754828150
package com.example.Buscador_Vuelos.di import android.content.Context import com.example.Buscador_Vuelos.data.FlightDatabase import com.example.Buscador_Vuelos.data.FlightRepository import com.example.Buscador_Vuelos.data.OfflineFlightRepository /** * App container for Dependency injection. */ interface AppContainer { val flightRepository: FlightRepository } /** * [AppContainer] implementation that provides instance of [OfflineFlightRepository] */ class AppDataContainer(private val context: Context) : AppContainer { /** * Implementation for [FlightRepository] */ override val flightRepository: FlightRepository by lazy { OfflineFlightRepository(FlightDatabase.getDatabase(context).flightDao()) } }
Buscador_Vuelos/app/src/main/java/com/example/Buscador_Vuelos/di/AppContainer.kt
1071900120
package com.example.Buscador_Vuelos /** * Interface to describe the navigation destinations for the app */ interface NavigationDestination { /** * Unique name to define the path for a composable */ val route: String /** * String resource id to that contains title to be displayed for the screen. */ val titleRes: Int }
Buscador_Vuelos/app/src/main/java/com/example/Buscador_Vuelos/NavigationDestination.kt
3207250502
package com.example.Buscador_Vuelos import androidx.compose.foundation.layout.padding import androidx.compose.material.Scaffold import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.navigation.NavType import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.rememberNavController import androidx.navigation.navArgument import com.example.Buscador_Vuelos.ui.screens.flight_screen.FlightScreen import com.example.Buscador_Vuelos.ui.screens.flight_screen.FlightScreenDestination import com.example.Buscador_Vuelos.ui.screens.search.SearchDestination import com.example.Buscador_Vuelos.ui.screens.search.SearchScreen @Composable fun FlightSearchApp() { val navController = rememberNavController() Scaffold() { paddingValues -> NavHost( navController = navController, startDestination = SearchDestination.route, modifier = Modifier.padding(paddingValues) ) { composable(route = SearchDestination.route) { SearchScreen( modifier = Modifier, onSelectCode = { navController.navigate("${FlightScreenDestination.route}/${it}") } ) } composable( route = FlightScreenDestination.routeWithArgs, arguments = listOf(navArgument(FlightScreenDestination.codeArg) { type = NavType.StringType } ) ) { navBackStackEntry -> // Retrieve the passed argument //val code = // navBackStackEntry.arguments?.getString(FlightScreenDestination.codeArg) FlightScreen() } } } }
Buscador_Vuelos/app/src/main/java/com/example/Buscador_Vuelos/FlightSearchApp.kt
1806177151
package com.example.Buscador_Vuelos.model import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey @Entity(tableName = "favorite") data class Favorite( @PrimaryKey(autoGenerate = true) val id: Int = 0, @ColumnInfo("departure_code") val departureCode: String, @ColumnInfo(name = "destination_code") val destinationCode: String, )
Buscador_Vuelos/app/src/main/java/com/example/Buscador_Vuelos/model/Favorite.kt
263810444
package com.example.Buscador_Vuelos.model import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey @Entity(tableName = "airport") data class Airport( @PrimaryKey val id: Int = 0, @ColumnInfo("iata_code") val code: String = "", @ColumnInfo(name = "name") val name: String = "", //@ColumnInfo(name = "passengers") val passengers: Int = 0 ) //fun Airport.toAir(): Air = Air( // id = id, // code = code, // name = name, //)
Buscador_Vuelos/app/src/main/java/com/example/Buscador_Vuelos/model/Airport.kt
871786476
package com.example.Buscador_Vuelos.data import com.example.Buscador_Vuelos.model.Airport import com.example.Buscador_Vuelos.model.Favorite import kotlinx.coroutines.flow.Flow interface FlightRepository { fun getAllAirportsFlow(): Flow<List<Airport>> fun getAllAirportsFlow(query: String): Flow<List<Airport>> fun getAirportByCodeFlow(code: String): Flow<Airport> suspend fun getAllAirports(): List<Airport> suspend fun getAllAirports(query: String): List<Airport> suspend fun getAirportByCode(code: String): Airport suspend fun getAirportById(id: Int): Airport fun getAllFavoritesFlightsFlow(): Flow<List<Favorite>> suspend fun getAllFavoritesFlights(): List<Favorite> suspend fun insertFavoriteFlight(flight: Favorite) suspend fun deleteFavoriteFlight(flight: Favorite) suspend fun getSingleFavorite(departureCode: String, destinationCode: String): Favorite }
Buscador_Vuelos/app/src/main/java/com/example/Buscador_Vuelos/data/FlightRepository.kt
2542284062
package com.example.Buscador_Vuelos.data import android.content.Context import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase import com.example.Buscador_Vuelos.FlightDao import com.example.Buscador_Vuelos.model.Airport import com.example.Buscador_Vuelos.model.Favorite @Database(entities = [Airport::class, Favorite::class], version = 1, exportSchema = false) abstract class FlightDatabase: RoomDatabase() { abstract fun flightDao(): FlightDao companion object { @Volatile private var Instance: FlightDatabase? = null fun getDatabase(context: Context): FlightDatabase { // if the Instance is not null, return it, otherwise create a new database instance. return Instance ?: synchronized(this) { Room.databaseBuilder( context, FlightDatabase::class.java, "flight_database" ) .createFromAsset("database/flight_search.db") /** * Setting this option in your app's database builder means that Room * permanently deletes all data from the tables in your database when it * attempts to perform a migration with no defined migration path. */ .fallbackToDestructiveMigration() .build() .also { Instance = it } } } } }
Buscador_Vuelos/app/src/main/java/com/example/Buscador_Vuelos/data/FlightDatabase.kt
1536099269
package com.example.Buscador_Vuelos.data import com.example.Buscador_Vuelos.FlightDao import com.example.Buscador_Vuelos.model.Airport import com.example.Buscador_Vuelos.model.Favorite import kotlinx.coroutines.flow.Flow class OfflineFlightRepository(private val airportDao: FlightDao) : FlightRepository { override fun getAllAirportsFlow(): Flow<List<Airport>> { return airportDao.getAllAirportsFlow() } override fun getAllAirportsFlow(query: String): Flow<List<Airport>> { return airportDao.getAllAirportsFlow(query) } override fun getAirportByCodeFlow(code: String): Flow<Airport> { return airportDao.getAirportByCodeFlow(code) } override suspend fun getAllAirports(): List<Airport> { return airportDao.getAllAirports() } override suspend fun getAllAirports(query: String): List<Airport> { return airportDao.getAllAirports(query) } override suspend fun getAirportByCode(code: String): Airport { return airportDao.getAirportByCode(code) } override suspend fun getAirportById(id: Int): Airport { return airportDao.getAirportById(id) } override fun getAllFavoritesFlightsFlow(): Flow<List<Favorite>> { return airportDao.getAllFavoritesFlow() } override suspend fun getAllFavoritesFlights(): List<Favorite> { return airportDao.getAllFavorites() } override suspend fun deleteFavoriteFlight(flight: Favorite) { return airportDao.deleteFavoriteFlight(flight) } override suspend fun getSingleFavorite(departureCode: String, destinationCode: String): Favorite { return airportDao.getSingleFavorite(departureCode, destinationCode) } override suspend fun insertFavoriteFlight(flight: Favorite) = airportDao.insertFavoriteFlight(flight) }
Buscador_Vuelos/app/src/main/java/com/example/Buscador_Vuelos/data/OfflineFlightRepository.kt
4290931978
package com.example.Buscador_Vuelos.data import androidx.datastore.core.DataStore import androidx.datastore.preferences.core.* import com.example.Buscador_Vuelos.data.UserPreferencesKeys.SEARCH_VALUE import kotlinx.coroutines.flow.* import java.io.IOException // Define your data class data class UserPreferences( val searchValue: String = "", ) // Define your preference keys object UserPreferencesKeys { val SEARCH_VALUE = stringPreferencesKey("search_value") } // Define a DataStore class to store and retrieve your data class UserPreferencesRepository(private val dataStore: DataStore<Preferences>) { // Update the user preferences suspend fun updateUserPreferences( searchValue: String, ) { dataStore.edit { preferences -> preferences[SEARCH_VALUE] = searchValue } } // Read the user preferences as a Flow val userPreferencesFlow: Flow<UserPreferences> = dataStore.data .catch { exception -> if (exception is IOException) { // Handle the exception } else { throw exception } } .map { preferences -> UserPreferences( searchValue = preferences[SEARCH_VALUE] ?: "", ) } }
Buscador_Vuelos/app/src/main/java/com/example/Buscador_Vuelos/data/UserPreferencesRepository.kt
3449550676
package com.example.Buscador_Vuelos import androidx.room.* import com.example.Buscador_Vuelos.model.Airport import com.example.Buscador_Vuelos.model.Favorite import kotlinx.coroutines.flow.Flow @Dao interface FlightDao { @Query( """ Select * from favorite ORDER BY id ASC """ ) //fun getAllAirports(): Flow<List<Airport>> suspend fun getAllFavorites(): List<Favorite> @Query( """ Select * from favorite ORDER BY id ASC """ ) fun getAllFavoritesFlow(): Flow<List<Favorite>> @Query( """ SELECT * FROM favorite WHERE departure_code = :departureCode AND destination_code = :destinationCode """ ) suspend fun getSingleFavorite(departureCode: String, destinationCode: String): Favorite //@Insert(onConflict = OnConflictStrategy.IGNORE) @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insertFavoriteFlight(flight: Favorite) @Delete suspend fun deleteFavoriteFlight(flight: Favorite) // Select * from airport // WHERE name LIKE :name // ORDER BY name ASC @Query( """ Select * from airport ORDER BY id ASC """ ) fun getAllAirportsFlow(): Flow<List<Airport>> @Query( """ Select * from airport ORDER BY id ASC """ ) //fun getAllAirports(): Flow<List<Airport>> suspend fun getAllAirports(): List<Airport> @Query( """ Select * from airport WHERE iata_code = :query OR name LIKE '%' || :query || '%' ORDER BY name ASC """ ) fun getAllAirportsFlow(query: String): Flow<List<Airport>> //"SELECT * from airport WHERE iata_code= :query OR name LIKE '%' || :query || '%' ") //WHERE name LIKE 'Fr%' @Query( """ Select * from airport WHERE iata_code = :query OR name LIKE '%' || :query || '%' ORDER BY name ASC """ ) //fun getAllAirports(query: String): Flow<List<Airport>> suspend fun getAllAirports(query: String): List<Airport> @Query( """ Select * from airport WHERE iata_code = :code """ ) //fun getAirportByCode(code: String): Flow<Airport> suspend fun getAirportByCode(code: String): Airport @Query( """ Select * from airport WHERE iata_code = :code """ ) fun getAirportByCodeFlow(code: String): Flow<Airport> @Query( """ Select * from airport WHERE id = :id """ ) //fun getAirportById(id: Int): Flow<Airport> suspend fun getAirportById(id: Int): Airport // //@Query("SELECT * FROM airport ORDER BY passengers DESC") //suspend fun getAirports(): List<Airport> // // @Query( // """ // Select * from airport // WHERE iata_code = :ito // ORDER BY name ASC // """ // ) // fun getAllFlights(ito: String): Flow<List<Airport>> //@Query("SELECT * FROM favorite") //fun getFavoriteFlightsStream(): Flow<List<FavoriteFlight>> //@Query("SELECT * FROM favorite WHERE id = :id") //suspend fun getFavoriteFlight(id: Int): FavoriteFlight? }
Buscador_Vuelos/app/src/main/java/com/example/Buscador_Vuelos/data/FlightDao.kt
2559283036
package com.example.Buscador_Vuelos.data import com.example.Buscador_Vuelos.model.Airport object MockData { val airports = listOf( Airport( id = 1, code = "OPO", name = "Francisco Sá Carne Airport", passengers = 5053134, ), Airport( id = 2, code = "SAA", name = "Stockholm land Airport", passengers = 7494765, ), Airport( id = 3, code = "WAW", name = "Warsaw Chopin Airport", passengers = 18860000, ), Airport( id = 4, code = "MRS", name = "Marseille Provence Airport", passengers = 10151743, ), Airport( id = 5, code = "BGY", name = "Milan Berg Airport", passengers = 3833063, ), ) }
Buscador_Vuelos/app/src/main/java/com/example/Buscador_Vuelos/data/MockData.kt
3523259949
package com.example.Buscador_Vuelos data class Flight( val id: Int = 0, val departureCode: String ="", val departureName: String="", val destinationCode: String="", val destinationName: String="", val isFavorite: Boolean=false )
Buscador_Vuelos/app/src/main/java/com/example/Buscador_Vuelos/data/Flight.kt
2154936283
package com.example.Buscador_Vuelos import android.app.Application import android.content.Context import androidx.datastore.core.DataStore import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.preferencesDataStore import com.example.Buscador_Vuelos.data.UserPreferencesRepository import com.example.Buscador_Vuelos.di.AppContainer import com.example.Buscador_Vuelos.di.AppDataContainer private const val LAYOUT_PREFERENCE_NAME = "layout_preferences" private val Context.dataStore: DataStore<Preferences> by preferencesDataStore( name = LAYOUT_PREFERENCE_NAME ) class FlightApplication : Application() { /** * AppContainer instance used by the rest of classes to obtain dependencies */ lateinit var container: AppContainer lateinit var userPreferencesRepository: UserPreferencesRepository override fun onCreate() { super.onCreate() container = AppDataContainer(this) userPreferencesRepository = UserPreferencesRepository(dataStore) } } // notes: code was done differently then the way we leannred in inventory codelab //class BusScheduleApplication: Application() { // val database: AppDatabase by lazy { AppDatabase.getDatabase(this) } //}
Buscador_Vuelos/app/src/main/java/com/example/Buscador_Vuelos/FlightApplication.kt
1396710038
package com.example.myapplication 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.myapplication", appContext.packageName) } }
boram5258/app/src/androidTest/java/com/example/myapplication/ExampleInstrumentedTest.kt
1188990709
package com.example.myapplication 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) } }
boram5258/app/src/test/java/com/example/myapplication/ExampleUnitTest.kt
2019423820
package com.example.myapplication.ui.theme import androidx.compose.ui.graphics.Color val Purple80 = Color(0xFFD0BCFF) val PurpleGrey80 = Color(0xFFCCC2DC) val Pink80 = Color(0xFFEFB8C8) val Purple40 = Color(0xFF6650a4) val PurpleGrey40 = Color(0xFF625b71) val Pink40 = Color(0xFF7D5260)
boram5258/app/src/main/java/com/example/myapplication/ui/theme/Color.kt
2513741509
package com.example.myapplication.ui.theme import android.app.Activity import android.os.Build import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import androidx.core.view.WindowCompat private val DarkColorScheme = darkColorScheme( primary = Purple80, secondary = PurpleGrey80, tertiary = Pink80 ) private val LightColorScheme = lightColorScheme( primary = Purple40, secondary = PurpleGrey40, tertiary = Pink40 /* Other default colors to override background = Color(0xFFFFFBFE), surface = Color(0xFFFFFBFE), onPrimary = Color.White, onSecondary = Color.White, onTertiary = Color.White, onBackground = Color(0xFF1C1B1F), onSurface = Color(0xFF1C1B1F), */ ) @Composable fun MyApplicationTheme( darkTheme: Boolean = isSystemInDarkTheme(), // Dynamic color is available on Android 12+ dynamicColor: Boolean = true, content: @Composable () -> Unit ) { val colorScheme = when { dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { val context = LocalContext.current if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) } darkTheme -> DarkColorScheme else -> LightColorScheme } val view = LocalView.current if (!view.isInEditMode) { SideEffect { val window = (view.context as Activity).window window.statusBarColor = colorScheme.primary.toArgb() WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme } } MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content ) }
boram5258/app/src/main/java/com/example/myapplication/ui/theme/Theme.kt
1455779958
package com.example.myapplication.ui.theme import androidx.compose.material3.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp // Set of Material typography styles to start with val Typography = Typography( bodyLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp, lineHeight = 24.sp, letterSpacing = 0.5.sp ) /* Other default text styles to override titleLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 22.sp, lineHeight = 28.sp, letterSpacing = 0.sp ), labelSmall = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Medium, fontSize = 11.sp, lineHeight = 16.sp, letterSpacing = 0.5.sp ) */ )
boram5258/app/src/main/java/com/example/myapplication/ui/theme/Type.kt
3144575447
package com.example.myapplication import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import com.example.myapplication.ui.theme.MyApplicationTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { MyApplicationTheme { // A surface container using the 'background' color from the theme Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) { Greeting("Android") } } } } } @Composable fun Greeting(name: String, modifier: Modifier = Modifier) { Text( text = "Hello $name!", modifier = modifier ) } @Preview(showBackground = true) @Composable fun GreetingPreview() { MyApplicationTheme { Greeting("Android") } }
boram5258/app/src/main/java/com/example/myapplication/MainActivity.kt
968789427
package ru.earn1ll.gamecubes 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("ru.earn1ll.gamecubes", appContext.packageName) } }
GameCubes/app/src/androidTest/java/ru/earn1ll/gamecubes/ExampleInstrumentedTest.kt
1603700185
package ru.earn1ll.gamecubes 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) } }
GameCubes/app/src/test/java/ru/earn1ll/gamecubes/ExampleUnitTest.kt
1732379326
package ru.earn1ll.gamecubes import androidx.appcompat.app.AppCompatActivity import android.os.Bundle class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } }
GameCubes/app/src/main/java/ru/earn1ll/gamecubes/MainActivity.kt
2273453469
package com.example.libreriaproject 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.libreriaproject", appContext.packageName) } }
LibreriaProjectAS/app/src/androidTest/java/com/example/libreriaproject/ExampleInstrumentedTest.kt
3809066642
package com.example.libreriaproject 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) } }
LibreriaProjectAS/app/src/test/java/com/example/libreriaproject/ExampleUnitTest.kt
1843576746
package com.example.libreriaproject import android.widget.Button import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.map class VinculadoViewModel : ViewModel() { private var new_item: Boolean = false private var _libros: MutableLiveData<MutableList<Libro>> = MutableLiveData(mutableListOf()) val libros: LiveData<MutableList<Libro>> get() = _libros private var _selected = MutableLiveData<Libro>(Libro("", "", "", "", false)) var selected = MutableLiveData<Libro>(Libro("", "", "", "", false)) val actionbutton: LiveData<String> = selected.map { libro -> when (libro.titulo) { "" -> "Nuevo Libro" else -> "Modificar" } } init { this._libros.value?.add( Libro( "Pocoyo", "Pepe", "350", "Inditex", true ) ) this._libros.value?.add( Libro( "El camino de los reyes", "Brandon Sanderson", "1200", "DeBolsillo", true ) ) this._libros.value?.add( Libro( "Alonso Leyenda", "Fernando Alonso", "333", "Alonsistas", true ) ) } private fun updateList() { var values = this._libros.value this._libros.value = values } private fun updateItem() { this._selected.value = this._selected.value?.copy() } fun settSelected(item: Libro) { this._selected.value = item this.selected.value = item.copy() this.new_item = false } fun settSelected(index: Int) { this._libros.value?.let { this._selected.value = it.get(index) this.selected.value = it.get(index).copy() this.new_item = false } } fun create_new() { this._selected.value = Libro("", "", "", "", false) this.selected.value = this._selected.value this.new_item = true } fun update() { if (new_item) { this.new_item = false this.selected.value?.let { this._libros.value?.add(it) this.updateList() } } else { this._selected.value?.let { it.activo = selected.value?.let { it.activo } ?: it.activo it.titulo = selected.value?.let { it.titulo } ?: it.titulo it.autor = selected.value?.let { it.autor } ?: it.autor it.paginas = selected.value?.let { it.paginas } ?: it.paginas it.editorial = selected.value?.let { it.editorial } ?: it.editorial this.updateList() this.updateItem() } } } fun remove(p: Libro) { if (!this.new_item) this._libros.value this._libros.value?.toMutableList().apply { remove(p) } } }
LibreriaProjectAS/app/src/main/java/com/example/libreriaproject/VinculadoViewModel.kt
3323739224
package com.example.libreriaproject import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.activity.viewModels import androidx.databinding.DataBindingUtil import androidx.lifecycle.Observer import androidx.recyclerview.widget.GridLayoutManager import com.example.libreriaproject.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding private val viewModel: VinculadoViewModel by viewModels() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = DataBindingUtil.setContentView(this, R.layout.activity_main) binding.lifecycleOwner = this setContentView(binding.root) binding.listado.layoutManager = GridLayoutManager(this, 2) binding.listado.adapter = viewModel.libros.value?.let { LibroRecyclerViewAdapter(it) } binding.delta = viewModel if (binding.listado.adapter is LibroRecyclerViewAdapter) { (binding.listado.adapter as LibroRecyclerViewAdapter).click = { position, persona -> run { this.viewModel.settSelected(persona) } } viewModel.libros.observe(this, Observer { listado -> binding.listado.adapter?.notifyDataSetChanged() }) } binding.actualizar.setOnClickListener() { this.viewModel.update() } binding.floatingActionButton.setOnClickListener{ this.viewModel.create_new() } } }
LibreriaProjectAS/app/src/main/java/com/example/libreriaproject/MainActivity.kt
2333850366
package com.example.libreriaproject data class Libro(var titulo:String, var autor:String, var paginas:String, var editorial:String, var activo:Boolean){}
LibreriaProjectAS/app/src/main/java/com/example/libreriaproject/Libro.kt
493019935
package com.example.libreriaproject import android.view.LayoutInflater import android.view.ViewGroup import android.widget.Button import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.example.libreriaproject.databinding.FragmentLibroitemBinding class LibroRecyclerViewAdapter( private val values: MutableList<Libro> ) : RecyclerView.Adapter<LibroRecyclerViewAdapter.ViewHolder>() { var click: ((Int, Libro) -> Unit)? = null override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { return ViewHolder( FragmentLibroitemBinding.inflate( LayoutInflater.from(parent.context), parent, false ) ) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val item = values[position] holder.idView.text = position.toString() holder.contentView.text = item.titulo holder.button.setOnClickListener { this.click?.let { it1 -> it1(position, values[position]) } } } override fun getItemCount(): Int = values.size inner class ViewHolder(binding: FragmentLibroitemBinding) : RecyclerView.ViewHolder(binding.root) { val idView: TextView = binding.itemNumber val contentView: TextView = binding.content var button: Button = binding.button override fun toString(): String { return super.toString() + " '" + contentView.text + "'" } } }
LibreriaProjectAS/app/src/main/java/com/example/libreriaproject/LibroRecyclerViewAdapter.kt
2490332982
import androidx.compose.ui.window.ComposeUIViewController fun MainViewController() = ComposeUIViewController { App() }
MyTask/composeApp/src/iosMain/kotlin/MainViewController.kt
4056994505
import platform.UIKit.UIDevice class IOSPlatform: Platform { override val name: String = UIDevice.currentDevice.systemName() + " " + UIDevice.currentDevice.systemVersion } actual fun getPlatform(): Platform = IOSPlatform()
MyTask/composeApp/src/iosMain/kotlin/Platform.ios.kt
110407275
import androidx.compose.foundation.background import androidx.compose.foundation.layout.* import androidx.compose.material.Icon import androidx.compose.material.IconButton import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Menu import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp import group.GroupViewBigLayout import group.GroupViewSmallLayout import group.createNewTaskGroup import org.jetbrains.compose.ui.tooling.preview.Preview import task.* @Composable @Preview fun App() { val taskGroups = remember { mutableStateListOf(createNewTaskGroup("Default")) } val selectedIndex = remember { mutableStateOf(0) } val showGroup = remember { mutableStateOf(false) } val detailTaskItem = remember { mutableStateOf(createNewTaskItem("")) } val isOpenDetail = remember { mutableStateOf(false) } if (selectedIndex.value != -1) { showGroup.value = false } MaterialTheme { BoxWithConstraints(Modifier.fillMaxWidth()) { val isLarge = maxWidth >= 600.dp Row { if (isLarge) { Box(modifier = Modifier.weight(4F)) { GroupViewBigLayout(taskGroups, selectedIndex) } } Column( modifier = Modifier.weight(7F) ) { if (isOpenDetail.value) { TaskDetail( taskItem = detailTaskItem.value, isOpenDetail = isOpenDetail, onDeleteItem = { taskGroups[selectedIndex.value].items.remove(detailTaskItem.value) } ) } else { if (!isLarge) { Row(verticalAlignment = Alignment.CenterVertically) { IconButton( onClick = { showGroup.value = true }, content = { Icon( imageVector = Icons.Default.Menu, contentDescription = "Open group" ) } ) Text( text = taskGroups[selectedIndex.value].title, maxLines = 1 ) } } Box(modifier = Modifier.weight(1F)) { TaskList( taskGroups[selectedIndex.value].items, onItemClick = { taskItem -> detailTaskItem.value = taskItem isOpenDetail.value = true } ) } AddTask { title -> taskGroups[selectedIndex.value].items.add(createNewTaskItem(title)) } } } } } } MaterialTheme { if (showGroup.value) { Box( modifier = Modifier .background(Color.White) .fillMaxWidth() .padding(16.dp) ) { GroupViewSmallLayout( taskGroups = taskGroups, selectedIndex = selectedIndex, onClose = { showGroup.value = false } ) } } } }
MyTask/composeApp/src/commonMain/kotlin/App.kt
2532070696
interface Platform { val name: String } expect fun getPlatform(): Platform
MyTask/composeApp/src/commonMain/kotlin/Platform.kt
960794953
import androidx.compose.ui.Modifier import androidx.compose.ui.input.key.Key import androidx.compose.ui.input.key.KeyEventType import androidx.compose.ui.input.key.key import androidx.compose.ui.input.key.onKeyEvent import androidx.compose.ui.input.key.type internal fun Modifier.onKeyUp(key: Key, action: () -> Unit): Modifier = onKeyEvent { event -> if ((event.type == KeyEventType.KeyUp) && (event.key == key)) { action() true } else { false } }
MyTask/composeApp/src/commonMain/kotlin/Utils.kt
3950429905
package group import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.material.Icon import androidx.compose.material.IconButton import androidx.compose.material.OutlinedTextField import androidx.compose.material.Text import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.AddCircle import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.input.key.Key import androidx.compose.ui.unit.dp import onKeyUp @Composable fun AddTaskGroup( onCreateGroup: (String) -> Unit ) { val input = remember { mutableStateOf("") } fun createGroup(title: String) { if (title == "") { return } onCreateGroup(title) input.value = "" } Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(16.dp) ) { OutlinedTextField( value = input.value, onValueChange = { input.value = it }, modifier = Modifier .weight(3F) .onKeyUp(Key.Enter, action = { createGroup(input.value) }), label = { Text("New Group") }, singleLine = true ) Spacer(modifier = Modifier.width(8.dp)) IconButton( enabled = input.value != "", modifier = Modifier.weight(1F), onClick = { createGroup(input.value) }, content = { Icon( imageVector = Icons.Default.AddCircle, contentDescription = "Create new task" ) } ) } }
MyTask/composeApp/src/commonMain/kotlin/group/AddTaskGroup.kt
678342898
package group import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.snapshots.SnapshotStateList import task.TaskItem import kotlin.random.Random data class TaskGroup( val id: Long, var title: String, val items: SnapshotStateList<TaskItem> ) fun createNewTaskGroup(title: String): TaskGroup { return TaskGroup(Random.nextLong(), title, mutableStateListOf()) }
MyTask/composeApp/src/commonMain/kotlin/group/TaskGroup.kt
3542180579
import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.material.* import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Delete import androidx.compose.material.icons.filled.Edit import androidx.compose.material.icons.filled.MoreVert import androidx.compose.runtime.Composable import androidx.compose.runtime.MutableState import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.snapshots.SnapshotStateList import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp import group.EditTaskGroup import group.TaskGroup @Composable fun TaskGroupList( taskGroups: SnapshotStateList<TaskGroup>, selectedIndex: MutableState<Int> ) { val listState = rememberLazyListState() LazyColumn(state = listState) { itemsIndexed(taskGroups) { index, taskGroup -> Column( modifier = Modifier .background( if(selectedIndex.value == index) { Color.Blue.copy(alpha = 0.2F) } else { Color.Transparent } ) .clickable { selectedIndex.value = index } ) { TaskGroupItem( taskGroup = taskGroup, onDeleteItem = { taskGroups.remove(taskGroup) } ) Divider() } } } } @Composable fun TaskGroupItem( taskGroup: TaskGroup, onDeleteItem: () -> Unit ) { val isExpnaded = remember { mutableStateOf(false) } val isOpenEdit = remember { mutableStateOf(false) } Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier.height(64.dp) ) { Text( text = taskGroup.title, modifier = Modifier.weight(1F).padding(horizontal = 8.dp) ) Spacer(modifier = Modifier.width(8.dp)) Box { IconButton( onClick = { isExpnaded.value = true }, content = { Icon( imageVector = Icons.Default.MoreVert, contentDescription = "Task more click" ) } ) DropdownMenu( expanded = isExpnaded.value, onDismissRequest = { isExpnaded.value = false }, content = { DeleteGroup { onDeleteItem() isExpnaded.value = false } EditGroup { isExpnaded.value = false isOpenEdit.value = true } } ) } } if (isOpenEdit.value) { EditTaskGroup( taskGroup = taskGroup, isOpenEdit = isOpenEdit ) } } @Composable fun DeleteGroup( onDeleteGroup: () -> Unit ) { DropdownMenuItem( onClick = onDeleteGroup, content = { Row(verticalAlignment = Alignment.CenterVertically) { Icon( imageVector = Icons.Default.Delete, contentDescription = "Delete task" ) Spacer(modifier = Modifier.width(8.dp)) Text("Delete") } } ) } @Composable fun EditGroup( onDialogEditGroup: () -> Unit ) { DropdownMenuItem( onClick = onDialogEditGroup, content = { Row(verticalAlignment = Alignment.CenterVertically) { Icon( imageVector = Icons.Default.Edit, contentDescription = "Edit title" ) Spacer(modifier = Modifier.width(8.dp)) Text("Edit") } } ) }
MyTask/composeApp/src/commonMain/kotlin/group/TaskGroupList.kt
423707172
package group import androidx.compose.material.* import androidx.compose.runtime.* import androidx.compose.ui.Modifier import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.input.key.Key import androidx.compose.ui.text.TextRange import androidx.compose.ui.text.input.TextFieldValue import onKeyUp @Composable fun EditTaskGroup( taskGroup: TaskGroup, isOpenEdit: MutableState<Boolean> ) { fun editGroup(title: String) { taskGroup.title = title isOpenEdit.value = false } val focusRequester = remember { FocusRequester() } val originalTitle = taskGroup.title val input = remember { mutableStateOf( TextFieldValue( text = taskGroup.title, selection = TextRange(taskGroup.title.length) ) ) } LaunchedEffect(Unit) { focusRequester.requestFocus() } AlertDialog( title = { Text("Edit group") }, text = { OutlinedTextField( value = input.value, onValueChange = { input.value = it }, modifier = Modifier .focusRequester(focusRequester) .onKeyUp( Key.Enter, action = { editGroup(input.value.text) } ), label = { Text("$originalTitle ->") }, singleLine = true ) }, onDismissRequest = { isOpenEdit.value = false }, confirmButton = { TextButton( onClick = { editGroup(input.value.text) }, content = { Text("OK") } ) }, dismissButton = { TextButton( onClick = { isOpenEdit.value = false }, content = { Text("Cancel") } ) } ) }
MyTask/composeApp/src/commonMain/kotlin/group/EditTaskGroup.kt
3334228820
package group import androidx.compose.foundation.layout.* import androidx.compose.material.Divider import androidx.compose.runtime.Composable import androidx.compose.runtime.MutableState import androidx.compose.runtime.snapshots.SnapshotStateList import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import TaskGroupList import androidx.compose.material.Icon import androidx.compose.material.IconButton import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Close @Composable fun GroupViewBigLayout( taskGroups: SnapshotStateList<TaskGroup>, selectedIndex: MutableState<Int> ) { Row { Column( modifier = Modifier.weight(3.5F), horizontalAlignment = Alignment.CenterHorizontally ) { Box(modifier = Modifier.weight(1F)) { TaskGroupList( taskGroups = taskGroups, selectedIndex = selectedIndex ) } AddTaskGroup { title -> taskGroups.add(createNewTaskGroup(title)) } } Divider( modifier = Modifier .fillMaxHeight() .width(1.dp) ) } } @Composable fun GroupViewSmallLayout( taskGroups: SnapshotStateList<TaskGroup>, selectedIndex: MutableState<Int>, onClose: () -> Unit ) { Column( horizontalAlignment = Alignment.End ) { IconButton( onClick = onClose, content = { Icon( imageVector = Icons.Default.Close, contentDescription = "Close group" ) } ) Box(modifier = Modifier.weight(1F)) { TaskGroupList( taskGroups = taskGroups, selectedIndex = selectedIndex ) } AddTaskGroup { title -> taskGroups.add(createNewTaskGroup(title)) } } }
MyTask/composeApp/src/commonMain/kotlin/group/GroupView.kt
3687647734
package task import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.material.* import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Delete import androidx.compose.runtime.Composable import androidx.compose.runtime.snapshots.SnapshotStateList import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp @Composable fun TaskList( taskItems: SnapshotStateList<TaskItem>, onItemClick: (TaskItem) -> Unit ) { val listState = rememberLazyListState() LazyColumn(state = listState) { items(taskItems) { taskItem -> Column(modifier = Modifier.clickable { onItemClick(taskItem) }) { TaskListItem( taskItem = taskItem, onDeleteItem = { taskItems.remove(taskItem) } ) Divider() } } } } @Composable fun TaskListItem( taskItem: TaskItem, onDeleteItem: () -> Unit ) { Row(verticalAlignment = Alignment.CenterVertically) { Checkbox( checked = taskItem.isDone.value, onCheckedChange = { taskItem.isDone.value = !taskItem.isDone.value } ) Spacer(modifier = Modifier.width(8.dp)) Text( text = taskItem.title, modifier = Modifier.weight(1F) ) Spacer(modifier = Modifier.width(8.dp)) IconButton( onClick = onDeleteItem, content = { Icon( imageVector = Icons.Default.Delete, contentDescription = "Delete task", tint = Color.Red ) } ) } }
MyTask/composeApp/src/commonMain/kotlin/task/TaskList.kt
1753107237
package task import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.material.Icon import androidx.compose.material.IconButton import androidx.compose.material.OutlinedTextField import androidx.compose.material.Text import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.AddCircle import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.input.key.Key import androidx.compose.ui.unit.dp import onKeyUp @Composable fun AddTask( onCreateTask: (String) -> Unit ) { val input = remember { mutableStateOf("") } fun createTask(title: String) { if (title == "") { return } onCreateTask(title) input.value = "" } Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(16.dp) ) { OutlinedTextField( value = input.value, onValueChange = { input.value = it }, modifier = Modifier .weight(1F) .onKeyUp(Key.Enter, action = { createTask(input.value) }), label = { Text("Input") }, singleLine = true ) Spacer(modifier = Modifier.width(8.dp)) IconButton( enabled = input.value != "", onClick = { createTask(input.value) }, content = { Icon( imageVector = Icons.Default.AddCircle, contentDescription = "Create new task" ) } ) } }
MyTask/composeApp/src/commonMain/kotlin/task/AddTask.kt
3665956835
package task import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.material.* import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.KeyboardArrowLeft import androidx.compose.material.icons.filled.Delete import androidx.compose.material3.DatePicker import androidx.compose.material3.DatePickerDialog import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.rememberDatePickerState import androidx.compose.runtime.Composable import androidx.compose.runtime.MutableState import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.TextRange import androidx.compose.ui.text.input.TextFieldValue @Composable fun TaskDetail( taskItem: TaskItem, isOpenDetail: MutableState<Boolean>, onDeleteItem: () -> Unit ) { val showDatePicker = remember { mutableStateOf(false) } val title = remember { mutableStateOf( TextFieldValue( text = taskItem.title, selection = TextRange(taskItem.title.length) ) ) } val description = remember { mutableStateOf( TextFieldValue( text = taskItem.description, selection = TextRange(taskItem.description.length) ) ) } Column { Row(verticalAlignment = Alignment.CenterVertically) { IconButton( onClick = { isOpenDetail.value = false }, content = { Icon( imageVector = Icons.AutoMirrored.Filled.KeyboardArrowLeft, contentDescription = "Close detail" ) } ) Spacer(Modifier.weight(1F)) IconButton( onClick = { onDeleteItem() isOpenDetail.value = false }, content = { Icon( imageVector = Icons.Default.Delete, contentDescription = "Delete task", tint = Color.Red ) } ) } OutlinedTextField( value = title.value, onValueChange = { title.value = it taskItem.title = it.text }, modifier = Modifier.fillMaxWidth(), label = { Text("Title") }, singleLine = true ) Row(verticalAlignment = Alignment.CenterVertically) { Text("Due Date") Spacer(Modifier.weight(1F)) TextButton( onClick = { showDatePicker.value = true }, content = { if (taskItem.dueDate != null) { Text("${taskItem.dueDate}") } else { Text("Not setted") } } ) } OutlinedTextField( value = description.value, onValueChange = { description.value = it taskItem.description = it.text }, modifier = Modifier .fillMaxWidth() .weight(1F), label = { Text("Description") } ) } if (showDatePicker.value) { DueDatePicker(taskItem, showDatePicker) } } @OptIn(ExperimentalMaterial3Api::class) @Composable fun DueDatePicker( taskItem: TaskItem, showDatePicker: MutableState<Boolean> ) { val datePickerState = rememberDatePickerState() DatePickerDialog( content = { DatePicker(datePickerState) }, onDismissRequest = { datePickerState.selectedDateMillis = null showDatePicker.value = false }, confirmButton = { TextButton( onClick = { taskItem.dueDate = datePickerState.selectedDateMillis showDatePicker.value = false }, content = { Text("OK") } ) }, dismissButton = { TextButton( onClick = { datePickerState.selectedDateMillis = null showDatePicker.value = false }, content = { Text("Cancel") } ) } ) }
MyTask/composeApp/src/commonMain/kotlin/task/TaskDetail.kt
1035918070
package task import androidx.compose.runtime.MutableState import androidx.compose.runtime.mutableStateOf import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import kotlin.random.Random @Serializable data class TaskItem( @SerialName("id") val id: Long, @SerialName("title") var title: String, @SerialName("task_group") var group: String, var isDone: MutableState<Boolean>, @SerialName("description") var description: String, var dueDate: Long? ) fun createNewTaskItem(title: String): TaskItem { return TaskItem( id = Random.nextLong(), title = title, group = "default", description = "", isDone = mutableStateOf(false), dueDate = null ) }
MyTask/composeApp/src/commonMain/kotlin/task/TaskItem.kt
2976441613
package task import kotlinx.serialization.Serializable @Serializable data class TestItem( val id: Int, val title: String, val task_group: String, val created: String, val is_done: String, val description: String )
MyTask/composeApp/src/commonMain/kotlin/task/TestItem.kt
1065062718
import group.TaskGroup import io.ktor.client.* import io.ktor.client.call.* import io.ktor.client.plugins.* import io.ktor.client.request.* import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.IO import kotlinx.coroutines.launch import task.TaskItem import task.TestItem object TaskClient { private const val BASE_URL = "http://121.183.249.112:2194/task/" private val client: HttpClient = HttpClient { defaultRequest { url(BASE_URL) } } fun getTasks(group: String, onResult: (List<TaskItem>) -> Unit) { CoroutineScope(Dispatchers.IO).launch { try { val response = client.get("json/task/$group") val result = response.body<List<TestItem>>() for (item in result) { print(item.title) } // CoroutineScope(Dispatchers.Main).launch { // onResult() // } } catch (e: Exception) { e.printStackTrace() } } } fun createTask(task: String, group: TaskGroup) { CoroutineScope(Dispatchers.IO).launch { try { val response = client.get("createtask/${group.title}") } catch (e: Exception) { e.printStackTrace() } } } }
MyTask/composeApp/src/commonMain/kotlin/TaskClient.kt
110096236
class JVMPlatform: Platform { override val name: String = "Java ${System.getProperty("java.version")}" } actual fun getPlatform(): Platform = JVMPlatform()
MyTask/composeApp/src/desktopMain/kotlin/Platform.jvm.kt
1652497929
import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.unit.DpSize import androidx.compose.ui.unit.dp import androidx.compose.ui.window.Window import androidx.compose.ui.window.application import java.awt.Dimension fun main() = application { Window(onCloseRequest = ::exitApplication, title = "MyTask") { with (LocalDensity.current) { val minSize = DpSize(200.dp, 300.dp).toSize() val minWidth = minSize.width.toInt() val minHeight = minSize.height.toInt() window.minimumSize = Dimension(minWidth, minHeight) } App() } }
MyTask/composeApp/src/desktopMain/kotlin/main.kt
1649964463
package org.iamhabi.mytask import App import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.runtime.Composable import androidx.compose.ui.tooling.preview.Preview class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { App() } } } @Preview @Composable fun AppAndroidPreview() { App() }
MyTask/composeApp/src/androidMain/kotlin/org/iamhabi/mytask/MainActivity.kt
2109469187
import android.os.Build class AndroidPlatform : Platform { override val name: String = "Android ${Build.VERSION.SDK_INT}" } actual fun getPlatform(): Platform = AndroidPlatform()
MyTask/composeApp/src/androidMain/kotlin/Platform.android.kt
3472575554