content
stringlengths 0
13M
| path
stringlengths 4
263
| contentHash
stringlengths 1
10
|
---|---|---|
package com.example.farmaapp.fragment.onBoarding
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.navigation.fragment.findNavController
import com.example.farmaapp.R
import com.example.farmaapp.databinding.FragmentOnBoardingTwoBinding
class OnBoardingTwoFragment : Fragment() {
private var _binding: FragmentOnBoardingTwoBinding? = null
private val binding get() = _binding!!
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = FragmentOnBoardingTwoBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initializeAdapter()
}
private fun initializeAdapter() {
binding.button.setOnClickListener {
findNavController().navigate(R.id.action_onBoardingFragment_to_loginOrRegisterRedirectFragment)
}
}
} | Farma_app/app/src/main/java/com/example/farmaapp/fragment/onBoarding/OnBoardingTwoFragment.kt | 743736788 |
package com.example.farmaapp.model
import android.os.Parcel
import android.os.Parcelable
data class Hourly(
val is_day: List<Int>,
val relativehumidity_2m: List<Int>,
val temperature_2m: List<Double>,
val time: List<String>,
val weathercode: List<Int>
) : Parcelable {
constructor(parcel: Parcel) : this(
TODO("is_day"),
TODO("relativehumidity_2m"),
TODO("temperature_2m"),
parcel.createStringArrayList()!!,
TODO("weathercode")
) {
}
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeStringList(time)
}
override fun describeContents(): Int {
return 0
}
companion object CREATOR : Parcelable.Creator<Hourly> {
override fun createFromParcel(parcel: Parcel): Hourly {
return Hourly(parcel)
}
override fun newArray(size: Int): Array<Hourly?> {
return arrayOfNulls(size)
}
}
} | Farma_app/app/src/main/java/com/example/farmaapp/model/Hourly.kt | 2793275157 |
package com.example.farmaapp.model
data class HourlyUnits(
val is_day: String,
val relativehumidity_2m: String,
val temperature_2m: String,
val time: String,
val weathercode: String
) | Farma_app/app/src/main/java/com/example/farmaapp/model/HourlyUnits.kt | 1679661949 |
package com.example.farmaapp.model
data class CurrentWeather(
val is_day: Int,
val temperature: Double,
val time: String,
val weathercode: Int,
val winddirection: Double,
val windspeed: Double
) | Farma_app/app/src/main/java/com/example/farmaapp/model/CurrentWeather.kt | 2778027722 |
package com.example.farmaapp.model
data class WeatherCode_(
val weatherCode: String,
val weather_img: Int
)
| Farma_app/app/src/main/java/com/example/farmaapp/model/WeatherCode_.kt | 4060967137 |
package com.example.farmaapp.model
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import com.example.farmaapp.model.newsModels.Articles
@Entity(tableName = "newsData")
data class NewsDBModel(
@PrimaryKey @ColumnInfo(name = "weatherId") val weatherId: String,
val articles: Articles
)
| Farma_app/app/src/main/java/com/example/farmaapp/model/NewsDBModel.kt | 4144508260 |
package com.example.farmaapp.model.newsModels
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
@Parcelize
data class Concept(
val label: Label,
val location: Location,
val score: Int,
val type: String,
val uri: String
) : Parcelable | Farma_app/app/src/main/java/com/example/farmaapp/model/newsModels/Concept.kt | 1453357808 |
package com.example.farmaapp.model.newsModels
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
@Parcelize
data class Label(
val eng: String
) : Parcelable | Farma_app/app/src/main/java/com/example/farmaapp/model/newsModels/Label.kt | 2042279022 |
package com.example.farmaapp.model.newsModels
data class Articles(
val count: Int,
val page: Int,
val pages: Int,
val results: List<Result>,
val totalResults: Int
) | Farma_app/app/src/main/java/com/example/farmaapp/model/newsModels/Articles.kt | 1035273237 |
package com.example.farmaapp.model.newsModels
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
@Parcelize
data class Result(
val authors: List<Author>,
val body: String,
val categories: List<Category>,
val concepts: List<Concept>,
val dataType: String,
val date: String,
val dateTime: String,
val dateTimePub: String,
val eventUri: String,
val image: String,
val isDuplicate: Boolean,
val lang: String,
val relevance: Int,
val sentiment: Double,
val shares: Shares,
val sim: Double,
val source: Source,
val time: String,
val title: String,
val uri: String,
val url: String,
val wgt: Int
) : Parcelable | Farma_app/app/src/main/java/com/example/farmaapp/model/newsModels/Result.kt | 2990432812 |
package com.example.farmaapp.model.newsModels
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
@Parcelize
data class Location(
val country: Country,
val label: Label,
val type: String
) : Parcelable | Farma_app/app/src/main/java/com/example/farmaapp/model/newsModels/Location.kt | 4064587148 |
package com.example.farmaapp.model.newsModels
data class NewsModel(
val articles: Articles
) | Farma_app/app/src/main/java/com/example/farmaapp/model/newsModels/NewsModel.kt | 2422685553 |
package com.example.farmaapp.model.newsModels
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
@Parcelize
data class Country(
val label: Label,
val type: String
) : Parcelable | Farma_app/app/src/main/java/com/example/farmaapp/model/newsModels/Country.kt | 2480694315 |
package com.example.farmaapp.model.newsModels
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
@Parcelize
data class Shares(
val facebook: Int
) : Parcelable | Farma_app/app/src/main/java/com/example/farmaapp/model/newsModels/Shares.kt | 3488672545 |
package com.example.farmaapp.model.newsModels
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
@Parcelize
data class Source(
val dataType: String,
val title: String,
val uri: String
) : Parcelable | Farma_app/app/src/main/java/com/example/farmaapp/model/newsModels/Source.kt | 1200289699 |
package com.example.farmaapp.model.newsModels
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
@Parcelize
data class Category(
val label: String,
val uri: String,
val wgt: Int
) : Parcelable | Farma_app/app/src/main/java/com/example/farmaapp/model/newsModels/Category.kt | 2308217905 |
package com.example.farmaapp.model.newsModels
import android.os.Parcel
import android.os.Parcelable
data class EachDayHourly(
val is_day: Int,
val relativehumidity_2m: Int,
val temperature_2m: Double,
val time: String,
val weathercode: Int
) : Parcelable {
constructor(parcel: Parcel) : this(
parcel.readInt(),
parcel.readInt(),
parcel.readDouble(),
parcel.readString()!!,
parcel.readInt()
) {
}
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeInt(is_day)
parcel.writeInt(relativehumidity_2m)
parcel.writeDouble(temperature_2m)
parcel.writeString(time)
parcel.writeInt(weathercode)
}
override fun describeContents(): Int {
return 0
}
companion object CREATOR : Parcelable.Creator<EachDayHourly> {
override fun createFromParcel(parcel: Parcel): EachDayHourly {
return EachDayHourly(parcel)
}
override fun newArray(size: Int): Array<EachDayHourly?> {
return arrayOfNulls(size)
}
}
}
| Farma_app/app/src/main/java/com/example/farmaapp/model/newsModels/EachDayHourly.kt | 869430753 |
package com.example.farmaapp.model.newsModels
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
@Parcelize
data class Author(
val isAgency: Boolean,
val name: String,
val type: String,
val uri: String
) : Parcelable | Farma_app/app/src/main/java/com/example/farmaapp/model/newsModels/Author.kt | 2685515018 |
package com.example.farmaapp.model
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "weatherInfo")
data class WeatherDBModel(
@PrimaryKey @ColumnInfo(name = "weatherId") val weatherId: String,
val current_weather: CurrentWeather,
val elevation: Double,
val generationtime_ms: Double,
val hourly: Hourly,
val hourly_units: HourlyUnits,
val latitude: Double,
val longitude: Double,
val timezone: String,
val timezone_abbreviation: String,
val utc_offset_seconds: Int
) | Farma_app/app/src/main/java/com/example/farmaapp/model/WeatherDBModel.kt | 148134511 |
package com.example.farmaapp.model
import android.os.Parcel
import android.os.Parcelable
import androidx.room.Entity
data class WeatherModel(
val current_weather: CurrentWeather,
val elevation: Double,
val generationtime_ms: Double,
val hourly: Hourly,
val hourly_units: HourlyUnits,
val latitude: Double,
val longitude: Double,
val timezone: String,
val timezone_abbreviation: String,
val utc_offset_seconds: Int
) : Parcelable {
constructor(parcel: Parcel) : this(
TODO("current_weather"),
parcel.readDouble(),
parcel.readDouble(),
parcel.readParcelable(Hourly::class.java.classLoader)!!,
TODO("hourly_units"),
parcel.readDouble(),
parcel.readDouble(),
parcel.readString()!!,
parcel.readString()!!,
parcel.readInt()
) {
}
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeDouble(elevation)
parcel.writeDouble(generationtime_ms)
parcel.writeParcelable(hourly, flags)
parcel.writeDouble(latitude)
parcel.writeDouble(longitude)
parcel.writeString(timezone)
parcel.writeString(timezone_abbreviation)
parcel.writeInt(utc_offset_seconds)
}
override fun describeContents(): Int {
return 0
}
companion object CREATOR : Parcelable.Creator<WeatherModel> {
override fun createFromParcel(parcel: Parcel): WeatherModel {
return WeatherModel(parcel)
}
override fun newArray(size: Int): Array<WeatherModel?> {
return arrayOfNulls(size)
}
}
} | Farma_app/app/src/main/java/com/example/farmaapp/model/WeatherModel.kt | 2316941006 |
package com.example.farmaapp.api
import com.example.farmaapp.custom.Constants.WEATHER_END_POINT
import com.example.farmaapp.model.WeatherModel
import retrofit2.Response
import retrofit2.http.GET
import retrofit2.http.Query
interface RetroApi {
@GET(WEATHER_END_POINT)
suspend fun getHourlyWeatherData(
@Query("latitude") lat: Double,
@Query("longitude") lon: Double
): Response<WeatherModel>
@GET("forecast?latitude=52.52&longitude=13.41&daily=temperature_2m,is_day,relativehumidity_2m&windspeed_unit=ms&forecast_days=1")
suspend fun getDailyWeatherData(): Response<WeatherModel>
} | Farma_app/app/src/main/java/com/example/farmaapp/api/RetroApi.kt | 2894346679 |
package com.example.farmaapp.api
import androidx.room.Dao
import com.example.farmaapp.custom.Constants.NEWS_END_POINT
import com.example.farmaapp.model.newsModels.NewsModel
import retrofit2.Response
import retrofit2.http.GET
import retrofit2.http.Url
interface NewsApi {
@GET(NEWS_END_POINT)
suspend fun getNewsData(): Response<NewsModel>
} | Farma_app/app/src/main/java/com/example/farmaapp/api/NewsApi.kt | 1637399525 |
package com.example.farmaapp.modules
import com.example.farmaapp.api.NewsApi
import com.example.farmaapp.api.RetroApi
import com.example.farmaapp.custom.Constants.BASE_URL
import com.example.farmaapp.custom.Constants.NEWS_BASE_URL
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import javax.inject.Singleton
@InstallIn(SingletonComponent::class)
@Module
class NetworkModule {
@Singleton
@Provides
fun providesRetrofit(): Retrofit.Builder {
return Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
}
@Singleton
@Provides
fun providesWeatherAPI(retrofitBuilder: Retrofit.Builder): RetroApi {
return retrofitBuilder.baseUrl(BASE_URL)
.build().create(RetroApi::class.java)
}
@Singleton
@Provides
fun providesNewsAPI(retrofitBuilder: Retrofit.Builder): NewsApi {
return retrofitBuilder.baseUrl(NEWS_BASE_URL)
.build().create(NewsApi::class.java)
}
} | Farma_app/app/src/main/java/com/example/farmaapp/modules/NetworkModule.kt | 2388974332 |
package com.example.farmaapp.modules
import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.preferencesDataStore
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class DataStoreProvider @Inject constructor() {
private val Context.dataStore: DataStore<Preferences> by preferencesDataStore("settings")
private var instance: DataStore<Preferences>? = null
fun getDataStoreInstance(context: Context): DataStore<Preferences> {
instance = context.dataStore
return instance as DataStore<Preferences>
}
} | Farma_app/app/src/main/java/com/example/farmaapp/modules/DataStoreProvider.kt | 4154795436 |
package com.example.farmaapp.custom
object Constants {
const val BASE_URL = "https://api.open-meteo.com/v1/"
const val MARKET_RATE_WEB_URL = "https://vegetablemarketprice.com/"
const val MARKET_RATE_WEB_HIDE_CLASS_USING_ELEMENT_URL = "javascript:(function() { " +
"document.getElementsByClassName('container-fluid')[0].style.display='none';" +
"document.getElementsByClassName('col-sm-12')[0].style.display='none'; })() "
const val MARKET_RATE_WEB_HIDE_BY_ID_USING_ELEMENT_URL = "javascript:(function() { " +
"document.getElementById('copywriteSpanTagFooter').style.display='none';" +
"document.getElementById('versionOfAppSpan').style.display='none';})()"
const val WEATHER_END_POINT = "forecast?latitude=52.52&longitude=13.41&hourly=temperature_2m,relativehumidity_2m,weathercode,is_day¤t_weather=true"
const val NEWS_BASE_URL = "https://newsapi.ai/api/v1/article/"
const val NEWS_END_POINT = "getArticles?query=%7B%22%24query%22%3A%7B%22%24and%22%3A%5B%7B%22%24and%22%3A%5B%7B%22conceptUri%22%3A%22http%3A%2F%2Fen.wikipedia.org%2Fwiki%2FAgriculture%22%7D%2C%7B%22conceptUri%22%3A%22http%3A%2F%2Fen.wikipedia.org%2Fwiki%2FFarmer%22%7D%5D%7D%2C%7B%22lang%22%3A%22hin%22%7D%5D%7D%2C%22%24filter%22%3A%7B%22forceMaxDataTimeWindow%22%3A%2231%22%7D%7D&resultType=articles&articlesSortBy=date&articlesCount=100&articleBodyLen=-1&apiKey=b0424d12-dd6f-45c5-bdf4-cfa8420bf4c9"
const val BANNER_ONE_URL = "https://thefoodtech.com/wp-content/uploads/2022/02/La-biotecnologi%CC%81a-en-la-agricultura-828x548.jpg"
const val BANNER_TWO_URL = "https://www.fundacionaquae.org/wp-content/uploads/2021/04/agricultura-sostenible.jpg"
const val HOURLY_DATA_KEY = "today_weather"
const val LOCATION_KEY = "location"
const val NEWS_ARR = "newsArr"
const val NEWS_POSITION = "position"
const val EXIT = "exit"
const val WEATHER_DATABASE_NAME = "weatherInformation"
const val NEWS_DATABASE_NAME = "NewsInformation"
const val CHECK_INTERNET_TOAST_MSG = "Check your internet Connection and try again"
const val CHART_ANIMATION_DURATION = 1000L
const val NEWS_TABLE_INDEX = "02"
const val WEATHER_TABLE_INDEX = "1"
const val CHAR_PATTERN_OUT = "hh a"
const val CHAR_PATTERN_IN = "hh:mm"
const val FORECAST_ITEM_POSITION = "position"
const val FORECAST_ITEM_POSITION_ARR = "arr"
const val DATE_PATTER_OUT = "EEEE,dd MMM"
const val DATE_PATTER_IN = "yyyy/mm/dd"
const val NEWS_CHAR_PATTERN_OUT = "hh:mm a"
const val NEWS_CHAR_PATTERN_IN = "hh:mm"
const val LOCATION_REQUEST_CODE = 1001
const val PUNE_LON = 73.856255
const val PUNE_LATITUDE = 18.516726
const val UTC = "UTC"
const val T = "T"
const val MM = "MM"
const val COLON = ":"
const val HYPHEN = "-"
const val COMMA = ","
const val SPACE = " "
const val DAY_24 = 24
const val JANUARY = "January"
const val FEBRUARY = "February"
const val MARCH = "March"
const val APRIL = "April"
const val MAY = "May"
const val JUNE = "June"
const val JULY = "July"
const val AUGUST = "August"
const val SEPTEMBER = "September"
const val OCTOBER = "October"
const val NOVEMBER = "November"
const val DECEMBER = "December"
const val CLEAR_SKY = "Clear sky"
const val MAINLY_CLEAR = "Mainly clear"
const val PARTLY_CLOUDY = "Partly cloudy"
const val CLOUDY = "Cloudy"
const val FOG = "Fog"
const val DRIZZLE_LIGHT = "Drizzle: Light"
const val DRIZZLE_MODERATE = "Drizzle: moderate"
const val DRIZZLE_DENSE_INTENSITY = "Drizzle: dense intensity"
const val FREEZING_DRIZZLE_LIGHT = "Freezing Drizzle: Light"
const val FREEZING_DRIZZLE_DENSE_INTENSITY = "Freezing Drizzle: dense intensity"
const val RAIN_SLIGHT = "Rain: Slight"
const val RAIN_MODERATE = "Rain: moderate"
const val RAIN_HEAVY_INTENSITY = "Rain: heavy intensity"
const val FREEZING_RAIN_LIGHT = "Freezing Rain: Light"
const val FREEZING_RAIN_HEAVY_INTENSITY = "Freezing Rain: heavy intensity"
const val SNOW_FALL_SLIGHT = "Snow fall: Slight"
const val SNOW_FALL_MODERATE = "Snow fall: moderate"
const val SNOW_FALL_HEAVY_INTENSITY = "Snow fall: heavy intensity"
const val SNOW_GRAINS = "Snow grains"
const val RAIN_SHOWERS_SLIGHT = "Rain showers: Slight"
const val RAIN_SHOWERS_MODERATE = "Rain showers: moderate"
const val RAIN_SHOWERS_VIOLENT = "Rain showers: violent"
const val SNOW_SHOWERS_SLIGHT = "Snow showers slight"
const val SNOW_SHOWERS_HEAVY = "Snow showers heavy"
const val THUNDERSTORM_SLIGHT_OR_MODERATE = "Thunderstorm: Slight or moderate"
const val THUNDERSTORM_WITH_SLIGHT = "Thunderstorm with slight"
const val THUNDERSTORM_WITH_HEAVY_HAIL = "Thunderstorm with heavy hail"
} | Farma_app/app/src/main/java/com/example/farmaapp/custom/Constants.kt | 1001191296 |
package com.example.farmaapp
import android.app.Application
import dagger.hilt.android.HiltAndroidApp
@HiltAndroidApp
class FargmApplication : Application() {
} | Farma_app/app/src/main/java/com/example/farmaapp/FargmApplication.kt | 3143600519 |
package com.example.farmaapp.viewholder
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import com.example.farmaapp.databinding.NewsArticleItemBinding
class NewsViewHolder(val binding: NewsArticleItemBinding) : ViewHolder(binding.root) | Farma_app/app/src/main/java/com/example/farmaapp/viewholder/NewsViewHolder.kt | 1515084374 |
package com.example.farmaapp.viewholder
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import com.example.farmaapp.databinding.HourlyWeatherForecastItemBinding
class HourlyViewHolder(val binding: HourlyWeatherForecastItemBinding) : ViewHolder(binding.root) | Farma_app/app/src/main/java/com/example/farmaapp/viewholder/HourlyViewHolder.kt | 4264374342 |
package com.example.farmaapp.viewholder
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import com.example.farmaapp.databinding.EachDayForecastItemBinding
class EachDayForecastViewHolder(val binding: EachDayForecastItemBinding) : ViewHolder(binding.root) | Farma_app/app/src/main/java/com/example/farmaapp/viewholder/EachDayForecastViewHolder.kt | 1984517866 |
package com.example.farmaapp.viewholder
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import com.example.farmaapp.databinding.NextForecastItemBinding
class NextForecastViewHolder(val binding : NextForecastItemBinding) : ViewHolder(binding.root) | Farma_app/app/src/main/java/com/example/farmaapp/viewholder/NextForecastViewHolder.kt | 2787943111 |
package com.example.farmaapp.viewholder
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import com.example.farmaapp.databinding.WeatherItemBinding
class WeatherViewHolder(val binding : WeatherItemBinding) : ViewHolder(binding.root) | Farma_app/app/src/main/java/com/example/farmaapp/viewholder/WeatherViewHolder.kt | 2478801527 |
package com.example.farmaapp.interface_
interface IOnBackPressed {
fun onBackPressed() : Boolean
} | Farma_app/app/src/main/java/com/example/farmaapp/interface_/IOnBackPressed.kt | 1027991183 |
package com.example.mystudiesapp
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.mystudiesapp", appContext.packageName)
}
} | My-Studies-App/app/src/androidTest/java/com/example/mystudiesapp/ExampleInstrumentedTest.kt | 3882683626 |
package com.example.mystudiesapp
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)
}
} | My-Studies-App/app/src/test/java/com/example/mystudiesapp/ExampleUnitTest.kt | 3364697566 |
package com.example.mystudiesapp.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) | My-Studies-App/app/src/main/java/com/example/mystudiesapp/ui/theme/Color.kt | 1623384182 |
package com.example.mystudiesapp.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 MyStudiesAppTheme(
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
)
} | My-Studies-App/app/src/main/java/com/example/mystudiesapp/ui/theme/Theme.kt | 3693336651 |
package com.example.mystudiesapp.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
)
*/
) | My-Studies-App/app/src/main/java/com/example/mystudiesapp/ui/theme/Type.kt | 1403212801 |
package com.example.mystudiesapp
import android.content.Intent
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import com.example.mystudiesapp.databinding.ActivityMainBinding
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.ktx.auth
import com.google.firebase.ktx.Firebase
import com.example.mystudiesapp.LoginScreen
class MainActivity : ComponentActivity() {
private val auth: FirebaseAuth by lazy { Firebase.auth }
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Inflate the layout using View Binding
binding = ActivityMainBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
// Start the LoginScreen activity when the MainActivity is created
startActivity(Intent(this, LoginScreen::class.java))
finish() // Optional: Finish the MainActivity to prevent going back to it from the LoginScreen
}
}
| My-Studies-App/app/src/main/java/com/example/mystudiesapp/MainActivity.kt | 1607790144 |
package com.example.mystudiesapp
import android.os.Bundle
import android.view.View
import android.widget.EditText
import android.widget.RelativeLayout
import androidx.appcompat.app.AppCompatActivity
import com.example.mystudiesapp.databinding.ActivityLoginScreenBinding
class LoginForm : AppCompatActivity() {
private lateinit var loginScreenBinding: ActivityLoginScreenBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Inflate the parent layout used in LoginScreen.kt
loginScreenBinding = ActivityLoginScreenBinding.inflate(layoutInflater)
val view = loginScreenBinding.root
setContentView(view)
// Access views from the LoginScreen layout
val usernameEditText: EditText = loginScreenBinding.usernameEditText
val passwordEditText: EditText = loginScreenBinding.passwordEditText
// You can now use usernameEditText and passwordEditText as needed
// ...
// For example, set hint for username and password
usernameEditText.hint = "Username"
passwordEditText.hint = "Password"
}
}
| My-Studies-App/app/src/main/java/com/example/mystudiesapp/LoginForm.kt | 1790875675 |
package com.example.mystudiesapp
import android.content.Intent
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.mystudiesapp.LoginForm
class LoginScreen : ComponentActivity() {
// ...
@Composable
fun LoginContent() {
// ... existing code ...
Button(
onClick = {
startActivity(Intent(this@LoginScreen, LoginForm::class.java))
},
modifier = Modifier
.fillMaxWidth()
.height(50.dp)
) {
Text("Open Login Form", fontSize = 20.sp)
}
// ... existing code ...
}
}
| My-Studies-App/app/src/main/java/com/example/mystudiesapp/LoginScreen.kt | 1062834813 |
package com.example.jobsheet02
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.jobsheet02", appContext.packageName)
}
} | Jobsheet2_Praktikum_Pemograman_Bergerak/app/src/androidTest/java/com/example/jobsheet02/ExampleInstrumentedTest.kt | 1781109883 |
package com.example.jobsheet02
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)
}
} | Jobsheet2_Praktikum_Pemograman_Bergerak/app/src/test/java/com/example/jobsheet02/ExampleUnitTest.kt | 1493351157 |
package com.example.jobsheet02
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.helloword)
val nameEditText: EditText = findViewById(R.id.nameEditText)
val buttonButton: Button = findViewById(R.id.buttonButton)
val buttonTextView: TextView = findViewById(R.id.buttonTextView)
buttonTextView.text = resources.getString(R.string.app_name)
buttonButton.setOnClickListener{
val name = nameEditText.text.toString()
buttonTextView.text = resources.getString(R.string.buttonTextView, name)
resources.getStringArray(R.array.names).forEach {
Log.i ("PZN",it)
}
}
}
} | Jobsheet2_Praktikum_Pemograman_Bergerak/app/src/main/java/com/example/jobsheet02/MainActivity.kt | 940202272 |
package com.varabyte.kobweb.intellij.util.module
import com.intellij.openapi.module.Module
import com.intellij.psi.PsiElement
import org.jetbrains.plugins.gradle.util.GradleUtil
/**
* Given an IntelliJ module, return the associated module that represents the root of a Gradle project.
*
* Often, a module you fetch for a [PsiElement] is the one associated with a source directory, but what we often
* actually want is its parent module. That is, instead of the module "app.site.jsMain" we want "app.site".
*
* If found, the module returned will be home to a Gradle build file, and you can be confident it represents the
* root of a Gradle project.
*/
fun Module.toGradleModule(): Module? {
@Suppress("UnstableApiUsage") // "findGradleModuleData" has been experimental for 5 years...
return GradleUtil.findGradleModuleData(this)?.let { moduleDataNode ->
GradleUtil.findGradleModule(this.project, moduleDataNode.data)
}
}
| kobweb-intellij-plugin/plugin/src/main/kotlin/com/varabyte/kobweb/intellij/util/module/ModuleExtensions.kt | 3965671476 |
package com.varabyte.kobweb.intellij.util.kobweb
import com.intellij.ide.util.PropertiesComponent
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.varabyte.kobweb.intellij.model.KobwebProjectType
import com.varabyte.kobweb.intellij.project.KobwebProject
import com.varabyte.kobweb.intellij.util.kobweb.project.findKobwebProject
import org.jetbrains.kotlin.psi.KtFile
enum class KobwebPluginState {
/**
* The Kobweb plugin is disabled for this project.
*
* This essentially means the user has installed the Kobweb plugin, but it should not be active for this project,
* because there aren't any Kobweb modules inside of it.
*/
DISABLED,
/**
* Indicates we started enabling the Kobweb plugin for this project, but a full Gradle sync is required to finish.
*/
UNINITIALIZED,
/**
* The Kobweb plugin is enabled for this project.
*
* At this point, the project has been scanned, and we can query all found Kobweb metadata information.
*/
INITIALIZED,
}
private const val KOBWEB_PLUGIN_STATE_PROPERTY = "kobweb-plugin-state"
var Project.kobwebPluginState: KobwebPluginState
get() = PropertiesComponent.getInstance(this).getValue(KOBWEB_PLUGIN_STATE_PROPERTY, KobwebPluginState.DISABLED.name).let { KobwebPluginState.valueOf(it) }
set(value) = PropertiesComponent.getInstance(this).setValue(KOBWEB_PLUGIN_STATE_PROPERTY, value.name)
val Project.isKobwebPluginEnabled get() = this.kobwebPluginState == KobwebPluginState.INITIALIZED
/**
* A collection of useful sets of [KobwebProjectType]s.
*
* These can be useful to pass into the [isInReadableKobwebProject] and [isInWritableKobwebProject] extension methods.
*/
object KobwebProjectTypes {
/**
* The set of all Kobweb project types.
*/
val All = KobwebProjectType.entries.toSet()
/**
* The set of core Kobweb project types that affect the frontend DOM / backend API routes.
*/
val Framework = setOf(KobwebProjectType.Application, KobwebProjectType.Library)
val WorkerOnly = setOf(KobwebProjectType.Worker)
}
/**
* Returns true if this is code inside the Kobweb framework itself.
*
* The user can easily end up in here if they navigate into it from their own code, e.g. to see how something is
* implemented or to look around at the docs or other API methods.
*
* Not every extension point we implement for the Kobweb plugin should be enabled for the framework itself, but some
* should be, so this method is provided for the extension point implementor to decide how broad it should apply.
*/
fun PsiElement.isInKobwebSource(): Boolean {
return (this.containingFile as? KtFile)?.packageFqName?.asString()?.startsWith("com.varabyte.kobweb") ?: false
}
private fun PsiElement.isInKobwebProject(test: (KobwebProject) -> Boolean): Boolean {
this.findKobwebProject()?.let { return test(it) } ?: return false
}
/**
* Useful test to see if a read-only Kobweb Plugin action (like an inspection) should run here.
*
* @param limitTo The [KobwebProject] types to limit this action to. By default, restricted to presentation types (that
* is, the parts of Kobweb that interact with the DOM). This default was chosen because this is by far the most
* common case, the kind of code that most people associate with Kobweb.
*/
fun PsiElement.isInReadableKobwebProject(limitTo: Set<KobwebProjectType> = KobwebProjectTypes.Framework): Boolean {
return isInKobwebProject { it.type in limitTo }
}
/**
* Useful test to see if a writing Kobweb Plugin action (like a refactor) should be allowed to run here.
*
* @param limitTo See the docs for [isInReadableKobwebProject] for more info.
*/
fun PsiElement.isInWritableKobwebProject(limitTo: Set<KobwebProjectType> = KobwebProjectTypes.Framework): Boolean {
return isInKobwebProject { it.type in limitTo && it.source is KobwebProject.Source.Local }
}
| kobweb-intellij-plugin/plugin/src/main/kotlin/com/varabyte/kobweb/intellij/util/kobweb/KobwebUtils.kt | 3404711226 |
package com.varabyte.kobweb.intellij.util.kobweb.project
import com.intellij.openapi.components.service
import com.intellij.openapi.module.Module
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiElement
import com.varabyte.kobweb.intellij.model.KobwebProjectType
import com.varabyte.kobweb.intellij.project.KobwebProject
import com.varabyte.kobweb.intellij.project.findKobwebModel
import com.varabyte.kobweb.intellij.services.project.KobwebProjectCacheService
import com.varabyte.kobweb.intellij.util.kobweb.isKobwebPluginEnabled
import com.varabyte.kobweb.intellij.util.module.toGradleModule
import com.varabyte.kobweb.intellij.util.psi.containingKlib
import org.jetbrains.kotlin.idea.base.util.module
// Constants useful for identifying external artifacts as Kobweb projects
private const val KOBWEB_METADATA_ROOT = "META-INF/kobweb"
private val KOBWEB_METADATA_IDENTIFIERS_LIBRARY = listOf(
"$KOBWEB_METADATA_ROOT/library.json",
// Legacy ways to identify a library, before library.json was introduced
// We can remove these after a few months and/or when Kobweb hits 1.0
"$KOBWEB_METADATA_ROOT/frontend.json",
"$KOBWEB_METADATA_ROOT/backend.json",
)
private const val KOBWEB_METADATA_IDENTIFIER_WORKER = "$KOBWEB_METADATA_ROOT/worker.json"
private fun Module.findKobwebProject(kobwebProjectsCache: KobwebProjectCacheService): KobwebProject? {
val gradleModule = this.toGradleModule() ?: return null
kobwebProjectsCache[gradleModule]?.let { return it }
return gradleModule.findKobwebModel()?.let { kobwebModel ->
KobwebProject(
gradleModule.name,
kobwebModel.projectType,
KobwebProject.Source.Local(gradleModule)
).also {
kobwebProjectsCache.add(it)
}
}
}
private fun VirtualFile.findKobwebProject(kobwebProjectsCache: KobwebProjectCacheService): KobwebProject? {
require(this.extension == "klib")
val klib = this
kobwebProjectsCache[klib]?.let { return it }
val kobwebProjectType = when {
KOBWEB_METADATA_IDENTIFIERS_LIBRARY.any { this.findFileByRelativePath(it) != null } -> {
KobwebProjectType.Library
}
this.findFileByRelativePath(KOBWEB_METADATA_IDENTIFIER_WORKER) != null -> {
KobwebProjectType.Worker
}
else -> return null
}
return KobwebProject(
klib.name,
kobwebProjectType,
KobwebProject.Source.External(klib)
).also { kobwebProjectsCache.add(it) }
}
/**
* Returns the Kobweb project associated with the owning context of this element, or null if none is found.
*
* Kobweb project information can be associated with both local modules and third-party artifacts (e.g. maven
* dependencies).
*
* The result is cached for subsequent calls.
*/
fun PsiElement.findKobwebProject(): KobwebProject? {
if (!project.isKobwebPluginEnabled) return null
val kobwebProjectsCache = project.service<KobwebProjectCacheService>()
if (kobwebProjectsCache.isMarkedNotKobweb(this)) return null
val kobwebProject =
this.module?.findKobwebProject(kobwebProjectsCache)
?: this.containingKlib?.findKobwebProject(kobwebProjectsCache)
if (kobwebProject == null) kobwebProjectsCache.markNotKobweb(this)
return kobwebProject
}
| kobweb-intellij-plugin/plugin/src/main/kotlin/com/varabyte/kobweb/intellij/util/kobweb/project/KobwebProjectUtils.kt | 932252321 |
package com.varabyte.kobweb.intellij.util.log
import com.intellij.ide.plugins.PluginManager
import com.intellij.openapi.diagnostic.LogLevel
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.extensions.PluginId
import org.apache.log4j.Level
@Suppress("OVERRIDE_DEPRECATION", "UnstableApiUsage")
private class DisabledLogger : Logger() {
override fun isDebugEnabled(): Boolean = false
override fun debug(message: String, t: Throwable?) = Unit
override fun info(message: String, t: Throwable?) = Unit
override fun warn(message: String, t: Throwable?) = Unit
override fun error(message: String, t: Throwable?, vararg details: String) = Unit
override fun setLevel(message: Level) = Unit
}
/**
* An aggressive logger that is intended for use during debugging (especially when testing manually installing plugins).
*
* IntelliJ makes it relatively easy to create new loggers, but unless you configure build log settings, those logs can
* easily get swallowed.
*
* This logger is never intended to be used in production, so it will only be enabled if the plugin is a snapshot build.
*/
class KobwebDebugLogger {
companion object {
val instance by lazy {
val plugin = PluginId.findId("com.varabyte.kobweb.intellij")?.let { pluginId ->
PluginManager.getInstance().findEnabledPlugin(pluginId)
}
if (plugin?.version?.endsWith("-SNAPSHOT") == true) {
Logger.getInstance(KobwebDebugLogger::class.java).apply { setLevel(LogLevel.ALL) }
} else {
DisabledLogger()
}
}
}
}
| kobweb-intellij-plugin/plugin/src/main/kotlin/com/varabyte/kobweb/intellij/util/log/KobwebDebugLogger.kt | 513557184 |
package com.varabyte.kobweb.intellij.util.psi
import com.intellij.openapi.roots.LibraryOrderEntry
import com.intellij.openapi.roots.OrderRootType
import com.intellij.openapi.roots.ProjectFileIndex
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiElement
/**
* Given a PSI element that represents a piece of code inside a Kotlin dependency, fetch its containing klib.
*
* Returns null if not part of a klib, e.g. a file in a local module.
*/
internal val PsiElement.containingKlib: VirtualFile?
get() {
return ProjectFileIndex.getInstance(this.project)
.getOrderEntriesForFile(this.containingFile.virtualFile)
.asSequence()
.filterIsInstance<LibraryOrderEntry>()
.mapNotNull { it.library?.getFiles(OrderRootType.CLASSES)?.toList() }
.flatten()
.toSet() // Remove duplicates
.singleOrNull { it.extension == "klib" }
}
| kobweb-intellij-plugin/plugin/src/main/kotlin/com/varabyte/kobweb/intellij/util/psi/PsiElementExtensions.kt | 3042424094 |
package com.varabyte.kobweb.intellij.notification
import com.intellij.notification.Notification
import com.intellij.notification.NotificationAction
import com.intellij.notification.NotificationGroupManager
import com.intellij.notification.NotificationType
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.project.Project
private val notificationGroup by lazy {
NotificationGroupManager.getInstance().getNotificationGroup("Kobweb")
}
/**
* A handle to a notification that provides some constrained operations on it.
*/
@JvmInline
value class KobwebNotificationHandle(private val notification: Notification) {
/**
* Manually expire the notification.
*
* This dismissed it and greys out any of its actions.
*/
fun expire() {
notification.expire()
}
}
/**
* A convenience class for generating notifications tagged with the Kobweb group.
*
* Use a [Builder] to build a notification, which you then fire by calling [Builder.notify] on it:
*
* ```
* KobwebNotifier.Builder("Hello, world!").notify(project)
* ```
*
* @see Notification
*/
class KobwebNotifier {
/**
* A builder class for creating notifications.
*
* You must call [notify] on the builder to actually display the notification.
*
* If you need to create two (or more) actions on a single notification, this is the preferred approach.
*/
@Suppress("MemberVisibilityCanBePrivate")
class Builder(private val message: String) {
constructor(title: String, message: String) : this(message) {
title(title)
}
private class ActionData(val text: String, val action: () -> Unit)
private var title: String = ""
private var type: NotificationType = NotificationType.INFORMATION
private var actionDataList = mutableListOf<ActionData>()
fun title(title: String) = apply { this.title = title }
/**
* Register a clickable action associated with this notification.
*
* You can register multiple actions per notification.
*
* Once clicked, the action will be performed and the notification will be dismissed.
*/
fun addAction(text: String, action: () -> Unit) =
apply { actionDataList.add(ActionData(text, action)) }
fun type(type: NotificationType) = apply { this.type = type }
fun notify(project: Project): KobwebNotificationHandle {
val notification = notificationGroup.createNotification(
title,
message,
type,
)
actionDataList.forEach { actionData ->
notification.addAction(object : NotificationAction(actionData.text) {
override fun actionPerformed(e: AnActionEvent, notification: Notification) {
actionData.action()
notification.expire()
}
})
}
notification.notify(project)
return KobwebNotificationHandle(notification)
}
}
}
| kobweb-intellij-plugin/plugin/src/main/kotlin/com/varabyte/kobweb/intellij/notification/KobwebNotifier.kt | 3594960810 |
package com.varabyte.kobweb.intellij.spellcheck
import com.intellij.spellchecker.dictionary.Dictionary
import com.intellij.spellchecker.dictionary.RuntimeDictionaryProvider
class KobwebDictionaryProvider : RuntimeDictionaryProvider {
override fun getDictionaries(): Array<Dictionary> = arrayOf(KobwebDictionary())
}
/**
* A collection of nonstandard words that are commonly encountered in Kobweb projects
*/
class KobwebDictionary : Dictionary {
private val words = setOf(
"frontmatter",
"kobweb",
"varabyte",
)
override fun getName(): String {
return "Kobweb Dictionary"
}
override fun contains(word: String): Boolean {
return words.contains(word.lowercase())
}
override fun getWords() = emptySet<String>()
}
| kobweb-intellij-plugin/plugin/src/main/kotlin/com/varabyte/kobweb/intellij/spellcheck/KobwebDictionary.kt | 551513219 |
package com.varabyte.kobweb.intellij.inspections
import com.intellij.codeInspection.InspectionSuppressor
import com.intellij.codeInspection.SuppressQuickFix
import com.intellij.psi.PsiElement
import com.varabyte.kobweb.intellij.util.kobweb.isInReadableKobwebProject
import org.jetbrains.kotlin.analysis.api.analyze
import org.jetbrains.kotlin.analysis.api.annotations.annotationClassIds
import org.jetbrains.kotlin.psi.KtNamedFunction
private val SUPPRESS_UNUSED_WHEN_ANNOTATED_WITH = arrayOf(
"com.varabyte.kobweb.api.Api",
"com.varabyte.kobweb.api.init.InitApi",
"com.varabyte.kobweb.core.App",
"com.varabyte.kobweb.core.Page",
"com.varabyte.kobweb.core.init.InitKobweb",
"com.varabyte.kobweb.silk.init.InitSilk",
)
/**
* Suppress the "Unused code" inspection, when we know that Kobweb will generate code that uses it.
*/
class UnusedInspectionSuppressor : InspectionSuppressor {
override fun isSuppressedFor(element: PsiElement, toolId: String): Boolean {
if (toolId != "unused") return false
if (!element.isInReadableKobwebProject()) return false
val ktFunction = element.parent as? KtNamedFunction ?: return false
analyze(ktFunction) {
val symbol = ktFunction.getSymbol()
symbol.annotationClassIds.forEach {
if (it.asFqNameString() in SUPPRESS_UNUSED_WHEN_ANNOTATED_WITH) return true
}
}
return false
}
override fun getSuppressActions(element: PsiElement?, toolId: String) = emptyArray<SuppressQuickFix>()
}
| kobweb-intellij-plugin/plugin/src/main/kotlin/com/varabyte/kobweb/intellij/inspections/UnusedInspectionSuppressor.kt | 1447421631 |
package com.varabyte.kobweb.intellij.inspections
import com.intellij.codeInspection.InspectionSuppressor
import com.intellij.codeInspection.SuppressQuickFix
import com.intellij.psi.PsiElement
import com.varabyte.kobweb.intellij.util.kobweb.isInKobwebSource
import com.varabyte.kobweb.intellij.util.kobweb.isInReadableKobwebProject
import org.jetbrains.kotlin.analysis.api.analyze
import org.jetbrains.kotlin.analysis.api.annotations.annotationClassIds
import org.jetbrains.kotlin.psi.KtNamedFunction
private val SUPPRESS_FUNCTION_NAME_WHEN_ANNOTATED_WITH = arrayOf(
"androidx.compose.runtime.Composable",
)
/**
* Suppress the "Function name should start with a lowercase letter" inspection.
*/
class FunctionNameInspectionSuppressor : InspectionSuppressor {
override fun isSuppressedFor(element: PsiElement, toolId: String): Boolean {
if (toolId != "FunctionName") return false
if (!element.isInReadableKobwebProject() && !element.isInKobwebSource()) return false
val ktFunction = element.parent as? KtNamedFunction ?: return false
analyze(ktFunction) {
val symbol = ktFunction.getSymbol()
symbol.annotationClassIds.forEach {
if (it.asFqNameString() in SUPPRESS_FUNCTION_NAME_WHEN_ANNOTATED_WITH) return true
}
}
return false
}
override fun getSuppressActions(element: PsiElement?, toolId: String) = emptyArray<SuppressQuickFix>()
}
| kobweb-intellij-plugin/plugin/src/main/kotlin/com/varabyte/kobweb/intellij/inspections/FunctionNameInspectionSuppressor.kt | 2775885743 |
package com.varabyte.kobweb.intellij.project
import com.intellij.openapi.module.Module
import com.intellij.openapi.vfs.VirtualFile
import com.varabyte.kobweb.intellij.model.KobwebProjectType
/**
* A Kobweb Project is a module that has applied one of the Kobweb Gradle Plugins.
*
* It can either be a local project inside the user's workspace or an external dependency (e.g. a maven artifact).
*
* @property name A human-readable name for this project.
*/
data class KobwebProject(
val name: String,
val type: KobwebProjectType,
val source: Source,
) {
/**
* Where the code for this Kobweb project lives, i.e. in the user's project or as an external dependency.
*/
sealed class Source {
/**
* The code for this Kobweb project lives in the user's project somewhere.
*
* This should be considered editable code, and refactoring actions should be available.
*/
data class Local(val module: Module) : Source()
/**
* The code for this Kobweb project lives in an external dependency (e.g. a maven artifact).
*
* This should be considered read-only code, and refactoring actions should not be available.
*/
data class External(val klib: VirtualFile) : Source()
}
}
| kobweb-intellij-plugin/plugin/src/main/kotlin/com/varabyte/kobweb/intellij/project/KobwebProject.kt | 1825367749 |
package com.varabyte.kobweb.intellij.project
import com.intellij.openapi.diagnostic.LogLevel
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.externalSystem.model.DataNode
import com.intellij.openapi.externalSystem.model.Key
import com.intellij.openapi.externalSystem.model.project.ModuleData
import com.intellij.openapi.externalSystem.model.project.ProjectData
import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil
import com.intellij.openapi.module.Module
import com.varabyte.kobweb.intellij.model.KobwebModel
import com.varabyte.kobweb.intellij.model.gradle.tooling.KobwebModelBuilderService
import org.gradle.tooling.model.idea.IdeaModule
import org.jetbrains.plugins.gradle.service.project.AbstractProjectResolverExtension
import org.jetbrains.plugins.gradle.util.GradleConstants
/**
* A project resolver that extends an IntelliJ module with information about its Kobweb contents (if any).
*
* Note: In this case, "project" here refers to a Gradle project, not an IntelliJ project.
*/
class KobwebGradleProjectResolver : AbstractProjectResolverExtension() {
companion object {
private val logger by lazy {
Logger.getInstance(KobwebGradleProjectResolver::class.java).apply { setLevel(LogLevel.ALL) }
}
}
object Keys {
internal val KOBWEB_MODEL = Key.create(KobwebModel::class.java, 0)
}
// Note that the classes returned by `getExtraProjectModelClasses` and `getToolingExtensionsClasses` are potentially
// consumed by a different JVM than the IDE one (e.g. the Gradle JVM). Therefore, they should be built separately
// from the rest of the plugin, using an older JDK.
override fun getExtraProjectModelClasses(): Set<Class<*>> = setOf(KobwebModel::class.java)
override fun getToolingExtensionsClasses(): Set<Class<*>> = setOf(
KobwebModel::class.java,
KobwebModelBuilderService::class.java
)
override fun preImportCheck() {
logger.info("Scanning modules in project \"${resolverCtx.projectPath}\", looking for Kobweb metadata...")
}
@Suppress("UnstableApiUsage") // Just used for logging, it's fine.
override fun resolveFinished(projectDataNode: DataNode<ProjectData>) {
logger.info("Finished scanning \"${resolverCtx.projectPath}\"")
}
override fun populateModuleExtraModels(gradleModule: IdeaModule, ideModule: DataNode<ModuleData>) {
super.populateModuleExtraModels(gradleModule, ideModule)
val kobwebModel = resolverCtx.getExtraProject(gradleModule, KobwebModel::class.java)
?: return // Kobweb model not found. No problem, it just means this module is not a Kobweb module
ideModule.createChild(Keys.KOBWEB_MODEL, kobwebModel)
logger.info("Module \"${gradleModule.name}\" is a Kobweb module [${kobwebModel.projectType}]")
}
}
fun Module.findKobwebModel(): KobwebModel? {
val modulePath = ExternalSystemApiUtil.getExternalProjectPath(this) ?: return null
return ExternalSystemApiUtil
.findModuleNode(project, GradleConstants.SYSTEM_ID, modulePath)
?.children
?.singleOrNull { it.key == KobwebGradleProjectResolver.Keys.KOBWEB_MODEL }
?.data as? KobwebModel
}
| kobweb-intellij-plugin/plugin/src/main/kotlin/com/varabyte/kobweb/intellij/project/KobwebGradleProjectResolver.kt | 4219085065 |
// ElementColorProvider interface uses standard AWT Color, as no darkened version is needed
@file:Suppress("UseJBColor")
package com.varabyte.kobweb.intellij.colors
import com.intellij.openapi.editor.ElementColorProvider
import com.intellij.psi.PsiElement
import com.intellij.psi.impl.source.tree.LeafPsiElement
import com.varabyte.kobweb.intellij.util.kobweb.isInKobwebSource
import com.varabyte.kobweb.intellij.util.kobweb.isInReadableKobwebProject
import org.jetbrains.kotlin.analysis.api.analyze
import org.jetbrains.kotlin.analysis.api.components.KtConstantEvaluationMode
import org.jetbrains.kotlin.idea.base.psi.kotlinFqName
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.js.translate.declaration.hasCustomGetter
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import java.awt.Color
import kotlin.math.abs
/**
* This constant prevents the color tracer from following references ridiculously deep into the codebase.
*
* If a method ultimately returns a color, it's unlikely that it will involve *that* many jumps to fetch it. Testing
* has showed that a search depth of 15 allows finding a result 3-4 references deep. If we don't limit this, we could
* possibly get stuck chasing a cyclical loop.
*
* Also, high limits may increase memory usage because we have to chase down every method we come across as possibly
* returning a color. Unlimited search depth might also introduce lag or, in the case of a cycle, a stack overflow.
*
* Note that Android Studio sets their depth a bit higher than we do. However, they also appear to do their tracing of
* colors differently. If there are reports in the wild about color preview not working, we can consider increasing this
* value at that time, though it is likely caused by their specific color function not being supported or the tracing
* algorithm being unable to analyze more complex code correctly.
*
* @see <a href="https://cs.android.com/android-studio/platform/tools/base/+/mirror-goog-studio-main:sdk-common/src/main/java/com/android/ide/common/resources/ResourceResolver.java;l=67?q=MAX_RESOURCE_INDIRECTION">Anroid Studio's ResourceResolver.java</a>
*/
private const val MAX_SEARCH_DEPTH = 15
private const val KOBWEB_COLOR_COMPANION_FQ_NAME = "com.varabyte.kobweb.compose.ui.graphics.Color.Companion"
/**
* Enables showing small rectangular gutter icons that preview Kobweb colors
*/
class KobwebColorProvider : ElementColorProvider {
override fun getColorFrom(element: PsiElement): Color? = when {
element !is LeafPsiElement -> null
element.elementType != KtTokens.IDENTIFIER -> null
element.parent is KtProperty -> null // Avoid showing multiple previews
!element.isInReadableKobwebProject() && !element.isInKobwebSource() -> null
else -> traceColor(element.parent) // Leaf is just text. The parent is the actual object
}
// TODO(#30): Support setting colors when possible
override fun setColorTo(element: PsiElement, color: Color) = Unit
}
/**
* Tries resolving references as deep as possible and checks if a Kobweb color is being referred to.
*
* @return the color being referenced, or null if the [element] ultimately doesn't resolve to
* a color at all (which is common) or if the amount of times we'd have to follow references to get to the color
* is too many, or it *was* a color but not one we could extract specific information
* about (e.g. a method that returns one of two colors based on a condition).
*/
private fun traceColor(element: PsiElement, currentDepth: Int = 0): Color? {
val nextElement = when (element) {
is KtDotQualifiedExpression -> element.selectorExpression
is KtNameReferenceExpression -> when {
element.parent is KtCallExpression -> element.parent // Element is name of a function
else -> element.findDeclaration()
}
is KtProperty -> when {
element.hasInitializer() -> element.initializer
element.hasCustomGetter() -> element.getter
else -> null
}
is KtPropertyAccessor -> element.bodyExpression
is KtCallExpression -> null.also {
val calleeExpression = element.calleeExpression as? KtNameReferenceExpression ?: return@also
val callee = calleeExpression.findDeclaration() as? KtNamedFunction ?: return@also
tryParseKobwebColorFunctionCall(callee, element.valueArguments)?.let { parsedColor ->
return parsedColor
}
}
else -> null
}
return if (currentDepth <= MAX_SEARCH_DEPTH) {
nextElement?.let { traceColor(it, currentDepth + 1) }
} else null
}
/**
* Checks if a called function is a Kobweb color function and if it is, tries extracting the color from the call.
*
* @param callee The function being called, that might be a Kobweb color function
* @param valueArguments The arguments the [callee] is called with
*
* @return The specified color, if it could be parsed and the callee is a Kobweb color function, otherwise null
*/
private fun tryParseKobwebColorFunctionCall(
callee: KtNamedFunction,
valueArguments: Collection<KtValueArgument>
): Color? = with(valueArguments) {
when {
callee.isKobwebColorFunction("rgb(r: Int, g: Int, b: Int)") ->
evaluateArguments<Int>(3)?.let { args ->
tryCreateRgbColor(args[0], args[1], args[2])
}
callee.isKobwebColorFunction("rgb(value: Int)") ->
evaluateArguments<Int>(1)?.let { args ->
tryCreateRgbColor(args[0])
}
callee.isKobwebColorFunction("rgba(value: Int)", "rgba(value: Long)") ->
(evaluateArguments<Int>(1) ?: evaluateArguments<Long, Int>(1) { it.toInt() })?.let { args ->
tryCreateRgbColor(args[0] shr Byte.SIZE_BITS)
}
callee.isKobwebColorFunction("argb(value: Int)", "argb(value: Long)") ->
(evaluateArguments<Int>(1) ?: evaluateArguments<Long, Int>(1) { it.toInt() })?.let { args ->
tryCreateRgbColor(args[0] and 0x00_FF_FF_FF)
}
callee.isKobwebColorFunction("hsl(h: Float, s: Float, l: Float)") ->
evaluateArguments<Float>(3)?.let { args ->
tryCreateHslColor(args[0], args[1], args[2])
}
callee.isKobwebColorFunction("hsla(h: Float, s: Float, l: Float, a: Float)") ->
evaluateArguments<Float>(4)?.let { args ->
tryCreateHslColor(args[0], args[1], args[2])
}
else -> null
}
}
// navigationElement returns the element where a feature like "Go to declaration" would point:
// The source declaration, if found, and not a compiled one, which would make further analyzing impossible.
private fun KtSimpleNameExpression.findDeclaration(): PsiElement? = this.mainReference.resolve()?.navigationElement
/**
* Evaluates a collection of value arguments to the specified type.
*
* For example, if we have a collection of decimal, hex, and binary arguments,
* this method can parse them into regular integer values, so 123, 0x7B and 0b0111_1011
* would all evaluate to 123.
*
* @param argCount The size the original and evaluated collections must have. If this value disagrees with the size of
* the passed in collection, it will throw an exception; it's essentially treated like an assertion at that point.
* Otherwise, it's used to avoid returning a final, evaluated array of unexpected size.
* @param evaluatedValueMapper Convenience parameter to avoid having to type `.map { ... }.toTypedArray()`
*
* @return the evaluated arguments of length [argCount] if evaluation of **all** arguments succeeded,
* and [argCount] elements were passed for evaluation, otherwise null
*/
private inline fun <reified Evaluated, reified Mapped> Collection<KtValueArgument>.evaluateArguments(
argCount: Int,
evaluatedValueMapper: (Evaluated) -> Mapped
): Array<Mapped>? {
check(this.size == argCount) { "evaluateArguments called on a collection expecting $argCount arguments, but it only had ${this.size}"}
val constantExpressions = this.mapNotNull { it.getArgumentExpression() as? KtConstantExpression }
val evaluatedArguments = constantExpressions.mapNotNull {
analyze(it.containingKtFile) {
it.evaluate(KtConstantEvaluationMode.CONSTANT_LIKE_EXPRESSION_EVALUATION)?.value as? Evaluated
}
}
return if (evaluatedArguments.size != argCount) null
else evaluatedArguments.map(evaluatedValueMapper).toTypedArray()
}
private inline fun <reified Evaluated> Collection<KtValueArgument>.evaluateArguments(argCount: Int) =
evaluateArguments<Evaluated, Evaluated>(argCount) { it }
private fun KtNamedFunction.isKobwebColorFunction(vararg functionSignatures: String): Boolean {
val actualFqName = this.kotlinFqName?.asString() ?: return false
val actualParameters = this.valueParameterList?.text ?: return false
val actual = actualFqName + actualParameters
return functionSignatures.any { functionSignature ->
val expected = "$KOBWEB_COLOR_COMPANION_FQ_NAME.$functionSignature"
expected == actual
}
}
private fun tryCreateRgbColor(r: Int, g: Int, b: Int) =
runCatching { Color(r, g, b) }.getOrNull()
private fun tryCreateRgbColor(rgb: Int) =
runCatching { Color(rgb) }.getOrNull()
private fun tryCreateHslColor(hue: Float, saturation: Float, lightness: Float): Color? {
// https://en.wikipedia.org/wiki/HSL_and_HSV#Color_conversion_formulae
val chroma = (1 - abs(2 * lightness - 1)) * saturation
val intermediateValue = chroma * (1 - abs(((hue / 60) % 2) - 1))
val hueSection = (hue.toInt() % 360) / 60
val r: Float
val g: Float
val b: Float
when (hueSection) {
0 -> {
r = chroma
g = intermediateValue
b = 0f
}
1 -> {
r = intermediateValue
g = chroma
b = 0f
}
2 -> {
r = 0f
g = chroma
b = intermediateValue
}
3 -> {
r = 0f
g = intermediateValue
b = chroma
}
4 -> {
r = intermediateValue
g = 0f
b = chroma
}
else -> {
check(hueSection == 5)
r = chroma
g = 0f
b = intermediateValue
}
}
val lightnessAdjustment = lightness - chroma / 2
return tryCreateRgbColor(
((r + lightnessAdjustment) * 255f).toInt(),
((g + lightnessAdjustment) * 255f).toInt(),
((b + lightnessAdjustment) * 255f).toInt()
)
}
| kobweb-intellij-plugin/plugin/src/main/kotlin/com/varabyte/kobweb/intellij/colors/KobwebColorProvider.kt | 1980112368 |
package com.varabyte.kobweb.intellij.startup
import com.intellij.notification.NotificationType
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.ActionPlaces
import com.intellij.openapi.actionSystem.PlatformDataKeys
import com.intellij.openapi.actionSystem.ex.ActionUtil
import com.intellij.openapi.components.service
import com.intellij.openapi.externalSystem.action.RefreshAllExternalProjectsAction
import com.intellij.openapi.externalSystem.service.project.manage.ProjectDataImportListener
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.modules
import com.intellij.openapi.project.rootManager
import com.intellij.openapi.roots.LibraryOrderEntry
import com.intellij.openapi.roots.ModuleOrderEntry
import com.intellij.openapi.startup.ProjectActivity
import com.varabyte.kobweb.intellij.notification.KobwebNotificationHandle
import com.varabyte.kobweb.intellij.notification.KobwebNotifier
import com.varabyte.kobweb.intellij.services.project.KobwebProjectCacheService
import com.varabyte.kobweb.intellij.util.kobweb.KobwebPluginState
import com.varabyte.kobweb.intellij.util.kobweb.kobwebPluginState
/**
* A simple heuristic for checking if this project has code in it somewhere that depends on Kobweb.
*
* This is useful as users may install the Kobweb plugin for one or two of their projects, but we should stay out of the
* way in every other kind of project.
*/
private fun Project.hasAnyKobwebDependency(): Boolean {
return this.modules.asSequence()
.flatMap { module -> module.rootManager.orderEntries.asSequence() }
.any { orderEntry ->
when (orderEntry) {
// Most projects will indicate a dependency on Kobweb via library coordinates, e.g. `com.varabyte.kobweb:core`
is LibraryOrderEntry -> orderEntry.libraryName.orEmpty().substringBefore(':') == "com.varabyte.kobweb"
// Very rare, but if a project depends on Kobweb source directly, that counts. This is essentially for
// the `kobweb/playground` project which devs use to test latest Kobweb on.
is ModuleOrderEntry -> orderEntry.moduleName.substringBefore('.') == "kobweb"
else -> false
}
}
}
/**
* Actions to perform after the project has been loaded.
*/
class KobwebPostStartupProjectActivity : ProjectActivity {
private class ImportListener(
private val project: Project,
private val syncRequestedNotification: KobwebNotificationHandle?
) : ProjectDataImportListener {
override fun onImportStarted(projectPath: String?) {
// If an import is kicked off in an indirect way, we should still dismiss the sync popup.
syncRequestedNotification?.expire()
}
override fun onImportFinished(projectPath: String?) {
project.kobwebPluginState = when (project.hasAnyKobwebDependency()) {
true -> KobwebPluginState.INITIALIZED
false -> KobwebPluginState.DISABLED
}
// After an import / gradle sync, let's just clear the cache, which should get automatically rebuilt
// as users interact with their code.
project.service<KobwebProjectCacheService>().clear()
}
}
override suspend fun execute(project: Project) {
if (project.hasAnyKobwebDependency() && project.kobwebPluginState == KobwebPluginState.DISABLED) {
project.kobwebPluginState = KobwebPluginState.UNINITIALIZED
}
val refreshProjectAction = ActionManager.getInstance().getAction("ExternalSystem.RefreshAllProjects") as? RefreshAllExternalProjectsAction
val syncRequestedNotification = if (refreshProjectAction != null && project.kobwebPluginState == KobwebPluginState.UNINITIALIZED) {
KobwebNotifier.Builder("The Kobweb plugin requires a one-time sync to enable functionality.")
.type(NotificationType.WARNING)
.addAction("Sync Project") {
ActionUtil.invokeAction(refreshProjectAction, { dataId ->
when {
PlatformDataKeys.PROJECT.`is`(dataId) -> project
else -> null
}
}, ActionPlaces.NOTIFICATION, null, null)
}
.notify(project)
} else null
val messageBusConnection = project.messageBus.connect()
messageBusConnection.subscribe(
ProjectDataImportListener.TOPIC,
ImportListener(project, syncRequestedNotification)
)
}
}
| kobweb-intellij-plugin/plugin/src/main/kotlin/com/varabyte/kobweb/intellij/startup/KobwebPostStartupProjectActivity.kt | 1069319402 |
package com.varabyte.kobweb.intellij.services.project
import com.intellij.openapi.module.Module
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiElement
import com.varabyte.kobweb.intellij.project.KobwebProject
import com.varabyte.kobweb.intellij.util.module.toGradleModule
import com.varabyte.kobweb.intellij.util.psi.containingKlib
import org.jetbrains.kotlin.idea.base.util.module
import java.util.*
/**
* A project service which caches [KobwebProject]s, allowing for quick lookups of whether a given element is part of one.
*
* Callers can fetch this service and then either register Kobweb Projects with it or query it.
*
* Knowing if you're inside a Kobweb project can be useful before running an inspection or action, so that we don't
* waste time processing code that isn't relevant to Kobweb (e.g. if we're in a multiplatform project with Kobweb,
* Android, and other types of modules).
*
* Note there's also an option to mark an element as explicitly NOT being part of a Kobweb project. This allows early
* aborting on followup checks, allowing the caller to distinguish the difference between "get returns null because
* this is not a kobweb project" vs "get returns null because we haven't put the value in the cache yet".
*
* @see KobwebProject
*/
interface KobwebProjectCacheService : Iterable<KobwebProject> {
operator fun get(module: Module): KobwebProject?
operator fun get(klib: VirtualFile): KobwebProject?
// This does NOT accept module / klib parameters like the `get` methods, because we need to support elements that
// potentially don't live in either a module nor a klib.
fun isMarkedNotKobweb(element: PsiElement): Boolean
fun add(project: KobwebProject)
fun addAll(collection: Collection<KobwebProject>)
fun markNotKobweb(element: PsiElement)
fun clear()
}
private class KobwebProjectCacheServiceImpl : KobwebProjectCacheService {
private val localProjects = Collections.synchronizedMap(mutableMapOf<Module, KobwebProject>())
private val externalProjects = Collections.synchronizedMap(mutableMapOf<VirtualFile, KobwebProject>())
private val notKobwebProjects = Collections.synchronizedSet(mutableSetOf<Any>())
override operator fun get(module: Module) = localProjects[module]
override operator fun get(klib: VirtualFile) = externalProjects[klib]
override fun add(project: KobwebProject) {
when (project.source) {
is KobwebProject.Source.External -> externalProjects[project.source.klib] = project
is KobwebProject.Source.Local -> localProjects[project.source.module] = project
}
}
// There are easily thousands of elements in a project, so it would be wasteful to store each one individually.
// Instead, we return a container as broad as possible and store that.
private fun PsiElement.toElementContainer(): Any = module?.toGradleModule() ?: containingKlib ?: containingFile
override fun isMarkedNotKobweb(element: PsiElement): Boolean {
return notKobwebProjects.contains(element.toElementContainer())
}
override fun addAll(collection: Collection<KobwebProject>) {
collection.forEach { add(it) }
}
override fun markNotKobweb(element: PsiElement) {
notKobwebProjects.add(element.toElementContainer())
}
override fun clear() {
externalProjects.clear()
localProjects.clear()
notKobwebProjects.clear()
}
override fun iterator(): Iterator<KobwebProject> {
return (localProjects.values + externalProjects.values).iterator()
}
override fun toString(): String {
return "KobwebProjects${this.iterator().asSequence().joinToString(prefix = "[", postfix = "]") { it.name }}"
}
}
| kobweb-intellij-plugin/plugin/src/main/kotlin/com/varabyte/kobweb/intellij/services/project/KobwebProjectCacheService.kt | 3796374862 |
package com.varabyte.kobweb.intellij.model
import java.io.Serializable
/**
* A Kobweb project is one that applies one of the Kobweb gradle plugins.
*/
enum class KobwebProjectType {
Application,
Library,
Worker,
}
/**
* A collection of data surfaced about a Kobweb project.
*
* This model is used as a way to communicate information between a Gradle project and the Kobweb IntelliJ plugin (which
* is why it is serializable).
*/
interface KobwebModel : Serializable {
val projectType: KobwebProjectType
}
| kobweb-intellij-plugin/kobweb-model/src/main/kotlin/com/varabyte/kobweb/intellij/model/KobwebModel.kt | 1613765807 |
package com.varabyte.kobweb.intellij.model.gradle.tooling
import com.varabyte.kobweb.intellij.model.KobwebModel
import com.varabyte.kobweb.intellij.model.KobwebProjectType
import org.gradle.api.Project
import org.jetbrains.plugins.gradle.tooling.AbstractModelBuilderService
import org.jetbrains.plugins.gradle.tooling.ModelBuilderContext
private class KobwebModelImpl(
override val projectType: KobwebProjectType,
) : KobwebModel
private fun Project.toKobwebModel(): KobwebModel? {
val projectType = with(pluginManager) {
when {
hasPlugin("com.varabyte.kobweb.application") -> KobwebProjectType.Application
hasPlugin("com.varabyte.kobweb.library") -> KobwebProjectType.Library
hasPlugin("com.varabyte.kobweb.worker") -> KobwebProjectType.Worker
else -> return null
}
}
return KobwebModelImpl(projectType)
}
/**
* A model builder that creates a [KobwebModel] for a Kobweb module.
*
* This service is declared in `META-INF/services`, where it will be found by the IntelliJ IDE engine and injected into
* Gradle.
*
* This allows our code to run directly in Gradle, giving us access to use Gradle APIs.
*
* The injected code then returns a serializable class (a model) which can be fetched with an
* `AbstractProjectResolverExtension` (which we implement elsewhere in this codebase).
*/
class KobwebModelBuilderService : AbstractModelBuilderService() {
override fun canBuild(modelName: String?) = modelName == KobwebModel::class.qualifiedName
override fun buildAll(modelName: String, project: Project, context: ModelBuilderContext): KobwebModel? {
return project.toKobwebModel()
?.also {
project.logger.info("Built Kobweb model for project ${project.displayName}, type ${it.projectType}")
}
}
override fun reportErrorMessage(
modelName: String,
project: Project,
context: ModelBuilderContext,
exception: Exception
) {
project.logger.warn(buildString {
appendLine("The Kobweb IntelliJ plugin added some code that caused an unexpected error in your Gradle project (${project.displayName}). Consider filing an issue with the plugin authors at https://github.com/varabyte/kobweb-intellij-plugin/issues")
append("Exception: ${exception.stackTraceToString()}")
})
}
}
| kobweb-intellij-plugin/kobweb-model/src/main/kotlin/com/varabyte/kobweb/intellij/model/gradle/tooling/KobwebModelBuilderService.kt | 1167447023 |
package org.example.app
import com.varabyte.kobweb.compose.css.TextAlign
import com.varabyte.kobweb.compose.ui.Modifier
import com.varabyte.kobweb.compose.ui.graphics.Colors
import com.varabyte.kobweb.compose.ui.modifiers.*
import com.varabyte.kobweb.silk.components.forms.ButtonStyle
import com.varabyte.kobweb.silk.components.forms.ButtonVars
import com.varabyte.kobweb.silk.components.layout.HorizontalDividerStyle
import com.varabyte.kobweb.silk.components.style.ComponentStyle
import com.varabyte.kobweb.silk.components.style.addVariantBase
import com.varabyte.kobweb.silk.components.style.base
import com.varabyte.kobweb.silk.init.InitSilk
import com.varabyte.kobweb.silk.init.InitSilkContext
import com.varabyte.kobweb.silk.init.registerStyleBase
import com.varabyte.kobweb.silk.theme.colors.palette.color
import com.varabyte.kobweb.silk.theme.colors.palette.toPalette
import com.varabyte.kobweb.silk.theme.modifyComponentStyleBase
import org.jetbrains.compose.web.css.cssRem
import org.jetbrains.compose.web.css.percent
import org.jetbrains.compose.web.css.px
@InitSilk
fun initSiteStyles(ctx: InitSilkContext) {
ctx.stylesheet.registerStyleBase("body") {
Modifier
.fontFamily(
"-apple-system", "BlinkMacSystemFont", "Segoe UI", "Roboto", "Oxygen", "Ubuntu",
"Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue", "sans-serif"
)
.fontSize(18.px)
.lineHeight(1.5)
}
// Silk dividers only extend 90% by default; we want full width dividers in our site
ctx.theme.modifyComponentStyleBase(HorizontalDividerStyle) {
Modifier.fillMaxWidth()
}
}
val HeadlineTextStyle by ComponentStyle.base {
Modifier
.fontSize(3.cssRem)
.textAlign(TextAlign.Start)
.lineHeight(1.2) //1.5x doesn't look as good on very large text
}
val SubheadlineTextStyle by ComponentStyle.base {
Modifier
.fontSize(1.cssRem)
.textAlign(TextAlign.Start)
.color(colorMode.toPalette().color.toRgb().copyf(alpha = 0.8f))
}
val CircleButtonVariant by ButtonStyle.addVariantBase {
Modifier.padding(0.px).borderRadius(50.percent)
}
val UncoloredButtonVariant by ButtonStyle.addVariantBase {
Modifier.setVariable(ButtonVars.BackgroundDefaultColor, Colors.Transparent)
}
| kobweb-intellij-plugin/sample-projects/app/site/src/jsMain/kotlin/org/example/app/AppStyles.kt | 2624411851 |
package org.example.app.components.sections
import androidx.compose.runtime.Composable
import com.varabyte.kobweb.compose.css.TextAlign
import com.varabyte.kobweb.compose.css.WhiteSpace
import com.varabyte.kobweb.compose.foundation.layout.Box
import com.varabyte.kobweb.compose.ui.Alignment
import com.varabyte.kobweb.compose.ui.Modifier
import com.varabyte.kobweb.compose.ui.modifiers.*
import com.varabyte.kobweb.compose.ui.toAttrs
import com.varabyte.kobweb.silk.components.navigation.Link
import com.varabyte.kobweb.silk.components.navigation.UncoloredLinkVariant
import com.varabyte.kobweb.silk.components.style.ComponentStyle
import com.varabyte.kobweb.silk.components.style.base
import com.varabyte.kobweb.silk.components.style.toModifier
import com.varabyte.kobweb.silk.components.style.vars.color.ColorVar
import com.varabyte.kobweb.silk.components.text.SpanText
import com.varabyte.kobweb.silk.theme.colors.ColorMode
import org.jetbrains.compose.web.css.cssRem
import org.jetbrains.compose.web.css.percent
import org.jetbrains.compose.web.dom.Span
import org.example.app.toSitePalette
val FooterStyle by ComponentStyle.base {
Modifier
.backgroundColor(colorMode.toSitePalette().nearBackground)
.padding(topBottom = 1.5.cssRem, leftRight = 10.percent)
}
@Composable
fun Footer(modifier: Modifier = Modifier) {
Box(FooterStyle.toModifier().then(modifier), contentAlignment = Alignment.Center) {
Span(Modifier.textAlign(TextAlign.Center).toAttrs()) {
val sitePalette = ColorMode.current.toSitePalette()
SpanText("Built with ")
Link(
"https://github.com/varabyte/kobweb",
"Kobweb",
Modifier.setVariable(ColorVar, sitePalette.brand.primary),
variant = UncoloredLinkVariant
)
SpanText(", template designed by ")
// Huge thanks to UI Rocket (https://ui-rocket.com) for putting this great template design together for us!
// If you like what you see here and want help building your own site, consider checking out their services.
Link(
"https://ui-rocket.com",
"UI Rocket",
Modifier.setVariable(ColorVar, sitePalette.brand.accent).whiteSpace(WhiteSpace.NoWrap),
variant = UncoloredLinkVariant
)
}
}
}
| kobweb-intellij-plugin/sample-projects/app/site/src/jsMain/kotlin/org/example/app/components/sections/Footer.kt | 3211969898 |
package org.example.app.components.sections
import androidx.compose.runtime.*
import com.varabyte.kobweb.browser.dom.ElementTarget
import com.varabyte.kobweb.compose.css.functions.clamp
import com.varabyte.kobweb.compose.foundation.layout.Column
import com.varabyte.kobweb.compose.foundation.layout.Row
import com.varabyte.kobweb.compose.foundation.layout.Spacer
import com.varabyte.kobweb.compose.ui.Alignment
import com.varabyte.kobweb.compose.ui.Modifier
import com.varabyte.kobweb.compose.ui.graphics.Colors
import com.varabyte.kobweb.compose.ui.modifiers.*
import com.varabyte.kobweb.silk.components.animation.Keyframes
import com.varabyte.kobweb.silk.components.animation.toAnimation
import com.varabyte.kobweb.silk.components.graphics.Image
import com.varabyte.kobweb.silk.components.icons.CloseIcon
import com.varabyte.kobweb.silk.components.icons.HamburgerIcon
import com.varabyte.kobweb.silk.components.icons.MoonIcon
import com.varabyte.kobweb.silk.components.icons.SunIcon
import com.varabyte.kobweb.silk.components.layout.breakpoint.displayIfAtLeast
import com.varabyte.kobweb.silk.components.layout.breakpoint.displayUntil
import com.varabyte.kobweb.silk.components.navigation.Link
import com.varabyte.kobweb.silk.components.navigation.UncoloredLinkVariant
import com.varabyte.kobweb.silk.components.navigation.UndecoratedLinkVariant
import com.varabyte.kobweb.silk.components.overlay.Overlay
import com.varabyte.kobweb.silk.components.overlay.OverlayVars
import com.varabyte.kobweb.silk.components.overlay.PopupPlacement
import com.varabyte.kobweb.silk.components.overlay.Tooltip
import com.varabyte.kobweb.silk.components.style.ComponentStyle
import com.varabyte.kobweb.silk.components.style.base
import com.varabyte.kobweb.silk.components.style.breakpoint.Breakpoint
import com.varabyte.kobweb.silk.components.style.toModifier
import com.varabyte.kobweb.silk.theme.colors.ColorMode
import org.jetbrains.compose.web.css.*
import org.example.app.components.widgets.IconButton
import org.example.app.toSitePalette
val NavHeaderStyle by ComponentStyle.base {
Modifier.fillMaxWidth().padding(1.cssRem)
}
@Composable
private fun NavLink(path: String, text: String) {
Link(path, text, variant = UndecoratedLinkVariant.then(UncoloredLinkVariant))
}
@Composable
private fun MenuItems() {
NavLink("/", "Home")
NavLink("/about", "About")
}
@Composable
private fun ColorModeButton() {
var colorMode by ColorMode.currentState
IconButton(onClick = { colorMode = colorMode.opposite },) {
if (colorMode.isLight) MoonIcon() else SunIcon()
}
Tooltip(ElementTarget.PreviousSibling, "Toggle color mode", placement = PopupPlacement.BottomRight)
}
@Composable
private fun HamburgerButton(onClick: () -> Unit) {
IconButton(onClick) {
HamburgerIcon()
}
}
@Composable
private fun CloseButton(onClick: () -> Unit) {
IconButton(onClick) {
CloseIcon()
}
}
val SideMenuSlideInAnim by Keyframes {
from {
Modifier.translateX(100.percent)
}
to {
Modifier
}
}
// Note: When the user closes the side menu, we don't immediately stop rendering it (at which point it would disappear
// abruptly). Instead, we start animating it out and only stop rendering it when the animation is complete.
enum class SideMenuState {
CLOSED,
OPEN,
CLOSING;
fun close() = when (this) {
CLOSED -> CLOSED
OPEN -> CLOSING
CLOSING -> CLOSING
}
}
@Composable
fun NavHeader() {
Row(NavHeaderStyle.toModifier(), verticalAlignment = Alignment.CenterVertically) {
Link("https://kobweb.varabyte.com") {
// Block display overrides inline display of the <img> tag, so it calculates centering better
Image("/kobweb-logo.png", "Kobweb Logo", Modifier.height(2.cssRem).display(DisplayStyle.Block))
}
Spacer()
Row(Modifier.gap(1.5.cssRem).displayIfAtLeast(Breakpoint.MD), verticalAlignment = Alignment.CenterVertically) {
MenuItems()
ColorModeButton()
}
Row(
Modifier
.fontSize(1.5.cssRem)
.gap(1.cssRem)
.displayUntil(Breakpoint.MD),
verticalAlignment = Alignment.CenterVertically
) {
var menuState by remember { mutableStateOf(SideMenuState.CLOSED) }
ColorModeButton()
HamburgerButton(onClick = { menuState = SideMenuState.OPEN })
if (menuState != SideMenuState.CLOSED) {
SideMenu(
menuState,
close = { menuState = menuState.close() },
onAnimationEnd = { if (menuState == SideMenuState.CLOSING) menuState = SideMenuState.CLOSED }
)
}
}
}
}
@Composable
private fun SideMenu(menuState: SideMenuState, close: () -> Unit, onAnimationEnd: () -> Unit) {
Overlay(
Modifier
.setVariable(OverlayVars.BackgroundColor, Colors.Transparent)
.onClick { close() }
) {
key(menuState) { // Force recompute animation parameters when close button is clicked
Column(
Modifier
.fillMaxHeight()
.width(clamp(8.cssRem, 33.percent, 10.cssRem))
.align(Alignment.CenterEnd)
// Close button will appear roughly over the hamburger button, so the user can close
// things without moving their finger / cursor much.
.padding(top = 1.cssRem, leftRight = 1.cssRem)
.gap(1.5.cssRem)
.backgroundColor(ColorMode.current.toSitePalette().nearBackground)
.animation(
SideMenuSlideInAnim.toAnimation(
duration = 200.ms,
timingFunction = if (menuState == SideMenuState.OPEN) AnimationTimingFunction.EaseOut else AnimationTimingFunction.EaseIn,
direction = if (menuState == SideMenuState.OPEN) AnimationDirection.Normal else AnimationDirection.Reverse,
fillMode = AnimationFillMode.Forwards
)
)
.borderRadius(topLeft = 2.cssRem)
.onClick { it.stopPropagation() }
.onAnimationEnd { onAnimationEnd() },
horizontalAlignment = Alignment.End
) {
CloseButton(onClick = { close() })
Column(Modifier.padding(right = 0.75.cssRem).gap(1.5.cssRem).fontSize(1.4.cssRem), horizontalAlignment = Alignment.End) {
MenuItems()
}
}
}
}
}
| kobweb-intellij-plugin/sample-projects/app/site/src/jsMain/kotlin/org/example/app/components/sections/NavHeader.kt | 2292771411 |
package org.example.app.components.layouts
import androidx.compose.runtime.Composable
import com.varabyte.kobweb.compose.css.FontWeight
import com.varabyte.kobweb.compose.css.Overflow
import com.varabyte.kobweb.compose.css.OverflowWrap
import com.varabyte.kobweb.compose.foundation.layout.Column
import com.varabyte.kobweb.compose.ui.Alignment
import com.varabyte.kobweb.compose.ui.Modifier
import com.varabyte.kobweb.compose.ui.modifiers.*
import com.varabyte.kobweb.silk.components.style.ComponentStyle
import com.varabyte.kobweb.silk.components.style.toModifier
import com.varabyte.kobweb.silk.theme.colors.palette.color
import com.varabyte.kobweb.silk.theme.colors.palette.toPalette
import org.jetbrains.compose.web.css.DisplayStyle
import org.jetbrains.compose.web.css.LineStyle
import org.jetbrains.compose.web.css.cssRem
import org.jetbrains.compose.web.css.px
import org.example.app.toSitePalette
val MarkdownStyle by ComponentStyle {
// The following rules apply to all descendant elements, indicated by the leading space.
// When you use `cssRule`, the name of this style is prefixed in front of it.
// See also: https://developer.mozilla.org/en-US/docs/Web/CSS/Descendant_combinator
cssRule("h1") {
Modifier
.fontSize(3.cssRem)
.fontWeight(400)
.margin(bottom = 2.5.cssRem)
.lineHeight(1.2) //1.5x doesn't look as good on very large text
}
cssRule("h2") {
Modifier
.fontSize(3.cssRem)
.fontWeight(300)
.margin(topBottom = 2.cssRem)
}
cssRule("h3") {
Modifier
.fontSize(2.4.cssRem)
.fontWeight(300)
.margin(topBottom = 1.5.cssRem)
}
cssRule("h4") {
Modifier
.fontSize(1.2.cssRem)
.fontWeight(FontWeight.Bolder)
.margin(top = 1.cssRem, bottom = 0.5.cssRem)
}
cssRule("p") {
Modifier.margin(bottom = 0.8.cssRem)
}
cssRule("ul") {
Modifier.fillMaxWidth().overflowWrap(OverflowWrap.BreakWord)
}
cssRule("li,ol,ul") {
Modifier.margin(bottom = 0.25.cssRem)
}
cssRule("code") {
Modifier
.color(colorMode.toPalette().color.toRgb().copyf(alpha = 0.8f))
.fontWeight(FontWeight.Bolder)
}
cssRule("pre") {
Modifier
.margin(top = 0.5.cssRem, bottom = 2.cssRem)
.fillMaxWidth()
}
cssRule("pre > code") {
Modifier
.display(DisplayStyle.Block)
.fillMaxWidth()
.backgroundColor(colorMode.toSitePalette().nearBackground)
.border(1.px, LineStyle.Solid, colorMode.toPalette().color)
.borderRadius(0.25.cssRem)
.padding(0.5.cssRem)
.fontSize(1.cssRem)
.overflow { x(Overflow.Auto) }
}
}
@Composable
fun MarkdownLayout(title: String, content: @Composable () -> Unit) {
PageLayout(title) {
Column(MarkdownStyle.toModifier().fillMaxSize(), horizontalAlignment = Alignment.Start) {
content()
}
}
}
| kobweb-intellij-plugin/sample-projects/app/site/src/jsMain/kotlin/org/example/app/components/layouts/MarkdownLayout.kt | 1967973623 |
package org.example.app.components.layouts
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import com.varabyte.kobweb.compose.dom.svg.*
import com.varabyte.kobweb.compose.foundation.layout.Box
import com.varabyte.kobweb.compose.foundation.layout.Column
import com.varabyte.kobweb.compose.foundation.layout.ColumnScope
import com.varabyte.kobweb.compose.ui.Alignment
import com.varabyte.kobweb.compose.ui.Modifier
import com.varabyte.kobweb.compose.ui.modifiers.*
import com.varabyte.kobweb.compose.ui.toAttrs
import com.varabyte.kobweb.silk.components.style.ComponentStyle
import com.varabyte.kobweb.silk.components.style.breakpoint.Breakpoint
import com.varabyte.kobweb.silk.components.style.toModifier
import com.varabyte.kobweb.silk.theme.colors.ColorMode
import kotlinx.browser.document
import org.jetbrains.compose.web.css.cssRem
import org.jetbrains.compose.web.css.fr
import org.jetbrains.compose.web.css.percent
import org.example.app.components.sections.Footer
import org.example.app.components.sections.NavHeader
import org.example.app.toSitePalette
val PageContentStyle by ComponentStyle {
base { Modifier.fillMaxSize().padding(leftRight = 2.cssRem, top = 4.cssRem) }
Breakpoint.MD { Modifier.maxWidth(60.cssRem) }
}
// NOTE: This is a fun little graphic that showcases what you can do with SVG. However, this probably does not make
// sense in your own site, so feel free to delete it.
@Composable
private fun SvgCobweb(modifier: Modifier) {
val color = ColorMode.current.toSitePalette().cobweb
// On mobile, the SVG would cause scrolling, so clamp its max width
Svg(attrs = modifier.maxWidth(100.percent).toAttrs {
width(25.cssRem)
height(20.cssRem)
}) {
val cobwebFadeOutId = SvgId("cobweb-fade-out")
Defs {
// Fade out the bottom right of the cobweb with a circular shape
RadialGradient(cobwebFadeOutId, attrs = {
cx(0)
cy(0)
r(120.percent)
}) {
Stop(50.percent, color)
Stop(100.percent, color, stopOpacity = 0f)
}
}
Path {
// d { ... } is useful for type-safe, readable SVG path construction, but I got a complex path from a
// designer, so using d(...) directly in this case
d("M-19.5501 -131.516L37.5899-59.412C34.8649 -10.82 13.8419 26.38 -14.8001 60.62L-21.5161 58.86V78.18L-18.9591 78.852C-3.60911 123.917 -9.87111 169.679 -17.1391 217.146L-21.5151 219.193V239.823L-12.3351 235.529C-5.81911 246.236 1.32289 262.576 6.72489 276.859C10.0329 285.624 13.1183 294.472 15.9779 303.394L-21.5151 341.084V343.514H2.42689L30.9769 314.814C40.2469 314.451 72.7469 313.341 113.677 314.064C160.421 314.889 216.289 318.364 252.727 327.731L257.807 343.515H277.439L270.009 320.427C305.949 278.917 341.921 239.902 401.743 218.087L453.517 238.573V218.476L410.534 201.468C404.16 162.258 423.289 124.803 441.154 84.788L453.517 82.203V63.111L447.194 64.434L441.744 61.631C385.656 32.8 365.41 -16.36 348.444 -71.07L392.628 -131.516H369.478L330.878 -78.706C272.605 -77.452 218.403 -81.169 176.432 -116.496L174.158 -131.516H155.258L158.096 -112.766C130.96 -83.776 100.532 -64.812 53.5119 -69.41L4.29189 -131.516H-19.5521H-19.5501ZM180.367 -90.512C220.975 -64.208 268.865 -59.618 317.121 -59.882L283.981 -14.542C247.393 -14.146 214.125 -17.576 188.136 -39.18L180.367 -90.512ZM161.533 -90.072L169.823 -35.297C152.008 -16.681 132.529 -5.117 101.828 -8.443L68.7519 -50.18C107.345 -50.92 137.11 -67.324 161.532 -90.072H161.533ZM334.857 -52.48C350.393 -5.51302 371.907 40.21 419.407 70.242L367.639 81.062L366.823 80.645C329.553 61.5 316.378 29.005 304.888 -8.18501L304.172 -10.5L334.855 -52.48H334.857ZM54.1169 -38.562L88.5099 4.836C85.9869 34.419 73.1059 57.496 55.3699 79.043L4.96589 65.81C28.6799 36.036 47.6059 2.41699 54.1179 -38.563L54.1169 -38.562ZM191.965 -13.872C215.901 -0.177994 243.015 3.528 270.369 4.076L237.459 49.104C222.401 42.74 211.322 31.351 198.889 18.779L196.546 16.409L191.964 -13.871L191.965 -13.872ZM173.187 -13.062L178.779 23.893C167.603 31.393 154.343 36.043 139.733 39.385L116.831 10.488C139.541 9.093 157.926 -0.192001 173.187 -13.062ZM290.567 8.11099C300.313 37.266 313.713 66.128 341.147 86.601L285.219 98.291C272.222 87.109 265.242 73.557 258.063 58.401L256.393 54.871L290.567 8.11099ZM104.135 24.554L123.277 48.708L123.199 49.418C121.269 66.783 114.322 79.048 106.549 92.481L75.0129 84.201C88.2249 66.845 98.9529 47.373 104.133 24.554H104.135ZM181.809 43.907L187.821 83.649C184.26 84.3288 180.81 85.5 177.571 87.129L152.394 55.362C162.584 52.612 172.524 49.017 181.808 43.908L181.809 43.907ZM201.169 46.95C208.524 53.528 216.689 59.672 226.321 64.34L210.487 86.002C209.307 85.5035 208.103 85.0636 206.88 84.684L201.17 46.949L201.169 46.95ZM138.419 67.814L163.329 99.244C161.729 101.454 160.361 103.823 159.249 106.314L125.335 97.412C130.29 88.655 135.165 79.159 138.419 67.814ZM243.944 71.896C249.064 82.311 255.048 92.991 263.597 102.809L232.454 109.317C230.89 104.865 228.541 100.73 225.517 97.107L243.944 71.896ZM2.17189 84.4L51.0449 97.23C60.2719 125.445 56.8399 154.31 52.2449 184.678L3.17289 207.64C9.12289 167.493 13.4619 126.226 2.17189 84.4ZM418.314 89.562C403.381 122.197 388.2 156.295 390.881 193.692L347.141 176.385C343.541 151.369 355.917 126.94 367.866 100.107L418.316 89.563L418.314 89.562ZM71.7379 102.662L99.3519 109.91L99.9139 111.31C106.014 126.443 105.297 143.082 102.814 161.018L72.4959 175.203C75.7099 151.691 77.4719 127.39 71.7379 102.662ZM345.033 104.879C335.99 124.696 327.236 145.682 327.781 168.726L291.194 154.249C291.19 141.101 292.589 131.409 300.314 120.329L305.294 113.185L345.034 104.878L345.033 104.879ZM120.673 115.507L155.91 124.759C156.126 128.317 156.825 131.829 157.988 135.199L122.718 151.702C123.768 139.802 123.644 127.654 120.673 115.507ZM279.833 118.507C275.208 127.94 273.453 137.397 272.885 147.005L233.607 131.465C233.873 130.34 234.077 129.192 234.247 128.035L279.832 118.507H279.833ZM225.037 148.169L261.541 162.612C252.631 167.192 244.225 173.148 236.864 178.772C233.505 181.339 230.209 183.988 226.978 186.714L216.876 155.317C219.916 153.317 222.662 150.909 225.038 148.169H225.037ZM166.917 151.653L129.26 189.51C126.702 183.31 123.242 178.363 119.672 174.275L119.76 173.719L166.914 151.653H166.917ZM184.647 160.325C189.395 161.652 194.351 162.077 199.256 161.58L209.729 194.12C196.415 193.96 172.116 194.196 148.036 197.13L184.646 160.326L184.647 160.325ZM288.133 173.135L313.496 183.169C284.096 198.089 263.12 219.065 244.244 240.369L233.2 206.05C236.754 202.876 241.93 198.42 248.21 193.623C259.63 184.896 274.418 175.923 283.895 173.996L288.133 173.135ZM101.635 182.2L103.152 183.725C109 189.6 113.125 194.028 114.375 204.475L83.2319 235.783C82.8819 233.513 82.4939 231.153 82.0319 228.641C80.0219 217.691 77.5839 205.699 72.7069 195.737L101.635 182.202V182.2ZM337.563 192.693L376.781 208.211C327.358 230.711 293.866 264.895 263.331 299.681L250.896 261.034C274.999 233.196 298.569 207.418 337.564 192.694L337.563 192.693ZM55.5769 203.75C58.5789 210.587 61.7989 221.92 63.6529 232.016C65.2349 240.626 66.1529 248.096 66.6329 252.466L30.7509 288.541C28.6803 282.405 26.4966 276.307 24.2009 270.251C18.8269 256.035 12.2079 240.239 4.59089 227.611L55.5769 203.751V203.75ZM206.44 212.898C210.408 212.892 213.254 212.928 215.79 212.963L226.186 245.263C199.929 241.113 167.553 241.073 139.129 242.078C123.554 242.628 111.125 243.405 101.272 244.143L125.38 219.906L126.33 219.676C150.076 213.886 186.19 212.93 206.44 212.898ZM164.248 260.288C189.172 260.235 214.614 261.554 232.664 265.391L246.092 307.118C207.384 298.888 157.108 296.141 114.006 295.38C86.7839 294.898 64.7689 295.192 50.1359 295.553L80.9359 264.59C88.7009 263.833 111.646 261.748 139.789 260.754C147.689 260.474 155.939 260.304 164.247 260.287L164.248 260.288Z")
transform { scale(0.6) }
fill(cobwebFadeOutId)
}
}
}
@Composable
fun PageLayout(title: String, content: @Composable ColumnScope.() -> Unit) {
LaunchedEffect(title) {
document.title = "Kobweb - $title"
}
Box(
Modifier
.fillMaxWidth()
.minHeight(100.percent)
// Create a box with two rows: the main content (fills as much space as it can) and the footer (which reserves
// space at the bottom). "min-content" means the use the height of the row, which we use for the footer.
// Since this box is set to *at least* 100%, the footer will always appear at least on the bottom but can be
// pushed further down if the first row grows beyond the page.
// Grids are powerful but have a bit of a learning curve. For more info, see:
// https://css-tricks.com/snippets/css/complete-guide-grid/
.gridTemplateRows { size(1.fr); size(minContent) },
contentAlignment = Alignment.Center
) {
SvgCobweb(Modifier.gridRow(1).align(Alignment.TopStart))
Column(
// Isolate the content, because otherwise the absolute-positioned SVG above will render on top of it.
// This is confusing but how browsers work. Read up on stacking contexts for more info.
// https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_positioned_layout/Understanding_z-index/Stacking_context
// Some people might have used z-index instead, but best practice is to avoid that if possible, because
// as a site gets complex, Z-fighting can be a huge pain to track down.
Modifier.fillMaxSize().gridRow(1),
horizontalAlignment = Alignment.CenterHorizontally,
) {
NavHeader()
Column(
PageContentStyle.toModifier(),
horizontalAlignment = Alignment.CenterHorizontally
) {
content()
}
}
// Associate the footer with the row that will get pushed off the bottom of the page if it can't fit.
Footer(Modifier.fillMaxWidth().gridRow(2))
}
}
| kobweb-intellij-plugin/sample-projects/app/site/src/jsMain/kotlin/org/example/app/components/layouts/PageLayout.kt | 3324552211 |
package org.example.app.components.widgets
import androidx.compose.runtime.Composable
import com.varabyte.kobweb.compose.ui.Modifier
import com.varabyte.kobweb.compose.ui.modifiers.setVariable
import com.varabyte.kobweb.silk.components.forms.Button
import com.varabyte.kobweb.silk.components.forms.ButtonVars
import org.jetbrains.compose.web.css.em
import org.example.app.CircleButtonVariant
import org.example.app.UncoloredButtonVariant
@Composable
fun IconButton(onClick: () -> Unit, content: @Composable () -> Unit) {
Button(
onClick = { onClick() },
Modifier.setVariable(ButtonVars.FontSize, 1.em), // Make button icon size relative to parent container font size
variant = CircleButtonVariant.then(UncoloredButtonVariant)
) {
content()
}
} | kobweb-intellij-plugin/sample-projects/app/site/src/jsMain/kotlin/org/example/app/components/widgets/IconButton.kt | 1523817677 |
package org.example.app
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import com.varabyte.kobweb.compose.css.ScrollBehavior
import com.varabyte.kobweb.compose.ui.modifiers.minHeight
import com.varabyte.kobweb.compose.ui.modifiers.scrollBehavior
import com.varabyte.kobweb.core.App
import com.varabyte.kobweb.silk.SilkApp
import com.varabyte.kobweb.silk.components.layout.Surface
import com.varabyte.kobweb.silk.components.style.common.SmoothColorStyle
import com.varabyte.kobweb.silk.components.style.toModifier
import com.varabyte.kobweb.silk.init.InitSilk
import com.varabyte.kobweb.silk.init.InitSilkContext
import com.varabyte.kobweb.silk.theme.colors.ColorMode
import kotlinx.browser.localStorage
import org.jetbrains.compose.web.css.vh
private const val COLOR_MODE_KEY = "app:colorMode"
@InitSilk
fun initColorMode(ctx: InitSilkContext) {
ctx.config.initialColorMode = localStorage.getItem(COLOR_MODE_KEY)?.let { ColorMode.valueOf(it) } ?: ColorMode.DARK
}
@App
@Composable
fun AppEntry(content: @Composable () -> Unit) {
SilkApp {
val colorMode = ColorMode.current
LaunchedEffect(colorMode) {
localStorage.setItem(COLOR_MODE_KEY, colorMode.name)
}
Surface(
SmoothColorStyle.toModifier()
.minHeight(100.vh)
.scrollBehavior(ScrollBehavior.Smooth)
) {
content()
}
}
} | kobweb-intellij-plugin/sample-projects/app/site/src/jsMain/kotlin/org/example/app/AppEntry.kt | 3430659577 |
package org.example.app
import com.varabyte.kobweb.compose.ui.graphics.Color
import com.varabyte.kobweb.compose.ui.graphics.Colors
import com.varabyte.kobweb.silk.init.InitSilk
import com.varabyte.kobweb.silk.init.InitSilkContext
import com.varabyte.kobweb.silk.theme.colors.ColorMode
import com.varabyte.kobweb.silk.theme.colors.palette.background
import com.varabyte.kobweb.silk.theme.colors.palette.color
/**
* @property nearBackground A useful color to apply to a container that should differentiate itself from the background
* but just a little.
*/
class SitePalette(
val nearBackground: Color,
val cobweb: Color,
val brand: Brand,
) {
class Brand(
val primary: Color = Color.rgb(0x3C83EF),
val accent: Color = Color.rgb(0xF3DB5B),
)
}
object SitePalettes {
val light = SitePalette(
nearBackground = Color.rgb(0xF4F6FA),
cobweb = Colors.LightGray,
brand = SitePalette.Brand(
primary = Color.rgb(0x3C83EF),
accent = Color.rgb(0xFCBA03),
)
)
val dark = SitePalette(
nearBackground = Color.rgb(0x13171F),
cobweb = Colors.LightGray.inverted(),
brand = SitePalette.Brand(
primary = Color.rgb(0x3C83EF),
accent = Color.rgb(0xF3DB5B),
)
)
}
fun ColorMode.toSitePalette(): SitePalette {
return when (this) {
ColorMode.LIGHT -> SitePalettes.light
ColorMode.DARK -> SitePalettes.dark
}
}
@InitSilk
fun initTheme(ctx: InitSilkContext) {
ctx.theme.palettes.light.background = Color.rgb(0xFAFAFA)
ctx.theme.palettes.light.color = Colors.Black
ctx.theme.palettes.dark.background = Color.rgb(0x06080B)
ctx.theme.palettes.dark.color = Colors.White
}
| kobweb-intellij-plugin/sample-projects/app/site/src/jsMain/kotlin/org/example/app/SiteTheme.kt | 330621933 |
package org.example.app.pages
import androidx.compose.runtime.Composable
import com.varabyte.kobweb.compose.css.StyleVariable
import com.varabyte.kobweb.compose.foundation.layout.Box
import com.varabyte.kobweb.compose.foundation.layout.Column
import com.varabyte.kobweb.compose.foundation.layout.Row
import com.varabyte.kobweb.compose.ui.Modifier
import com.varabyte.kobweb.compose.ui.graphics.Color
import com.varabyte.kobweb.compose.ui.graphics.Colors
import com.varabyte.kobweb.compose.ui.modifiers.*
import com.varabyte.kobweb.compose.ui.toAttrs
import com.varabyte.kobweb.core.Page
import com.varabyte.kobweb.core.rememberPageContext
import com.varabyte.kobweb.silk.components.forms.Button
import com.varabyte.kobweb.silk.components.layout.breakpoint.displayIfAtLeast
import com.varabyte.kobweb.silk.components.navigation.Link
import com.varabyte.kobweb.silk.components.style.ComponentStyle
import com.varabyte.kobweb.silk.components.style.base
import com.varabyte.kobweb.silk.components.style.breakpoint.Breakpoint
import com.varabyte.kobweb.silk.components.style.toAttrs
import com.varabyte.kobweb.silk.components.style.toModifier
import com.varabyte.kobweb.silk.components.text.SpanText
import com.varabyte.kobweb.silk.theme.colors.ColorMode
import com.varabyte.kobweb.silk.theme.colors.ColorSchemes
import org.jetbrains.compose.web.css.*
import org.jetbrains.compose.web.dom.Div
import org.jetbrains.compose.web.dom.Text
import org.example.app.HeadlineTextStyle
import org.example.app.SubheadlineTextStyle
import org.example.app.components.layouts.PageLayout
import org.example.app.toSitePalette
// Container that has a tagline and grid on desktop, and just the tagline on mobile
val HeroContainerStyle by ComponentStyle {
base { Modifier.fillMaxWidth().gap(2.cssRem) }
Breakpoint.MD { Modifier.margin { top(20.vh) } }
}
// A demo grid that appears on the homepage because it looks good
val HomeGridStyle by ComponentStyle.base {
Modifier
.gap(0.5.cssRem)
.width(70.cssRem)
.height(18.cssRem)
}
private val GridCellColorVar by StyleVariable<Color>()
val HomeGridCellStyle by ComponentStyle.base {
Modifier
.backgroundColor(GridCellColorVar.value())
.boxShadow(blurRadius = 0.6.cssRem, color = GridCellColorVar.value())
.borderRadius(1.cssRem)
}
@Composable
private fun GridCell(color: Color, row: Int, column: Int, width: Int? = null, height: Int? = null) {
Div(
HomeGridCellStyle.toModifier()
.setVariable(GridCellColorVar, color)
.gridItem(row, column, width, height)
.toAttrs()
)
}
@Page
@Composable
fun HomePage() {
PageLayout("Home") {
Row(HeroContainerStyle.toModifier()) {
Box {
val sitePalette = ColorMode.current.toSitePalette()
Column(Modifier.gap(2.cssRem)) {
Div(HeadlineTextStyle.toAttrs()) {
SpanText(
"Use this template as your starting point for ", Modifier.color(
when (ColorMode.current) {
ColorMode.LIGHT -> Colors.Black
ColorMode.DARK -> Colors.White
}
)
)
SpanText(
"Kobweb",
Modifier
.color(sitePalette.brand.accent)
// Use a shadow so this light-colored word is more visible in light mode
.textShadow(0.px, 0.px, blurRadius = 0.5.cssRem, color = Colors.Gray)
)
}
Div(SubheadlineTextStyle.toAttrs()) {
SpanText("You can read the ")
Link("/about", "About")
SpanText(" page for more information.")
}
val ctx = rememberPageContext()
Button(onClick = {
// Change this click handler with your call-to-action behavior
// here. Link to an order page? Open a calendar UI? Play a movie?
// Up to you!
ctx.router.tryRoutingTo("/about")
}, colorScheme = ColorSchemes.Blue) {
Text("This could be your CTA")
}
}
}
Div(HomeGridStyle
.toModifier()
.displayIfAtLeast(Breakpoint.MD)
.grid {
rows { repeat(3) { size(1.fr) } }
columns { repeat(5) {size(1.fr) } }
}
.toAttrs()
) {
val sitePalette = ColorMode.current.toSitePalette()
GridCell(sitePalette.brand.primary, 1, 1, 2, 2)
GridCell(ColorSchemes.Monochrome._600, 1, 3)
GridCell(ColorSchemes.Monochrome._100, 1, 4, width = 2)
GridCell(sitePalette.brand.accent, 2, 3, width = 2)
GridCell(ColorSchemes.Monochrome._300, 2, 5)
GridCell(ColorSchemes.Monochrome._800, 3, 1, width = 5)
}
}
}
}
| kobweb-intellij-plugin/sample-projects/app/site/src/jsMain/kotlin/org/example/app/pages/Index.kt | 2020385620 |
package io.github.gmazzo.android.manifest.lock.demo
import android.app.Activity
class MainActivity : Activity()
| gradle-android-manifest-lock-plugin/demo/src/main/kotlin/io/github/gmazzo/android/manifest/lock/demo/MainActivity.kt | 3508177154 |
package io.github.gmazzo.android.manifest.lock
import io.github.gmazzo.android.manifest.lock.Manifest.Entry
import org.junit.jupiter.api.Assertions.assertEquals
import kotlin.test.Test
class ManifestLockFactoryTest {
private val main = Manifest(
namespace = "org.test.app",
minSDK = 14,
targetSDK = 34,
permissions = listOf(
Entry("permission1"),
Entry("permission2", mapOf("required" to "true")),
Entry("permission2", mapOf("required" to "true", "until" to "30")),
),
features = listOf(
Entry("feature1"),
Entry("feature2", mapOf("required" to "true")),
Entry(attributes = mapOf("custom" to "1")),
),
libraries = listOf(
Entry("lib1"),
Entry("lib2", mapOf("required" to "true")),
),
exports = mapOf(
"activity" to setOf("export1"),
"service" to setOf("export2"),
)
)
@Test
fun `when all manifests are the same`() {
val lock = ManifestLockFactory.create(
mapOf(
"debug" to main,
"release" to main,
)
)
assertEquals(
"""
main:
namespace: org.test.app
minSDK: 14
targetSDK: 34
permissions:
- permission1
- permission2:
required: true
- permission2:
required: true
until: 30
features:
- feature1
- feature2:
required: true
- custom: 1
libraries:
- lib1
- lib2:
required: true
exports:
activity:
- export1
service:
- export2
fingerprint: 119f92fb3493aeaaadffb717199050e7
""".trimIndent(),
lock.content
)
}
@Test
fun `when one varies on package`() {
val lock = ManifestLockFactory.create(
mapOf(
"debug" to main,
"release" to main.copy(namespace = "org.test.app.release"),
)
)
assertEquals(
"""
main:
minSDK: 14
targetSDK: 34
permissions:
- permission1
- permission2:
required: true
- permission2:
required: true
until: 30
features:
- feature1
- feature2:
required: true
- custom: 1
libraries:
- lib1
- lib2:
required: true
exports:
activity:
- export1
service:
- export2
variants:
debug:
namespace: org.test.app
release:
namespace: org.test.app.release
fingerprint: 8b4b97542b3e84216505ddb6161610d4
""".trimIndent(),
lock.content
)
}
@Test
fun `when many has differences`() {
val lock = ManifestLockFactory.create(
mapOf(
"debug" to main.copy(
minSDK = 10,
features = main.features!! + Entry("feature2", mapOf("required" to "false")) + Entry("debugFeature1"),
exports = mapOf("activity" to main.exports!!["activity"]!! + "debugExport1") + main.exports.filterKeys { it != "activity" },
),
"release" to main.copy(
namespace = "org.test.app.release",
permissions = main.permissions!! + Entry("releasePermission1"),
features = main.features + Entry("releaseFeature1" , mapOf("required" to "true")),
libraries = main.libraries!! + Entry("releaseLib1"),
),
)
)
assertEquals(
"""
main:
targetSDK: 34
permissions:
- permission1
- permission2:
required: true
- permission2:
required: true
until: 30
features:
- feature1
- feature2:
required: true
- custom: 1
libraries:
- lib1
- lib2:
required: true
exports:
activity:
- export1
service:
- export2
variants:
debug:
namespace: org.test.app
minSDK: 10
features:
- feature2:
required: false
- debugFeature1
exports:
activity:
- debugExport1
release:
namespace: org.test.app.release
minSDK: 14
permissions:
- releasePermission1
features:
- releaseFeature1:
required: true
libraries:
- releaseLib1
fingerprint: 575faf711192e7fe52f7e0577e81e574
""".trimIndent(),
lock.content
)
}
} | gradle-android-manifest-lock-plugin/plugin/src/test/kotlin/io/github/gmazzo/android/manifest/lock/ManifestLockFactoryTest.kt | 4293744944 |
package io.github.gmazzo.android.manifest.lock
import org.gradle.kotlin.dsl.apply
import org.gradle.testfixtures.ProjectBuilder
import kotlin.test.Test
import kotlin.test.assertNotNull
class AndroidManifestLockPluginTest {
@Test
fun `plugin applies correctly on application`() =
`plugin applies correctly`("com.android.application")
@Test
fun `plugin applies correctly on library`() =
`plugin applies correctly`("com.android.library")
private fun `plugin applies correctly`(androidPlugin: String) {
val project = ProjectBuilder.builder().build()
project.apply(plugin = androidPlugin)
project.apply(plugin = "io.github.gmazzo.android.manifest.lock")
assertNotNull(project.tasks.findByName("androidManifestLock"))
}
}
| gradle-android-manifest-lock-plugin/plugin/src/test/kotlin/io/github/gmazzo/android/manifest/lock/AndroidManifestLockPluginTest.kt | 3315640610 |
package io.github.gmazzo.android.manifest.lock
import io.github.gmazzo.android.manifest.lock.Manifest.Entry
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
import java.io.File
class ManifestReaderTest {
@Test
fun `parses a manifest correctly`() {
val source = File(javaClass.getResource("/AndroidManifest.xml")!!.file)
val parsed = ManifestReader.parse(source)
assertEquals("io.github.gmazzo.android.manifest.lock.test", parsed.namespace)
assertEquals(24, parsed.minSDK)
assertEquals(34, parsed.targetSDK)
assertEquals(
listOf(
Entry("android.permission.ACCESS_COARSE_LOCATION"),
Entry("android.permission.ACCESS_FINE_LOCATION"),
Entry("android.permission.ACCESS_NETWORK_STATE"),
Entry("android.permission.ACCESS_WIFI_STATE"),
Entry("android.permission.CALL_PHONE", mapOf("required" to "false")),
Entry("android.permission.CAMERA", mapOf("required" to "false")),
Entry("android.permission.DETECT_SCREEN_CAPTURE"),
Entry("android.permission.FOREGROUND_SERVICE"),
Entry("android.permission.FOREGROUND_SERVICE_MEDIA_PROJECTION"),
Entry("android.permission.INTERNET"),
Entry("android.permission.MODIFY_AUDIO_SETTINGS"),
Entry("android.permission.POST_NOTIFICATIONS"),
Entry("android.permission.READ_CONTACTS"),
Entry("android.permission.READ_EXTERNAL_STORAGE", mapOf("maxSdkVersion" to "32")),
Entry("android.permission.READ_MEDIA_IMAGES"),
Entry("android.permission.READ_MEDIA_VIDEO"),
Entry("android.permission.RECEIVE_BOOT_COMPLETED"),
Entry("android.permission.RECORD_AUDIO"),
Entry("android.permission.REORDER_TASKS"),
Entry("android.permission.VIBRATE"),
Entry("android.permission.WAKE_LOCK"),
Entry("android.permission.WRITE_EXTERNAL_STORAGE", mapOf("maxSdkVersion" to "28")),
Entry("com.google.android.c2dm.permission.RECEIVE"),
Entry("com.google.android.finsky.permission.BIND_GET_INSTALL_REFERRER_SERVICE"),
Entry("com.google.android.providers.gsf.permission.READ_GSERVICES")
), parsed.permissions
)
assertEquals(
listOf(
Entry(attributes = mapOf("glEsVersion" to "0x00020000", "required" to "true")),
Entry("android.hardware.camera", mapOf("required" to "false")),
Entry("android.hardware.camera.autofocus", mapOf("required" to "false")),
Entry("android.hardware.telephony", mapOf("required" to "false")),
), parsed.features
)
assertEquals(
listOf(
Entry("android.ext.adservices", mapOf("required" to "false")),
Entry("androidx.window.extensions", mapOf("required" to "false")),
Entry("androidx.window.sidecar", mapOf("required" to "false")),
Entry("org.apache.http.legacy", mapOf("required" to "false")),
), parsed.libraries
)
assertEquals(
mapOf(
"activity" to setOf(
"com.testapp.onboarding.splash.SplashActivity",
"com.testapp.payments.core.processout.ProcessOutCallbackActivity"
),
"service" to setOf("androidx.work.impl.background.systemjob.SystemJobService"),
"receiver" to setOf("androidx.work.impl.diagnostics.DiagnosticsReceiver"),
), parsed.exports
)
}
}
| gradle-android-manifest-lock-plugin/plugin/src/test/kotlin/io/github/gmazzo/android/manifest/lock/ManifestReaderTest.kt | 2661666126 |
package io.github.gmazzo.android.manifest.lock
import org.w3c.dom.Node
import org.w3c.dom.NodeList
import java.io.File
import javax.xml.namespace.NamespaceContext
import javax.xml.parsers.DocumentBuilderFactory
import javax.xml.xpath.XPathConstants
import javax.xml.xpath.XPathExpression
import javax.xml.xpath.XPathFactory
internal object ManifestReader {
private const val ANDROID_NS = "http://schemas.android.com/apk/res/android"
private val docBuilderFactory = DocumentBuilderFactory.newInstance()
.apply { isNamespaceAware = true }
private val xPath = XPathFactory.newInstance().newXPath().apply { namespaceContext = AndroidNamespaceContext }
private val getPackageName = xPath.compile("/manifest/@package")
private val getMinSDK = xPath.compile("/manifest/uses-sdk/@android:minSdkVersion")
private val getTargetSDK = xPath.compile("/manifest/uses-sdk/@android:targetSdkVersion")
private val getPermissions = xPath.compile("/manifest/uses-permission")
private val getFeatures = xPath.compile("/manifest/uses-feature")
private val getLibraries = xPath.compile("/manifest/application/uses-library")
private val getExports = xPath.compile("//*[@android:exported='true']")
fun parse(manifest: File): Manifest {
val source = docBuilderFactory.newDocumentBuilder().parse(manifest)
val packageName = getPackageName.evaluate(source).takeUnless { it.isBlank() }
val minSDK = getMinSDK.evaluate(source).toIntOrNull()
val targetSDK = getTargetSDK.evaluate(source).toIntOrNull()
val permissions = getPermissions.collectEntries(source)
val features = getFeatures.collectEntries(source)
val libraries = getLibraries.collectEntries(source)
val exports = getExports.collect(source)
.groupingBy { it.nodeName }
.fold(emptySet<String>()) { acc, node -> acc + node.attributes.getNamedItemNS(ANDROID_NS, "name").nodeValue }
return Manifest(packageName, minSDK, targetSDK, permissions, features, libraries, exports)
}
private fun XPathExpression.collect(source: Any): Sequence<Node> {
val items = evaluate(source, XPathConstants.NODESET) as NodeList
return (0 until items.length).asSequence().map(items::item)
}
private fun XPathExpression.collectEntries(source: Any): List<Manifest.Entry>? = collect(source)
.map { node ->
val attrs = (0 until node.attributes.length).asSequence()
.map(node.attributes::item)
.filter { it.namespaceURI == ANDROID_NS }
.map { it.localName to it.nodeValue }
.toMap(linkedMapOf())
val name = attrs.remove("name")
Manifest.Entry(name, attrs.takeUnless { it.isEmpty() })
}
.toList()
.sortedBy { it.name }
.takeUnless { it.isEmpty() }
private object AndroidNamespaceContext : NamespaceContext {
override fun getNamespaceURI(prefix: String?) = when (prefix) {
"android" -> ANDROID_NS
else -> null
}
override fun getPrefix(namespaceURI: String?) = when (namespaceURI) {
ANDROID_NS -> "android"
else -> null
}
override fun getPrefixes(namespaceURI: String?) =
throw UnsupportedOperationException()
}
}
| gradle-android-manifest-lock-plugin/plugin/src/main/kotlin/io/github/gmazzo/android/manifest/lock/ManifestReader.kt | 2495640988 |
package io.github.gmazzo.android.manifest.lock
import org.gradle.api.file.RegularFileProperty
import org.gradle.api.provider.Property
@JvmDefaultWithoutCompatibility
interface AndroidManifestLockExtension {
/**
* The location of the generated lock file.
*
* Defaults to `src/main/AndroidManifest.lock`
*/
val lockFile: RegularFileProperty
/**
* The build will fail if the [lockFile] has changed based on the current manifest inputs.
*
* If the file does not exist already, it will be created, sill failing.
*
* Defaults to `false`
*/
val failOnLockChange: Property<Boolean>
}
| gradle-android-manifest-lock-plugin/plugin/src/main/kotlin/io/github/gmazzo/android/manifest/lock/AndroidManifestLockExtension.kt | 2555014141 |
package io.github.gmazzo.android.manifest.lock
import com.android.build.api.artifact.SingleArtifact
import com.android.build.api.variant.AndroidComponentsExtension
import com.android.build.gradle.BaseExtension
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.file.RegularFile
import org.gradle.api.plugins.ExtensionAware
import org.gradle.api.provider.Provider
import org.gradle.kotlin.dsl.create
import org.gradle.kotlin.dsl.getValue
import org.gradle.kotlin.dsl.mapProperty
import org.gradle.kotlin.dsl.provideDelegate
import org.gradle.kotlin.dsl.register
import java.io.File
class AndroidManifestLockPlugin : Plugin<Project> {
override fun apply(project: Project) = project.plugins.withId("com.android.base") {
val android: BaseExtension by project.extensions
val androidComponents: AndroidComponentsExtension<*, *, *> by project.extensions
val manifest = android.sourceSets.named("main").map { it.manifest.srcFile }
val manifests = project.objects.mapProperty<String, RegularFile>()
androidComponents.onVariants(androidComponents.selector().all()) {
manifests.put(
it.name,
it.artifacts.get(SingleArtifact.MERGED_MANIFEST),
)
}
val extension = project.createExtension(android, manifest)
val lockTask = project.tasks.register<AndroidManifestLockTask>("androidManifestLock") {
variantManifests.set(manifests)
lockFile.set(extension.lockFile)
failOnLockChange.set(extension.failOnLockChange)
}
project.tasks.named("check") {
dependsOn(lockTask)
}
}
private fun Project.createExtension(android: BaseExtension, manifest: Provider<File>) = (android as ExtensionAware)
.extensions
.create<AndroidManifestLockExtension>("manifestLock")
.apply {
lockFile
.convention(manifest.map { file ->
val lock = file.resolveSibling("${file.nameWithoutExtension}.lock.yaml")
layout.projectDirectory.file(lock.path)
})
.finalizeValueOnRead()
failOnLockChange
.convention(false)
.finalizeValueOnRead()
}
}
| gradle-android-manifest-lock-plugin/plugin/src/main/kotlin/io/github/gmazzo/android/manifest/lock/AndroidManifestLockPlugin.kt | 3199181616 |
package io.github.gmazzo.android.manifest.lock
import io.github.gmazzo.android.manifest.lock.ManifestLockFactory.yaml
import kotlinx.serialization.Serializable
import kotlinx.serialization.encodeToString
import org.gradle.kotlin.dsl.provideDelegate
@Serializable
internal data class ManifestLock(
val main: Manifest,
val variants: Map<String, Manifest>? = null,
val fingerprint: String,
) {
val content: String by lazy { yaml.encodeToString(this) + "\n" }
}
| gradle-android-manifest-lock-plugin/plugin/src/main/kotlin/io/github/gmazzo/android/manifest/lock/ManifestLock.kt | 2101290216 |
package io.github.gmazzo.android.manifest.lock
import kotlinx.serialization.Serializable
@Serializable
internal data class Manifest(
val namespace: String? = null,
val minSDK: Int? = null,
val targetSDK: Int? = null,
val permissions: List<Entry>? = null,
val features: List<Entry>? = null,
val libraries: List<Entry>? = null,
val exports: Map<String, Set<String>>? = null,
) {
@Serializable(with = ManifestEntrySerializer::class)
data class Entry(val name: String? = null, val attributes: Map<String, String>? = null)
}
| gradle-android-manifest-lock-plugin/plugin/src/main/kotlin/io/github/gmazzo/android/manifest/lock/Manifest.kt | 3079225121 |
package io.github.gmazzo.android.manifest.lock
import org.gradle.api.DefaultTask
import org.gradle.api.file.RegularFile
import org.gradle.api.file.RegularFileProperty
import org.gradle.api.provider.MapProperty
import org.gradle.api.provider.Property
import org.gradle.api.tasks.CacheableTask
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.InputFiles
import org.gradle.api.tasks.Internal
import org.gradle.api.tasks.OutputFile
import org.gradle.api.tasks.PathSensitive
import org.gradle.api.tasks.PathSensitivity
import org.gradle.api.tasks.TaskAction
@CacheableTask
abstract class AndroidManifestLockTask : DefaultTask() {
@get:Internal
abstract val variantManifests: MapProperty<String, RegularFile>
@get:InputFiles
@get:PathSensitive(PathSensitivity.NONE)
@Suppress("LeakingThis", "unused")
internal val variantManifestsFiles =
variantManifests.map { it.values }
@get:OutputFile
abstract val lockFile: RegularFileProperty
@get:Input
abstract val failOnLockChange: Property<Boolean>
private val rootDir = project.rootDir
@TaskAction
fun generateLock() {
val manifests = variantManifests.get()
.mapValues { (_, manifest) -> ManifestReader.parse(manifest.asFile) }
val lock = ManifestLockFactory.create(manifests)
val file = lockFile.get().asFile
val content = file.takeIf { it.exists() }?.readText()
if (content != lock.content) {
file.writeText(lock.content)
val message = "${file.toRelativeString(rootDir)} has changed, please commit the updated lock file"
if (failOnLockChange.get()) error(message) else logger.warn(message)
}
}
}
| gradle-android-manifest-lock-plugin/plugin/src/main/kotlin/io/github/gmazzo/android/manifest/lock/AndroidManifestLockTask.kt | 3162438888 |
package io.github.gmazzo.android.manifest.lock
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.Serializer
import kotlinx.serialization.builtins.MapSerializer
import kotlinx.serialization.builtins.serializer
import kotlinx.serialization.encoding.Encoder
@OptIn(ExperimentalSerializationApi::class)
@Serializer(forClass = Manifest.Entry::class)
internal object ManifestEntrySerializer {
private val nameSerializer = String.serializer()
private val attrsSerializer = MapSerializer(String.serializer(), String.serializer())
private val complexSerializer = MapSerializer(String.serializer(), attrsSerializer)
override fun serialize(encoder: Encoder, value: Manifest.Entry) {
when (value.name) {
null -> value.attributes?.let { attrsSerializer.serialize(encoder, it) }
else -> when (value.attributes.isNullOrEmpty()) {
true -> nameSerializer.serialize(encoder, value.name)
else -> complexSerializer.serialize(encoder, mapOf(value.name to value.attributes))
}
}
}
}
| gradle-android-manifest-lock-plugin/plugin/src/main/kotlin/io/github/gmazzo/android/manifest/lock/ManifestEntrySerializer.kt | 2912816556 |
package io.github.gmazzo.android.manifest.lock
import com.charleskorn.kaml.SingleLineStringStyle
import com.charleskorn.kaml.Yaml
import com.charleskorn.kaml.YamlConfiguration
import com.charleskorn.kaml.encodeToStream
import java.io.ByteArrayOutputStream
import java.security.MessageDigest
internal object ManifestLockFactory {
val yaml = Yaml(
configuration = YamlConfiguration(
encodeDefaults = false,
singleLineStringStyle = SingleLineStringStyle.Plain,
),
)
private val emptyManifest =
Manifest(null, null, null, null, null, null, null)
fun create(manifests: Map<String, Manifest>): ManifestLock {
val main = computeMain(manifests.values.asSequence())
val variants = computeVariants(main, manifests)
val fingerprint = computeFingerprint(main, manifests)
return ManifestLock(main, variants, fingerprint)
}
private fun computeMain(manifests: Sequence<Manifest>): Manifest {
val namespace = manifests.mapNotNull(Manifest::namespace).sameOrNull()
val minSDK = manifests.mapNotNull(Manifest::minSDK).sameOrNull()
val targetSDK = manifests.mapNotNull(Manifest::targetSDK).sameOrNull()
val permissions = manifests.mapNotNull(Manifest::permissions).onlySame()
val features = manifests.mapNotNull(Manifest::features).onlySame()
val libraries = manifests.mapNotNull(Manifest::libraries).onlySame()
val exports = manifests.mapNotNull(Manifest::exports)
.reduceOrNull { acc, it -> acc.mapValues { (type, names) -> names.intersect(it[type].orEmpty()) } }
?.withoutEmpties()
return Manifest(namespace, minSDK, targetSDK, permissions, features, libraries, exports)
}
private fun <Type> Sequence<Type?>.sameOrNull() = this
.reduceOrNull { acc, it -> if (acc == it) acc else null }
private fun <Type> Sequence<Iterable<Type>>.onlySame() = this
.map { it.toSet() }
.reduceOrNull { acc, it -> acc.intersect(it) }
?.toList()
private fun computeVariants(main: Manifest, manifests: Map<String, Manifest>) =
manifests.entries.asSequence().mapNotNull { (variant, m) ->
when (val reduced = m.copy(
namespace = m.namespace.takeIf { it != main.namespace },
minSDK = m.minSDK.takeIf { it != main.minSDK },
targetSDK = m.targetSDK.takeIf { it != main.targetSDK },
permissions = m.permissions?.without(main.permissions),
features = m.features?.without(main.features),
libraries = m.libraries?.without(main.libraries),
exports = m.exports.orEmpty()
.mapValues { (type, names) -> names - main.exports?.get(type).orEmpty() }
.withoutEmpties(),
)) {
emptyManifest -> null
else -> variant to reduced
}
}.toMap().takeUnless { it.isEmpty() }
private fun List<Manifest.Entry>.without(other: List<Manifest.Entry>?) = when (other) {
null -> this
else -> this - other.toSet()
}.takeUnless { it.isEmpty() }
private fun Map<String, Set<String>>.withoutEmpties() = this
.filterValues { it.isNotEmpty() }
.takeUnless { it.isEmpty() }
private fun computeFingerprint(main: Manifest, variants: Map<String, Manifest>): String {
val content = with(ByteArrayOutputStream()) {
yaml.encodeToStream(main, this)
yaml.encodeToStream(variants, this)
toByteArray()
}
val md5 = MessageDigest.getInstance("MD5")
return md5.digest(content).joinToString(separator = "") { "%02x".format(it) }
}
}
| gradle-android-manifest-lock-plugin/plugin/src/main/kotlin/io/github/gmazzo/android/manifest/lock/ManifestLockFactory.kt | 3877234974 |
package com.example.randomdogs
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.randomdogs", appContext.packageName)
}
} | RandomDogs-android/app/src/androidTest/java/com/example/randomdogs/ExampleInstrumentedTest.kt | 2761326574 |
package com.example.randomdogs
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)
}
} | RandomDogs-android/app/src/test/java/com/example/randomdogs/ExampleUnitTest.kt | 2974667598 |
package com.example.randomdogs
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}
| RandomDogs-android/app/src/main/java/com/example/randomdogs/MainActivity.kt | 2545683413 |
package com.example.randomdogs
import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.navigation.navGraphViewModels
import coil.load
import com.example.randomdogs.databinding.FragmentDogBinding
import kotlinx.coroutines.launch
class DogFragment : Fragment(R.layout.fragment_dog) {
private val viewModel by navGraphViewModels<DogViewModel>(R.id.main_graph)
private var _binding: FragmentDogBinding? = null
private val binding: FragmentDogBinding
get() = _binding ?: FragmentDogBinding.bind(requireView()).also { _binding = it }
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
lifecycleScope.launch {
viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.CREATED) {
viewModel.dogImage.collect {
binding.imageView.load(it)
}
}
}
loadImage()
binding.anotherDogButton.setOnClickListener {
loadImage()
}
}
override fun onDestroyView() {
_binding = null
super.onDestroyView()
}
private fun loadImage() = viewModel.fetchNewImage()
} | RandomDogs-android/app/src/main/java/com/example/randomdogs/DogFragment.kt | 646772757 |
package com.example.randomdogs
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.compose.material3.MaterialTheme
import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.platform.ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import com.example.randomdogs.screen.DogScreen
class DogComposeFragment : Fragment() {
private val viewModel by activityViewModels<DogViewModel>()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
) = ComposeView(requireContext()).apply {
id = View.generateViewId()
setViewCompositionStrategy(DisposeOnViewTreeLifecycleDestroyed)
setContent {
MaterialTheme {
DogScreen(urlState = viewModel.dogImage) {
viewModel.fetchNewImage()
}
}
}
}
} | RandomDogs-android/app/src/main/java/com/example/randomdogs/DogComposeFragment.kt | 1001470784 |
package com.example.randomdogs
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.compose.material3.MaterialTheme
import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.platform.ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import com.example.randomdogs.screen.LayoutChoice
import com.example.randomdogs.screen.LayoutChoiceScreen
class LayoutDecisionFragment : Fragment() {
private val onLayoutChoice = { it: LayoutChoice ->
val navId = when (it) {
LayoutChoice.Compose -> R.id.dog_screen_compose
LayoutChoice.Xml -> R.id.dog_screen_xml
}
findNavController().navigate(navId)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
) = ComposeView(requireContext()).apply {
id = View.generateViewId()
setViewCompositionStrategy(DisposeOnViewTreeLifecycleDestroyed)
setContent {
MaterialTheme {
LayoutChoiceScreen(onChoice = onLayoutChoice)
}
}
}
} | RandomDogs-android/app/src/main/java/com/example/randomdogs/LayoutDecisionFragment.kt | 1645430491 |
package com.example.randomdogs.network
import com.example.randomdogs.data.RandomDogDataModel
import io.ktor.client.HttpClient
import io.ktor.client.call.body
import io.ktor.client.engine.okhttp.OkHttp
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
import io.ktor.client.request.get
import io.ktor.serialization.kotlinx.json.json
import kotlinx.serialization.json.Json
class ApiInterface {
companion object {
private const val BASE_URL = "https://dog.ceo/api"
}
private val client by lazy {
HttpClient(OkHttp) {
expectSuccess = true
install(ContentNegotiation) {
json(Json {
ignoreUnknownKeys = true
})
}
}
}
suspend fun fetchDogImage() =
client.get("$BASE_URL/breeds/image/random").body<RandomDogDataModel>()
} | RandomDogs-android/app/src/main/java/com/example/randomdogs/network/ApiInterface.kt | 665416765 |
package com.example.randomdogs.network
class ApiProvider {
companion object {
val apiClient: ApiInterface by lazy { ApiInterface() }
}
} | RandomDogs-android/app/src/main/java/com/example/randomdogs/network/ApiClient.kt | 3395625730 |
package com.example.randomdogs.screen
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage
import coil.compose.rememberAsyncImagePainter
import com.example.randomdogs.R
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flowOf
@Composable
fun DogScreen(modifier: Modifier = Modifier, urlState: Flow<String>, fetchNewImage: () -> Unit) {
val url by urlState.collectAsState(initial = "")
LaunchedEffect(Unit) { fetchNewImage() }
Surface {
Column(
modifier = modifier
.fillMaxSize()
.padding(vertical = 16.dp),
verticalArrangement = Arrangement.SpaceBetween,
horizontalAlignment = Alignment.CenterHorizontally
) {
AsyncImage(
model = url,
contentDescription = "image of dog",
modifier = Modifier.fillMaxSize(fraction = 0.9f)
)
OutlinedButton(onClick = { fetchNewImage() }) {
Text(text = stringResource(id = R.string.another_random_dog))
}
}
}
}
@Preview
@Composable
fun PreviewDogScreen() {
DogScreen(urlState = flowOf("https://uploads.dailydot.com/2018/10/olli-the-polite-cat.jpg?auto=compress&fm=pjpg")) {
println("asked to fetch new image")
}
} | RandomDogs-android/app/src/main/java/com/example/randomdogs/screen/DogScreen.kt | 1828819 |
package com.example.randomdogs.screen
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.randomdogs.R
enum class LayoutChoice {
Compose,
Xml;
}
@Composable
fun LayoutChoiceScreen(modifier: Modifier = Modifier, onChoice: (LayoutChoice) -> Unit) {
Surface {
Column(
modifier = modifier
.fillMaxSize()
.background(Color.White),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally,
) {
OutlinedButton(onClick = { onChoice(LayoutChoice.Xml) }) {
Text(text = stringResource(id = R.string.xml_based))
}
Spacer(modifier = Modifier.height(16.dp))
OutlinedButton(onClick = { onChoice(LayoutChoice.Compose) }) {
Text(text = stringResource(id = R.string.compose_based))
}
}
}
}
@Preview
@Composable
fun PreviewLayoutChoiceScreen() {
LayoutChoiceScreen(onChoice = { println("Choice $it") })
} | RandomDogs-android/app/src/main/java/com/example/randomdogs/screen/LayoutChoiceScreen.kt | 2562393238 |
package com.example.randomdogs.data
import kotlinx.serialization.Serializable
@Serializable
data class RandomDogDataModel(val message: String, val status: String) | RandomDogs-android/app/src/main/java/com/example/randomdogs/data/RandomDogDataModel.kt | 492476324 |
package com.example.randomdogs
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.randomdogs.network.ApiInterface
import com.example.randomdogs.network.ApiProvider
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.launch
class DogViewModel : ViewModel() {
private val service: ApiInterface by lazy { ApiProvider.apiClient }
var dogImage = MutableSharedFlow<String>(replay = 1)
fun fetchNewImage() = viewModelScope.launch {
val message = service.fetchDogImage().message
dogImage.tryEmit(message)
}
}
| RandomDogs-android/app/src/main/java/com/example/randomdogs/DogViewModel.kt | 804336114 |
package com.example.projectmanagment
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.projectmanagment", appContext.packageName)
}
} | Project_Management/app/src/androidTest/java/com/example/projectmanagment/ExampleInstrumentedTest.kt | 19298889 |
package com.example.projectmanagment
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)
}
} | Project_Management/app/src/test/java/com/example/projectmanagment/ExampleUnitTest.kt | 4009923021 |
package com.example.projectmanagment
import android.app.Application
import android.content.Context
class MyApp : Application() {
override fun onCreate() {
super.onCreate()
val sharedPreferences = applicationContext.getSharedPreferences("MyPrefs", Context.MODE_PRIVATE)
}
} | Project_Management/app/src/main/java/com/example/projectmanagment/MyApp.kt | 209102483 |
package com.example.projectmanagment.Conference
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.example.projectmanagment.R
import com.example.projectmanagment.Storage.SharedData
import com.example.projectmanagment.Todo
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.zegocloud.uikit.prebuilt.videoconference.ZegoUIKitPrebuiltVideoConferenceConfig
import com.zegocloud.uikit.prebuilt.videoconference.ZegoUIKitPrebuiltVideoConferenceFragment
class Meet : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(R.layout.activity_meet)
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.fragment_container)) { v, insets ->
val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
insets
}
addFragment()
val btmnav = findViewById<BottomNavigationView>(R.id.bottom_navigation)
btmnav.selectedItemId = R.id.item_2
btmnav.setOnItemSelectedListener { item ->
when (item.itemId) {
R.id.item_1 -> {
startActivity(Intent(this, SharedData::class.java))
finish()
true
}
R.id.item_2 -> {
Toast.makeText(this, "Already There", Toast.LENGTH_SHORT).show()
true
}
R.id.item_3 -> {
startActivity(Intent(this, Todo::class.java))
finish()
true
}
else -> false
}
}
}
fun addFragment() {
val appID : Long = 1724648990
val appSign: String = "5b5cfa238e3b7b3e4a544579cb4cf826a76a8710a9f876a8c5d81cdff13fe790"
val conferenceID = 123456
val sharedPreferences = applicationContext.getSharedPreferences("MyPrefs", Context.MODE_PRIVATE)
val userID = 5454554
val userName = "Chandan"
val config = ZegoUIKitPrebuiltVideoConferenceConfig()
val fragment = ZegoUIKitPrebuiltVideoConferenceFragment.newInstance(appID, appSign,
userID.toString(), userName, conferenceID.toString(), config)
supportFragmentManager.beginTransaction()
.replace(R.id.meetFragment, fragment)
.addToBackStack("MeetFragment")
.commit()
}
} | Project_Management/app/src/main/java/com/example/projectmanagment/Conference/Meet.kt | 1489603457 |
package com.example.projectmanagment.Projects
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.projectmanagment.GlobalData
import com.example.projectmanagment.R
import com.example.projectmanagment.Storage.SharedData
import com.example.projectmanagment.UserData.Login
import com.example.projectmanagment.databinding.ActivityMainBinding
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
import com.google.firebase.firestore.FirebaseFirestore
import kotlin.random.Random
class MainActivity : AppCompatActivity() {
lateinit var binding: ActivityMainBinding
private lateinit var projectsArrayList : ArrayList<Projects>
private lateinit var projName : ArrayList<String>
private lateinit var projId : ArrayList<Int>
private lateinit var auth: FirebaseAuth
private lateinit var database: FirebaseDatabase
private lateinit var uid: String
private val rotateOpen : Animation by lazy { AnimationUtils.loadAnimation(this, R.anim.rotate_open_anim) }
private val rotateClose : Animation by lazy { AnimationUtils.loadAnimation(this, R.anim.rotate_close_anim) }
private val fromBottom : Animation by lazy { AnimationUtils.loadAnimation(this, R.anim.from_bottom_anim) }
private val toBottom : Animation by lazy { AnimationUtils.loadAnimation(this, R.anim.to_bottom_anim) }
private var clicked = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
insets
}
val sharedPreferences = applicationContext.getSharedPreferences("MyPrefs", MODE_PRIVATE)
// Initialize Firebase components
auth = FirebaseAuth.getInstance()
database = FirebaseDatabase.getInstance()
uid = auth.currentUser?.uid ?: ""
binding.btnLogout.setOnClickListener {
signOut()
navigateToLogin()
}
projectsArrayList = ArrayList()
projName = ArrayList()
projId = ArrayList()
binding.rvProjects.layoutManager = LinearLayoutManager(this)
binding.rvProjects.setHasFixedSize(true)
binding.rvProjects.adapter = ProjectsAdapter(projectsArrayList)
getdata()
binding.btnAdd.setOnClickListener {
onAddButtonClicked()
}
binding.btnAddProject1.setOnClickListener {
binding.cvCreateProject.visibility = View.VISIBLE
Toast.makeText(this, "Add Project", Toast.LENGTH_SHORT).show()
toAddProject()
}
binding.btnJoinProject1.setOnClickListener {
toJoinProject()
}
}
private fun getdata() {
val database = FirebaseDatabase.getInstance()
val myRef = database.getReference(uid)
myRef.addListenerForSingleValueEvent(object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
projectsArrayList.clear()
if (dataSnapshot.exists() && dataSnapshot.hasChildren()) {
for (projectSnapshot in dataSnapshot.children) {
val projName =
projectSnapshot.child("projectTitle").getValue(String::class.java)
val projCode =
projectSnapshot.child("projectCode").getValue(Int::class.java)
if (projName != null && projCode != null) {
projectsArrayList.add(Projects(projName, projCode))
}
}
val adapter = ProjectsAdapter(projectsArrayList)
binding.rvProjects.adapter = adapter
adapter.notifyDataSetChanged()
} else {
println("No projects found.")
}
}
override fun onCancelled(databaseError: DatabaseError) {
// Handle errors here
println("Database Error: ${databaseError.message}")
}
})
}
private fun toJoinProject() {
clicked = !clicked
if (!clicked) {
binding.cvJoinProject.isClickable = true
binding.cvJoinProject.visibility = View.VISIBLE
binding.btnJoin2.setOnClickListener {
if (binding.tvProjectCode2.text.toString().isNotEmpty()) {
GlobalData.projectCode = binding.tvProjectCode2.text.toString().toInt()
binding.cvJoinProject.visibility = View.INVISIBLE
binding.tvProjectCode2.text?.clear()
binding.cvJoinProject.isClickable = false
startActivity(Intent(this, SharedData::class.java))
} else {
Toast.makeText(this, "Please enter a project ID", Toast.LENGTH_SHORT).show()
}
}
} else {
binding.cvJoinProject.isClickable = false
binding.cvJoinProject.visibility = View.INVISIBLE
}
}
private fun toAddProject() {
binding.cvCreateProject.visibility = View.VISIBLE
clicked = !clicked
if (!clicked){
binding.btnCreateProject2.setOnClickListener {
if (binding.tvProjectTitle.text.toString().isNotEmpty() ) {
val random : Random = Random
val randomNumber = random.nextInt(9999) // You can adjust the range of random numbers as needed
val projName = binding.tvProjectTitle.text.toString()
val projCode = randomNumber
val sharedPreferences = applicationContext.getSharedPreferences("MyPrefs", MODE_PRIVATE)
val editor = sharedPreferences.edit()
editor.putString("projCode", projCode.toString())
database.getReference(uid).child(uid+projCode).setValue(Projects(projName, projCode)).addOnSuccessListener {
getdata()
binding.cvCreateProject.visibility = View.GONE
binding.tvProjectTitle.text?.clear()
binding.tvProjectTitle.visibility = View.GONE
}
editor.apply()
} else {
Toast.makeText(this, "Please enter a project name", Toast.LENGTH_SHORT).show()
}
}
} else {
binding.cvCreateProject.isClickable = false
binding.cvCreateProject.visibility = View.INVISIBLE
}
}
private fun onAddButtonClicked() {
setVisibility(clicked)
setAnimation(clicked)
clicked = !clicked
}
private fun setAnimation(clicked: Boolean) {
if (!clicked) {
binding.btnAdd.startAnimation(rotateOpen)
binding.btnAddProject1.startAnimation(fromBottom)
binding.btnJoinProject1.startAnimation(fromBottom)
binding.btnJoinProject1.isClickable = true
binding.btnAddProject1.isClickable = true
}
else {
binding.btnAdd.startAnimation(rotateClose)
binding.btnJoinProject1.startAnimation(toBottom)
binding.btnAddProject1.startAnimation(toBottom)
binding.btnJoinProject1.isClickable = false
binding.btnAddProject1.isClickable = false
}
}
private fun setVisibility(clicked: Boolean) {
if (!clicked) {
binding.btnAddProject1.visibility = View.VISIBLE
binding.btnJoinProject1.visibility = View.VISIBLE
} else {
binding.btnAddProject1.visibility = View.INVISIBLE
binding.btnJoinProject1.visibility = View.INVISIBLE
}
}
private fun signOut() {
FirebaseAuth.getInstance().signOut()
}
private fun navigateToLogin() {
val intent = Intent(this, Login::class.java)
startActivity(intent)
finish() // Optional: Finish the current activity to prevent going back to it after signing out
}
} | Project_Management/app/src/main/java/com/example/projectmanagment/Projects/MainActivity.kt | 3792950115 |
package com.example.projectmanagment.Projects
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.projectmanagment.R
class ProjectsAdapter(private val projects: List<Projects>) : RecyclerView.Adapter<ProjectsAdapter.MyViewHolder>() {
class MyViewHolder (itemView : View) : RecyclerView.ViewHolder(itemView) {
val tvProjectTitle : TextView = itemView.findViewById(R.id.tv_project_name)
val tvProjectCode : TextView = itemView.findViewById(R.id.tv_project_code)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val itemView = LayoutInflater.from(parent.context).inflate(R.layout.project_list_items, parent, false)
return MyViewHolder(itemView)
}
override fun getItemCount(): Int {
return projects.size
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
val currentItem = projects[position]
holder.tvProjectTitle.text = currentItem.projectTitle
holder.tvProjectCode.text = currentItem.projectCode.toString()
}
} | Project_Management/app/src/main/java/com/example/projectmanagment/Projects/ProjectsAdapter.kt | 815727070 |
package com.example.projectmanagment.Projects
data class Projects(
var projectTitle: String,
var projectCode: Int
)
| Project_Management/app/src/main/java/com/example/projectmanagment/Projects/Projects.kt | 2397361985 |
package com.example.projectmanagment
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.example.projectmanagment.Conference.Meet
import com.example.projectmanagment.Storage.SharedData
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.google.android.material.snackbar.Snackbar
class Todo : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(R.layout.activity_todo)
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
insets
}
val btmnav = findViewById<BottomNavigationView>(R.id.bottom_navigation)
btmnav.selectedItemId = R.id.item_3
btmnav.setOnItemSelectedListener { item ->
when (item.itemId) {
R.id.item_1 -> {
startActivity(Intent(this, SharedData::class.java))
finish()
true
}
R.id.item_2 -> {
startActivity(Intent(this, Meet::class.java))
finish()
true
}
R.id.item_3 -> {
Toast.makeText(this, "Already There", Toast.LENGTH_SHORT).show()
true
}
else -> false
}
}
val floatbtn = findViewById<com.google.android.material.floatingactionbutton.FloatingActionButton>(R.id.floatingActionButton)
floatbtn.setOnClickListener {
val contextView = floatbtn
Snackbar.make(contextView, "This is just for testing purposes..!", Snackbar.LENGTH_SHORT)
.show()
}
}
} | Project_Management/app/src/main/java/com/example/projectmanagment/Todo.kt | 2753849993 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.