repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 55
values | size
stringlengths 2
6
| content
stringlengths 55
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
979
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.93
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
domaframework/doma | doma-kotlin/src/test/kotlin/org/seasar/doma/jdbc/criteria/KEntityqlBatchUpdateTest.kt | 1 | 1579 | package org.seasar.doma.jdbc.criteria
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
import org.seasar.doma.jdbc.criteria.entity.Emp
import org.seasar.doma.jdbc.criteria.entity.Emp_
import org.seasar.doma.jdbc.criteria.mock.MockConfig
import java.math.BigDecimal
internal class KEntityqlBatchUpdateTest {
private val entityql = org.seasar.doma.kotlin.jdbc.criteria.KEntityql(MockConfig())
@Test
fun test() {
val emp = Emp()
emp.id = 1
emp.name = "aaa"
emp.salary = BigDecimal("1000")
emp.version = 1
val e = Emp_()
val stmt = entityql.update(e, listOf(emp))
val sql = stmt.asSql()
Assertions.assertEquals(
"update EMP set NAME = 'aaa', SALARY = 1000, VERSION = 1 + 1 where ID = 1 and VERSION = 1",
sql.formattedSql
)
}
@Test
fun ignoreVersion() {
val emp = Emp()
emp.id = 1
emp.name = "aaa"
emp.salary = BigDecimal("1000")
emp.version = 1
val e = Emp_()
val stmt = entityql.update(e, listOf(emp)) { ignoreVersion = true }
val sql = stmt.asSql()
Assertions.assertEquals(
"update EMP set NAME = 'aaa', SALARY = 1000, VERSION = 1 where ID = 1",
sql.formattedSql
)
}
@Test
fun empty() {
val e = Emp_()
val stmt = entityql.update(e, emptyList())
val sql = stmt.asSql()
Assertions.assertEquals("This SQL is empty because target entities are empty.", sql.formattedSql)
}
}
| apache-2.0 | 66ade3e4e2cd08b9d8d7f242a49e2646 | 28.792453 | 105 | 0.595947 | 3.9475 | false | true | false | false |
ModerateFish/component | app/src/main/java/com/thornbirds/repodemo/MainActivity.kt | 1 | 5344 | package com.thornbirds.repodemo
import android.content.ComponentName
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.IBinder
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.view.View
import androidx.appcompat.widget.Toolbar
import androidx.fragment.app.Fragment
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.google.android.material.snackbar.Snackbar
import com.thornbirds.framework.activity.ComponentActivity
import com.thornbirds.repodemo.MyService.MyServiceImpl
class MainActivity : ComponentActivity() {
override val TAG: String = "MainActivity"
private var mPersistFragment: Fragment? = null
private var mAddFragment1: Fragment? = null
private var mAddFragment2: Fragment? = null
private var mReplaceFragment1: Fragment? = null
private var mReplaceFragment2: Fragment? = null
private var mMyService: MyServiceImpl? = null
private val mServiceConnection: ServiceConnection = object : ServiceConnection {
override fun onServiceConnected(name: ComponentName, service: IBinder) {
mMyService = service as MyServiceImpl
Log.d(TAG, "onServiceDisconnected mMyService")
mMyService!!.print("log onServiceConnected")
}
override fun onServiceDisconnected(name: ComponentName) {
mMyService = null
Log.d(TAG, "onServiceDisconnected mMyService")
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val toolbar = findViewById<View>(R.id.toolbar) as Toolbar
setSupportActionBar(toolbar)
val fab = findViewById<View>(R.id.fab) as FloatingActionButton
fab.setOnClickListener { view ->
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show()
// Intent intent = new Intent(MainActivity.this, com.thornbirds.framework.MainActivity.class);
// startActivity(intent);
val fragmentManager =
supportFragmentManager
if (mAddFragment1 == null) {
val fragment: Fragment = TestFragment()
val bundle = Bundle()
bundle.putInt(TestFragment.EXTRA_FRAGMENT_ID, 1)
fragment.arguments = bundle
fragmentManager.beginTransaction().add(R.id.root_container, fragment).commit()
mAddFragment1 = fragment
} else if (mAddFragment2 == null) {
val fragment: Fragment = TestFragment()
val bundle = Bundle()
bundle.putInt(TestFragment.EXTRA_FRAGMENT_ID, 2)
fragment.arguments = bundle
fragmentManager.beginTransaction().add(R.id.root_container, fragment).commit()
mAddFragment2 = fragment
} else if (mReplaceFragment1 == null) {
val fragment: Fragment = TestFragment()
val bundle = Bundle()
bundle.putInt(TestFragment.EXTRA_FRAGMENT_ID, 3)
fragment.arguments = bundle
fragmentManager.beginTransaction().replace(R.id.root_container, fragment).commit()
mReplaceFragment1 = fragment
} else if (mReplaceFragment2 == null) {
val fragment: Fragment = TestFragment()
val bundle = Bundle()
bundle.putInt(TestFragment.EXTRA_FRAGMENT_ID, 4)
fragment.arguments = bundle
fragmentManager.beginTransaction().replace(R.id.root_container, fragment).commit()
mReplaceFragment2 = fragment
}
}
mPersistFragment = supportFragmentManager.findFragmentById(R.id.test_fragment)
val intent = Intent(this, MyService::class.java)
bindService(intent, mServiceConnection, BIND_AUTO_CREATE)
}
override fun onResume() {
super.onResume()
Log.d(TAG, "onResume mMyService")
if (mMyService != null) {
mMyService!!.print("log onResume")
}
}
override fun onStop() {
super.onStop()
Log.d(TAG, "onStop mMyService")
if (mMyService != null) {
mMyService!!.print("log onStop")
}
}
override fun onDestroy() {
super.onDestroy()
Log.d(TAG, "onDestroy mMyService")
if (mMyService != null) {
mMyService!!.print("log onDestroy")
}
unbindService(mServiceConnection)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.menu_main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
val id = item.itemId
return if (id == R.id.action_settings) {
true
} else super.onOptionsItemSelected(item)
}
} | apache-2.0 | e230b096236380b5d0a34ab30de2c5ad | 40.115385 | 121 | 0.639409 | 5.099237 | false | true | false | false |
googlecodelabs/tv-watchnext | step_final/src/main/java/com/example/android/watchnextcodelab/channels/WatchNextNotificationReceiver.kt | 1 | 2729 | /*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.example.android.watchnextcodelab.channels
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.support.media.tv.TvContractCompat
import android.util.Log
import com.example.android.watchnextcodelab.database.MockDatabase
import com.example.android.watchnextcodelab.watchlist.WatchlistManager
private const val TAG = "WatchNextNotificationReceiver"
class WatchNextNotificationReceiver : BroadcastReceiver() {
private val watchlistManager = WatchlistManager.get()
private val database = MockDatabase.get()
override fun onReceive(context: Context, intent: Intent) {
val extras = intent.extras
// TODO: Step 10 extract the EXTRA_WATCH_NEXT_PROGRAM_ID
val watchNextProgramId = extras.getLong(TvContractCompat.EXTRA_WATCH_NEXT_PROGRAM_ID)
when(intent.action) {
// TODO: Step 11 remove the movie from the watchlist.
// A program has been removed from the watch next row.
TvContractCompat.ACTION_WATCH_NEXT_PROGRAM_BROWSABLE_DISABLED -> {
Log.d(TAG, "Program removed from watch next watch-next: $watchNextProgramId")
database.findAllMovieProgramIds(context)
.find { it.watchNextProgramId == watchNextProgramId }
?.apply {
watchlistManager.removeMovieFromWatchlist(context, movieId)
}
}
// TODO: Step 12 add the movie to the watchlist.
TvContractCompat.ACTION_PREVIEW_PROGRAM_ADDED_TO_WATCH_NEXT -> {
val programId = extras.getLong(TvContractCompat.EXTRA_PREVIEW_PROGRAM_ID)
Log.d(TAG,
"Preview program added to watch next program: $programId watch-next: $watchNextProgramId")
database.findAllMovieProgramIds(context)
.find { it.programIds.contains(programId) }
?.apply {
watchlistManager.addToWatchlist(context, movieId)
}
}
}
}
}
| apache-2.0 | eda2c720107103d2b7bc4fc292980c5c | 38.550725 | 110 | 0.673873 | 4.890681 | false | false | false | false |
mrkirby153/KirBot | src/main/kotlin/me/mrkirby153/KirBot/command/executors/fun/CommandJumbo.kt | 1 | 3240 | package me.mrkirby153.KirBot.command.executors.`fun`
import me.mrkirby153.KirBot.command.CommandCategory
import me.mrkirby153.KirBot.command.annotations.Command
import me.mrkirby153.KirBot.command.annotations.CommandDescription
import me.mrkirby153.KirBot.command.annotations.IgnoreWhitelist
import me.mrkirby153.KirBot.command.args.CommandContext
import me.mrkirby153.KirBot.utils.Context
import me.mrkirby153.KirBot.utils.EMOJI_RE
import me.mrkirby153.KirBot.utils.HttpUtils
import net.dv8tion.jda.api.Permission
import okhttp3.Request
import java.awt.Image
import java.awt.image.BufferedImage
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import javax.imageio.ImageIO
class CommandJumbo {
@Command(name = "jumbo", arguments = ["<emojis:string...>"], category = CommandCategory.FUN,
permissions = [Permission.MESSAGE_ATTACH_FILES])
@CommandDescription("Sends a bigger version of the given emojis")
@IgnoreWhitelist
fun execute(context: Context, cmdContext: CommandContext) {
val emojis = cmdContext.get<String>("emojis")!!
val urls = mutableListOf<String>()
emojis.split(" ").forEach { e ->
val matcher = EMOJI_RE.toPattern().matcher(e)
if (matcher.find()) {
val id = matcher.group(2)
urls.add("https://discordapp.com/api/emojis/$id.png")
} else {
urls.add(getEmojiUrl(e))
}
}
var img: BufferedImage? = null
urls.forEach { e ->
val request = Request.Builder().url(e).build()
val resp = HttpUtils.CLIENT.newCall(request).execute()
val r = ImageIO.read(resp.body()?.byteStream())
if (img == null)
img = r
else
img = joinBufferedImage(img!!, r)
}
val finalImg = img ?: return
val os = ByteArrayOutputStream()
ImageIO.write(finalImg, "png", os)
val `is` = ByteArrayInputStream(os.toByteArray())
context.channel.sendFile(`is`, "emoji.png").queue {
os.close()
`is`.close()
}
}
private fun getEmojiUrl(emoji: String): String {
val first = String.format("%04X", emoji.codePoints().findFirst().asInt)
return "https://twemoji.maxcdn.com/2/72x72/${first.toLowerCase()}.png"
}
private fun joinBufferedImage(img1: BufferedImage, img2: BufferedImage): BufferedImage {
val offset = 5
val width = img1.width + img2.width + offset
val height = Math.max(img1.height, img2.height) + offset
val newImage = BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB)
val g2 = newImage.graphics
g2.drawImage(img1, 0, 0, null)
g2.drawImage(img2, img1.width + offset, 0, null)
g2.dispose()
return newImage
}
fun resizeImage(img: BufferedImage, width: Int, height: Int): BufferedImage {
val tmp = img.getScaledInstance(width, height, Image.SCALE_SMOOTH)
val dImg = BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB)
val g2d = dImg.createGraphics()
g2d.drawImage(tmp, 0, 0, null)
g2d.dispose()
return dImg
}
} | mit | 8c19314796f0f9c7c73be38f9abe8dc9 | 34.615385 | 96 | 0.64321 | 4.106464 | false | false | false | false |
SimpleTimeTracking/StandaloneClient | src/main/kotlin/org/stt/command/CommandTextParser.kt | 1 | 4108 | package org.stt.command
import org.antlr.v4.runtime.tree.RuleNode
import org.stt.grammar.EnglishCommandsBaseVisitor
import org.stt.grammar.EnglishCommandsParser
import org.stt.grammar.EnglishCommandsParser.CommandContext
import org.stt.model.TimeTrackingItem
import java.time.Duration
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import java.time.format.DateTimeParseException
import java.time.temporal.TemporalQueries
class CommandTextParser(private val formatters: List<DateTimeFormatter>) {
private val parserVisitor = MyEnglishCommandsBaseVisitor()
internal fun walk(commandContext: CommandContext): Any {
return commandContext.accept(parserVisitor)
}
private inner class MyEnglishCommandsBaseVisitor : EnglishCommandsBaseVisitor<Any>() {
override fun visitDate(ctx: EnglishCommandsParser.DateContext): LocalDate {
ctx.text
return LocalDate.parse(ctx.text)
}
override fun visitDateTime(ctx: EnglishCommandsParser.DateTimeContext): LocalDateTime {
val temporalAccessor = formatters
.mapNotNull { formatter ->
try {
return@mapNotNull formatter.parse(ctx.text)
} catch (e: DateTimeParseException) {
return@mapNotNull null
}
}
.firstOrNull() ?: throw DateTimeParseException("Invalid date format", ctx.text, 0)
val date = temporalAccessor.query(TemporalQueries.localDate())
val time = temporalAccessor.query(TemporalQueries.localTime())
return LocalDateTime.of(date ?: LocalDate.now(), time)
}
override fun visitSinceFormat(ctx: EnglishCommandsParser.SinceFormatContext): Array<LocalDateTime?> {
return arrayOf(visitDateTime(ctx.start), if (ctx.end != null) visitDateTime(ctx.end) else null)
}
override fun visitResumeLastCommand(ctx: EnglishCommandsParser.ResumeLastCommandContext): Any {
return ResumeLastActivity(LocalDateTime.now())
}
override fun visitAgoFormat(ctx: EnglishCommandsParser.AgoFormatContext): Array<LocalDateTime?> {
val amount = ctx.amount
val timeUnit = ctx.timeUnit()
val duration = when {
timeUnit.HOURS() != null -> Duration.ofHours(amount.toLong())
timeUnit.MINUTES() != null -> Duration.ofMinutes(amount.toLong())
timeUnit.SECONDS() != null -> Duration.ofSeconds(amount.toLong())
else -> throw IllegalStateException("Unknown ago unit: " + ctx.text)
}
return arrayOf(LocalDateTime.now().minus(duration), null)
}
override fun visitFromToFormat(ctx: EnglishCommandsParser.FromToFormatContext): Array<LocalDateTime?> {
val start = visitDateTime(ctx.start)
val end = if (ctx.end != null) visitDateTime(ctx.end) else null
return arrayOf(start, end)
}
override fun visitTimeFormat(ctx: EnglishCommandsParser.TimeFormatContext): Array<LocalDateTime?> {
return super.visitTimeFormat(ctx) as? Array<LocalDateTime?>
?: return arrayOf(LocalDateTime.now(), null)
}
override fun visitItemWithComment(ctx: EnglishCommandsParser.ItemWithCommentContext): Any {
val period = visitTimeFormat(ctx.timeFormat())
return if (period[1] != null) {
TimeTrackingItem(ctx.text, period[0]!!, period[1])
} else {
TimeTrackingItem(ctx.text, period[0]!!)
}
}
override fun visitFinCommand(ctx: EnglishCommandsParser.FinCommandContext): LocalDateTime {
return if (ctx.at != null) {
visitDateTime(ctx.at)
} else LocalDateTime.now()
}
override fun shouldVisitNextChild(node: RuleNode?, currentResult: Any?): Boolean {
return currentResult == null
}
}
}
| gpl-3.0 | c6c731d327de531108e8ba52f841f030 | 42.702128 | 111 | 0.644352 | 5.219822 | false | false | false | false |
MyDogTom/detekt | detekt-cli/src/main/kotlin/io/gitlab/arturbosch/detekt/cli/console/ComplexityReportGenerator.kt | 1 | 2035 | package io.gitlab.arturbosch.detekt.cli.console
import io.gitlab.arturbosch.detekt.api.Detektion
import io.gitlab.arturbosch.detekt.api.PREFIX
import io.gitlab.arturbosch.detekt.api.format
internal class ComplexityReportGenerator(private val complexityMetric: ComplexityMetric) {
private var numberOfSmells = 0
private var smellPerThousandLines = 0
private var mccPerThousandLines = 0
private var commentSourceRatio = 0
companion object Factory {
fun create(detektion: Detektion): ComplexityReportGenerator = ComplexityReportGenerator(ComplexityMetric(detektion))
}
fun generate(): String? {
if (cannotGenerate()) return null
return with(StringBuilder()) {
append("Complexity Report:".format())
append("${complexityMetric.loc} lines of code (loc)".format(PREFIX))
append("${complexityMetric.sloc} source lines of code (sloc)".format(PREFIX))
append("${complexityMetric.lloc} logical lines of code (lloc)".format(PREFIX))
append("${complexityMetric.cloc} comment lines of code (cloc)".format(PREFIX))
append("${complexityMetric.mcc} McCabe complexity (mcc)".format(PREFIX))
append("$numberOfSmells number of total code smells".format(PREFIX))
append("$commentSourceRatio % comment source ratio".format(PREFIX))
append("$mccPerThousandLines mcc per 1000 lloc".format(PREFIX))
append("$smellPerThousandLines code smells per 1000 lloc".format(PREFIX))
toString()
}
}
private fun cannotGenerate(): Boolean {
return when {
complexityMetric.mcc == null -> true
complexityMetric.lloc == null || complexityMetric.lloc == 0 -> true
complexityMetric.sloc == null || complexityMetric.sloc == 0 -> true
complexityMetric.cloc == null -> true
else -> {
numberOfSmells = complexityMetric.findings.sumBy { it.value.size }
smellPerThousandLines = numberOfSmells * 1000 / complexityMetric.lloc
mccPerThousandLines = complexityMetric.mcc * 1000 / complexityMetric.lloc
commentSourceRatio = complexityMetric.cloc * 100 / complexityMetric.sloc
false
}
}
}
}
| apache-2.0 | 5ee068c42382a2ae8e6e38c7de866146 | 39.7 | 118 | 0.75086 | 4.257322 | false | false | false | false |
avast/android-lectures | Lecture 2/Demo-app/app/src/main/java/com/avast/mff/lecture2/MainActivity.kt | 1 | 1936 | package com.avast.mff.lecture2
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.Toast
import com.google.android.material.textfield.TextInputLayout
class MainActivity : AppCompatActivity() {
lateinit var btnSubmit: Button
lateinit var etUsername: TextInputLayout
lateinit var etPassword: TextInputLayout
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Manual view binding
btnSubmit = findViewById(R.id.btn_submit)
etUsername = findViewById(R.id.txt_username)
etPassword = findViewById(R.id.txt_password)
/**
* Restore the UI state after configuration change.
*/
savedInstanceState?.let {
etUsername.editText?.setText(it.getString(KEY_USERNAME, ""))
etPassword.editText?.setText(it.getString(KEY_PASS, ""))
}
btnSubmit.setOnClickListener {
Toast.makeText(this, R.string.txt_sample_toast, Toast.LENGTH_LONG).show()
// Pass values to the secondary activity.
val intent = Intent(this, SecondActivity::class.java).apply {
putExtra(KEY_USERNAME, etUsername.editText?.text.toString())
putExtra(KEY_PASS, etPassword.editText?.text.toString())
}
startActivity(intent)
}
}
/**
* Save UI state for configuration changes.
*/
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putString(KEY_USERNAME, etUsername.editText?.text.toString())
outState.putString(KEY_PASS, etPassword.editText?.text.toString())
}
companion object {
const val KEY_USERNAME = "username"
const val KEY_PASS = "pass"
}
} | apache-2.0 | cd8b7319fe1b0634dc779aa3efa54090 | 32.396552 | 85 | 0.666839 | 4.780247 | false | false | false | false |
Vakosta/Chapper | app/src/main/java/org/chapper/chapper/data/model/Message.kt | 1 | 1501 | package org.chapper.chapper.data.model
import android.text.format.DateUtils
import com.raizlabs.android.dbflow.annotation.Column
import com.raizlabs.android.dbflow.annotation.PrimaryKey
import com.raizlabs.android.dbflow.annotation.Table
import com.raizlabs.android.dbflow.annotation.Unique
import com.raizlabs.android.dbflow.structure.BaseModel
import org.chapper.chapper.data.database.AppDatabase
import org.chapper.chapper.data.status.MessageStatus
import org.chapper.chapper.domain.usecase.DateUseCase
import java.text.SimpleDateFormat
import java.util.*
@Table(database = AppDatabase::class)
data class Message(
@PrimaryKey
@Unique
var id: String = UUID.randomUUID().toString(),
@Column
var chatId: String = "",
@Column
var status: MessageStatus = MessageStatus.INCOMING_UNREAD,
@Column
var text: String = "",
@Column
var date: Date = Date()
) : BaseModel() {
fun getTimeString(): String = when {
DateUtils.isToday(date.time) -> SimpleDateFormat("HH:mm").format(date)
DateUseCase.isDateInCurrentWeek(date) -> SimpleDateFormat("EEE").format(date)
else -> SimpleDateFormat("MMM d").format(date)
}
fun isMine(): Boolean {
return (status == MessageStatus.OUTGOING_READ
|| status == MessageStatus.OUTGOING_UNREAD
|| status == MessageStatus.OUTGOING_NOT_SENT)
}
fun isAction(): Boolean = status == MessageStatus.ACTION
} | gpl-2.0 | 08d5141085d3fba8f26efefb35833df5 | 30.291667 | 85 | 0.694204 | 4.40176 | false | false | false | false |
ZsemberiDaniel/EgerBusz | app/src/main/java/com/zsemberidaniel/egerbuszuj/adapters/ChooseStopAdapter.kt | 1 | 7869 | package com.zsemberidaniel.egerbuszuj.adapters
import android.support.v4.content.res.ResourcesCompat
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import com.zsemberidaniel.egerbuszuj.R
import com.zsemberidaniel.egerbuszuj.realm.objects.Stop
import java.util.ArrayList
import java.util.Collections
import java.util.HashMap
import java.util.HashSet
import java.util.TreeSet
import eu.davidea.flexibleadapter.FlexibleAdapter
import eu.davidea.flexibleadapter.items.AbstractHeaderItem
import eu.davidea.flexibleadapter.items.AbstractSectionableItem
import eu.davidea.flexibleadapter.items.IFilterable
import eu.davidea.viewholders.FlexibleViewHolder
import io.realm.Realm
/**
* Created by zsemberi.daniel on 2017. 05. 12..
*/
class ChooseStopAdapter(val items: MutableList<ChooseStopAdapter.ChooseStopItem>)
: FlexibleAdapter<ChooseStopAdapter.ChooseStopItem>(ArrayList(items)) {
private var filter: String = ""
/**
* Updates the starred attribute of the ChooseStopItems, sorts them, then updates the display as well
* If it is filtered it will remove the filter and update the whole data set
*/
private fun updateAndSortDataSet() {
// remove filter because this function will take the whole list from the constructor into consideration
if (isFiltered) {
searchText = ""
}
// Update starred
val realm = Realm.getDefaultInstance()
for (i in items.indices)
items[i].isStarred = realm.where<Stop>(Stop::class.java).equalTo(Stop.CN_ID, items[i].stopId)
.findFirst().isStarred
realm.close()
// sort
Collections.sort(items)
// update display
setNotifyMoveOfFilteredItems(true)
super.updateDataSet(ArrayList(items), true)
}
override fun clear() {
super.clear()
items.clear()
}
override fun addItem(item: ChooseStopItem): Boolean {
items.add(item)
return super.addItem(item)
}
override fun addItem(position: Int, item: ChooseStopItem): Boolean {
items.add(0, item)
return super.addItem(position, item)
}
override fun addItems(position: Int, items: MutableList<ChooseStopItem>): Boolean {
this.items.addAll(0, items)
return super.addItems(position, items)
}
/**
* @return Is the FlexibleAdapter filtered in any way?
*/
val isFiltered: Boolean
get() = filter != ""
override fun setSearchText(searchText: String) {
this.filter = searchText
super.setSearchText(searchText)
}
override fun onPostFilter() {
super.onPostFilter()
// update and sort the data set in case the user starred a stop
if (filter == "")
updateAndSortDataSet()
}
class ChooseStopItem(private val letterHeader: ChooseStopHeader, private val starredHeader: ChooseStopHeader,
val stopId: String, val stopName: String, starred: Boolean)
: AbstractSectionableItem<ChooseStopItem.ChooseStopItemViewHolder, ChooseStopHeader>(if (starred) starredHeader else letterHeader),
IFilterable, Comparable<ChooseStopItem> {
var isStarred: Boolean = false
internal set
init {
this.isStarred = starred
}
override fun equals(`object`: Any?): Boolean =
if (`object` is ChooseStopItem) `object`.stopId == stopId else false
override fun hashCode(): Int = stopId.hashCode()
override fun getLayoutRes(): Int = R.layout.stop_list_item
override fun createViewHolder(adapter: FlexibleAdapter<*>, inflater: LayoutInflater?,
parent: ViewGroup?): ChooseStopItemViewHolder
= ChooseStopItemViewHolder(inflater!!.inflate(layoutRes, parent, false), adapter)
override fun bindViewHolder(adapter: FlexibleAdapter<*>, holder: ChooseStopItemViewHolder, position: Int,
payloads: List<*>) {
holder.stopNameTextView.text = stopName
setStarredImageCorrectly(holder)
// setup on click listener for the starred image
holder.starredImageView.setOnClickListener {
// Toggle starred in database
Realm.getDefaultInstance().executeTransaction { realm ->
val stop = realm.where<Stop>(Stop::class.java).equalTo(Stop.CN_ID, stopId).findFirst()
isStarred = if (isStarred) false else true
stop.isStarred = isStarred
}
// update display
setStarredImageCorrectly(holder)
if (isStarred)
setHeader(starredHeader)
else
setHeader(letterHeader)
// only update and sort the data set if it is not filtered because if it is filtered
// it updates it in a way which displays all of the data
if (adapter is ChooseStopAdapter && !adapter.isFiltered)
adapter.updateAndSortDataSet()
}
}
override fun filter(constraint: String): Boolean {
return stopName.toLowerCase().contains(constraint.toLowerCase())
}
/**
* Sets the starred image of the given viewHolder correctly based on this class' starred
* boolean. It gets the drawable from ResourceCompat
* @param viewHolder
*/
private fun setStarredImageCorrectly(viewHolder: ChooseStopItemViewHolder) {
if (isStarred) {
viewHolder.starredImageView.setImageDrawable(
ResourcesCompat.getDrawable(viewHolder.starredImageView.resources, R.drawable.ic_star, null)
)
} else {
viewHolder.starredImageView.setImageDrawable(
ResourcesCompat.getDrawable(viewHolder.starredImageView.resources, R.drawable.ic_star_border, null)
)
}
}
override fun compareTo(o: ChooseStopItem): Int {
if (o.isStarred && !isStarred) return 1
if (isStarred && !o.isStarred) return -1
return -o.stopName.compareTo(stopName)
}
class ChooseStopItemViewHolder(view: View, adapter: FlexibleAdapter<*>) : FlexibleViewHolder(view, adapter, false) {
var stopNameTextView: TextView = view.findViewById(R.id.stopNameText) as TextView
var starredImageView: ImageView = view.findViewById(R.id.starredImgView) as ImageView
}
}
class ChooseStopHeader(private val letter: Char) : AbstractHeaderItem<ChooseStopHeader.ChooseStopHeaderViewHolder>() {
override fun equals(o: Any?): Boolean =
if (o is ChooseStopHeader) o.letter == letter else false
override fun hashCode(): Int = letter.toString().hashCode()
override fun getLayoutRes(): Int = R.layout.letter_item_header
override fun createViewHolder(adapter: FlexibleAdapter<*>, inflater: LayoutInflater, parent: ViewGroup): ChooseStopHeaderViewHolder =
ChooseStopHeaderViewHolder(inflater.inflate(layoutRes, parent, false), adapter)
override fun bindViewHolder(adapter: FlexibleAdapter<*>?, holder: ChooseStopHeaderViewHolder, position: Int, payloads: List<*>) {
holder.letterTextView.text = letter.toString()
}
class ChooseStopHeaderViewHolder(view: View, adapter: FlexibleAdapter<*>) : FlexibleViewHolder(view, adapter, true) {
val letterTextView: TextView = view.findViewById(R.id.letterTextView) as TextView
}
}
}
| apache-2.0 | aaa9c9cf0d1e89b6fc14694856bd4aeb | 38.345 | 156 | 0.647859 | 5.291863 | false | false | false | false |
blackbbc/Tucao | app/src/main/kotlin/me/sweetll/tucao/business/download/DownloadSettingActivity.kt | 1 | 1301 | package me.sweetll.tucao.business.download
import android.content.Context
import android.content.Intent
import androidx.databinding.DataBindingUtil
import android.os.Bundle
import androidx.appcompat.widget.Toolbar
import android.view.View
import me.sweetll.tucao.R
import me.sweetll.tucao.base.BaseActivity
import me.sweetll.tucao.databinding.ActivityDownloadSettingBinding
class DownloadSettingActivity: BaseActivity() {
lateinit var binding: ActivityDownloadSettingBinding
override fun getToolbar(): Toolbar = binding.toolbar
override fun getStatusBar(): View = binding.statusBar
override fun initView(savedInstanceState: Bundle?) {
binding = DataBindingUtil.setContentView(this, R.layout.activity_download_setting)
fragmentManager.beginTransaction()
.replace(R.id.contentFrame, DownloadSettingFragment())
.commit()
}
companion object {
fun intentTo(context: Context) {
val intent = Intent(context, DownloadSettingActivity::class.java)
context.startActivity(intent)
}
}
override fun initToolbar() {
super.initToolbar()
delegate.supportActionBar?.let {
it.title = "离线设置"
it.setDisplayHomeAsUpEnabled(true)
}
}
}
| mit | a95c9aaea784014fc357476e31124aad | 29.785714 | 90 | 0.712297 | 4.935115 | false | false | false | false |
Bodo1981/swapi.co | app/src/main/java/com/christianbahl/swapico/details/DetailsFragment.kt | 1 | 3350 | package com.christianbahl.swapico.details
import android.os.Bundle
import android.support.v4.widget.NestedScrollView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import com.christianbahl.swapico.App
import com.christianbahl.swapico.R
import com.christianbahl.swapico.list.DaggerTypeComponent
import com.christianbahl.swapico.list.TypeComponent
import com.christianbahl.swapico.list.TypeModule
import com.christianbahl.swapico.list.model.ListType
import com.christianbahl.swapico.model.IListData
import com.hannesdorfmann.fragmentargs.annotation.Arg
import com.hannesdorfmann.fragmentargs.annotation.FragmentWithArgs
import com.hannesdorfmann.mosby.mvp.viewstate.lce.LceViewState
import com.hannesdorfmann.mosby.mvp.viewstate.lce.MvpLceViewStateFragment
import com.hannesdorfmann.mosby.mvp.viewstate.lce.data.RetainingLceViewState
import kotlinx.android.synthetic.main.fragment_details.*
import org.jetbrains.anko.find
/**
* @author Christian Bahl
*/
@FragmentWithArgs
class DetailsFragment : MvpLceViewStateFragment<NestedScrollView, IListData, DetailsView, DetailsPresenter>() {
@Arg var detailsId = 1
@Arg lateinit var listType: ListType
lateinit private var typeComponent: TypeComponent
private var data: IListData? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
retainInstance = true
DetailsFragmentBuilder.injectArguments(this)
val app = activity.applicationContext as App
typeComponent = DaggerTypeComponent.builder()
.typeModule(TypeModule(listType))
.netComponent(app.netComponent()).build()
}
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater?.inflate(R.layout.fragment_details, container, false)
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
toolbar.navigationIcon = resources.getDrawable(R.drawable.abc_ic_ab_back_mtrl_am_alpha, null)
toolbar.setNavigationOnClickListener { activity.onBackPressed() }
}
override fun getErrorMessage(e: Throwable?, pullToRefresh: Boolean): String? = getString(R.string.cb_error_view_text)
override fun createViewState(): LceViewState<IListData, DetailsView>? = RetainingLceViewState()
override fun createPresenter(): DetailsPresenter? = typeComponent.detailsPresenter()
override fun getData(): IListData? = data
override fun loadData(pullToRefresh: Boolean) {
presenter.loadData(detailsId, listType, pullToRefresh)
}
override fun setData(data: IListData?) {
this.data = data
buildLayout(data?.displayData)
}
private fun buildLayout(layoutData: Map<String, String>?) {
val inflater = LayoutInflater.from(activity)
layoutData?.forEach {
if (it.key === "Opening Crawl") {
toolbarText.text = it.value
} else if (it.key === "Title") {
toolbar.title = it.value
} else {
var ll = inflater.inflate(R.layout.row_key_value, scrollViewContainer, false) as LinearLayout
ll.find<TextView>(R.id.key).text = it.key
ll.find<TextView>(R.id.value).text = it.value
scrollViewContainer.addView(ll)
}
}
}
} | apache-2.0 | 03b2e12865eb1ec39317d51201ad209c | 34.273684 | 119 | 0.766866 | 4.356307 | false | false | false | false |
cfig/Nexus_boot_image_editor | bbootimg/src/main/kotlin/avb/desc/UnknownDescriptor.kt | 1 | 4862 | // Copyright 2021 [email protected]
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package avb.desc
import cfig.helper.Helper
import cfig.io.Struct3
import org.apache.commons.codec.binary.Hex
import org.slf4j.LoggerFactory
import java.io.ByteArrayInputStream
import java.io.InputStream
class UnknownDescriptor(var data: ByteArray = byteArrayOf()) : Descriptor(0, 0, 0) {
@Throws(IllegalArgumentException::class)
constructor(stream: InputStream, seq: Int = 0) : this() {
this.sequence = seq
val info = Struct3(FORMAT).unpack(stream)
this.tag = (info[0] as ULong).toLong()
this.num_bytes_following = (info[1] as ULong).toLong()
log.debug("UnknownDescriptor: tag = $tag, len = ${this.num_bytes_following}")
this.data = ByteArray(this.num_bytes_following.toInt())
if (this.num_bytes_following.toInt() != stream.read(data)) {
throw IllegalArgumentException("descriptor SIZE mismatch")
}
}
override fun encode(): ByteArray {
return Helper.join(Struct3(FORMAT).pack(this.tag, this.data.size.toLong()), data)
}
override fun toString(): String {
return "UnknownDescriptor(tag=$tag, SIZE=${data.size}, data=${Hex.encodeHexString(data)}"
}
fun analyze(): Descriptor {
return when (this.tag.toUInt()) {
0U -> {
PropertyDescriptor(ByteArrayInputStream(this.encode()), this.sequence)
}
1U -> {
HashTreeDescriptor(ByteArrayInputStream(this.encode()), this.sequence)
}
2U -> {
HashDescriptor(ByteArrayInputStream(this.encode()), this.sequence)
}
3U -> {
KernelCmdlineDescriptor(ByteArrayInputStream(this.encode()), this.sequence)
}
4U -> {
ChainPartitionDescriptor(ByteArrayInputStream(this.encode()), this.sequence)
}
else -> {
this
}
}
}
companion object {
private const val SIZE = 16
private const val FORMAT = "!QQ"
private val log = LoggerFactory.getLogger(UnknownDescriptor::class.java)
fun parseDescriptors(stream: InputStream, totalSize: Long): List<UnknownDescriptor> {
log.debug("Parse descriptors stream, SIZE = $totalSize")
val ret: MutableList<UnknownDescriptor> = mutableListOf()
var currentSize = 0L
while (true) {
val desc = UnknownDescriptor(stream)
currentSize += desc.data.size + SIZE
log.debug("current SIZE = $currentSize")
ret.add(desc)
if (currentSize == totalSize) {
log.debug("parse descriptor done")
break
} else if (currentSize > totalSize) {
log.error("Read more than expected")
throw IllegalStateException("Read more than expected")
} else {
log.debug(desc.toString())
log.debug("read another descriptor")
}
}
return ret
}
fun parseDescriptors2(stream: InputStream, totalSize: Long): List<Descriptor> {
log.debug("Parse descriptors stream, SIZE = $totalSize")
val ret: MutableList<Descriptor> = mutableListOf()
var currentSize = 0L
var seq = 0
while (true) {
val desc = UnknownDescriptor(stream, ++seq)
currentSize += desc.data.size + SIZE
log.debug("current SIZE = $currentSize")
log.debug(desc.toString())
ret.add(desc.analyze())
if (currentSize == totalSize) {
log.debug("parse descriptor done")
break
} else if (currentSize > totalSize) {
log.error("Read more than expected")
throw IllegalStateException("Read more than expected")
} else {
log.debug(desc.toString())
log.debug("read another descriptor")
}
}
return ret
}
init {
assert(SIZE == Struct3(FORMAT).calcSize())
}
}
}
| apache-2.0 | 8d2a1918e54604a2b775267da1e6dfd8 | 37.587302 | 97 | 0.571781 | 4.90121 | false | false | false | false |
youkai-app/Youkai | app/src/main/kotlin/app/youkai/ui/feature/media/MediaActivity.kt | 1 | 6487 | package app.youkai.ui.feature.media
import android.app.AlertDialog
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.support.design.widget.AppBarLayout
import android.support.design.widget.Snackbar
import android.widget.Toast
import app.youkai.R
import app.youkai.data.models.BaseMedia
import app.youkai.data.models.Titles
import app.youkai.data.models.ext.MediaType
import app.youkai.ui.feature.media.summary.SummaryFragment
import app.youkai.util.ext.snackbar
import app.youkai.util.ext.toVisibility
import app.youkai.util.ext.whenNotNull
import app.youkai.util.string
import com.hannesdorfmann.mosby.mvp.viewstate.MvpViewStateActivity
import com.hannesdorfmann.mosby.mvp.viewstate.ViewState
import kotlinx.android.synthetic.main.activity_media.*
class MediaActivity : MvpViewStateActivity<MediaView, BaseMediaPresenter>(), MediaView {
override fun createPresenter(): BaseMediaPresenter = BaseMediaPresenter()
override fun createViewState(): ViewState<MediaView> = MediaState()
override fun onNewViewStateInstance() {
/* do nothing */
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_media)
setSupportActionBar(toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
/* Set up title show/hide */
appbar.addOnOffsetChangedListener(object : AppBarLayout.OnOffsetChangedListener {
var isShow = false
var scrollRange = -1
override fun onOffsetChanged(appBarLayout: AppBarLayout, verticalOffset: Int) {
if (scrollRange == -1) {
scrollRange = appBarLayout.totalScrollRange
}
if (scrollRange + verticalOffset == 0) {
toolbar.setTitleTextColor(resources.getColor(android.R.color.white))
isShow = true
} else if (isShow) {
toolbar.setTitleTextColor(resources.getColor(android.R.color.transparent))
isShow = false
}
}
})
var mediaId: String = ""
var type = MediaType.NO_IDEA
whenNotNull(intent.extras) {
mediaId = it.getString(ARG_ID)
type = MediaType.fromString(it.getString(ARG_TYPE))
}
when (type) {
MediaType.ANIME -> setPresenter(AnimePresenter())
MediaType.MANGA -> setPresenter(MangaPresenter())
}
presenter.attachView(this)
presenter.set(mediaId)
titleView.setOnClickListener {
presenter.onTitleClicked()
}
alternativeTitles.setOnClickListener {
presenter.onAlternativeTitlesClicked()
}
trailer.setOnClickListener {
presenter.onTrailerClicked()
}
fab.setOnClickListener {
presenter
}
}
override fun onSupportNavigateUp(): Boolean {
finish()
return true
}
override fun setSummary(media: BaseMedia?) {
(summaryFragment as SummaryFragment).setMedia(media, onTablet())
}
override fun setPoster(url: String?) {
poster.setImageURI(url)
}
override fun setCover(url: String?) {
cover.setImageURI(url)
}
override fun setTitle(title: String) {
toolbar.title = title
this.titleView.text = title
}
override fun setAlternativeTitlesButtonVisible(visible: Boolean) {
alternativeTitles.visibility = visible.toVisibility()
}
override fun setTrailerButtonVisible(visible: Boolean) {
trailer.visibility = visible.toVisibility()
}
override fun setFavorited(favorited: Boolean) {
// TODO: Implement later
}
override fun setType(type: String) {
this.type.text = type
}
override fun setReleaseSummary(summary: String) {
releaseSummary.text = summary
}
override fun setAgeRating(rating: String) {
ageRating.text = rating
}
override fun setFabIcon(res: Int) {
fab.setImageResource(res)
}
override fun enableFab(enable: Boolean) {
fab?.imageAlpha = if (!enable) {
153 // 60%
} else {
255 // 100%
}
fab?.isEnabled = enable
}
override fun showFullscreenCover() {
// TODO: Implement later
}
override fun showFullscreenPoster() {
// TODO: Implement later
}
override fun showAlternativeTitles(titles: Titles?, abbreviatedTitles: List<String>?) {
AlertDialog.Builder(this@MediaActivity)
.setTitle(R.string.title_alternative_titles)
.setMessage([email protected](
R.string.content_alternative_titles_message,
titles?.en ?: "?",
titles?.enJp ?: "?",
titles?.jaJp ?: "?",
abbreviatedTitles?.joinToString(", ")
))
.setPositiveButton(R.string.ok, null)
.show()
}
override fun showTrailer(videoId: String) {
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("https://youtube.com/watch?v=$videoId")))
}
override fun showLibraryEdit() {
/*val bottomSheetDialogFragment = EditBottomSheetFragment()
bottomSheetDialogFragment.show(supportFragmentManager, bottomSheetDialogFragment.tag)*/
}
override fun showToast(text: String) {
Toast.makeText(this@MediaActivity, text, Toast.LENGTH_LONG).show()
}
override fun showErrorSnackbar(text: String, actionListener: () -> Unit) {
nestedScrollView.snackbar(text, Snackbar.LENGTH_INDEFINITE) {
setAction(string(R.string.retry), {
actionListener()
})
// setActionTextColor(color)
}
}
override fun onTablet(): Boolean {
// TODO: Real check
return false
}
companion object {
private const val ARG_ID = "id"
private const val ARG_TYPE = "type"
fun getLaunchIntent(context: Context, id: String?, type: MediaType): Intent {
val intent = Intent(context, MediaActivity::class.java)
intent.putExtra(ARG_ID, id ?: "-1")
intent.putExtra(ARG_TYPE, type.toString())
return intent
}
}
}
| gpl-3.0 | 51fd1002366e8a2ddc82cdcab8b15779 | 29.744076 | 100 | 0.625867 | 4.895849 | false | false | false | false |
sabi0/intellij-community | python/src/com/jetbrains/python/inspections/PyDataclassInspection.kt | 2 | 24437 | /*
* Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
*/
package com.jetbrains.python.inspections
import com.intellij.codeInspection.LocalInspectionToolSession
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.psi.PsiElementVisitor
import com.intellij.psi.PsiNameIdentifierOwner
import com.intellij.util.containers.ContainerUtil
import com.jetbrains.python.PyNames
import com.jetbrains.python.codeInsight.stdlib.*
import com.jetbrains.python.codeInsight.typing.PyTypingTypeProvider
import com.jetbrains.python.psi.*
import com.jetbrains.python.psi.impl.PyCallExpressionHelper
import com.jetbrains.python.psi.impl.PyEvaluator
import com.jetbrains.python.psi.impl.stubs.PyDataclassFieldStubImpl
import com.jetbrains.python.psi.resolve.PyResolveContext
import com.jetbrains.python.psi.stubs.PyDataclassFieldStub
import com.jetbrains.python.psi.types.*
class PyDataclassInspection : PyInspection() {
companion object {
private val ORDER_OPERATORS = setOf("__lt__", "__le__", "__gt__", "__ge__")
private val DATACLASSES_HELPERS = setOf("dataclasses.fields", "dataclasses.asdict", "dataclasses.astuple", "dataclasses.replace")
private val ATTRS_HELPERS = setOf("attr.__init__.fields",
"attr.__init__.fields_dict",
"attr.__init__.asdict",
"attr.__init__.astuple",
"attr.__init__.assoc",
"attr.__init__.evolve")
}
override fun buildVisitor(holder: ProblemsHolder,
isOnTheFly: Boolean,
session: LocalInspectionToolSession): PsiElementVisitor = Visitor(holder, session)
private class Visitor(holder: ProblemsHolder, session: LocalInspectionToolSession) : PyInspectionVisitor(holder, session) {
override fun visitPyTargetExpression(node: PyTargetExpression?) {
super.visitPyTargetExpression(node)
if (node != null) checkMutatingFrozenAttribute(node)
}
override fun visitPyDelStatement(node: PyDelStatement?) {
super.visitPyDelStatement(node)
if (node != null) {
node
.targets
.asSequence()
.filterIsInstance<PyReferenceExpression>()
.forEach { checkMutatingFrozenAttribute(it) }
}
}
override fun visitPyClass(node: PyClass?) {
super.visitPyClass(node)
if (node != null) {
val dataclassParameters = parseDataclassParameters(node, myTypeEvalContext)
if (dataclassParameters != null) {
if (dataclassParameters.type == PyDataclassParameters.Type.STD) {
processDataclassParameters(node, dataclassParameters)
val postInit = node.findMethodByName(DUNDER_POST_INIT, false, myTypeEvalContext)
val initVars = mutableListOf<PyTargetExpression>()
node.processClassLevelDeclarations { element, _ ->
if (element is PyTargetExpression) {
if (!PyTypingTypeProvider.isClassVar(element, myTypeEvalContext)) {
processDefaultFieldValue(element)
processAsInitVar(element, postInit)?.let { initVars.add(it) }
}
processFieldFunctionCall(element)
}
true
}
if (postInit != null) {
processPostInitDefinition(postInit, dataclassParameters, initVars)
}
}
else if (dataclassParameters.type == PyDataclassParameters.Type.ATTRS) {
processAttrsParameters(node, dataclassParameters)
node
.findMethodByName(DUNDER_ATTRS_POST_INIT, false, myTypeEvalContext)
?.also { processAttrsPostInitDefinition(it, dataclassParameters) }
processAttrsDefaultThroughDecorator(node)
processAttrsInitializersAndValidators(node)
processAttrsAutoAttribs(node, dataclassParameters)
processAttrIbFunctionCalls(node)
}
PyNamedTupleInspection.inspectFieldsOrder(
node,
this::registerProblem,
{
val stub = it.stub
val fieldStub = if (stub == null) PyDataclassFieldStubImpl.create(it) else stub.getCustomStub(PyDataclassFieldStub::class.java)
fieldStub?.initValue() != false && !PyTypingTypeProvider.isClassVar(it, myTypeEvalContext)
},
{
val fieldStub = PyDataclassFieldStubImpl.create(it)
if (fieldStub != null) {
fieldStub.hasDefault() ||
fieldStub.hasDefaultFactory() ||
dataclassParameters.type == PyDataclassParameters.Type.ATTRS &&
node.methods.any { m -> m.decoratorList?.findDecorator("${it.name}.default") != null }
}
else {
val assignedValue = it.findAssignedValue()
assignedValue != null && !resolvesToOmittedDefault(assignedValue, dataclassParameters.type)
}
}
)
}
}
}
override fun visitPyBinaryExpression(node: PyBinaryExpression?) {
super.visitPyBinaryExpression(node)
if (node != null && ORDER_OPERATORS.contains(node.referencedName)) {
val leftClass = getInstancePyClass(node.leftExpression) ?: return
val rightClass = getInstancePyClass(node.rightExpression) ?: return
val leftDataclassParameters = parseDataclassParameters(leftClass, myTypeEvalContext)
if (leftClass != rightClass &&
leftDataclassParameters != null &&
parseDataclassParameters(rightClass, myTypeEvalContext) != null) {
registerProblem(node.psiOperator,
"'${node.referencedName}' not supported between instances of '${leftClass.name}' and '${rightClass.name}'",
ProblemHighlightType.GENERIC_ERROR)
}
if (leftClass == rightClass && leftDataclassParameters?.order == false) {
registerProblem(node.psiOperator,
"'${node.referencedName}' not supported between instances of '${leftClass.name}'",
ProblemHighlightType.GENERIC_ERROR)
}
}
}
override fun visitPyCallExpression(node: PyCallExpression?) {
super.visitPyCallExpression(node)
if (node != null) {
val resolveContext = PyResolveContext.noImplicits().withTypeEvalContext(myTypeEvalContext)
val markedCallee = node.multiResolveCallee(resolveContext).singleOrNull()
val callee = markedCallee?.element
val calleeQName = callee?.qualifiedName
if (markedCallee != null && callee != null) {
val dataclassType = when {
DATACLASSES_HELPERS.contains(calleeQName) -> PyDataclassParameters.Type.STD
ATTRS_HELPERS.contains(calleeQName) -> PyDataclassParameters.Type.ATTRS
else -> return
}
val mapping = PyCallExpressionHelper.mapArguments(node, markedCallee, myTypeEvalContext)
val dataclassParameter = callee.getParameters(myTypeEvalContext).firstOrNull()
val dataclassArgument = mapping.mappedParameters.entries.firstOrNull { it.value == dataclassParameter }?.key
if (dataclassType == PyDataclassParameters.Type.STD) {
processHelperDataclassArgument(dataclassArgument, calleeQName!!)
}
else if (dataclassType == PyDataclassParameters.Type.ATTRS) {
processHelperAttrsArgument(dataclassArgument, calleeQName!!)
}
}
}
}
override fun visitPyReferenceExpression(node: PyReferenceExpression?) {
super.visitPyReferenceExpression(node)
if (node != null && node.isQualified) {
val cls = getInstancePyClass(node.qualifier) ?: return
if (parseStdDataclassParameters(cls, myTypeEvalContext) != null) {
cls.processClassLevelDeclarations { element, _ ->
if (element is PyTargetExpression && element.name == node.name && isInitVar(element)) {
registerProblem(node.lastChild,
"'${cls.name}' object could have no attribute '${element.name}' because it is declared as init-only",
ProblemHighlightType.GENERIC_ERROR_OR_WARNING)
return@processClassLevelDeclarations false
}
true
}
}
}
}
private fun checkMutatingFrozenAttribute(expression: PyQualifiedExpression) {
val cls = getInstancePyClass(expression.qualifier) ?: return
if (parseDataclassParameters(cls, myTypeEvalContext)?.frozen == true) {
registerProblem(expression, "'${cls.name}' object attribute '${expression.name}' is read-only", ProblemHighlightType.GENERIC_ERROR)
}
}
private fun getInstancePyClass(element: PyTypedElement?): PyClass? {
val type = element?.let { myTypeEvalContext.getType(it) } as? PyClassType
return if (type != null && !type.isDefinition) type.pyClass else null
}
private fun processDataclassParameters(cls: PyClass, dataclassParameters: PyDataclassParameters) {
if (!dataclassParameters.eq && dataclassParameters.order) {
registerProblem(dataclassParameters.eqArgument, "'eq' must be true if 'order' is true", ProblemHighlightType.GENERIC_ERROR)
}
var initMethodExists = false
var reprMethodExists = false
var eqMethodExists = false
var orderMethodsExist = false
var mutatingMethodsExist = false
var hashMethodExists = false
cls.methods.forEach {
when (it.name) {
PyNames.INIT -> initMethodExists = true
"__repr__" -> reprMethodExists = true
"__eq__" -> eqMethodExists = true
in ORDER_OPERATORS -> orderMethodsExist = true
"__setattr__", "__delattr__" -> mutatingMethodsExist = true
PyNames.HASH -> hashMethodExists = true
}
}
hashMethodExists = hashMethodExists || cls.findClassAttribute(PyNames.HASH, false, myTypeEvalContext) != null
// argument to register problem, argument name and method name
val useless = mutableListOf<Triple<PyExpression?, String, String>>()
if (dataclassParameters.init && initMethodExists) {
useless.add(Triple(dataclassParameters.initArgument, "init", PyNames.INIT))
}
if (dataclassParameters.repr && reprMethodExists) {
useless.add(Triple(dataclassParameters.reprArgument, "repr", "__repr__"))
}
if (dataclassParameters.eq && eqMethodExists) {
useless.add(Triple(dataclassParameters.eqArgument, "eq", "__eq__"))
}
useless.forEach {
registerProblem(it.first,
"'${it.second}' is ignored if the class already defines '${it.third}' method",
ProblemHighlightType.GENERIC_ERROR_OR_WARNING)
}
if (dataclassParameters.order && orderMethodsExist) {
registerProblem(dataclassParameters.orderArgument,
"'order' should be false if the class defines one of order methods",
ProblemHighlightType.GENERIC_ERROR)
}
if (dataclassParameters.frozen && mutatingMethodsExist) {
registerProblem(dataclassParameters.frozenArgument,
"'frozen' should be false if the class defines '__setattr__' or '__delattr__'",
ProblemHighlightType.GENERIC_ERROR)
}
if (dataclassParameters.unsafeHash && hashMethodExists) {
registerProblem(dataclassParameters.unsafeHashArgument,
"'unsafe_hash' should be false if the class defines '${PyNames.HASH}'",
ProblemHighlightType.GENERIC_ERROR)
}
}
private fun processAttrsParameters(cls: PyClass, dataclassParameters: PyDataclassParameters) {
var initMethod: PyFunction? = null
var reprMethod: PyFunction? = null
var strMethod: PyFunction? = null
val cmpMethods = mutableListOf<PyFunction>()
val mutatingMethods = mutableListOf<PyFunction>()
var hashMethod: PsiNameIdentifierOwner? = null
cls.methods.forEach {
when (it.name) {
PyNames.INIT -> initMethod = it
"__repr__" -> reprMethod = it
"__str__" -> strMethod = it
"__eq__",
in ORDER_OPERATORS -> cmpMethods.add(it)
"__setattr__", "__delattr__" -> mutatingMethods.add(it)
PyNames.HASH -> hashMethod = it
}
}
hashMethod = hashMethod ?: cls.findClassAttribute(PyNames.HASH, false, myTypeEvalContext)
// element to register problem and corresponding attr.s parameter
val problems = mutableListOf<Pair<PsiNameIdentifierOwner?, String>>()
if (dataclassParameters.init && initMethod != null) {
problems.add(initMethod to "init")
}
if (dataclassParameters.repr && reprMethod != null) {
problems.add(reprMethod to "repr")
}
if (PyEvaluator.evaluateAsBoolean(PyUtil.peelArgument(dataclassParameters.others["str"]), false) && strMethod != null) {
problems.add(strMethod to "str")
}
if (dataclassParameters.order && cmpMethods.isNotEmpty()) {
cmpMethods.forEach { problems.add(it to "cmp") }
}
if (dataclassParameters.frozen && mutatingMethods.isNotEmpty()) {
mutatingMethods.forEach { problems.add(it to "frozen") }
}
if (dataclassParameters.unsafeHash && hashMethod != null) {
problems.add(hashMethod to "hash")
}
problems.forEach {
it.first?.apply {
registerProblem(nameIdentifier,
"'$name' is ignored if the class already defines '${it.second}' parameter",
ProblemHighlightType.GENERIC_ERROR_OR_WARNING)
}
}
if (dataclassParameters.order && dataclassParameters.frozen && hashMethod != null) {
registerProblem(hashMethod?.nameIdentifier,
"'${PyNames.HASH}' is ignored if the class already defines 'cmp' and 'frozen' parameters",
ProblemHighlightType.GENERIC_ERROR_OR_WARNING)
}
}
private fun processDefaultFieldValue(field: PyTargetExpression) {
if (field.annotationValue == null) return
val value = field.findAssignedValue()
if (PyUtil.isForbiddenMutableDefault(value, myTypeEvalContext)) {
registerProblem(value,
"Mutable default '${value?.text}' is not allowed. Use 'default_factory'",
ProblemHighlightType.GENERIC_ERROR)
}
}
private fun processAttrsDefaultThroughDecorator(cls: PyClass) {
val initializers = mutableMapOf<String, MutableList<PyFunction>>()
cls.methods.forEach { method ->
val decorators = method.decoratorList?.decorators
if (decorators != null) {
decorators
.asSequence()
.mapNotNull { it.qualifiedName }
.filter { it.componentCount == 2 && it.endsWith("default") }
.mapNotNull { it.firstComponent }
.firstOrNull()
?.also { name ->
val attribute = cls.findClassAttribute(name, false, myTypeEvalContext)
if (attribute != null) {
initializers.computeIfAbsent(name, { _ -> mutableListOf() }).add(method)
val stub = PyDataclassFieldStubImpl.create(attribute)
if (stub != null && (stub.hasDefault() || stub.hasDefaultFactory())) {
registerProblem(method.nameIdentifier, "A default is set using 'attr.ib()'", ProblemHighlightType.GENERIC_ERROR)
}
}
}
}
}
initializers.values.forEach { sameAttrInitializers ->
val first = sameAttrInitializers[0]
sameAttrInitializers
.asSequence()
.drop(1)
.forEach { registerProblem(it.nameIdentifier, "A default is set using '${first.name}'", ProblemHighlightType.GENERIC_ERROR) }
}
}
private fun processAttrsInitializersAndValidators(cls: PyClass) {
cls.visitMethods(
{ method ->
val decorators = method.decoratorList?.decorators
if (decorators != null) {
decorators
.asSequence()
.mapNotNull { it.qualifiedName }
.filter { it.componentCount == 2 }
.mapNotNull { it.lastComponent }
.forEach {
val expectedParameters = when (it) {
"default" -> 1
"validator" -> 3
else -> return@forEach
}
val actualParameters = method.parameterList
if (actualParameters.parameters.size != expectedParameters) {
val message = "'${method.name}' should take only $expectedParameters parameter" +
if (expectedParameters > 1) "s" else ""
registerProblem(actualParameters, message, ProblemHighlightType.GENERIC_ERROR)
}
}
}
true
},
false,
myTypeEvalContext
)
}
private fun processAttrsAutoAttribs(cls: PyClass, dataclassParameters: PyDataclassParameters) {
if (PyEvaluator.evaluateAsBoolean(PyUtil.peelArgument(dataclassParameters.others["auto_attribs"]), false)) {
cls.processClassLevelDeclarations { element, _ ->
if (element is PyTargetExpression && element.annotation == null && PyDataclassFieldStubImpl.create(element) != null) {
registerProblem(element, "Attribute '${element.name}' lacks a type annotation", ProblemHighlightType.GENERIC_ERROR)
}
true
}
}
}
private fun processAttrIbFunctionCalls(cls: PyClass) {
cls.processClassLevelDeclarations { element, _ ->
if (element is PyTargetExpression) {
val call = element.findAssignedValue() as? PyCallExpression
val stub = PyDataclassFieldStubImpl.create(element)
if (call != null && stub != null) {
if (stub.hasDefaultFactory()) {
if (stub.hasDefault()) {
registerProblem(call.argumentList, "Cannot specify both 'default' and 'factory'", ProblemHighlightType.GENERIC_ERROR)
}
else {
// at least covers the following case: `attr.ib(default=attr.Factory(...), factory=...)`
val default = call.getKeywordArgument("default")
val factory = call.getKeywordArgument("factory")
if (default != null && factory != null && !resolvesToOmittedDefault(default, PyDataclassParameters.Type.ATTRS)) {
registerProblem(call.argumentList, "Cannot specify both 'default' and 'factory'", ProblemHighlightType.GENERIC_ERROR)
}
}
}
}
}
true
}
}
private fun processAsInitVar(field: PyTargetExpression, postInit: PyFunction?): PyTargetExpression? {
if (isInitVar(field)) {
if (postInit == null) {
registerProblem(field,
"Attribute '${field.name}' is useless until '$DUNDER_POST_INIT' is declared",
ProblemHighlightType.LIKE_UNUSED_SYMBOL)
}
return field
}
return null
}
private fun processFieldFunctionCall(field: PyTargetExpression) {
val fieldStub = PyDataclassFieldStubImpl.create(field) ?: return
val call = field.findAssignedValue() as? PyCallExpression ?: return
if (PyTypingTypeProvider.isClassVar(field, myTypeEvalContext) || isInitVar(field)) {
if (fieldStub.hasDefaultFactory()) {
registerProblem(call.getKeywordArgument("default_factory"),
"Field cannot have a default factory",
ProblemHighlightType.GENERIC_ERROR)
}
}
else if (fieldStub.hasDefault() && fieldStub.hasDefaultFactory()) {
registerProblem(call.argumentList, "Cannot specify both 'default' and 'default_factory'", ProblemHighlightType.GENERIC_ERROR)
}
}
private fun processPostInitDefinition(postInit: PyFunction,
dataclassParameters: PyDataclassParameters,
initVars: List<PyTargetExpression>) {
if (!dataclassParameters.init) {
registerProblem(postInit.nameIdentifier,
"'$DUNDER_POST_INIT' would not be called until 'init' parameter is set to True",
ProblemHighlightType.LIKE_UNUSED_SYMBOL)
}
val implicitParameters = postInit.getParameters(myTypeEvalContext)
val parameters = if (implicitParameters.isEmpty()) emptyList<PyCallableParameter>() else ContainerUtil.subList(implicitParameters, 1)
val message = "'$DUNDER_POST_INIT' should take all init-only variables in the same order as they are defined"
if (parameters.size != initVars.size) {
registerProblem(postInit.parameterList, message, ProblemHighlightType.GENERIC_ERROR)
}
else {
parameters
.asSequence()
.zip(initVars.asSequence())
.all { it.first.name == it.second.name }
.also { if (!it) registerProblem(postInit.parameterList, message) }
}
}
private fun processAttrsPostInitDefinition(postInit: PyFunction, dataclassParameters: PyDataclassParameters) {
if (!dataclassParameters.init) {
registerProblem(postInit.nameIdentifier,
"'$DUNDER_ATTRS_POST_INIT' would not be called until 'init' parameter is set to True",
ProblemHighlightType.LIKE_UNUSED_SYMBOL)
}
if (postInit.getParameters(myTypeEvalContext).size != 1) {
registerProblem(postInit.parameterList,
"'$DUNDER_ATTRS_POST_INIT' should not take any parameters except '${PyNames.CANONICAL_SELF}'",
ProblemHighlightType.GENERIC_ERROR)
}
}
private fun processHelperDataclassArgument(argument: PyExpression?, calleeQName: String) {
if (argument == null) return
val allowDefinition = calleeQName == "dataclasses.fields"
if (isNotExpectedDataclass(myTypeEvalContext.getType(argument), PyDataclassParameters.Type.STD, allowDefinition, true)) {
val message = "'$calleeQName' method should be called on dataclass instances" + if (allowDefinition) " or types" else ""
registerProblem(argument, message)
}
}
private fun processHelperAttrsArgument(argument: PyExpression?, calleeQName: String) {
if (argument == null) return
val instance = calleeQName != "attr.__init__.fields" && calleeQName != "attr.__init__.fields_dict"
if (isNotExpectedDataclass(myTypeEvalContext.getType(argument), PyDataclassParameters.Type.ATTRS, !instance, instance)) {
val presentableCalleeQName = calleeQName.replaceFirst(".__init__.", ".")
val message = "'$presentableCalleeQName' method should be called on attrs " + if (instance) "instances" else "types"
registerProblem(argument, message)
}
}
private fun isInitVar(field: PyTargetExpression): Boolean {
return (myTypeEvalContext.getType(field) as? PyClassType)?.classQName == DATACLASSES_INITVAR_TYPE
}
private fun isNotExpectedDataclass(type: PyType?,
dataclassType: PyDataclassParameters.Type,
allowDefinition: Boolean,
allowInstance: Boolean): Boolean {
if (type is PyStructuralType || PyTypeChecker.isUnknown(type, myTypeEvalContext)) return false
if (type is PyUnionType) return type.members.all { isNotExpectedDataclass(it, dataclassType, allowDefinition, allowInstance) }
return type !is PyClassType ||
!allowDefinition && type.isDefinition ||
!allowInstance && !type.isDefinition ||
parseDataclassParameters(type.pyClass, myTypeEvalContext)?.type != dataclassType
}
}
} | apache-2.0 | a0ddfa73e428b519c1a0d0370bf8bf25 | 40.774359 | 141 | 0.627409 | 5.459562 | false | false | false | false |
minjaesong/terran-basic-java-vm | src/net/torvald/terranvm/runtime/compiler/tbasic/Compiler.kt | 1 | 2879 | package net.torvald.terranvm.runtime.compiler.tbasic
/**
* Created by minjaesong on 2018-05-08.
*/
class Tbasic {
private val keywords = hashSetOf<String>(
"ABORT",
"ABORTM",
"ABS",
"ASC",
"BACKCOL",
"BEEP",
"CBRT",
"CEIL",
"CHR",
"CLR",
"CLS",
"COS",
"DEF FN",
"DELETE",
"DIM",
"END",
"FLOOR",
"FOR",
"GET",
"GOSUB",
"GOTO",
"HTAB",
"IF",
"INPUT",
"INT",
"INV",
"LABEL",
"LEFT",
"LEN",
"LIST",
"LOAD",
"LOG",
"MAX",
"MID",
"MIN",
"NEW",
"NEXT",
"PRINT",
"RAD",
"REM",
"RENUM",
"RETURN",
"RIGHT",
"RND",
"ROUND",
"RUN",
"SAVE",
"SCROLL",
"SGN",
"SIN",
"SQRT",
"STR",
"TAB",
"TAN",
"TEXTCOL",
"TEMIT",
"VAL",
"VTAB",
"PEEK",
"POKE"
)
private val delimeters = hashSetOf<Char>(
'(',')',',',':','"',' '
)
fun tokeniseLine(line: String): LineStructure {
var charIndex = 0
val sb = StringBuilder()
val tokensList = ArrayList<String>()
val lineNumber: Int
fun appendToList(s: String) {
if (s.isNotBlank()) tokensList.add(s)
}
if (line[0] !in '0'..'9') {
throw IllegalArgumentException("Line number not prepended to this BASIC statement: $line")
}
// scan for the line number
while (true) {
if (line[charIndex] !in '0'..'9') {
lineNumber = sb.toString().toInt()
sb.delete(0, sb.length)
charIndex++
break
}
sb.append(line[charIndex])
charIndex++
}
// the real tokenise
// --> scan until meeting numbers or delimeters
while (charIndex <= line.length) {
while (true) {
if (charIndex == line.length || line[charIndex] in delimeters) {
appendToList(sb.toString())
sb.delete(0, sb.length)
charIndex++
break
}
sb.append(line[charIndex])
charIndex++
}
}
return LineStructure(lineNumber, tokensList)
}
data class LineStructure(var lineNum: Int, val tokens: MutableList<String>)
} | mit | 64db7d6a8328911952d977aa13a3c998 | 20.818182 | 102 | 0.375478 | 4.643548 | false | false | false | false |
hellenxu/AndroidAdvanced | CrashCases/app/src/main/java/six/ca/crashcases/fragment/biz/HomeActivity.kt | 1 | 5939 | package six.ca.crashcases.fragment.biz
import android.os.Bundle
import android.view.MenuItem
import android.view.View
import androidx.core.view.GravityCompat
import androidx.core.view.get
import androidx.core.view.iterator
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import com.google.android.material.bottomnavigation.BottomNavigationView
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import six.ca.crashcases.R
import six.ca.crashcases.databinding.ActHomeBinding
import six.ca.crashcases.fragment.core.BaseActivity
import six.ca.crashcases.fragment.core.TeApplication
import six.ca.crashcases.fragment.data.AccountType
import six.ca.crashcases.fragment.data.AppEventCenterInterface
import six.ca.crashcases.fragment.data.Event
import javax.inject.Inject
import kotlin.random.Random
/**
* @author hellenxu
* @date 2020-08-20
* Copyright 2020 Six. All rights reserved.
*/
class HomeActivity: BaseActivity(), BottomNavigationView.OnNavigationItemSelectedListener {
private lateinit var homeBinding: ActHomeBinding
private lateinit var homeViewModel: HomeViewModel
private lateinit var contentAdapter: ContentAdapter
private val tabs: MutableList<String> = mutableListOf()
@set:Inject
internal lateinit var vmFactory: ViewModelProvider.Factory
@set:Inject
internal lateinit var appEventCenter: AppEventCenterInterface
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
TeApplication.instance.appComponent.inject(this)
homeBinding = ActHomeBinding.inflate(layoutInflater)
setContentView(homeBinding.root)
initViews()
initViewModel()
}
override fun onResume() {
super.onResume()
}
override fun onPause() {
super.onPause()
}
override fun onStop() {
super.onStop()
appEventCenter.reset()
}
override fun onDestroy() {
super.onDestroy()
}
private fun initViews() {
homeBinding.contentVp2.isUserInputEnabled = false
homeBinding.slidingNav.setNavigationItemSelectedListener {
switchAccount()
homeBinding.drawer.closeDrawer(GravityCompat.START)
true
}
}
private fun switchAccount() {
val accountType =
when (Random.Default.nextInt(3)) {
0 -> AccountType.VIP
1 -> AccountType.STANDARD
else -> AccountType.GUEST
}
setSelectedAccount(accountType)
}
private fun setSelectedAccount(accountType: AccountType) {
profileManager.setSelectedAccountType(accountType)
contentAdapter.initData(accountType)
homeBinding.bottomNav.menu.clear()
homeBinding.bottomNav.inflateMenu(getMenuResId(accountType))
tabs.clear()
homeBinding.bottomNav.menu.iterator().forEach {
tabs.add(it.title.toString())
}
val pos = contentAdapter.currentIndex.coerceAtLeast(0).coerceAtMost(homeBinding.bottomNav.menu.size() - 1)
val selectedItem = homeBinding.bottomNav.menu.getItem(pos)
homeBinding.bottomNav.selectedItemId = selectedItem.itemId
homeBinding.contentVp2.setCurrentItem(pos, false)
}
private fun initData() {
homeBinding.bottomNav.setOnNavigationItemSelectedListener(this)
contentAdapter = ContentAdapter(this)
homeBinding.contentVp2.adapter = contentAdapter
setSelectedAccount(profileManager.accountType)
lifecycleScope.launch {
appEventCenter.subscribe().collect {event ->
when (event) {
is Event.SwitchTab -> {
// trigger scenario: click text -> back press -> click app bringing back to foreground
contentAdapter.updateCurrentTab(event.tab)
val pos = contentAdapter.currentIndex
.coerceAtLeast(0)
.coerceAtMost(homeBinding.bottomNav.menu.size() - 1)
homeBinding.bottomNav.selectedItemId =
homeBinding.bottomNav.menu.getItem(pos).itemId
homeBinding.contentVp2.setCurrentItem(pos, false)
}
Event.Update -> {
}
}
}
}
}
private fun initViewModel() {
homeViewModel = vmFactory.create(HomeViewModel::class.java)
homeViewModel.currentState.observe(::getLifecycle, ::updateUI)
homeViewModel.retrieveProfile()
}
private fun updateUI(state: ScreenState){
when (state) {
ScreenState.Loading -> {
homeBinding.loading.visibility = View.VISIBLE
homeBinding.error.visibility = View.GONE
}
ScreenState.Success -> {
homeBinding.loading.visibility = View.GONE
homeBinding.error.visibility = View.GONE
initData()
}
ScreenState.Error -> {
homeBinding.loading.visibility = View.GONE
homeBinding.error.visibility = View.VISIBLE
}
}
}
override fun onNavigationItemSelected(item: MenuItem): Boolean {
val pos = tabs.indexOf(item.title)
contentAdapter.updateCurrentTab(pos)
homeBinding.contentVp2.setCurrentItem(contentAdapter.currentIndex, false)
return true
}
private fun getMenuResId(accountType: AccountType): Int {
return when(accountType) {
AccountType.VIP -> R.menu.vip_bottom_menu
AccountType.STANDARD -> R.menu.standard_bottom_menu
AccountType.GUEST -> R.menu.guest_bottom_menu
}
}
}
// use viewpager2, no crash when bringing it back from background after one night in background. | apache-2.0 | 4c845f230dbd43825618578dd138dae9 | 32 | 114 | 0.654656 | 5.297948 | false | false | false | false |
linroid/steps | OpenGL/AirHockey/app/src/main/java/com/linroid/airhockey/utils/Sizeof.kt | 1 | 210 | package com.linroid.airhockey.utils
/**
* @author linroid <[email protected]>
* @since 12/05/2017
*/
object Sizeof {
val INT = 4
val SHORT = 2
val FLOAT = 4
val DOUBLE = 8
val CHAR = 1
} | mit | 27b8ac87f849af9ab678e93ecaa3215e | 15.230769 | 38 | 0.604762 | 3.088235 | false | false | false | false |
FHannes/intellij-community | platform/testGuiFramework/src/com/intellij/testGuiFramework/generators/LocalContextCodeGenerator.kt | 3 | 1977 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.testGuiFramework.generators
import java.awt.Component
import java.awt.Point
import java.awt.event.MouseEvent
/**
* An abstract class for contexts such as ProjectView, ToolWindow, Editor and others.
*
* @author Sergey Karashevich
*/
abstract class LocalContextCodeGenerator<C : Component> : ContextCodeGenerator<C> {
override fun priority(): Int = 0 // prioritize component code generators 0 - for common, (n) - for the most specific
@Suppress("UNCHECKED_CAST")
fun generateCode(cmp: Component, me: MouseEvent, cp: Point): String {
return generate(typeSafeCast(cmp), me, cp)
}
fun findComponentInHierarchy(componentDeepest: Component): Component? {
val myAcceptor: (Component) -> Boolean = acceptor()
var curCmp = componentDeepest
while (!myAcceptor(curCmp) && curCmp.parent != null) curCmp = curCmp.parent
if (myAcceptor(curCmp)) return curCmp else return null
}
abstract fun acceptor(): (Component) -> Boolean
override fun accept(cmp: Component) = (findComponentInHierarchy(cmp) != null)
override fun buildContext(component: Component, mouseEvent: MouseEvent, convertedPoint: Point) =
Context(originalGenerator = this, component = typeSafeCast(findComponentInHierarchy(component)!!),
code = generate(typeSafeCast(findComponentInHierarchy(component)!!), mouseEvent, convertedPoint))
}
| apache-2.0 | ab67d31aedddccb7525dafb12f9cb413 | 35.611111 | 118 | 0.742539 | 4.422819 | false | false | false | false |
GeoffreyMetais/vlc-android | application/tools/src/main/java/org/videolan/tools/livedata/LiveDataMap.kt | 1 | 1612 | /*
* ************************************************************************
* LiveDataMap.kt
* *************************************************************************
* Copyright © 2020 VLC authors and VideoLAN
* Author: Nicolas POMEPUY
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
* **************************************************************************
*
*
*/
package org.videolan.tools.livedata
import androidx.lifecycle.MutableLiveData
class LiveDataMap<K, V> : MutableLiveData<MutableMap<K, V>>() {
private val emptyMap = mutableMapOf<K, V>()
override fun getValue(): MutableMap<K, V> {
return super.getValue() ?: emptyMap
}
fun clear() {
value = value.apply { clear() }
}
fun add(key: K, item: V) {
value = value.apply { put(key, item) }
}
fun remove(key: K) {
value = value.apply { remove(key) }
}
fun get(key: K): V? = value[key]
}
| gpl-2.0 | c5f298c76238af179c23cd8d2d655a32 | 31.22 | 80 | 0.582247 | 4.5 | false | false | false | false |
SpineEventEngine/core-java | buildSrc/src/main/kotlin/io/spine/internal/gradle/javascript/plugin/JsPlugins.kt | 2 | 3180 | /*
* Copyright 2022, TeamDev. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package io.spine.internal.gradle.javascript.plugin
import io.spine.internal.gradle.javascript.JsContext
import io.spine.internal.gradle.javascript.JsEnvironment
import org.gradle.api.Project
import org.gradle.api.plugins.ExtensionContainer
import org.gradle.api.plugins.PluginContainer
import org.gradle.api.tasks.TaskContainer
/**
* A scope for applying and configuring JavaScript-related plugins.
*
* The scope extends [JsContext] and provides shortcuts for key project's containers:
*
* 1. [plugins].
* 2. [extensions].
* 3. [tasks].
*
* Let's imagine one wants to apply and configure `FooBar` plugin. To do that, several steps
* should be completed:
*
* 1. Declare the corresponding extension function upon [JsPlugins] named after the plugin.
* 2. Apply and configure the plugin inside that function.
* 3. Call the resulted extension in your `build.gradle.kts` file.
*
* Here's an example of `javascript/plugin/FooBar.kt`:
*
* ```
* fun JsPlugins.fooBar() {
* plugins.apply("com.fooBar")
* extensions.configure<FooBarExtension> {
* // ...
* }
* }
* ```
*
* And here's how to apply it in `build.gradle.kts`:
*
* ```
* import io.spine.internal.gradle.javascript.javascript
* import io.spine.internal.gradle.javascript.plugins.fooBar
*
* // ...
*
* javascript {
* plugins {
* fooBar()
* }
* }
* ```
*/
class JsPlugins(jsEnv: JsEnvironment, project: Project) : JsContext(jsEnv, project) {
internal val plugins = project.plugins
internal val extensions = project.extensions
internal val tasks = project.tasks
internal fun plugins(configurations: PluginContainer.() -> Unit) =
plugins.run(configurations)
internal fun extensions(configurations: ExtensionContainer.() -> Unit) =
extensions.run(configurations)
internal fun tasks(configurations: TaskContainer.() -> Unit) =
tasks.run(configurations)
}
| apache-2.0 | afe8ced4792d894b4928be87c2c577d9 | 33.565217 | 92 | 0.719811 | 4.056122 | false | true | false | false |
tasks/tasks | app/src/main/java/org/tasks/location/LocationPickerActivity.kt | 1 | 15217 | package org.tasks.location
import android.app.Activity
import android.content.Intent
import android.content.res.Configuration
import android.os.Bundle
import android.os.Parcelable
import android.view.MenuItem
import android.view.View
import androidx.activity.viewModels
import androidx.appcompat.widget.SearchView
import androidx.appcompat.widget.Toolbar
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.core.content.ContextCompat
import androidx.core.widget.ContentLoadingProgressBar
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.appbar.AppBarLayout
import com.google.android.material.appbar.AppBarLayout.Behavior.DragCallback
import com.google.android.material.appbar.AppBarLayout.OnOffsetChangedListener
import com.google.android.material.appbar.CollapsingToolbarLayout
import com.todoroo.andlib.utility.AndroidUtilities
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.tasks.Event
import org.tasks.PermissionUtil.verifyPermissions
import org.tasks.R
import org.tasks.Strings.isNullOrEmpty
import org.tasks.activities.PlaceSettingsActivity
import org.tasks.analytics.Firebase
import org.tasks.billing.Inventory
import org.tasks.caldav.GeoUtils.toLikeString
import org.tasks.data.LocationDao
import org.tasks.data.Place
import org.tasks.data.Place.Companion.newPlace
import org.tasks.data.PlaceUsage
import org.tasks.databinding.ActivityLocationPickerBinding
import org.tasks.dialogs.DialogBuilder
import org.tasks.extensions.Context.toast
import org.tasks.extensions.setOnQueryTextListener
import org.tasks.injection.InjectingAppCompatActivity
import org.tasks.location.LocationPickerAdapter.OnLocationPicked
import org.tasks.location.LocationSearchAdapter.OnPredictionPicked
import org.tasks.location.MapFragment.MapFragmentCallback
import org.tasks.preferences.ActivityPermissionRequestor
import org.tasks.preferences.PermissionChecker
import org.tasks.preferences.PermissionRequestor
import org.tasks.preferences.Preferences
import org.tasks.themes.ColorProvider
import org.tasks.themes.Theme
import timber.log.Timber
import javax.inject.Inject
import kotlin.math.abs
@AndroidEntryPoint
class LocationPickerActivity : InjectingAppCompatActivity(), Toolbar.OnMenuItemClickListener, MapFragmentCallback, OnLocationPicked, SearchView.OnQueryTextListener, OnPredictionPicked, MenuItem.OnActionExpandListener {
private lateinit var toolbar: Toolbar
private lateinit var appBarLayout: AppBarLayout
private lateinit var toolbarLayout: CollapsingToolbarLayout
private lateinit var coordinatorLayout: CoordinatorLayout
private lateinit var searchView: View
private lateinit var loadingIndicator: ContentLoadingProgressBar
private lateinit var chooseRecentLocation: View
private lateinit var recyclerView: RecyclerView
@Inject lateinit var theme: Theme
@Inject lateinit var locationDao: LocationDao
@Inject lateinit var permissionChecker: PermissionChecker
@Inject lateinit var permissionRequestor: ActivityPermissionRequestor
@Inject lateinit var dialogBuilder: DialogBuilder
@Inject lateinit var map: MapFragment
@Inject lateinit var geocoder: Geocoder
@Inject lateinit var inventory: Inventory
@Inject lateinit var colorProvider: ColorProvider
@Inject lateinit var locationService: LocationService
@Inject lateinit var firebase: Firebase
@Inject lateinit var preferences: Preferences
private var mapPosition: MapPosition? = null
private var recentsAdapter: LocationPickerAdapter? = null
private var searchAdapter: LocationSearchAdapter? = null
private var places: List<PlaceUsage> = emptyList()
private var offset = 0
private lateinit var search: MenuItem
private var searchJob: Job? = null
private val viewModel: PlaceSearchViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
theme.applyTheme(this)
window.statusBarColor = ContextCompat.getColor(this, android.R.color.transparent)
val binding = ActivityLocationPickerBinding.inflate(layoutInflater)
setContentView(binding.root)
toolbar = binding.toolbar
appBarLayout = binding.appBarLayout
toolbarLayout = binding.collapsingToolbarLayout
coordinatorLayout = binding.coordinator
searchView = binding.search.apply {
setOnClickListener { searchPlace() }
}
loadingIndicator = binding.loadingIndicator
chooseRecentLocation = binding.chooseRecentLocation
recyclerView = binding.recentLocations
val configuration = resources.configuration
if (configuration.orientation == Configuration.ORIENTATION_LANDSCAPE
&& configuration.smallestScreenWidthDp < 480) {
searchView.visibility = View.GONE
}
val currentPlace: Place? = intent.getParcelableExtra(EXTRA_PLACE)
if (savedInstanceState == null) {
mapPosition = currentPlace?.mapPosition ?: intent.getParcelableExtra(EXTRA_MAP_POSITION)
} else {
mapPosition = savedInstanceState.getParcelable(EXTRA_MAP_POSITION)
offset = savedInstanceState.getInt(EXTRA_APPBAR_OFFSET)
viewModel.restoreState(savedInstanceState)
}
toolbar.setNavigationIcon(R.drawable.ic_outline_arrow_back_24px)
toolbar.setNavigationOnClickListener { collapseToolbar() }
toolbar.inflateMenu(R.menu.menu_location_picker)
val menu = toolbar.menu
search = menu.findItem(R.id.menu_search)
search.setOnActionExpandListener(this)
toolbar.setOnMenuItemClickListener(this)
val themeColor = theme.themeColor
themeColor.applyToNavigationBar(this)
val dark = preferences.mapTheme == 2
|| preferences.mapTheme == 0 && theme.themeBase.isDarkTheme(this)
map.init(this, this, dark)
val params = appBarLayout.layoutParams as CoordinatorLayout.LayoutParams
val behavior = AppBarLayout.Behavior()
behavior.setDragCallback(
object : DragCallback() {
override fun canDrag(appBarLayout: AppBarLayout): Boolean {
return false
}
})
params.behavior = behavior
appBarLayout.addOnOffsetChangedListener(
OnOffsetChangedListener { appBarLayout: AppBarLayout, offset: Int ->
if (offset == 0 && this.offset != 0) {
closeSearch()
AndroidUtilities.hideKeyboard(this)
}
this.offset = offset
toolbar.alpha = abs(offset / appBarLayout.totalScrollRange.toFloat())
})
coordinatorLayout.addOnLayoutChangeListener(
object : View.OnLayoutChangeListener {
override fun onLayoutChange(
v: View, l: Int, t: Int, r: Int, b: Int, ol: Int, ot: Int, or: Int, ob: Int) {
coordinatorLayout.removeOnLayoutChangeListener(this)
locationDao
.getPlaceUsage()
.observe(this@LocationPickerActivity) {
places: List<PlaceUsage> -> updatePlaces(places)
}
}
})
if (offset != 0) {
appBarLayout.post { expandToolbar(false) }
}
findViewById<View>(R.id.google_marker).visibility = View.VISIBLE
searchAdapter = LocationSearchAdapter(viewModel.getAttributionRes(dark), this)
recentsAdapter = LocationPickerAdapter(this, inventory, colorProvider, this)
recentsAdapter!!.setHasStableIds(true)
recyclerView.layoutManager = LinearLayoutManager(this)
recyclerView.adapter = if (search.isActionViewExpanded) searchAdapter else recentsAdapter
binding.currentLocation.setOnClickListener { currentLocation() }
binding.selectThisLocation.setOnClickListener { selectLocation() }
}
override fun onMapReady(mapFragment: MapFragment) {
map = mapFragment
updateMarkers()
if (permissionChecker.canAccessForegroundLocation()) {
mapFragment.showMyLocation()
}
mapPosition
?.let { map.movePosition(it, false) }
?: moveToCurrentLocation(false)
}
override fun onBackPressed() {
if (closeSearch()) {
return
}
if (offset != 0) {
collapseToolbar()
return
}
super.onBackPressed()
}
private fun closeSearch(): Boolean = search.isActionViewExpanded && search.collapseActionView()
override fun onPlaceSelected(place: Place) {
returnPlace(place)
}
private fun currentLocation() {
if (permissionRequestor.requestForegroundLocation()) {
moveToCurrentLocation(true)
}
}
override fun onRequestPermissionsResult(
requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
if (requestCode == PermissionRequestor.REQUEST_FOREGROUND_LOCATION) {
if (verifyPermissions(grantResults)) {
map.showMyLocation()
moveToCurrentLocation(true)
} else {
dialogBuilder
.newDialog(R.string.missing_permissions)
.setMessage(R.string.location_permission_required_location)
.setPositiveButton(R.string.ok, null)
.show()
}
} else {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
}
private fun selectLocation() {
val mapPosition = map.mapPosition ?: return
loadingIndicator.visibility = View.VISIBLE
lifecycleScope.launch {
try {
returnPlace(geocoder.reverseGeocode(mapPosition) ?: newPlace(mapPosition))
} catch (e: Exception) {
loadingIndicator.visibility = View.GONE
firebase.reportException(e)
toast(e.message)
}
}
}
private fun searchPlace() {
mapPosition = map.mapPosition
expandToolbar(true)
search.expandActionView()
}
private fun moveToCurrentLocation(animate: Boolean) {
if (!permissionChecker.canAccessForegroundLocation()) {
return
}
lifecycleScope.launch {
try {
locationService.currentLocation()?.let { map.movePosition(it, animate) }
} catch (e: Exception) {
toast(e.message)
}
}
}
private fun returnPlace(place: Place?) {
if (place == null) {
Timber.e("Place is null")
return
}
AndroidUtilities.hideKeyboard(this)
lifecycleScope.launch {
var place = place
if (place.id <= 0) {
val existing = locationDao.findPlace(
place.latitude.toLikeString(),
place.longitude.toLikeString())
if (existing == null) {
place.id = locationDao.insert(place)
} else {
place = existing
}
}
setResult(Activity.RESULT_OK, Intent().putExtra(EXTRA_PLACE, place as Parcelable?))
finish()
}
}
override fun onResume() {
super.onResume()
map.onResume()
viewModel.observe(
this,
{ searchAdapter!!.submitList(it) },
{ returnPlace(it) },
{ handleError(it) }
)
}
override fun onDestroy() {
super.onDestroy()
map.onDestroy()
}
private fun handleError(error: Event<String>) {
val message = error.ifUnhandled
if (!isNullOrEmpty(message)) {
toast(message)
}
}
private fun updatePlaces(places: List<PlaceUsage>) {
this.places = places
updateMarkers()
recentsAdapter!!.submitList(places)
val params = appBarLayout.layoutParams as CoordinatorLayout.LayoutParams
val height = coordinatorLayout.height
if (this.places.isEmpty()) {
params.height = height
chooseRecentLocation.visibility = View.GONE
collapseToolbar()
} else {
params.height = height * 75 / 100
chooseRecentLocation.visibility = View.VISIBLE
}
}
private fun updateMarkers() {
map.setMarkers(places.map(PlaceUsage::place))
}
private fun collapseToolbar() {
appBarLayout.setExpanded(true, true)
}
private fun expandToolbar(animate: Boolean) {
appBarLayout.setExpanded(false, animate)
}
override fun onPause() {
super.onPause()
map.onPause()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putParcelable(EXTRA_MAP_POSITION, map.mapPosition)
outState.putInt(EXTRA_APPBAR_OFFSET, offset)
viewModel.saveState(outState)
}
override fun onMenuItemClick(item: MenuItem): Boolean =
if (item.itemId == R.id.menu_search) {
searchPlace()
true
} else false
override fun picked(place: Place) {
returnPlace(place)
}
override fun settings(place: Place) {
val intent = Intent(this, PlaceSettingsActivity::class.java)
intent.putExtra(PlaceSettingsActivity.EXTRA_PLACE, place as Parcelable)
startActivity(intent)
}
override fun onQueryTextSubmit(query: String): Boolean = false
override fun onQueryTextChange(query: String): Boolean {
searchJob?.cancel()
searchJob = lifecycleScope.launch {
delay(SEARCH_DEBOUNCE_TIMEOUT)
viewModel.query(query, map.mapPosition)
}
return true
}
override fun picked(prediction: PlaceSearchResult) {
viewModel.fetch(prediction)
}
override fun onMenuItemActionExpand(item: MenuItem): Boolean {
search.setOnQueryTextListener(this)
searchAdapter!!.submitList(emptyList())
recyclerView.adapter = searchAdapter
return true
}
override fun onMenuItemActionCollapse(item: MenuItem): Boolean {
search.setOnQueryTextListener(null)
recyclerView.adapter = recentsAdapter
if (places.isEmpty()) {
collapseToolbar()
}
return true
}
companion object {
const val EXTRA_PLACE = "extra_place"
private const val EXTRA_MAP_POSITION = "extra_map_position"
private const val EXTRA_APPBAR_OFFSET = "extra_appbar_offset"
private const val SEARCH_DEBOUNCE_TIMEOUT = 300L
}
} | gpl-3.0 | 037f52c5d3f0473b8608c2f54a57cb80 | 36.950125 | 218 | 0.659723 | 5.41916 | false | false | false | false |
soniccat/android-taskmanager | authorization/src/main/java/com/example/alexeyglushkov/authorization/requestbuilder/ParameterList.kt | 1 | 2560 | package com.example.alexeyglushkov.authorization.requestbuilder
import org.junit.Assert
import java.util.*
import kotlin.collections.ArrayList
/**
* @author Pablo Fernandez
*/
class ParameterList {
private val params: MutableList<Parameter>
constructor() {
params = ArrayList()
}
internal constructor(params: List<Parameter>?) {
this.params = ArrayList(params)
}
constructor(map: Map<String, String>) : this() {
for ((key, value) in map) {
params.add(Parameter(key, value))
}
}
fun add(key: String, value: String) {
params.add(Parameter(key, value))
}
fun appendTo(url: String): String {
val queryString = asFormUrlEncodedString()
return if (queryString == EMPTY_STRING) {
url
} else {
var resultUrl = url + if (url.indexOf(QUERY_STRING_SEPARATOR) != -1) PARAM_SEPARATOR else QUERY_STRING_SEPARATOR
resultUrl += queryString
resultUrl
}
}
fun asOauthBaseString(): String? {
return OAuthEncoder.encode(asFormUrlEncodedString())
}
fun asFormUrlEncodedString(): String {
if (params.size == 0) return EMPTY_STRING
val builder = StringBuilder()
for (p in params) {
builder.append('&').append(p.asUrlEncodedPair())
}
return builder.toString().substring(1)
}
fun addAll(other: ParameterList) {
params.addAll(other.params)
}
fun addQuerystring(queryString: String) {
if (queryString.length > 0) {
for (param in queryString.split(PARAM_SEPARATOR).toTypedArray()) {
val pair = param.split(PAIR_SEPARATOR).toTypedArray()
val key = OAuthEncoder.decode(pair[0])
val value = if (pair.size > 1) OAuthEncoder.decode(pair[1]) else EMPTY_STRING
if (key != null && value != null) {
params.add(Parameter(key, value))
}
}
}
}
operator fun contains(param: Parameter?): Boolean {
return params.contains(param)
}
fun size(): Int {
return params.size
}
fun sort(): ParameterList {
val sorted = ParameterList(params)
Collections.sort(sorted.params)
return sorted
}
companion object {
private const val QUERY_STRING_SEPARATOR = '?'
private const val PARAM_SEPARATOR = "&"
private const val PAIR_SEPARATOR = "="
private const val EMPTY_STRING = ""
}
} | mit | 3bd17ba8c07442bfac501e8ccd7253aa | 26.537634 | 124 | 0.586719 | 4.475524 | false | false | false | false |
neo4j-contrib/neo4j-apoc-procedures | extended/src/main/kotlin/apoc/nlp/aws/AWSVirtualKeyPhrasesGraph.kt | 1 | 3972 | package apoc.nlp.aws
import apoc.graph.document.builder.DocumentToGraph
import apoc.nlp.NLPHelperFunctions
import apoc.nlp.NLPVirtualGraph
import apoc.result.VirtualGraph
import apoc.result.VirtualNode
import com.amazonaws.services.comprehend.model.BatchDetectKeyPhrasesResult
import org.neo4j.graphdb.Label
import org.neo4j.graphdb.Node
import org.neo4j.graphdb.Relationship
import org.neo4j.graphdb.RelationshipType
import org.neo4j.graphdb.Transaction
data class AWSVirtualKeyPhrasesGraph(private val detectEntitiesResult: BatchDetectKeyPhrasesResult, private val sourceNodes: List<Node>, val relType: RelationshipType, val relProperty: String, val cutoff: Number): NLPVirtualGraph() {
override fun extractDocument(index: Int, sourceNode: Node) : ArrayList<Map<String, Any>> = AWSProcedures.transformResults(index, sourceNode, detectEntitiesResult).value["keyPhrases"] as ArrayList<Map<String, Any>>
companion object {
const val SCORE_PROPERTY = "score"
val KEYS = listOf("text")
val LABEL = Label { "KeyPhrase" }
val ID_KEYS = listOf("text")
}
override fun createVirtualGraph(transaction: Transaction?): VirtualGraph {
val storeGraph = transaction != null
val allNodes: MutableSet<Node> = mutableSetOf()
val nonSourceNodes: MutableSet<Node> = mutableSetOf()
val allRelationships: MutableSet<Relationship> = mutableSetOf()
sourceNodes.forEachIndexed { index, sourceNode ->
val document = extractDocument(index, sourceNode) as List<Map<String, Any>>
val virtualNodes = LinkedHashMap<MutableSet<String>, MutableSet<Node>>()
val virtualNode = VirtualNode(sourceNode, sourceNode.propertyKeys.toList())
val documentToNodes = DocumentToGraph.DocumentToNodes(nonSourceNodes, transaction)
val entityNodes = mutableSetOf<Node>()
val relationships = mutableSetOf<Relationship>()
for (item in document) {
val labels: Array<Label> = labels(item)
val idValues: Map<String, Any> = idValues(item)
val score = item[SCORE_PROPERTY] as Number
if(score.toDouble() >= cutoff.toDouble()) {
val node = if (storeGraph) {
val keyPhraseNode = documentToNodes.getOrCreateRealNode(labels, idValues)
setProperties(keyPhraseNode, item)
entityNodes.add(keyPhraseNode)
val nodeAndScore = Pair(keyPhraseNode, score)
relationships.add(NLPHelperFunctions.mergeRelationship(sourceNode, nodeAndScore, relType, relProperty))
sourceNode
} else {
val keyPhraseNode = documentToNodes.getOrCreateVirtualNode(virtualNodes, labels, idValues)
setProperties(keyPhraseNode, item)
entityNodes.add(keyPhraseNode)
DocumentToGraph.getNodesWithSameLabels(virtualNodes, labels).add(keyPhraseNode)
val nodeAndScore = Pair(keyPhraseNode, score)
relationships.add(NLPHelperFunctions.mergeRelationship(virtualNode, nodeAndScore, relType, relProperty))
virtualNode
}
allNodes.add(node)
}
}
nonSourceNodes.addAll(entityNodes)
allNodes.addAll(entityNodes)
allRelationships.addAll(relationships)
}
return VirtualGraph("Graph", allNodes, allRelationships, emptyMap())
}
private fun idValues(item: Map<String, Any>) = ID_KEYS.map { it to item[it].toString() }.toMap()
private fun labels(item: Map<String, Any>) = arrayOf(LABEL)
private fun setProperties(entityNode: Node, item: Map<String, Any>) {
KEYS.forEach { key -> entityNode.setProperty(key, item[key].toString()) }
}
}
| apache-2.0 | c3def1fe97d46153c86b7b22d93a7d7c | 44.655172 | 233 | 0.65433 | 4.849817 | false | false | false | false |
rsiebert/TVHClient | app/src/main/java/org/tvheadend/tvhclient/ui/features/dvr/timer_recordings/TimerRecordingViewModel.kt | 1 | 4604 | package org.tvheadend.tvhclient.ui.features.dvr.timer_recordings
import android.app.Application
import android.content.Context
import android.content.Intent
import androidx.lifecycle.LiveData
import androidx.lifecycle.MediatorLiveData
import androidx.lifecycle.MutableLiveData
import org.tvheadend.data.entity.Channel
import org.tvheadend.data.entity.ServerProfile
import org.tvheadend.data.entity.TimerRecording
import org.tvheadend.tvhclient.R
import org.tvheadend.tvhclient.service.ConnectionService
import org.tvheadend.tvhclient.ui.base.BaseViewModel
import timber.log.Timber
import java.util.*
class TimerRecordingViewModel(application: Application) : BaseViewModel(application) {
var selectedListPosition = 0
val currentIdLiveData = MutableLiveData("")
var recording = TimerRecording()
var recordingLiveData = MediatorLiveData<TimerRecording>()
val recordings: LiveData<List<TimerRecording>> = appRepository.timerRecordingData.getLiveDataItems()
var recordingProfileNameId = 0
private val defaultChannelSortOrder = application.applicationContext.resources.getString(R.string.pref_default_channel_sort_order)
/**
* Returns an intent with the recording data
*/
fun getIntentData(context: Context, recording: TimerRecording): Intent {
val intent = Intent(context, ConnectionService::class.java)
intent.putExtra("directory", recording.directory)
intent.putExtra("title", recording.title)
intent.putExtra("name", recording.name)
if (isTimeEnabled) {
intent.putExtra("start", recording.start)
intent.putExtra("stop", recording.stop)
} else {
intent.putExtra("start", (0).toLong())
intent.putExtra("stop", (0).toLong())
}
intent.putExtra("daysOfWeek", recording.daysOfWeek)
intent.putExtra("priority", recording.priority)
intent.putExtra("enabled", if (recording.isEnabled) 1 else 0)
if (recording.channelId > 0) {
intent.putExtra("channelId", recording.channelId)
}
return intent
}
var isTimeEnabled: Boolean = false
set(value) {
field = value
if (!value) {
startTimeInMillis = Calendar.getInstance().timeInMillis
stopTimeInMillis = Calendar.getInstance().timeInMillis
}
}
init {
recordingLiveData.addSource(currentIdLiveData) { value ->
if (value.isNotEmpty()) {
recordingLiveData.value = appRepository.timerRecordingData.getItemById(value)
}
}
}
fun loadRecordingByIdSync(id: String) {
recording = appRepository.timerRecordingData.getItemById(id) ?: TimerRecording()
isTimeEnabled = recording.start > 0 && recording.stop > 0
}
var startTimeInMillis: Long = 0
get() {
return recording.startTimeInMillis
}
set(milliSeconds) {
field = milliSeconds
recording.start = getMinutesFromTime(milliSeconds)
}
var stopTimeInMillis: Long = 0
get() {
return recording.stopTimeInMillis
}
set(milliSeconds) {
field = milliSeconds
recording.stop = getMinutesFromTime(milliSeconds)
}
/**
* The start and stop time handling is done in milliseconds within the app, but the
* server requires and provides minutes instead. In case the start and stop times of
* a recording need to be updated the milliseconds will be converted to minutes.
*/
private fun getMinutesFromTime(milliSeconds : Long) : Long {
val calendar = Calendar.getInstance()
calendar.timeInMillis = milliSeconds
val hour = calendar.get(Calendar.HOUR_OF_DAY)
val minute = calendar.get(Calendar.MINUTE)
val minutes = (hour * 60 + minute).toLong()
Timber.d("Time in millis is $milliSeconds, start minutes are $minutes")
return minutes
}
fun getChannelList(): List<Channel> {
val channelSortOrder = Integer.valueOf(sharedPreferences.getString("channel_sort_order", defaultChannelSortOrder) ?: defaultChannelSortOrder)
return appRepository.channelData.getChannels(channelSortOrder)
}
fun getRecordingProfileNames(): Array<String> {
return appRepository.serverProfileData.recordingProfileNames
}
fun getRecordingProfile(): ServerProfile? {
return appRepository.serverProfileData.getItemById(appRepository.serverStatusData.activeItem.timerRecordingServerProfileId)
}
}
| gpl-3.0 | 1bd037e5f381811611b12f6f819eea4b | 36.430894 | 149 | 0.686142 | 5.031694 | false | false | false | false |
FFlorien/AmpachePlayer | app/src/sharedTest/java/be/florien/anyflow/data/user/AuthPersistenceFake.kt | 1 | 933 | package be.florien.anyflow.data.user
import be.florien.anyflow.data.TimeOperations
class AuthPersistenceFake : AuthPersistence() {
override val serverUrl = InMemorySecret()
override val authToken = InMemorySecret()
override val user = InMemorySecret()
override val password = InMemorySecret()
inner class InMemorySecret() : ExpirationSecret {
override var secret: String = ""
get() = if (TimeOperations.getCurrentDate().after(TimeOperations.getDateFromMillis(expiration))) "" else field
override var expiration: Long = 0L
override fun setSecretData(secret: String, expiration: Long) {
this.expiration = expiration
this.secret = secret
}
override fun hasSecret(): Boolean = secret.isNotEmpty()
override fun isDataValid(): Boolean = TimeOperations.getDateFromMillis(expiration).after(TimeOperations.getCurrentDate())
}
} | gpl-3.0 | 980f0f312d4f6e8256757e45b75f3c15 | 34.923077 | 129 | 0.700965 | 5.331429 | false | false | false | false |
DemonWav/IntelliJBukkitSupport | src/main/kotlin/platform/bukkit/PaperModuleType.kt | 1 | 1561 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2021 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.bukkit
import com.demonwav.mcdev.asset.PlatformAssets
import com.demonwav.mcdev.facet.MinecraftFacet
import com.demonwav.mcdev.platform.AbstractModuleType
import com.demonwav.mcdev.platform.PlatformType
import com.demonwav.mcdev.platform.bukkit.generation.BukkitEventGenerationPanel
import com.demonwav.mcdev.platform.bukkit.util.BukkitConstants
import com.demonwav.mcdev.platform.bungeecord.util.BungeeCordConstants
import com.demonwav.mcdev.util.CommonColors
import com.intellij.psi.PsiClass
object PaperModuleType : AbstractModuleType<BukkitModule<PaperModuleType>>("com.destroystokyo.paper", "paper-api") {
private const val ID = "PAPER_MODULE_TYPE"
init {
CommonColors.applyStandardColors(colorMap, BukkitConstants.CHAT_COLOR_CLASS)
CommonColors.applyStandardColors(colorMap, BungeeCordConstants.CHAT_COLOR_CLASS)
}
override val platformType = PlatformType.PAPER
override val icon = PlatformAssets.PAPER_ICON
override val id = ID
override val ignoredAnnotations = BukkitModuleType.IGNORED_ANNOTATIONS
override val listenerAnnotations = BukkitModuleType.LISTENER_ANNOTATIONS
override val isEventGenAvailable = true
override fun generateModule(facet: MinecraftFacet): BukkitModule<PaperModuleType> = BukkitModule(facet, this)
override fun getEventGenerationPanel(chosenClass: PsiClass) = BukkitEventGenerationPanel(chosenClass)
}
| mit | 29b963ecce2e070795d21ebce0ff4d21 | 37.073171 | 116 | 0.80205 | 4.397183 | false | false | false | false |
ohmae/mmupnp | mmupnp/src/test/java/net/mm2d/upnp/internal/server/MulticastEventReceiverTest.kt | 1 | 9400 | /*
* Copyright (c) 2019 大前良介 (OHMAE Ryosuke)
*
* This software is released under the MIT License.
* http://opensource.org/licenses/MIT
*/
package net.mm2d.upnp.internal.server
import io.mockk.every
import io.mockk.mockk
import io.mockk.mockkConstructor
import io.mockk.spyk
import io.mockk.unmockkConstructor
import io.mockk.verify
import net.mm2d.upnp.Http
import net.mm2d.upnp.HttpRequest
import net.mm2d.upnp.internal.thread.TaskExecutors
import net.mm2d.upnp.internal.thread.ThreadCondition
import net.mm2d.upnp.internal.util.closeQuietly
import net.mm2d.upnp.util.NetworkUtils
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
import java.io.ByteArrayOutputStream
import java.net.MulticastSocket
import java.net.SocketTimeoutException
@Suppress("TestFunctionName", "NonAsciiCharacters")
@RunWith(JUnit4::class)
class MulticastEventReceiverTest {
private lateinit var taskExecutors: TaskExecutors
@Before
fun setUp() {
taskExecutors = TaskExecutors()
}
@After
fun tearDown() {
taskExecutors.terminate()
}
@Test(timeout = 20000L)
fun `start stop デッドロックしない`() {
val networkInterface = NetworkUtils.getAvailableInet4Interfaces()[0]
val receiver = MulticastEventReceiver(taskExecutors, Address.IP_V4, networkInterface, mockk())
receiver.start()
receiver.stop()
}
@Test(timeout = 20000L)
fun `stop デッドロックしない`() {
val networkInterface = NetworkUtils.getAvailableInet4Interfaces()[0]
val receiver = MulticastEventReceiver(taskExecutors, Address.IP_V4, networkInterface, mockk())
receiver.stop()
}
@Test(timeout = 20000L)
fun `run 正常動作`() {
mockkConstructor(ThreadCondition::class)
every { anyConstructed<ThreadCondition>().isCanceled() } returns false
val networkInterface = NetworkUtils.getAvailableInet4Interfaces()[0]
val receiver = spyk(MulticastEventReceiver(taskExecutors, Address.IP_V4, networkInterface, mockk()))
val socket: MulticastSocket = mockk(relaxed = true)
every { receiver.createMulticastSocket(any()) } returns socket
every { receiver.receiveLoop(any()) } answers { nothing }
receiver.run()
verify {
socket.joinGroup(any())
receiver.receiveLoop(any())
socket.leaveGroup(any())
socket.closeQuietly()
}
unmockkConstructor(ThreadCondition::class)
}
@Test(timeout = 20000L)
fun `run すでにcancel`() {
mockkConstructor(ThreadCondition::class)
every { anyConstructed<ThreadCondition>().isCanceled() } returns true
val networkInterface = NetworkUtils.getAvailableInet4Interfaces()[0]
val receiver = spyk(MulticastEventReceiver(taskExecutors, Address.IP_V4, networkInterface, mockk()))
val socket: MulticastSocket = mockk(relaxed = true)
every { receiver.createMulticastSocket(any()) } returns socket
every { receiver.receiveLoop(any()) } answers { nothing }
receiver.run()
verify(inverse = true) {
socket.joinGroup(any())
receiver.receiveLoop(any())
socket.leaveGroup(any())
socket.closeQuietly()
}
unmockkConstructor(ThreadCondition::class)
}
@Test(timeout = 20000L)
fun `receiveLoop 1ループ`() {
mockkConstructor(ThreadCondition::class)
every { anyConstructed<ThreadCondition>().isCanceled() } returns false
val networkInterface = NetworkUtils.getAvailableInet4Interfaces()[0]
val receiver = spyk(MulticastEventReceiver(taskExecutors, Address.IP_V4, networkInterface, mockk()))
val socket: MulticastSocket = mockk(relaxed = true)
every { receiver.onReceive(any(), any()) } answers {
every { anyConstructed<ThreadCondition>().isCanceled() } returns true
}
receiver.receiveLoop(socket)
verify(exactly = 1) { receiver.onReceive(any(), any()) }
unmockkConstructor(ThreadCondition::class)
}
@Test(timeout = 20000L)
fun `receiveLoop SocketTimeoutExceptionが発生しても次のループに入る`() {
mockkConstructor(ThreadCondition::class)
every { anyConstructed<ThreadCondition>().isCanceled() } returns false
val networkInterface = NetworkUtils.getAvailableInet4Interfaces()[0]
val receiver = spyk(MulticastEventReceiver(taskExecutors, Address.IP_V4, networkInterface, mockk()))
val socket: MulticastSocket = mockk(relaxed = true)
every { receiver.onReceive(any(), any()) } throws (SocketTimeoutException()) andThenAnswer {
every { anyConstructed<ThreadCondition>().isCanceled() } returns true
}
receiver.receiveLoop(socket)
verify(exactly = 2) { receiver.onReceive(any(), any()) }
unmockkConstructor(ThreadCondition::class)
}
@Test(timeout = 20000L)
fun `receiveLoop receiveの時点でcancelされればonReceiveはコールされない`() {
mockkConstructor(ThreadCondition::class)
every { anyConstructed<ThreadCondition>().isCanceled() } returns false
val networkInterface = NetworkUtils.getAvailableInet4Interfaces()[0]
val receiver = spyk(MulticastEventReceiver(taskExecutors, Address.IP_V4, networkInterface, mockk()))
val socket: MulticastSocket = mockk(relaxed = true)
every { socket.receive(any()) } throws (SocketTimeoutException()) andThenAnswer {
every { anyConstructed<ThreadCondition>().isCanceled() } returns true
}
receiver.receiveLoop(socket)
verify(exactly = 2) { socket.receive(any()) }
verify(inverse = true) { receiver.onReceive(any(), any()) }
unmockkConstructor(ThreadCondition::class)
}
@Test
fun `onReceive 条件がそろわなければ通知されない`() {
val listener: (uuid: String, svcid: String, lvl: String, seq: Long, properties: List<Pair<String, String>>) -> Unit =
mockk(relaxed = true)
val networkInterface = NetworkUtils.getAvailableInet4Interfaces()[0]
val receiver = MulticastEventReceiver(taskExecutors, Address.IP_V4, networkInterface, listener)
val request = HttpRequest.create()
request.setStartLine("NOTIFY * HTTP/1.0")
request.toByteArray().also {
receiver.onReceive(it, it.size)
}
verify(inverse = true) { listener.invoke(any(), any(), any(), any(), any()) }
request.setHeader(Http.NT, Http.UPNP_EVENT)
request.toByteArray().also {
receiver.onReceive(it, it.size)
}
verify(inverse = true) { listener.invoke(any(), any(), any(), any(), any()) }
request.setHeader(Http.NTS, Http.UPNP_PROPCHANGE)
request.toByteArray().also {
receiver.onReceive(it, it.size)
}
verify(inverse = true) { listener.invoke(any(), any(), any(), any(), any()) }
request.setHeader(Http.LVL, "")
request.toByteArray().also {
receiver.onReceive(it, it.size)
}
verify(inverse = true) { listener.invoke(any(), any(), any(), any(), any()) }
request.setHeader(Http.LVL, "upnp:/info")
request.toByteArray().also {
receiver.onReceive(it, it.size)
}
verify(inverse = true) { listener.invoke(any(), any(), any(), any(), any()) }
request.setHeader(Http.SEQ, "hoge")
request.toByteArray().also {
receiver.onReceive(it, it.size)
}
verify(inverse = true) { listener.invoke(any(), any(), any(), any(), any()) }
request.setHeader(Http.SEQ, "1")
request.toByteArray().also {
receiver.onReceive(it, it.size)
}
verify(inverse = true) { listener.invoke(any(), any(), any(), any(), any()) }
request.setHeader(Http.SVCID, "")
request.toByteArray().also {
receiver.onReceive(it, it.size)
}
verify(inverse = true) { listener.invoke(any(), any(), any(), any(), any()) }
request.setHeader(Http.SVCID, "svcid")
request.toByteArray().also {
receiver.onReceive(it, it.size)
}
verify(inverse = true) { listener.invoke(any(), any(), any(), any(), any()) }
request.setHeader(Http.USN, "uuid:01234567-89ab-cdef-0123-456789abcdef")
request.toByteArray().also {
receiver.onReceive(it, it.size)
}
verify(inverse = true) { listener.invoke(any(), any(), any(), any(), any()) }
request.setBody(
"<e:propertyset xmlns:e=\"urn:schemas-upnp-org:event-1-0\">\n" +
"<e:property>\n" +
"<SystemUpdateID>0</SystemUpdateID>\n" +
"</e:property>\n" +
"<e:property>\n" +
"<ContainerUpdateIDs></ContainerUpdateIDs>\n" +
"</e:property>\n" +
"</e:propertyset>", true
)
request.toByteArray().also {
receiver.onReceive(it, it.size)
}
verify(exactly = 1) { listener.invoke(any(), any(), any(), any(), any()) }
}
private fun HttpRequest.toByteArray(): ByteArray = ByteArrayOutputStream().also { writeData(it) }.toByteArray()
}
| mit | 8eccebe1a9d57ac746af91751ea367a3 | 37.516667 | 125 | 0.638576 | 4.483026 | false | false | false | false |
drakeet/MultiType | sample/src/main/kotlin/com/drakeet/multitype/sample/weibo/WeiboContentDeserializer.kt | 1 | 1640 | /*
* Copyright (c) 2016-present. Drakeet Xu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.drakeet.multitype.sample.weibo
import com.google.gson.*
import com.drakeet.multitype.sample.weibo.content.SimpleImage
import com.drakeet.multitype.sample.weibo.content.SimpleText
import java.lang.reflect.Type
/**
* @author Drakeet Xu
*/
class WeiboContentDeserializer : JsonDeserializer<WeiboContent> {
@Throws(JsonParseException::class)
override fun deserialize(json: JsonElement, type: Type, context: JsonDeserializationContext): WeiboContent? {
val gson = WeiboJsonParser.GSON
val jsonObject = json as JsonObject
val contentType = stringOrEmpty(jsonObject.get("content_type"))
var content: WeiboContent? = null
if (SimpleText.TYPE == contentType) {
content = gson.fromJson(json, SimpleText::class.java)
} else if (SimpleImage.TYPE == contentType) {
content = gson.fromJson(json, SimpleImage::class.java)
}
return content
}
private fun stringOrEmpty(jsonElement: JsonElement): String {
return if (jsonElement.isJsonNull) "" else jsonElement.asString
}
}
| apache-2.0 | 16efe2cfbb3d7e219a13a2fd2df6e9ff | 33.893617 | 111 | 0.742073 | 4.173028 | false | false | false | false |
dkluffy/dkluff-code | code/LuffySubber/app/新建文件夹/Movie.kt | 1 | 1495 | /*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package android.dktv.com.luffysubber
import java.io.Serializable
/**
* Movie class represents video entity with title, description, image thumbs and video url.
*/
data class Movie(
var id: Long = 0,
var title: String? = null,
var description: String? = null,
var backgroundImageUrl: String? = null,
var cardImageUrl: String? = null,
var videoUrl: String? = null,
var studio: String? = null
) : Serializable {
override fun toString(): String {
return "Movie{" +
"id=" + id +
", title='" + title + '\'' +
", videoUrl='" + videoUrl + '\'' +
", backgroundImageUrl='" + backgroundImageUrl + '\'' +
", cardImageUrl='" + cardImageUrl + '\'' +
'}'
}
companion object {
internal const val serialVersionUID = 727566175075960653L
}
}
| apache-2.0 | c9d9932e6665dcd60afdf002df23ed2c | 32.222222 | 100 | 0.636789 | 4.295977 | false | false | false | false |
soywiz/korge | @old/korge-spriter/src/commonMain/kotlin/com/soywiz/korge/ext/spriter/com/brashmonkey/spriter/Data.kt | 1 | 2540 | package com.soywiz.korge.ext.spriter.com.brashmonkey.spriter
@Suppress("unused", "MemberVisibilityCanBePrivate")
/**
* Represents all the data which necessary to animate a Spriter generated SCML file.
* An instance of this class holds [Folder]s and [Entity] instances.
* Specific [Folder] and [Entity] instances can be accessed via the corresponding methods, i.e. getEntity()
* and getFolder().
* @author Trixt0r
*/
class Data(
val scmlVersion: String,
val generator: String,
val generatorVersion: String,
val pixelMode: PixelMode,
folders: Int,
entities: Int,
val atlases: List<String>
) {
/**
* Represents the rendering mode stored in the spriter data root.
*/
enum class PixelMode {
NONE, PIXEL_ART;
companion object {
/**
* @param mode
* *
* @return The pixel mode for the given int value. Default is [NONE].
*/
operator fun get(mode: Int): PixelMode {
when (mode) {
1 -> return PIXEL_ART
else -> return NONE
}
}
}
}
val folders: Array<Folder> = Array(folders) { Folder.DUMMY }
val entities: Array<Entity> = Array(entities) { Entity.DUMMY }
private var folderPointer = 0
private var entityPointer = 0
fun addFolder(folder: Folder) {
this.folders[folderPointer++] = folder
}
fun addEntity(entity: Entity) {
this.entities[entityPointer++] = entity
}
fun getFolder(name: String): Folder? {
val index = getFolderIndex(name)
return if (index >= 0) getFolder(index) else null
}
fun getFolderIndex(name: String): Int = this.folders.firstOrNull { it.name == name }?.id ?: -1
fun getFolder(index: Int): Folder = this.folders[index]
fun getEntity(index: Int): Entity = this.entities[index]
fun getEntity(name: String): Entity? {
val index = getEntityIndex(name)
return if (index >= 0) getEntity(index) else null
}
fun getEntityIndex(name: String): Int = this.entities.firstOrNull { it.name == name }?.id ?: -1
fun getFile(folder: Folder, file: Int): File = folder.getFile(file)
fun getFile(folder: Int, file: Int): File = getFile(this.getFolder(folder), file)
fun getFile(ref: FileReference): File = this.getFile(ref.folder, ref.file)
/**
* @return The string representation of this spriter data
*/
override fun toString(): String {
var toReturn = "" + this::class +
"|[Version: " + scmlVersion +
", Generator: " + generator +
" (" + generatorVersion + ")]"
for (folder in folders)
toReturn += "\n" + folder
for (entity in entities)
toReturn += "\n" + entity
toReturn += "]"
return toReturn
}
}
| apache-2.0 | 3d456c39a590e4836a350191b81960eb | 26.021277 | 107 | 0.676772 | 3.446404 | false | false | false | false |
ivan-osipov/Clabo | src/main/kotlin/com/github/ivan_osipov/clabo/api/model/Audio.kt | 1 | 460 | package com.github.ivan_osipov.clabo.api.model
import com.google.gson.annotations.SerializedName
class Audio : AbstractFileDescriptor() {
@SerializedName("duration")
private var _duration: Int? = null
val duration: Int
get() = _duration!!
@SerializedName("performer")
var performer: String? = null
@SerializedName("title")
var title: String? = null
@SerializedName("mime_type")
var mimeType: String? = null
} | apache-2.0 | 868421ccd145283938fdd7ce455ec061 | 19.954545 | 49 | 0.678261 | 4.144144 | false | false | false | false |
openstreetview/android | app/src/main/java/com/telenav/osv/data/collector/datatype/datatypes/BaseObject.kt | 1 | 1756 | package com.telenav.osv.data.collector.datatype.datatypes
import androidx.annotation.NonNull
import com.telenav.osv.data.collector.datatype.util.LibraryUtil
import com.telenav.osv.data.collector.datatype.util.LibraryUtil.AvailableData
/**
* This class represents the super class of all data types inside the DataCollector library
* @param <T>
</T> */
open class BaseObject<T> {
var timestamp = System.currentTimeMillis()
protected var actualValue: T? = null
open var statusCode = -1
var dataSource = ""
protected set
private var sensorType = ""
constructor() {}
constructor(value: T, statusCode: Int) {
actualValue = value
this.statusCode = statusCode
}
protected constructor(value: T, statusCode: Int, @NonNull @AvailableData sensorType: String) : this(value, statusCode) {
this.sensorType = sensorType
}
open fun getSensorType(): String? {
return sensorType
}
val errorCodeDescription: String
get() {
var status = " "
status += when (statusCode) {
LibraryUtil.OBD_NOT_AVAILABLE, LibraryUtil.PHONE_SENSOR_NOT_AVAILABLE -> LibraryUtil.SENSOR_NOT_AVAILABLE_DESCRIPTION
LibraryUtil.OBD_READ_SUCCESS, LibraryUtil.PHONE_SENSOR_READ_SUCCESS -> LibraryUtil.SENSOR_READ_SUCCESS_DESCRIPTION
LibraryUtil.OBD_INITIALIZATION_FAILURE -> LibraryUtil.SENSOR_INITIALIZATION_FAILURE_DESCRIPTION
LibraryUtil.OBD_AVAILABLE -> LibraryUtil.SENSOR_AVAILABLE_DESCRIPTION
LibraryUtil.OBD_READ_FAILURE -> LibraryUtil.SENSOR_READ_FAILURE_DESCRIPTION
else -> LibraryUtil.SENSOR_READ_FAILURE_DESCRIPTION
}
return status
}
} | lgpl-3.0 | c015963d360b322f96b3a5fd07fd409d | 37.195652 | 133 | 0.679954 | 4.771739 | false | false | false | false |
MaTriXy/retrofit | retrofit/src/main/java/retrofit2/KotlinExtensions.kt | 1 | 3111 | /*
* Copyright (C) 2018 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:JvmName("KotlinExtensions")
package retrofit2
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.yield
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
inline fun <reified T> Retrofit.create(): T = create(T::class.java)
suspend fun <T : Any> Call<T>.await(): T {
return suspendCancellableCoroutine { continuation ->
continuation.invokeOnCancellation {
cancel()
}
enqueue(object : Callback<T> {
override fun onResponse(call: Call<T>, response: Response<T>) {
if (response.isSuccessful) {
val body = response.body()
if (body == null) {
val invocation = call.request().tag(Invocation::class.java)!!
val method = invocation.method()
val e = KotlinNullPointerException("Response from " +
method.declaringClass.name +
'.' +
method.name +
" was null but response body type was declared as non-null")
continuation.resumeWithException(e)
} else {
continuation.resume(body)
}
} else {
continuation.resumeWithException(HttpException(response))
}
}
override fun onFailure(call: Call<T>, t: Throwable) {
continuation.resumeWithException(t)
}
})
}
}
@JvmName("awaitNullable")
suspend fun <T : Any> Call<T?>.await(): T? {
return suspendCancellableCoroutine { continuation ->
continuation.invokeOnCancellation {
cancel()
}
enqueue(object : Callback<T?> {
override fun onResponse(call: Call<T?>, response: Response<T?>) {
if (response.isSuccessful) {
continuation.resume(response.body())
} else {
continuation.resumeWithException(HttpException(response))
}
}
override fun onFailure(call: Call<T?>, t: Throwable) {
continuation.resumeWithException(t)
}
})
}
}
suspend fun <T : Any> Call<T>.awaitResponse(): Response<T> {
return suspendCancellableCoroutine { continuation ->
continuation.invokeOnCancellation {
cancel()
}
enqueue(object : Callback<T> {
override fun onResponse(call: Call<T>, response: Response<T>) {
continuation.resume(response)
}
override fun onFailure(call: Call<T>, t: Throwable) {
continuation.resumeWithException(t)
}
})
}
}
internal suspend fun Exception.yieldAndThrow(): Nothing {
yield()
throw this
}
| apache-2.0 | 3a39518db6e1b85cb1eb1b43dd9d1d53 | 29.203883 | 76 | 0.646095 | 4.534985 | false | false | false | false |
lchli/MiNote | host/src/main/java/com/lch/menote/note/data/db/AppDbOpenHelper.kt | 1 | 2952 | package com.lch.menote.note.data.db
import android.content.Context
import android.content.ContextWrapper
import android.database.DatabaseErrorHandler
import android.database.sqlite.SQLiteDatabase
import android.util.Log
import com.apkfuns.logutils.LogUtils
import com.lch.menote.note.data.db.gen.DaoMaster
import com.lch.menote.ConstantUtil
import com.lchli.utils.tool.ExtFileUtils
import org.apache.commons.io.FileUtils
import org.greenrobot.greendao.database.Database
import java.io.File
class AppDbOpenHelper : DaoMaster.DevOpenHelper {
constructor(context: Context, name: String, factory: SQLiteDatabase.CursorFactory, isSdcardDatabase: Boolean = false) : super(chooseContext(context, isSdcardDatabase), name, factory)
constructor(context: Context, name: String, isSdcardDatabase: Boolean = false) : super(chooseContext(context, isSdcardDatabase), name)
/**
* in production environment,you can Override this to impl your needs.
*
*
* note:when upgrade you must modify DaoMaster#SCHEMA_VERSION.
*
* @param db
* @param oldVersion
* @param newVersion
*/
override fun onUpgrade(db: Database?, oldVersion: Int, newVersion: Int) {
Log.e("greenDAO", "Upgrading schema from version $oldVersion to $newVersion by dropping all tables")
if (oldVersion == 1) {
db!!.execSQL("ALTER TABLE note ADD CATEGORY integer")
} else {
DaoMaster.dropAllTables(db, true)
onCreate(db)
}
}
companion object {
private fun chooseContext(context: Context, isSdcardDatabase: Boolean): Context {
return if (!isSdcardDatabase) {
context
} else object : ContextWrapper(context) {
override fun getDatabasePath(name: String): File {
try {
FileUtils.forceMkdir(File(ConstantUtil.DB_DIR))
} catch (e: Exception) {
e.printStackTrace()
}
val noteDb = File(ConstantUtil.DB_DIR, name)
LogUtils.e("DB_DIR exists:" + File(ConstantUtil.DB_DIR).exists())
ExtFileUtils.makeFile(noteDb.absolutePath)
LogUtils.e("db:" + noteDb.absolutePath)
return noteDb
}
override fun openOrCreateDatabase(name: String, mode: Int, factory: SQLiteDatabase.CursorFactory?): SQLiteDatabase {
return SQLiteDatabase.openOrCreateDatabase(getDatabasePath(name), factory)
}
override fun openOrCreateDatabase(name: String, mode: Int, factory: SQLiteDatabase.CursorFactory?, errorHandler: DatabaseErrorHandler?): SQLiteDatabase {
return SQLiteDatabase.openOrCreateDatabase(getDatabasePath(name).path, factory, errorHandler)
}
}
}
}
} | gpl-3.0 | 125f05b7d20a31640a98421068d8477d | 29.132653 | 186 | 0.638211 | 4.961345 | false | false | false | false |
salRoid/Filmy | app/src/main/java/tech/salroid/filmy/ui/activities/CharacterDetailsActivity.kt | 1 | 6733 | package tech.salroid.filmy.ui.activities
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.text.Html
import android.view.MenuItem
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.preference.PreferenceManager
import androidx.recyclerview.widget.GridLayoutManager
import com.bumptech.glide.Glide
import org.json.JSONException
import tech.salroid.filmy.R
import tech.salroid.filmy.data.local.model.CastDetailsResponse
import tech.salroid.filmy.data.local.model.CastMovie
import tech.salroid.filmy.data.local.model.CastMovieDetailsResponse
import tech.salroid.filmy.data.network.NetworkUtil
import tech.salroid.filmy.databinding.ActivityDetailedCastBinding
import tech.salroid.filmy.ui.activities.fragment.FullReadFragment
import tech.salroid.filmy.ui.adapters.CharacterDetailsActivityAdapter
import tech.salroid.filmy.utility.toReadableDate
class CharacterDetailsActivity : AppCompatActivity() {
private var characterId: String? = null
private var characterTitle: String? = null
private var moviesList: ArrayList<CastMovie>? = null
private var characterBio: String? = null
private var fullReadFragment: FullReadFragment? = null
private var nightMode = false
private lateinit var binding: ActivityDetailedCastBinding
override fun onCreate(savedInstanceState: Bundle?) {
val sp = PreferenceManager.getDefaultSharedPreferences(this)
nightMode = sp.getBoolean("dark", false)
if (nightMode) setTheme(R.style.AppTheme_Base_Dark) else setTheme(R.style.AppTheme_Base)
super.onCreate(savedInstanceState)
binding = ActivityDetailedCastBinding.inflate(layoutInflater)
setContentView(binding.root)
setSupportActionBar(binding.toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.title = ""
binding.more.setOnClickListener {
if (!(moviesList == null && characterTitle == null)) {
val intent = Intent(this@CharacterDetailsActivity, FullMovieActivity::class.java)
intent.putExtra("cast_movies", moviesList)
intent.putExtra("toolbar_title", characterTitle)
startActivity(intent)
}
}
binding.characterMovies.layoutManager = GridLayoutManager(this@CharacterDetailsActivity, 3)
binding.characterMovies.isNestedScrollingEnabled = false
binding.overviewContainer.setOnClickListener {
if (characterTitle != null && characterBio != null) {
fullReadFragment = FullReadFragment()
val args = Bundle()
args.putString("title", characterTitle)
args.putString("desc", characterBio)
fullReadFragment!!.arguments = args
supportFragmentManager.beginTransaction()
.replace(R.id.main, fullReadFragment!!).addToBackStack("DESC").commit()
}
}
val intent = intent
if (intent != null) {
characterId = intent.getStringExtra("id")
}
characterId?.let {
NetworkUtil.getCastDetails(it, { details ->
details?.let { it1 ->
showPersonalDetails(it1)
}
}, {
})
NetworkUtil.getCastMovieDetails(it, { details ->
details?.let { it1 ->
this.moviesList = it1.castMovies
showPersonMovies(it1)
}
}, {
})
}
}
override fun onResume() {
super.onResume()
val sp = PreferenceManager.getDefaultSharedPreferences(this)
val nightModeNew = sp.getBoolean("dark", false)
if (nightMode != nightModeNew) recreate()
}
private fun showPersonalDetails(details: CastDetailsResponse) {
try {
val dataName = details.name
val dataProfile = "http://image.tmdb.org/t/p/w185" + details.profilePath
val dataOverview = details.biography
val dataBirthday = details.birthday
val dataBirthPlace = details.placeOfBirth
characterTitle = dataName
characterBio = dataOverview
binding.name.text = dataName
if (dataBirthday == "null") {
binding.dob.visibility = View.GONE
} else {
binding.dob.text = dataBirthday?.toReadableDate()
}
if (dataBirthPlace == "null") {
binding.birthPlace.visibility = View.GONE
} else {
binding.birthPlace.text = dataBirthPlace
}
if (dataOverview?.isEmpty() == true) {
binding.overviewContainer.visibility = View.GONE
binding.overview.visibility = View.GONE
} else {
if (Build.VERSION.SDK_INT >= 24) {
binding.overview.text = Html.fromHtml(dataOverview, Html.FROM_HTML_MODE_LEGACY)
}
}
try {
Glide.with(this)
.load(dataProfile)
.fitCenter().into(binding.displayProfile)
} catch (e: Exception) {
}
} catch (e: JSONException) {
e.printStackTrace()
}
}
private fun showPersonMovies(castMovieDetails: CastMovieDetailsResponse) {
val charAdapter =
CharacterDetailsActivityAdapter(castMovieDetails.castMovies, true) { movie, _ ->
val intent = Intent(this, MovieDetailsActivity::class.java)
intent.putExtra("id", movie.id.toString())
intent.putExtra("title", movie.title)
intent.putExtra("network_applicable", true)
intent.putExtra("activity", false)
startActivity(intent)
}
binding.characterMovies.adapter = charAdapter
if (castMovieDetails.castMovies.size > 4) {
binding.more.visibility = View.VISIBLE
} else {
binding.more.visibility = View.INVISIBLE
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == android.R.id.home) {
supportFinishAfterTransition()
}
return super.onOptionsItemSelected(item)
}
override fun onBackPressed() {
val fragment = supportFragmentManager.findFragmentByTag("DESC") as FullReadFragment?
if (fragment != null && fragment.isVisible) {
supportFragmentManager.beginTransaction().remove(fullReadFragment!!).commit()
} else {
super.onBackPressed()
}
}
} | apache-2.0 | bfc2fe612c57b4278be131288da6a74e | 36.411111 | 99 | 0.623645 | 5.203246 | false | false | false | false |
mvarnagiris/expensius | app/src/main/kotlin/com/mvcoding/expensius/feature/settings/SettingsItemView.kt | 1 | 1153 | /*
* Copyright (C) 2016 Mantas Varnagiris.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package com.mvcoding.expensius.feature.settings
import android.content.Context
import android.util.AttributeSet
import android.widget.LinearLayout
import kotlinx.android.synthetic.main.item_view_settings.view.*
class SettingsItemView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) :
LinearLayout(context, attrs, defStyleAttr) {
fun setTitle(title: String) = with(titleTextView) { text = title }
fun setSubtitle(subtitle: String) = with(subtitleTextView) { text = subtitle; visibility = if (subtitle.isBlank()) GONE else VISIBLE }
} | gpl-3.0 | 02c0cd9ef058b157bf88c05fe94a1de8 | 41.740741 | 139 | 0.759757 | 4.334586 | false | false | false | false |
petropavel13/2photo-android | TwoPhoto/app/src/main/java/com/github/petropavel13/twophoto/adapters/PostEntriesPagerAdapter.kt | 1 | 2272 | package com.github.petropavel13.twophoto.adapters
import android.content.Context
import android.support.v4.view.PagerAdapter
import android.support.v4.view.ViewPager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.github.petropavel13.twophoto.R
import com.github.petropavel13.twophoto.model.Post
import com.github.petropavel13.twophoto.views.EntryView
import java.util.HashMap
/**
* Created by petropavel on 31/03/15.
*/
class PostEntriesPagerAdapter(ctx: Context, var entries: List<Post.Entry>): PagerAdapter() {
private val inflater = ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
private var _onEntryTapListener: View.OnClickListener? = null
var onEntryTapListener: View.OnClickListener?
get() = _onEntryTapListener
set(newValue) {
_onEntryTapListener = newValue
_positionViewMap.values.forEach { it.onTapListener = newValue }
}
private var _showEntriesDescription = true
var showEntriesDescription: Boolean
get() = _showEntriesDescription
set(newValue) {
_showEntriesDescription = newValue
_positionViewMap.values.forEach { it.showDescriptionText = newValue }
}
private val _positionViewMap = HashMap<Int, EntryView>(3)
fun getViewForAtPosition(position: Int): EntryView? = _positionViewMap.get(position)
override fun getCount() = entries.count()
override fun isViewFromObject(view: View?, obj: Any?): Boolean {
return obj === view
}
override fun instantiateItem(container: View?, position: Int): Any? {
with(inflater.inflate(R.layout.entry_layout, container as? ViewGroup, false) as EntryView) {
entry = entries[position]
onTapListener = _onEntryTapListener
showDescriptionText = showEntriesDescription
(container as ViewPager).addView(this, 0)
_positionViewMap.put(position, this)
return this
}
}
override fun destroyItem(container: View?, position: Int, item: Any?) {
with(item as EntryView) {
(container as ViewPager).removeView(this)
_positionViewMap.remove(position)
}
}
} | mit | 1af8dd553bd9b61ded77cc8087b73dca | 29.716216 | 100 | 0.693222 | 4.694215 | false | false | false | false |
taigua/exercism | kotlin/acronym/src/main/kotlin/Acronym.kt | 1 | 459 | object Acronym {
fun generate(s: String) : String {
val l = s.split(Regex("\\W+"))
var acronym = ""
for (word in l) {
acronym += word[0].toUpperCase()
val remainer = word.drop(1)
val upperRemainer = remainer.replace(Regex("[^A-Z]"), "")
if (!upperRemainer.isEmpty() && remainer != upperRemainer)
acronym += upperRemainer
}
return acronym
}
} | mit | 4edd192ef0cc0848cb106048676177a9 | 29.666667 | 70 | 0.501089 | 4.25 | false | false | false | false |
holisticon/ranked | backend/views/leaderboard/src/main/kotlin/PlayerRankingByElo.kt | 1 | 3415 | @file:Suppress("UNUSED")
package de.holisticon.ranked.view.leaderboard
import de.holisticon.ranked.model.Elo
import de.holisticon.ranked.model.UserName
import de.holisticon.ranked.model.event.PlayerRankingChanged
import mu.KLogging
import org.axonframework.config.ProcessingGroup
import org.axonframework.eventhandling.EventHandler
import org.axonframework.eventhandling.Timestamp
import org.springframework.stereotype.Component
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import java.time.Instant
import java.time.LocalDateTime
import java.time.ZoneId
import java.util.concurrent.atomic.AtomicReference
import java.util.function.Supplier
const val PROCESSING_GROUP = "PlayerLeaderBoard"
/**
* The rest controller just provides a facade for [PlayerRankingByEloHandler.get].
*/
@RestController
@RequestMapping(value = ["/view/elo"])
class PlayerLeaderBoardView(
private val playerRankingByElo: PlayerRankingByEloHandler
) {
@GetMapping(path = ["/player"])
fun userListByEloRank() : List<PlayerElo> = playerRankingByElo.get()
@GetMapping(path = ["/player/{userName}"])
fun eloHistoryByPlayer(@PathVariable("userName") userName: String): MutableList<Pair<LocalDateTime, Elo>> = playerRankingByElo.getHistory(userName)
}
/**
* The business logic for elo-rankings, handles axon events that affect players and elo and provides a sorted list
* descending by elo value.
*/
@Component
@ProcessingGroup(PROCESSING_GROUP)
class PlayerRankingByEloHandler : Supplier<List<PlayerElo>> {
companion object : KLogging()
/**
* Holds a mutable list of userName->elo, this is the data store that is updated with every elo change.
*/
private val ranking = mutableMapOf<UserName, Elo>()
/**
* Holds a mutable list of userName->List<timestamp, elo>, this is the history of elo values that is updated with every elo change.
*/
private val rankingHistory = mutableMapOf<UserName, MutableList<Pair<LocalDateTime, Elo>>>()
/**
* The cache holds an immutable list of [PlayerElo] for the json return. It is sorted descending by elo value.
* A cache is used because we only need to sort once per update and can return the same immutable sorted list
* for every get request after that.
*/
private val cache = AtomicReference<List<PlayerElo>>(listOf())
@EventHandler
fun on(e: PlayerRankingChanged, @Timestamp t: Instant) {
logger.debug { "Player '${e.player}' new rating is '${e.eloRanking}'" }
ranking[e.player] = e.eloRanking
rankingHistory.putIfAbsent(e.player, mutableListOf())
rankingHistory[e.player]!!.add(Pair(LocalDateTime.ofInstant(t, ZoneId.of("Europe/Berlin")), e.eloRanking))
cache.set(ranking.map { it.toPair() }.map { PlayerElo(it.first, it.second) }.sorted())
}
override fun get() = cache.get()!!
fun getHistory(userName: String) = rankingHistory[UserName(userName)] ?: mutableListOf()
}
/**
* The return value for the player ranking provides a username (string) and an elo value (int).
*/
data class PlayerElo(val userName: UserName, val elo: Elo) : Comparable<PlayerElo> {
constructor(userName: String, elo: Elo) : this(UserName(userName), elo)
override fun compareTo(other: PlayerElo): Int = other.elo.compareTo(elo)
}
| bsd-3-clause | edcc8f24dea0aaa61b1c633a5005a21a | 35.72043 | 149 | 0.761347 | 4.174817 | false | false | false | false |
InfiniteSoul/ProxerAndroid | src/main/kotlin/me/proxer/app/news/widget/NewsWidgetUpdateWorker.kt | 1 | 8375 | package me.proxer.app.news.widget
import android.app.PendingIntent
import android.app.PendingIntent.FLAG_UPDATE_CURRENT
import android.appwidget.AppWidgetManager
import android.content.ComponentName
import android.content.Context
import android.view.View
import android.widget.RemoteViews
import androidx.work.Constraints
import androidx.work.ExistingWorkPolicy
import androidx.work.NetworkType
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.WorkManager
import androidx.work.Worker
import androidx.work.WorkerParameters
import com.mikepenz.iconics.IconicsDrawable
import com.mikepenz.iconics.typeface.library.community.material.CommunityMaterial
import com.mikepenz.iconics.utils.colorRes
import com.mikepenz.iconics.utils.paddingDp
import com.mikepenz.iconics.utils.sizeDp
import com.squareup.moshi.Moshi
import me.proxer.app.BuildConfig
import me.proxer.app.MainActivity
import me.proxer.app.R
import me.proxer.app.forum.TopicActivity
import me.proxer.app.util.ErrorUtils
import me.proxer.app.util.ErrorUtils.ErrorAction
import me.proxer.app.util.extension.intentFor
import me.proxer.app.util.extension.safeInject
import me.proxer.app.util.extension.toInstantBP
import me.proxer.app.util.extension.unsafeLazy
import me.proxer.app.util.wrapper.MaterialDrawerWrapper
import me.proxer.library.ProxerApi
import me.proxer.library.ProxerCall
import org.koin.core.KoinComponent
import timber.log.Timber
/**
* @author Ruben Gees
*/
class NewsWidgetUpdateWorker(
context: Context,
workerParams: WorkerParameters
) : Worker(context, workerParams), KoinComponent {
companion object : KoinComponent {
private const val NAME = "NewsWidgetUpdateWorker"
private val workManager by safeInject<WorkManager>()
fun enqueueWork() {
val workRequest = OneTimeWorkRequestBuilder<NewsWidgetUpdateWorker>()
.setConstraints(
Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build()
)
.build()
workManager.beginUniqueWork(NAME, ExistingWorkPolicy.REPLACE, workRequest).enqueue()
}
}
private val api by safeInject<ProxerApi>()
private val moshi by safeInject<Moshi>()
private val appWidgetManager by unsafeLazy { AppWidgetManager.getInstance(applicationContext) }
private val widgetIds by unsafeLazy {
appWidgetManager.getAppWidgetIds(ComponentName(applicationContext, NewsWidgetProvider::class.java))
}
private val darkWidgetIds by unsafeLazy {
appWidgetManager.getAppWidgetIds(ComponentName(applicationContext, NewsWidgetDarkProvider::class.java))
}
private var currentCall: ProxerCall<*>? = null
override fun doWork(): Result {
widgetIds.forEach { id -> bindLoadingLayout(appWidgetManager, id, false) }
darkWidgetIds.forEach { id -> bindLoadingLayout(appWidgetManager, id, true) }
return try {
val news = if (!isStopped) {
api.notifications.news()
.build()
.also { currentCall = it }
.safeExecute()
.map {
SimpleNews(it.id, it.threadId, it.categoryId, it.subject, it.category, it.date.toInstantBP())
}
} else {
emptyList()
}
if (!isStopped) {
if (news.isEmpty()) {
val noDataAction = ErrorAction(R.string.error_no_data_news)
widgetIds.forEach { id -> bindErrorLayout(appWidgetManager, id, noDataAction, false) }
darkWidgetIds.forEach { id -> bindErrorLayout(appWidgetManager, id, noDataAction, true) }
} else {
widgetIds.forEach { id -> bindListLayout(appWidgetManager, id, news, false) }
darkWidgetIds.forEach { id -> bindListLayout(appWidgetManager, id, news, true) }
}
}
Result.success()
} catch (error: Throwable) {
Timber.e(error)
if (!isStopped) {
val action = ErrorUtils.handle(error)
widgetIds.forEach { id -> bindErrorLayout(appWidgetManager, id, action, false) }
darkWidgetIds.forEach { id -> bindErrorLayout(appWidgetManager, id, action, true) }
}
return Result.failure()
}
}
override fun onStopped() {
currentCall?.cancel()
currentCall = null
}
private fun bindListLayout(appWidgetManager: AppWidgetManager, id: Int, news: List<SimpleNews>, dark: Boolean) {
val views = RemoteViews(
BuildConfig.APPLICATION_ID,
when (dark) {
true -> R.layout.layout_widget_news_dark_list
false -> R.layout.layout_widget_news_list
}
)
val serializedNews = news
.map { moshi.adapter(SimpleNews::class.java).toJson(it) }
.toTypedArray()
val intent = when (dark) {
true -> applicationContext.intentFor<NewsWidgetDarkService>(
NewsWidgetDarkService.ARGUMENT_NEWS to serializedNews
)
false -> applicationContext.intentFor<NewsWidgetService>(
NewsWidgetService.ARGUMENT_NEWS to serializedNews
)
}
val detailIntent = applicationContext.intentFor<TopicActivity>()
val detailPendingIntent = PendingIntent.getActivity(applicationContext, 0, detailIntent, FLAG_UPDATE_CURRENT)
bindBaseLayout(id, views)
views.setPendingIntentTemplate(R.id.list, detailPendingIntent)
views.setRemoteAdapter(R.id.list, intent)
appWidgetManager.updateAppWidget(id, views)
}
private fun bindErrorLayout(appWidgetManager: AppWidgetManager, id: Int, errorAction: ErrorAction, dark: Boolean) {
val views = RemoteViews(
BuildConfig.APPLICATION_ID,
when (dark) {
true -> R.layout.layout_widget_news_dark_error
false -> R.layout.layout_widget_news_error
}
)
val errorIntent = errorAction.toIntent()
bindBaseLayout(id, views)
views.setTextViewText(R.id.errorText, applicationContext.getString(errorAction.message))
if (errorIntent != null) {
val errorPendingIntent = PendingIntent.getActivity(applicationContext, 0, errorIntent, FLAG_UPDATE_CURRENT)
views.setTextViewText(R.id.errorButton, applicationContext.getString(errorAction.buttonMessage))
views.setOnClickPendingIntent(R.id.errorButton, errorPendingIntent)
} else {
views.setViewVisibility(R.id.errorButton, View.GONE)
}
appWidgetManager.updateAppWidget(id, views)
}
private fun bindLoadingLayout(appWidgetManager: AppWidgetManager, id: Int, dark: Boolean) {
val views = RemoteViews(
BuildConfig.APPLICATION_ID,
when (dark) {
true -> R.layout.layout_widget_news_dark_loading
false -> R.layout.layout_widget_news_loading
}
)
bindBaseLayout(id, views)
appWidgetManager.updateAppWidget(id, views)
}
private fun bindBaseLayout(id: Int, views: RemoteViews) {
val intent = MainActivity.getSectionIntent(applicationContext, MaterialDrawerWrapper.DrawerItem.NEWS)
val pendingIntent = PendingIntent.getActivity(applicationContext, 0, intent, FLAG_UPDATE_CURRENT)
val updateIntent = applicationContext.intentFor<NewsWidgetProvider>()
.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE)
.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, intArrayOf(id))
val updatePendingIntent = PendingIntent.getBroadcast(applicationContext, 0, updateIntent, FLAG_UPDATE_CURRENT)
views.setOnClickPendingIntent(R.id.title, pendingIntent)
views.setOnClickPendingIntent(R.id.refresh, updatePendingIntent)
views.setImageViewBitmap(
R.id.refresh,
IconicsDrawable(applicationContext, CommunityMaterial.Icon.cmd_refresh)
.colorRes(android.R.color.white)
.sizeDp(32)
.paddingDp(8)
.toBitmap()
)
}
}
| gpl-3.0 | fd18b26d3f74fbbed0a645b8dee029e6 | 36.222222 | 119 | 0.658985 | 5.008971 | false | false | false | false |
wordpress-mobile/AztecEditor-Android | aztec/src/main/kotlin/org/wordpress/aztec/util/SpanWrapper.kt | 1 | 3259 | package org.wordpress.aztec.util
import android.text.Spannable
import org.wordpress.android.util.AppLog
class SpanWrapper<T>(var spannable: Spannable, var span: T) {
private var frozenStart: Int = -1
private var frozenEnd: Int = -1
private var frozenFlags: Int = -1
fun remove() {
frozenStart = start
frozenEnd = end
frozenFlags = flags
spannable.removeSpan(span)
}
fun reapply() {
if (frozenFlags != -1 && frozenEnd != -1 && frozenStart != -1) {
setSpanOrLogError(span, frozenStart, frozenEnd, frozenFlags)
}
}
var start: Int
get() { return spannable.getSpanStart(span) }
set(start) { setSpanOrLogError(span, start, end, flags) }
var end: Int
get() { return spannable.getSpanEnd(span) }
set(end) { setSpanOrLogError(span, start, end, flags) }
var flags: Int
get() { return spannable.getSpanFlags(span) }
set(flags) { setSpanOrLogError(span, start, end, flags) }
private fun setSpanOrLogError(span: T, start: Int, end: Int, flags: Int) {
// Silently ignore invalid PARAGRAPH spans that don't start or end at paragraph boundary
if (isInvalidParagraph(spannable, start, end, flags)) return
spannable.setSpan(span, start, end, flags)
}
companion object {
// Copied from SpannableStringBuilder
private val START_MASK = 0xF0
private val END_MASK = 0x0F
private val START_SHIFT = 4
private val PARAGRAPH = 3
fun isInvalidParagraph(spannable: Spannable, start: Int, end: Int, flags: Int) : Boolean {
// Copied from SpannableStringBuilder that throws an exception in this case.
val flagsStart = flags and START_MASK shr START_SHIFT
if (isInvalidParagraph(spannable, start, flagsStart)) {
AppLog.w(AppLog.T.EDITOR, "PARAGRAPH span must start at paragraph boundary"
+ " (" + start + " follows " + spannable.get(start - 1) + ")")
return true
}
val flagsEnd = flags and END_MASK
if (isInvalidParagraph(spannable, end, flagsEnd)) {
AppLog.w(AppLog.T.EDITOR, "PARAGRAPH span must end at paragraph boundary"
+ " (" + end + " follows " + spannable.get(end - 1) + ")")
return true
}
return false
}
private fun isInvalidParagraph(spannable: Spannable, index: Int, flag: Int): Boolean {
return flag == PARAGRAPH && index != 0 && index != spannable.length && spannable.get(index - 1) != '\n'
}
inline fun <reified T : Any> getSpans(spannable: Spannable, start: Int, end: Int): List<SpanWrapper<T>> {
return getSpans(spannable, spannable.getSpans(start, end, T::class.java))
}
fun <T> getSpans(spannable: Spannable, start: Int, end: Int, type: Class<T>): List<SpanWrapper<T>> {
return getSpans(spannable, spannable.getSpans(start, end, type))
}
fun <T> getSpans(spannable: Spannable, spanObjects: Array<T>): List<SpanWrapper<T>> {
return spanObjects.map { it -> SpanWrapper(spannable, it) }
}
}
}
| mpl-2.0 | 36adbeee64075b14be0bb01bebe09469 | 36.45977 | 115 | 0.602025 | 4.305152 | false | false | false | false |
kenrube/Fantlab-client | app/src/main/kotlin/ru/fantlab/android/ui/widgets/ViewPagerView.kt | 2 | 1551 | package ru.fantlab.android.ui.widgets
import android.annotation.SuppressLint
import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import androidx.viewpager.widget.PagerAdapter
import androidx.viewpager.widget.ViewPager
/**
* Created by kosh20111 on 10/8/2015.
*
*
* Viewpager that has scrolling animation by default
*/
class ViewPagerView : ViewPager {
private var isEnabled: Boolean = false
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
val attrsArray = intArrayOf(android.R.attr.enabled)
val array = context.obtainStyledAttributes(attrs, attrsArray)
isEnabled = array.getBoolean(0, true)
array.recycle()
}
override fun isEnabled(): Boolean {
return isEnabled
}
override fun setEnabled(enabled: Boolean) {
this.isEnabled = enabled
requestLayout()
}
override fun setAdapter(adapter: PagerAdapter?) {
super.setAdapter(adapter)
if (isInEditMode) return
adapter?.let {
offscreenPageLimit = it.count
}
}
@SuppressLint("ClickableViewAccessibility")
override fun onTouchEvent(event: MotionEvent): Boolean {
try {
return !isEnabled() || super.onTouchEvent(event)
} catch (ex: IllegalArgumentException) {
ex.printStackTrace()
}
return false
}
override fun onInterceptTouchEvent(event: MotionEvent): Boolean {
try {
return isEnabled() && super.onInterceptTouchEvent(event)
} catch (ex: IllegalArgumentException) {
ex.printStackTrace()
}
return false
}
}
| gpl-3.0 | 3dc22db1d99302475385a418be16cf00 | 22.5 | 77 | 0.749194 | 3.926582 | false | false | false | false |
tarantelklient/kotlin-argparser | src/main/kotlin/argparser/Argparser.kt | 1 | 3786 | package argparser
import argparser.exception.NotAllowedValueException
import argparser.exception.NotDeclaredException
import argparser.exception.RequiredNotPassedException
/**
* This is a simple argument parser for command line
* tools.
*
* @param description Description for the program
* @param programName Name of the program
*/
class Argparser(var description: String = "", var programName: String = "") {
private var arguments: HashMap<String, Argument> = HashMap()
/**
* Add an option to the parser.
*
* @param description Description
* @param option The name of the option
* @param hasValue Should there be a value after the option
*/
fun addArgument(description: String, option: String, defaultValue: String = "",
optional: Boolean = false, hasValue: Boolean = true) {
val a = Argument(
defaultValue = defaultValue,
description = description,
hasValue = hasValue,
optional = optional
)
arguments.put(option.replace("--", ""), a)
}
/**
* Parse the arguments passed to the program.
*
* @param args Arguments from the command line
*/
fun parse(args: Array<String>): Map<String, String> {
var cmd: String
var lastArg: Argument? = null
// Is there a help option?
if (args.contains("--help")) {
printHelp()
return emptyMap()
}
// Reset arguments
arguments.forEach { _, a ->
a.isSet = false
a.value = a.defaultValue
}
// Parse each argument
args.forEach { arg ->
// Is it a option?
if (arg.startsWith("--")) {
cmd = arg.replace("--", "")
if (!arguments.containsKey(cmd))
throw NotDeclaredException("The option '$arg' was not declared.")
lastArg = arguments[cmd]
lastArg?.isSet = true
} else {
if (lastArg!!.hasValue)
lastArg!!.value += "$arg "
else
throw NotAllowedValueException("There mustn't be a value after the option ${lastArg!!.value}")
}
}
return transformOptions()
}
/**
* Print all arguments and values if the command
* 'help' was used.
*/
private fun printHelp() {
if (programName.isNotEmpty())
println("usage:\n\t$programName [option_1] [value_1] ...")
// Filter the arguments
val opt = arguments.filterValues { argument -> argument.optional }
val req = arguments.filterValues { argument -> !argument.optional }
println("")
println("description:\n\t$description")
if (req.isNotEmpty()) {
println("")
println("required arguments: ")
req.forEach { k, v ->
if (!v.optional)
println("\t--$k\t\t${v.description}")
}
}
if (opt.isNotEmpty()) {
println("")
println("optional arguments: ")
opt.forEach { k, v ->
if (v.optional)
println("\t--$k\t\t${v.description}")
}
}
}
/**
* Transform the arguments list into a map.
*
* @return option list as map
*/
private fun transformOptions(): Map<String, String> {
val result: HashMap<String, String> = HashMap()
arguments.forEach { k, v ->
if (!v.isSet && !v.optional)
throw RequiredNotPassedException("Required argument was not passed.")
result.put(k, v.value.trim())
}
return result
}
}
| mit | 8dda50d490302f627b8eeff169df15d1 | 28.348837 | 114 | 0.534601 | 4.897801 | false | false | false | false |
mwolfson/android-historian | app/src/main/java/com/designdemo/uaha/view/product/device/DeviceTypeAdapter.kt | 1 | 3085 | package com.designdemo.uaha.view.product.device
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Build
import android.util.TypedValue
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import com.bumptech.glide.Glide
import com.designdemo.uaha.view.detail.DetailActivity
import com.support.android.designlibdemo.R
import androidx.core.app.ActivityOptionsCompat
import androidx.recyclerview.widget.RecyclerView
import com.designdemo.uaha.data.model.product.ProductEntity
import kotlinx.android.synthetic.main.list_item_device.view.*
class DeviceTypeAdapter(private val activity: Activity, context: Context, private val values: List<ProductEntity>) :
RecyclerView.Adapter<DeviceTypeAdapter.ViewHolder>() {
private val typedValue = TypedValue()
private val background: Int
class ViewHolder(val view: View) : RecyclerView.ViewHolder(view) {
var boundString: String? = null
val imageView: ImageView = view.device_item_avatar
val titleText: TextView = view.device_item_title
val subTitleText: TextView = view.device_item_subtext
override fun toString() = super.toString() + " '" + titleText.text
}
fun getValueAt(position: Int) = values[position]
init {
context.theme.resolveAttribute(R.attr.selectableItemBackground, typedValue, true)
background = typedValue.resourceId
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.list_item_device, parent, false)
view.setBackgroundResource(background)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.boundString = values[position].title
holder.titleText.text = values[position].title
holder.subTitleText.text = values[position].subTitle
holder.view.setOnClickListener { v ->
val context = v.context
val intent = Intent(context, DetailActivity::class.java)
val intentString = "${values[position].title}-${values[position].subTitle}"
intent.putExtra(DetailActivity.EXTRA_APP_NAME, intentString)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
val transitionName = context.getString(R.string.transition_string)
val options = ActivityOptionsCompat.makeSceneTransitionAnimation(
activity,
holder.imageView,
transitionName)
context.startActivity(intent, options.toBundle())
} else {
context.startActivity(intent)
}
}
Glide.with(holder.imageView.context)
.load(values[position].imgId)
.fitCenter()
.into(holder.imageView)
}
override fun getItemCount() = values.size
}
| apache-2.0 | 2168ef5398ee1a86583107a3873ce821 | 36.621951 | 116 | 0.691086 | 4.760802 | false | false | false | false |
inorichi/tachiyomi-extensions | src/all/hitomi/src/eu/kanade/tachiyomi/extension/all/hitomi/HitomiNozomi.kt | 1 | 8437 | package eu.kanade.tachiyomi.extension.all.hitomi
import eu.kanade.tachiyomi.extension.all.hitomi.Hitomi.Companion.LTN_BASE_URL
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.network.asObservable
import eu.kanade.tachiyomi.network.asObservableSuccess
import okhttp3.Headers
import okhttp3.OkHttpClient
import okhttp3.Request
import rx.Observable
import rx.Single
import java.security.MessageDigest
private typealias HashedTerm = ByteArray
private data class DataPair(val offset: Long, val length: Int)
private data class Node(
val keys: List<ByteArray>,
val datas: List<DataPair>,
val subnodeAddresses: List<Long>
)
/**
* Kotlin port of the hitomi.la search algorithm
* @author NerdNumber9
*/
class HitomiNozomi(
private val client: OkHttpClient,
private val tagIndexVersion: Long,
private val galleriesIndexVersion: Long
) {
fun getGalleryIdsForQuery(query: String, language: String, popular: Boolean): Single<List<Int>> {
if (':' in query) {
val sides = query.split(':')
val namespace = sides[0]
var tag = sides[1]
var area: String? = namespace
if (namespace == "female" || namespace == "male") {
area = "tag"
tag = query
} else if (namespace == "language") {
return getGalleryIdsFromNozomi(null, "index", tag, popular)
}
return getGalleryIdsFromNozomi(area, tag, language, popular)
}
val key = hashTerm(query)
val field = "galleries"
return getNodeAtAddress(field, 0).flatMap { node ->
if (node == null) {
Single.just(null)
} else {
BSearch(field, key, node).flatMap { data ->
if (data == null) {
Single.just(null)
} else {
getGalleryIdsFromData(data)
}
}
}
}
}
private fun getGalleryIdsFromData(data: DataPair?): Single<List<Int>> {
if (data == null) {
return Single.just(emptyList())
}
val url = "$LTN_BASE_URL/$GALLERIES_INDEX_DIR/galleries.$galleriesIndexVersion.data"
val (offset, length) = data
if (length > 100000000 || length <= 0) {
return Single.just(emptyList())
}
return client.newCall(rangedGet(url, offset, offset + length - 1))
.asObservable()
.map {
it.body?.bytes() ?: ByteArray(0)
}
.onErrorReturn { ByteArray(0) }
.map { inbuf ->
if (inbuf.isEmpty()) {
return@map emptyList<Int>()
}
val view = ByteCursor(inbuf)
val numberOfGalleryIds = view.nextInt()
val expectedLength = numberOfGalleryIds * 4 + 4
if (numberOfGalleryIds > 10000000 ||
numberOfGalleryIds <= 0 ||
inbuf.size != expectedLength
) {
return@map emptyList<Int>()
}
(1..numberOfGalleryIds).map {
view.nextInt()
}
}.toSingle()
}
@Suppress("FunctionName")
private fun BSearch(field: String, key: ByteArray, node: Node?): Single<DataPair?> {
fun compareByteArrays(dv1: ByteArray, dv2: ByteArray): Int {
val top = dv1.size.coerceAtMost(dv2.size)
for (i in 0 until top) {
val dv1i = dv1[i].toInt() and 0xFF
val dv2i = dv2[i].toInt() and 0xFF
if (dv1i < dv2i) {
return -1
} else if (dv1i > dv2i) {
return 1
}
}
return 0
}
fun locateKey(key: ByteArray, node: Node): Pair<Boolean, Int> {
var cmpResult = -1
var lastI = 0
for (nodeKey in node.keys) {
cmpResult = compareByteArrays(key, nodeKey)
if (cmpResult <= 0) break
lastI++
}
return (cmpResult == 0) to lastI
}
fun isLeaf(node: Node): Boolean {
return !node.subnodeAddresses.any {
it != 0L
}
}
if (node == null || node.keys.isEmpty()) {
return Single.just(null)
}
val (there, where) = locateKey(key, node)
if (there) {
return Single.just(node.datas[where])
} else if (isLeaf(node)) {
return Single.just(null)
}
return getNodeAtAddress(field, node.subnodeAddresses[where]).flatMap { newNode ->
BSearch(field, key, newNode)
}
}
private fun decodeNode(data: ByteArray): Node {
val view = ByteCursor(data)
val numberOfKeys = view.nextInt()
val keys = (1..numberOfKeys).map {
val keySize = view.nextInt()
view.next(keySize)
}
val numberOfDatas = view.nextInt()
val datas = (1..numberOfDatas).map {
val offset = view.nextLong()
val length = view.nextInt()
DataPair(offset, length)
}
val numberOfSubnodeAddresses = B + 1
val subnodeAddresses = (1..numberOfSubnodeAddresses).map {
view.nextLong()
}
return Node(keys, datas, subnodeAddresses)
}
private fun getNodeAtAddress(field: String, address: Long): Single<Node?> {
var url = "$LTN_BASE_URL/$INDEX_DIR/$field.$tagIndexVersion.index"
if (field == "galleries") {
url = "$LTN_BASE_URL/$GALLERIES_INDEX_DIR/galleries.$galleriesIndexVersion.index"
}
return client.newCall(rangedGet(url, address, address + MAX_NODE_SIZE - 1))
.asObservableSuccess()
.map {
it.body?.bytes() ?: ByteArray(0)
}
.onErrorReturn { ByteArray(0) }
.map { nodedata ->
if (nodedata.isNotEmpty()) {
decodeNode(nodedata)
} else null
}.toSingle()
}
fun getGalleryIdsFromNozomi(area: String?, tag: String, language: String, popular: Boolean): Single<List<Int>> {
val replacedTag = tag.replace('_', ' ')
var nozomiAddress = "$LTN_BASE_URL/$COMPRESSED_NOZOMI_PREFIX/$replacedTag-$language$NOZOMI_EXTENSION"
if (area != null) {
nozomiAddress = if (popular) {
"$LTN_BASE_URL/$COMPRESSED_NOZOMI_PREFIX/$area/popular/$replacedTag-$language$NOZOMI_EXTENSION"
} else {
"$LTN_BASE_URL/$COMPRESSED_NOZOMI_PREFIX/$area/$replacedTag-$language$NOZOMI_EXTENSION"
}
}
return client.newCall(
Request.Builder()
.url(nozomiAddress)
.build()
)
.asObservableSuccess()
.map { resp ->
val body = resp.body!!.bytes()
val cursor = ByteCursor(body)
(1..body.size / 4).map {
cursor.nextInt()
}
}.toSingle()
}
private fun hashTerm(query: String): HashedTerm {
val md = MessageDigest.getInstance("SHA-256")
md.update(query.toByteArray(HASH_CHARSET))
return md.digest().copyOf(4)
}
companion object {
private const val INDEX_DIR = "tagindex"
private const val GALLERIES_INDEX_DIR = "galleriesindex"
private const val COMPRESSED_NOZOMI_PREFIX = "n"
private const val NOZOMI_EXTENSION = ".nozomi"
private const val MAX_NODE_SIZE = 464
private const val B = 16
private val HASH_CHARSET = Charsets.UTF_8
fun rangedGet(url: String, rangeBegin: Long, rangeEnd: Long?): Request {
return GET(
url,
Headers.Builder()
.add("Range", "bytes=$rangeBegin-${rangeEnd ?: ""}")
.build()
)
}
fun getIndexVersion(httpClient: OkHttpClient, name: String): Observable<Long> {
return httpClient.newCall(GET("$LTN_BASE_URL/$name/version?_=${System.currentTimeMillis()}"))
.asObservableSuccess()
.map { it.body!!.string().toLong() }
}
}
}
| apache-2.0 | 20a5e616ffed57fd0367723bd1443595 | 31.828794 | 116 | 0.531587 | 4.473489 | false | false | false | false |
campos20/tnoodle | tnoodle-server/src/main/kotlin/org/worldcubeassociation/tnoodle/server/model/cache/CoroutineScrambleCacher.kt | 1 | 1218 | package org.worldcubeassociation.tnoodle.server.model.cache
import kotlinx.atomicfu.atomic
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.produce
import org.worldcubeassociation.tnoodle.scrambles.Puzzle
import java.util.concurrent.Executors
import java.util.concurrent.ThreadFactory
import kotlin.coroutines.CoroutineContext
class CoroutineScrambleCacher(val puzzle: Puzzle, capacity: Int) : CoroutineScope {
override val coroutineContext: CoroutineContext
get() = JOB_CONTEXT
@ExperimentalCoroutinesApi
private val buffer = produce(capacity = capacity) {
while (true) {
send(puzzle.generateScramble())
.also { size += 1 }
}
}
private val size = atomic(0)
val available: Int
get() = size.value
suspend fun yieldScramble(): String = buffer.receive()
.also { size -= 1 }
fun getScramble(): String = runBlocking { yieldScramble() }
companion object {
private val DAEMON_FACTORY = ThreadFactory { Executors.defaultThreadFactory().newThread(it).apply { isDaemon = true } }
private val JOB_CONTEXT = Executors.newFixedThreadPool(2, DAEMON_FACTORY).asCoroutineDispatcher()
}
}
| gpl-3.0 | c34b4f5249b48e0acaffa6d5dbda6498 | 31.918919 | 127 | 0.710181 | 4.757813 | false | false | false | false |
HabitRPG/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/models/inventory/Food.kt | 2 | 522 | package com.habitrpg.android.habitica.models.inventory
import io.realm.RealmObject
import io.realm.annotations.PrimaryKey
open class Food : RealmObject(), Item {
@PrimaryKey
override var key: String = ""
override var text: String = ""
override var event: ItemEvent? = null
var notes: String? = null
override var value: Int = 0
var target: String? = null
var article: String? = null
var canDrop: Boolean? = null
override val type: String
get() = "food"
}
| gpl-3.0 | 24a2132c5cb0d72cf54d94834579f829 | 27 | 54 | 0.651341 | 4.176 | false | false | false | false |
westnordost/osmagent | app/src/main/java/de/westnordost/streetcomplete/quests/sidewalk/AddSidewalkForm.kt | 1 | 5125 | package de.westnordost.streetcomplete.quests.sidewalk
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.ViewGroup.LayoutParams.MATCH_PARENT
import android.widget.ImageView
import android.widget.TextView
import androidx.annotation.AnyThread
import androidx.appcompat.app.AlertDialog
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.quests.AbstractQuestFormAnswerFragment
import de.westnordost.streetcomplete.quests.StreetSideRotater
import de.westnordost.streetcomplete.view.ListAdapter
import kotlinx.android.synthetic.main.quest_street_side_puzzle.*
class AddSidewalkForm : AbstractQuestFormAnswerFragment<SidewalkAnswer>() {
override val contentLayoutResId = R.layout.quest_street_side_puzzle
override val contentPadding = false
private var streetSideRotater: StreetSideRotater? = null
private var leftSide: Sidewalk? = null
private var rightSide: Sidewalk? = null
// just a shortcut
private val isLeftHandTraffic get() = countryInfo.isLeftHandTraffic
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
savedInstanceState?.getString(SIDEWALK_RIGHT)?.let { rightSide = Sidewalk.valueOf(it) }
savedInstanceState?.getString(SIDEWALK_LEFT)?.let { leftSide = Sidewalk.valueOf(it) }
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
puzzleView.listener = { isRight -> showSidewalkSelectionDialog(isRight) }
streetSideRotater = StreetSideRotater(puzzleView, compassNeedle, elementGeometry)
val defaultResId =
if (isLeftHandTraffic) R.drawable.ic_sidewalk_unknown_l
else R.drawable.ic_sidewalk_unknown
puzzleView.setLeftSideImageResource(leftSide?.iconResId ?: defaultResId)
puzzleView.setRightSideImageResource(rightSide?.iconResId ?: defaultResId)
checkIsFormComplete()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
rightSide?.let { outState.putString(SIDEWALK_RIGHT, it.name) }
leftSide?.let { outState.putString(SIDEWALK_LEFT, it.name) }
}
@AnyThread
override fun onMapOrientation(rotation: Float, tilt: Float) {
streetSideRotater?.onMapOrientation(rotation, tilt)
}
override fun onClickOk() {
applyAnswer(SidewalkAnswer(
left = leftSide == Sidewalk.YES,
right = rightSide == Sidewalk.YES
))
}
override fun isFormComplete() = leftSide != null && rightSide != null
private fun showSidewalkSelectionDialog(isRight: Boolean) {
val recyclerView = RecyclerView(activity!!)
recyclerView.layoutParams = RecyclerView.LayoutParams(MATCH_PARENT, MATCH_PARENT)
recyclerView.layoutManager = GridLayoutManager(activity, 2)
val alertDialog = AlertDialog.Builder(activity!!)
.setTitle(R.string.quest_select_hint)
.setView(recyclerView)
.create()
recyclerView.adapter = createAdapter(Sidewalk.values().toList()) { sidewalk ->
alertDialog.dismiss()
if (isRight) {
puzzleView.replaceRightSideImageResource(sidewalk.puzzleResId)
rightSide = sidewalk
} else {
puzzleView.replaceLeftSideImageResource(sidewalk.puzzleResId)
leftSide = sidewalk
}
checkIsFormComplete()
}
alertDialog.show()
}
private fun createAdapter(items: List<Sidewalk>, callback: (Sidewalk) -> Unit) =
object : ListAdapter<Sidewalk>(items) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
object : ListAdapter.ViewHolder<Sidewalk>(
LayoutInflater.from(parent.context).inflate(R.layout.labeled_icon_button_cell, parent, false)
) {
override fun onBind(with: Sidewalk) {
val imageView = itemView.findViewById<ImageView>(R.id.imageView)
val textView = itemView.findViewById<TextView>(R.id.textView)
imageView.setImageDrawable(resources.getDrawable(with.iconResId))
textView.setText(with.nameResId)
itemView.setOnClickListener { callback(with) }
}
}
}
private enum class Sidewalk(val iconResId: Int, val puzzleResId: Int, val nameResId: Int) {
NO(R.drawable.ic_sidewalk_no, R.drawable.ic_sidewalk_puzzle_no, R.string.quest_sidewalk_value_no),
YES(R.drawable.ic_sidewalk_yes, R.drawable.ic_sidewalk_puzzle_yes, R.string.quest_sidewalk_value_yes)
}
companion object {
private const val SIDEWALK_LEFT = "sidewalk_left"
private const val SIDEWALK_RIGHT = "sidewalk_right"
}
}
| gpl-3.0 | 5499b4d090f884b3b16370e6528dcb8f | 39.674603 | 113 | 0.685073 | 5.104582 | false | false | false | false |
InsertKoinIO/koin | android/koin-android/src/main/java/org/koin/android/ext/koin/KoinExt.kt | 1 | 3240 | /*
* Copyright 2017-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.koin.android.ext.koin
import android.app.Application
import android.content.Context
import org.koin.android.logger.AndroidLogger
import org.koin.core.KoinApplication
import org.koin.core.annotation.KoinInternalApi
import org.koin.core.logger.Level
import org.koin.core.registry.saveProperties
import org.koin.dsl.bind
import org.koin.dsl.binds
import org.koin.dsl.module
import java.util.*
/**
* Koin extensions for Android
*
* @author Arnaud Giuliani
*/
/**
* Setup Android Logger for Koin
* @param level
*/
@OptIn(KoinInternalApi::class)
fun KoinApplication.androidLogger(
level: Level = Level.INFO,
): KoinApplication {
koin.setupLogger(AndroidLogger(level))
return this
}
/**
* Add Context instance to Koin container
* @param androidContext - Context
*/
fun KoinApplication.androidContext(androidContext: Context): KoinApplication {
if (koin.logger.isAt(Level.INFO)) {
koin.logger.info("[init] declare Android Context")
}
if (androidContext is Application) {
koin.loadModules(listOf(module {
single { androidContext } binds arrayOf(Context::class,Application::class)
}))
} else {
koin.loadModules(listOf(module {
single{ androidContext }
}))
}
return this
}
/**
* Load properties file from Assets
* @param androidContext
* @param koinPropertyFile
*/
@OptIn(KoinInternalApi::class)
fun KoinApplication.androidFileProperties(
koinPropertyFile: String = "koin.properties",
): KoinApplication {
val koinProperties = Properties()
val androidContext = koin.get<Context>()
try {
val hasFile = androidContext.assets?.list("")?.contains(koinPropertyFile) ?: false
if (hasFile) {
try {
androidContext.assets.open(koinPropertyFile).use { koinProperties.load(it) }
val nb = koin.propertyRegistry.saveProperties(koinProperties)
if (koin.logger.isAt(Level.INFO)) {
koin.logger.info("[Android-Properties] loaded $nb properties from assets/$koinPropertyFile")
}
} catch (e: Exception) {
koin.logger.error("[Android-Properties] error for binding properties : $e")
}
} else {
if (koin.logger.isAt(Level.INFO)) {
koin.logger.info("[Android-Properties] no assets/$koinPropertyFile file to load")
}
}
} catch (e: Exception) {
koin.logger.error("[Android-Properties] error while loading properties from assets/$koinPropertyFile : $e")
}
return this
}
| apache-2.0 | c9e27f04e66619e752ae4f698657d0c6 | 30.456311 | 115 | 0.676235 | 4.337349 | false | false | false | false |
k-kagurazaka/rx-property-android | sample/src/main/kotlin/jp/keita/kagurazaka/rxproperty/sample/todo/TodoViewModel.kt | 1 | 2104 | package jp.keita.kagurazaka.rxproperty.sample.todo
import jp.keita.kagurazaka.rxproperty.NoParameter
import jp.keita.kagurazaka.rxproperty.RxCommand
import jp.keita.kagurazaka.rxproperty.RxProperty
import jp.keita.kagurazaka.rxproperty.sample.BR
import jp.keita.kagurazaka.rxproperty.sample.R
import jp.keita.kagurazaka.rxproperty.sample.ViewModelBase
import jp.keita.kagurazaka.rxproperty.toRxCommand
import me.tatarka.bindingcollectionadapter2.ItemBinding
class TodoViewModel : ViewModelBase() {
val todoList: TodoList = TodoList()
val todoListItem: ItemBinding<TodoItemViewModel> = ItemBinding.of(BR.todoListItemVM, R.layout.item_todo)
val viewModeIndex: RxProperty<Int> = RxProperty(0).asManaged()
val inputTodoItem: RxProperty<TodoItemViewModel>
= RxProperty(TodoItemViewModel()).asManaged()
val addCommand: RxCommand<NoParameter> = inputTodoItem
.switchMap { it.onHasErrorChanged }
.map { !it }
.toRxCommand<NoParameter>(false)
.asManaged()
val deleteDoneCommand: RxCommand<Any> = RxCommand()
init {
val updateTodoList: (Int) -> Unit = {
val list = when (it) {
0 -> TodoRepository.all
1 -> TodoRepository.active
2 -> TodoRepository.done
else -> throw IllegalStateException()
}
todoList.replace(list)
}
TodoRepository.onChanged
.subscribe { updateTodoList(viewModeIndex.get()) } // Not smart :(
.asManaged()
viewModeIndex
.subscribe { updateTodoList(it) }
.asManaged()
addCommand.subscribe {
inputTodoItem.get().let {
TodoRepository.store(it.model)
it.dispose()
inputTodoItem.set(TodoItemViewModel())
}
}.asManaged()
deleteDoneCommand.subscribe {
TodoRepository.deleteDone()
}.asManaged()
}
override fun dispose() {
TodoRepository.clear()
super.dispose()
}
}
| mit | b9fbef9080d7c58bb0d80d76d0901d85 | 31.369231 | 108 | 0.630703 | 4.770975 | false | false | false | false |
NerdNumber9/TachiyomiEH | app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/browse/CatalogueItem.kt | 1 | 2295 | package eu.kanade.tachiyomi.ui.catalogue.browse
import android.support.v7.widget.RecyclerView
import android.view.Gravity
import android.view.View
import android.view.ViewGroup.LayoutParams.MATCH_PARENT
import android.widget.FrameLayout
import com.f2prateek.rx.preferences.Preference
import eu.davidea.flexibleadapter.FlexibleAdapter
import eu.davidea.flexibleadapter.items.AbstractFlexibleItem
import eu.davidea.flexibleadapter.items.IFlexible
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.database.models.Manga
import eu.kanade.tachiyomi.data.preference.getOrDefault
import eu.kanade.tachiyomi.widget.AutofitRecyclerView
import kotlinx.android.synthetic.main.catalogue_grid_item.view.*
class CatalogueItem(val manga: Manga, private val catalogueAsList: Preference<Boolean>) :
AbstractFlexibleItem<CatalogueHolder>() {
override fun getLayoutRes(): Int {
return if (catalogueAsList.getOrDefault())
R.layout.catalogue_list_item
else
R.layout.catalogue_grid_item
}
override fun createViewHolder(view: View, adapter: FlexibleAdapter<IFlexible<RecyclerView.ViewHolder>>): CatalogueHolder {
val parent = adapter.recyclerView
return if (parent is AutofitRecyclerView) {
view.apply {
card.layoutParams = FrameLayout.LayoutParams(
MATCH_PARENT, parent.itemWidth / 3 * 4)
gradient.layoutParams = FrameLayout.LayoutParams(
MATCH_PARENT, parent.itemWidth / 3 * 4 / 2, Gravity.BOTTOM)
}
CatalogueGridHolder(view, adapter)
} else {
CatalogueListHolder(view, adapter)
}
}
override fun bindViewHolder(adapter: FlexibleAdapter<IFlexible<RecyclerView.ViewHolder>>,
holder: CatalogueHolder,
position: Int,
payloads: List<Any?>?) {
holder.onSetValues(manga)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other is CatalogueItem) {
return manga.id!! == other.manga.id!!
}
return false
}
override fun hashCode(): Int {
return manga.id!!.hashCode()
}
} | apache-2.0 | ea6013bb4992fcef7ed0249c4cb080e6 | 34.323077 | 126 | 0.664052 | 4.811321 | false | false | false | false |
spkingr/50-android-kotlin-projects-in-100-days | ProjectAMap/app/src/main/java/me/liuqingwen/android/projectamap/MainActivity.kt | 1 | 8873 | package me.liuqingwen.android.projectamap
import android.content.Context
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.view.WindowManager
import android.view.inputmethod.InputMethodManager
import android.widget.ArrayAdapter
import com.amap.api.maps.AMap
import com.amap.api.maps.CameraUpdateFactory
import com.amap.api.maps.model.LatLng
import com.amap.api.maps.model.LatLngBounds
import com.amap.api.maps.model.MarkerOptions
import com.amap.api.maps.model.MyLocationStyle
import com.amap.api.services.core.LatLonPoint
import com.amap.api.services.core.PoiItem
import com.amap.api.services.help.Inputtips
import com.amap.api.services.help.InputtipsQuery
import com.amap.api.services.poisearch.PoiResult
import com.amap.api.services.poisearch.PoiSearch
import kotlinx.android.synthetic.main.layout_activity_main.*
import org.jetbrains.anko.toast
//Log:73-135, Lat:17-53
val LatLonPoint.latLon:LatLng
get()
{
return LatLng(this.latitude, this.longitude)
}
const val CITY = "长沙"
class MainActivity : AppCompatActivity()
{
private var isFullScreen = false
private var isSearching = false
private lateinit var map:AMap
private val searchItems by lazy(LazyThreadSafetyMode.NONE) { arrayListOf<String>() }
private val searchAdapter by lazy(LazyThreadSafetyMode.NONE) { ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, this.searchItems) }
private var poiQuery:PoiSearch.Query? = null
private val poiSearch by lazy(LazyThreadSafetyMode.NONE) { PoiSearch(this, this.poiQuery).apply { this.setOnPoiSearchListener([email protected]) } }
private val searchListener = object : PoiSearch.OnPoiSearchListener {
override fun onPoiItemSearched(item: PoiItem?, code: Int)
{
[email protected] = false
}
override fun onPoiSearched(result: PoiResult?, code: Int)
{
if (code == 1000 && result?.pois != null)
{
[email protected](result.pois)
}
else
{
[email protected]("Search failed!")
}
[email protected] = false
}
}
private fun showResult(poiItems:List<PoiItem>)
{
this.map.clear()
if (poiItems.isNotEmpty())
{
poiItems.forEach {
val info = "Lat:${it.latLonPoint.latitude}, Log:${it.latLonPoint.longitude}"
val marker = this.map.addMarker(MarkerOptions().infoWindowEnable(true).snippet(info).position(it.latLonPoint.latLon).title(it.title))
marker.hideInfoWindow()
}
val longitude1 = poiItems.maxBy { it.latLonPoint.longitude }!!.latLonPoint.longitude
val longitude2 = poiItems.minBy { it.latLonPoint.longitude }!!.latLonPoint.longitude
val latitude1 = poiItems.maxBy { it.latLonPoint.latitude }!!.latLonPoint.latitude
val latitude2 = poiItems.minBy { it.latLonPoint.latitude }!!.latLonPoint.latitude
val bounds = LatLngBounds.builder().include(LatLng(latitude1, longitude1)).include(LatLng(latitude2, longitude2)).build()
this.map.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, 50))
}
}
override fun onCreate(savedInstanceState: Bundle?)
{
super.onCreate(savedInstanceState)
setContentView(R.layout.layout_activity_main)
this.window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN)
this.mapView.onCreate(savedInstanceState)
this.init()
}
private fun init()
{
this.isFullScreen = true
this.supportActionBar?.hide()
this.window.decorView.setOnSystemUiVisibilityChangeListener {visibility ->
this.isFullScreen = visibility and View.SYSTEM_UI_FLAG_FULLSCREEN != 0
}
this.switchMapType.setOnClickListener {
this.map.mapType = if (this.switchMapType.isChecked) AMap.MAP_TYPE_NORMAL else AMap.MAP_TYPE_SATELLITE
}
this.buttonSearch.setOnClickListener {
this.hideKeyboard()
val text = this.textSearch.text.toString()
this.searchMap(text)
}
this.textSearch.setAdapter(this.searchAdapter)
this.textSearch.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable?) {}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int)
{
if (s?.isNotBlank() == true && s.length >= 2)
{
[email protected](s.toString())
}
}
})
this.textSearch.setOnItemClickListener { _, _, _, _ ->
this.hideKeyboard()
this.searchMap(this.textSearch.text.toString())
}
this.textSearch.setOnClickListener {
this.textSearch.showDropDown()
}
this.config()
}
private fun queryInputTips(text:String)
{
val inputTipsQuery = InputtipsQuery(text, CITY)
inputTipsQuery.cityLimit = true
val inputTips = Inputtips(this, inputTipsQuery)
inputTips.setInputtipsListener { list, code ->
if (code == 1000 && list?.isNotEmpty() == true)
{
this.searchAdapter.clear()
list.map { it.name }.let { this.searchAdapter.addAll(it) }
this.searchAdapter.notifyDataSetChanged()
}
}
inputTips.requestInputtipsAsyn()
}
private fun hideKeyboard()
{
this.currentFocus?.let {
val inputManager = this.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
inputManager.hideSoftInputFromWindow(it.windowToken, 0)
}
}
private fun searchMap(searchText:String)
{
if (this.isSearching || searchText.isBlank())
{
return
}
this.isSearching = true
this.poiQuery = PoiSearch.Query(searchText, "", CITY)
this.poiQuery?.pageSize = 10
this.poiQuery?.pageNum = 1
this.poiSearch.searchPOIAsyn()
}
private fun config()
{
this.map = this.mapView.map
this.map.setOnMapLoadedListener {
}
this.map.setOnMapClickListener {
if (! this.isFullScreen)
{
this.window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_FULLSCREEN
}
}
val myLocationStyle = MyLocationStyle().apply {
this.interval(5000)
this.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE_NO_CENTER)
this.showMyLocation(true)
}
this.map.myLocationStyle = myLocationStyle
this.map.isMyLocationEnabled = true
this.map.setOnMyLocationChangeListener {
if (it.latitude in 17.0..53.0 && it.longitude in 73.0..135.0)
{
this.map.moveCamera(CameraUpdateFactory.changeLatLng(LatLng(it.latitude, it.longitude)))
}
}
this.map.uiSettings.isCompassEnabled = true
this.map.uiSettings.isZoomControlsEnabled = true
this.map.uiSettings.isMyLocationButtonEnabled = true
/*this.map.setLocationSource(object : LocationSource{
override fun deactivate()
{
info("------------------>setLocationSource: deactivate")
}
override fun activate(p0: LocationSource.OnLocationChangedListener?)
{
info("------------------>setLocationSource: activate")
}
})*/
this.map.setOnMarkerClickListener {
this.map.animateCamera(CameraUpdateFactory.newLatLngZoom(it.position, 17.0f))
it.showInfoWindow()
false
}
}
override fun onDestroy()
{
super.onDestroy()
this.mapView.onDestroy()
}
override fun onResume()
{
super.onResume()
this.window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_FULLSCREEN
this.hideKeyboard()
this.mapView.onResume()
}
override fun onPause()
{
super.onPause()
this.mapView.onPause()
}
override fun onSaveInstanceState(outState: Bundle?)
{
super.onSaveInstanceState(outState)
this.mapView.onSaveInstanceState(outState)
}
}
| mit | 9b7c49b2cbf2b797a04a4377c1fe9f66 | 34.476 | 167 | 0.624535 | 4.742781 | false | false | false | false |
y20k/trackbook | app/src/main/java/org/y20k/trackbook/helpers/LogHelper.kt | 1 | 3568 | /*
* LogHelper.kt
* Implements the LogHelper object
* A LogHelper wraps the logging calls to be able to strip them out of release versions
*
* This file is part of
* TRACKBOOK - Movement Recorder for Android
*
* Copyright (c) 2016-22 - Y20K.org
* Licensed under the MIT-License
* http://opensource.org/licenses/MIT
*
* Trackbook uses osmdroid - OpenStreetMap-Tools for Android
* https://github.com/osmdroid/osmdroid
*/
package org.y20k.trackbook.helpers
import android.util.Log
import org.y20k.trackbook.BuildConfig
/*
* LogHelper object
*/
object LogHelper {
private const val TESTING: Boolean = true // set to "false"
private const val LOG_PREFIX: String = "trackbook_"
private const val MAX_LOG_TAG_LENGTH: Int = 64
private const val LOG_PREFIX_LENGTH: Int = LOG_PREFIX.length
fun makeLogTag(str: String): String {
return if (str.length > MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH) {
LOG_PREFIX + str.substring(0, MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 1)
} else LOG_PREFIX + str
}
fun makeLogTag(cls: Class<*>): String {
// don't use this when obfuscating class names
return makeLogTag(cls.simpleName)
}
fun v(tag: String, vararg messages: Any) {
// Only log VERBOSE if build type is DEBUG or if TESTING is true
if (BuildConfig.DEBUG || TESTING) {
log(tag, Log.VERBOSE, null, *messages)
}
}
fun d(tag: String, vararg messages: Any) {
// Only log DEBUG if build type is DEBUG or if TESTING is true
if (BuildConfig.DEBUG || TESTING) {
log(tag, Log.DEBUG, null, *messages)
}
}
fun i(tag: String, vararg messages: Any) {
log(tag, Log.INFO, null, *messages)
}
fun w(tag: String, vararg messages: Any) {
log(tag, Log.WARN, null, *messages)
}
fun w(tag: String, t: Throwable, vararg messages: Any) {
log(tag, Log.WARN, t, *messages)
}
fun e(tag: String, vararg messages: Any) {
log(tag, Log.ERROR, null, *messages)
}
fun e(tag: String, t: Throwable, vararg messages: Any) {
log(tag, Log.ERROR, t, *messages)
}
private fun log(tag: String, level: Int, t: Throwable?, vararg messages: Any) {
val message: String
if (t == null && messages.size == 1) {
// handle this common case without the extra cost of creating a stringbuffer:
message = messages[0].toString()
} else {
val sb = StringBuilder()
for (m in messages) {
sb.append(m)
}
if (t != null) {
sb.append("\n").append(Log.getStackTraceString(t))
}
message = sb.toString()
}
Log.println(level, tag, message)
// if (Log.isLoggable(tag, level)) {
// val message: String
// if (t == null && messages != null && messages.size == 1) {
// // handle this common case without the extra cost of creating a stringbuffer:
// message = messages[0].toString()
// } else {
// val sb = StringBuilder()
// if (messages != null)
// for (m in messages) {
// sb.append(m)
// }
// if (t != null) {
// sb.append("\n").append(Log.getStackTraceString(t))
// }
// message = sb.toString()
// }
// Log.println(level, tag, message)
// }
}
} | mit | 96810852908ae905c2a4f3e7b740f6f4 | 30.034783 | 95 | 0.558857 | 3.916575 | false | false | false | false |
FirebaseExtended/codelab-appdistribution-android | start/app/src/main/java/com/google/firebase/appdistributioncodelab/kotlin/MainActivity.kt | 1 | 2204 | /*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.firebase.appdistributioncodelab.kotlin
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.google.firebase.appdistribution.FirebaseAppDistribution
import com.google.firebase.appdistribution.ktx.appDistribution
import com.google.firebase.appdistributioncodelab.databinding.ActivityMainBinding
import com.google.firebase.ktx.Firebase
class MainActivity : AppCompatActivity() {
private lateinit var firebaseAppDistribution: FirebaseAppDistribution
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
firebaseAppDistribution = Firebase.appDistribution
binding.updatebutton.setOnClickListener { view ->
checkForUpdate()
}
binding.signinButton.setOnClickListener { view ->
signIn()
}
}
private fun checkForUpdate() {
}
private fun signIn() {
}
private fun isTesterSignedIn() : Boolean {
return false
}
private fun configureUpdateButton() {
binding.updatebutton.visibility = if (isTesterSignedIn()) View.VISIBLE else View.GONE
}
private fun configureSigninButton() {
binding.signinButton.text = if (isTesterSignedIn()) "Sign Out" else "Sign In"
binding.signinButton.visibility = View.VISIBLE
}
companion object {
private const val TAG = "AppDistribution-Codelab"
}
}
| apache-2.0 | 0f5b8045e765e7a2e1c96646bdbfdc91 | 31.411765 | 93 | 0.729129 | 5.043478 | false | false | false | false |
CarlosEsco/tachiyomi | app/src/main/java/eu/kanade/tachiyomi/data/track/bangumi/Collection.kt | 1 | 413 | package eu.kanade.tachiyomi.data.track.bangumi
import kotlinx.serialization.Serializable
@Serializable
data class Collection(
val `private`: Int? = 0,
val comment: String? = "",
val ep_status: Int? = 0,
val lasttouch: Int? = 0,
val rating: Float? = 0f,
val status: Status? = Status(),
val tag: List<String?>? = listOf(),
val user: User? = User(),
val vol_status: Int? = 0,
)
| apache-2.0 | 2c4d8951590a0602cdeaa9cbf31e3109 | 24.8125 | 46 | 0.62954 | 3.385246 | false | false | false | false |
Heiner1/AndroidAPS | database/src/main/java/info/nightscout/androidaps/database/transactions/SyncTemporaryBasalWithTempIdTransaction.kt | 1 | 1470 | package info.nightscout.androidaps.database.transactions
import info.nightscout.androidaps.database.entities.TemporaryBasal
/**
* Creates or updates the TemporaryBasal from pump synchronization
*/
class SyncTemporaryBasalWithTempIdTransaction(
private val bolus: TemporaryBasal,
private val newType: TemporaryBasal.Type?
) : Transaction<SyncTemporaryBasalWithTempIdTransaction.TransactionResult>() {
override fun run(): TransactionResult {
bolus.interfaceIDs.temporaryId ?: bolus.interfaceIDs.pumpType
?: bolus.interfaceIDs.pumpSerial ?: throw IllegalStateException("Some pump ID is null")
val result = TransactionResult()
val current = database.temporaryBasalDao.findByPumpTempIds(bolus.interfaceIDs.temporaryId!!, bolus.interfaceIDs.pumpType!!, bolus.interfaceIDs.pumpSerial!!)
if (current != null) {
val old = current.copy()
current.timestamp = bolus.timestamp
current.rate = bolus.rate
current.duration = bolus.duration
current.isAbsolute = bolus.isAbsolute
current.type = newType ?: current.type
current.interfaceIDs.pumpId = bolus.interfaceIDs.pumpId
database.temporaryBasalDao.updateExistingEntry(current)
result.updated.add(Pair(old, current))
}
return result
}
class TransactionResult {
val updated = mutableListOf<Pair<TemporaryBasal, TemporaryBasal>>()
}
} | agpl-3.0 | 4af0aa6c87840af605f04e7ab87b0656 | 39.861111 | 164 | 0.707483 | 5.54717 | false | false | false | false |
PolymerLabs/arcs | java/arcs/core/data/proto/HandleProtoDecoder.kt | 1 | 2345 | /*
* Copyright 2020 Google LLC.
*
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
*
* Code distributed by Google as part of this project is also subject to an additional IP rights
* grant found at
* http://polymer.github.io/PATENTS.txt
*/
package arcs.core.data.proto
import arcs.core.data.Recipe.Handle
import arcs.core.data.TypeVariable
/** Converts [HandleProto.Fate] into [Handle.Fate]. */
fun HandleProto.Fate.decode() = when (this) {
HandleProto.Fate.UNSPECIFIED ->
throw IllegalArgumentException("HandleProto.Fate value not set.")
HandleProto.Fate.CREATE -> Handle.Fate.CREATE
HandleProto.Fate.USE -> Handle.Fate.USE
HandleProto.Fate.MAP -> Handle.Fate.MAP
HandleProto.Fate.COPY -> Handle.Fate.COPY
HandleProto.Fate.JOIN -> Handle.Fate.JOIN
HandleProto.Fate.UNRECOGNIZED ->
throw IllegalArgumentException("Invalid HandleProto.Fate value.")
}
/** Converts [Handle.Fate] into [HandleProto.Fate] enum. */
fun Handle.Fate.encode(): HandleProto.Fate = when (this) {
Handle.Fate.CREATE -> HandleProto.Fate.CREATE
Handle.Fate.USE -> HandleProto.Fate.USE
Handle.Fate.MAP -> HandleProto.Fate.MAP
Handle.Fate.COPY -> HandleProto.Fate.COPY
Handle.Fate.JOIN -> HandleProto.Fate.JOIN
}
/**
* Converts [HandleProto] into [Handle].
*
* If a type is not set in the [HandleProto], it is initialized to a newly created TypeVariable.
* @param knownHandles is a map of [Handle]s used the the recipe level to decode associatedHandles.
*/
fun HandleProto.decode(knownHandles: Map<String, Handle> = emptyMap()) = Handle(
name = name,
id = id,
fate = fate.decode(),
tags = tagsList,
storageKey = storageKey,
type = if (hasType()) type.decode() else TypeVariable(name),
annotations = annotationsList.map { it.decode() },
associatedHandles = associatedHandlesList.map { requireNotNull(knownHandles[it]) }
)
/** Converts a [Handle] to a [HandleProto]. */
fun Handle.encode(): HandleProto {
val builder = HandleProto.newBuilder()
.setName(name)
.setId(id)
.setFate(fate.encode())
.addAllTags(tags)
.setType(type.encode())
.addAllAnnotations(annotations.map { it.encode() })
.addAllAssociatedHandles(associatedHandles.map { it.name })
storageKey?.let { builder.setStorageKey(it) }
return builder.build()
}
| bsd-3-clause | 790068558a04ba31869f415fc4ca8ba6 | 32.5 | 99 | 0.721109 | 3.819218 | false | false | false | false |
bajdcc/jMiniLang | src/main/kotlin/com/bajdcc/LALR1/interpret/test/TestInterpret8.kt | 1 | 4901 | package com.bajdcc.LALR1.interpret.test
import com.bajdcc.LALR1.grammar.Grammar
import com.bajdcc.LALR1.grammar.runtime.RuntimeCodePage
import com.bajdcc.LALR1.grammar.runtime.RuntimeException
import com.bajdcc.LALR1.interpret.Interpreter
import com.bajdcc.LALR1.syntax.handler.SyntaxException
import com.bajdcc.util.lexer.error.RegexException
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
object TestInterpret8 {
@JvmStatic
fun main(args: Array<String>) {
try {
val codes = arrayOf(
"import \"sys.base\"; import \"sys.list\";\n" +
"var a = [];\n" +
"call g_array_add(a, 5);\n" +
"call g_array_set(a, 0, 4);\n" +
"call g_printn(call g_array_get(a, 0));\n" +
"call g_array_remove(a, 0);\n" +
"call g_array_add(a, 50);\n" +
"call g_array_add(a, 100);\n" +
"call g_array_set(a, 1, 400);\n" +
"call g_printn(call g_array_get(a, 1));\n" +
"call g_array_pop(a);\n" +
"call g_array_pop(a);\n" +
"call g_printn(call g_array_size(a));\n" +
"\n" +
"let a = {};\n" +
"call g_map_put(a, \"x\", 5);\n" +
"call g_map_put(a, \"y\", 10);\n" +
"call g_map_put(a, \"x\", 50);\n" +
"call g_printn(call g_map_size(a));\n" +
"call g_printn(call g_map_get(a, \"x\"));\n" +
"call g_printn(call g_map_get(a, \"y\"));\n" +
"call g_printn(call g_map_contains(a, \"x\"));\n" +
"call g_map_remove(a, \"x\");\n" +
"call g_printn(call g_map_contains(a, \"x\"));\n" +
"call g_printn(call g_map_size(a));\n" +
"\n",
"import \"sys.base\"; import \"sys.list\";\n" +
"var create_node = func ~(data) {\n" +
" var new_node = g_new_map;\n" +
" call g_map_put(new_node, \"data\", data);\n" +
" call g_map_put(new_node, \"prev\", g_null);\n" +
" call g_map_put(new_node, \"next\", g_null);\n" +
" return new_node;\n" +
"};\n" +
"var append = func ~(head, obj) {\n" +
" var new_node = call create_node(obj);\n" +
" call g_map_put(new_node, \"next\", head);\n" +
" call g_map_put(head, \"prev\", new_node);\n" +
" return new_node;" +
"};\n" +
"var head = call create_node(0);\n" +
"foreach (var i : call g_range(1, 10)) {\n" +
" let head = call append(head, i);\n" +
"}\n" +
"var p = head;\n" +
"while (!call g_is_null(p)) {\n" +
" call g_printn(call g_map_get(p, \"data\"));\n" +
" let p = call g_map_get(p, \"next\");\n" +
"}\n" +
"\n")
println(codes[codes.size - 1])
val interpreter = Interpreter()
val grammar = Grammar(codes[codes.size - 1])
//System.out.println(grammar.toString());
val page = grammar.codePage
//System.out.println(page.toString());
val baos = ByteArrayOutputStream()
RuntimeCodePage.exportFromStream(page, baos)
val bais = ByteArrayInputStream(baos.toByteArray())
interpreter.run("test_1", bais)
} catch (e: RegexException) {
System.err.println()
System.err.println(e.position.toString() + "," + e.message)
e.printStackTrace()
} catch (e: SyntaxException) {
System.err.println()
System.err.println(e.position.toString() + "," + e.message + " "
+ e.info)
e.printStackTrace()
} catch (e: RuntimeException) {
System.err.println()
System.err.println(e.position.toString() + ": " + e.info)
e.printStackTrace()
} catch (e: Exception) {
System.err.println()
System.err.println(e.message)
e.printStackTrace()
}
}
}
| mit | 043babca87265bd85907b7cf8c15ac73 | 46.582524 | 81 | 0.406244 | 4.070598 | false | false | false | false |
Maccimo/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/pullUp/KotlinPullUpHelper.kt | 2 | 32438 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.refactoring.pullUp
import com.intellij.psi.*
import com.intellij.psi.codeStyle.JavaCodeStyleManager
import com.intellij.psi.impl.light.LightField
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.refactoring.classMembers.MemberInfoBase
import com.intellij.refactoring.memberPullUp.PullUpData
import com.intellij.refactoring.memberPullUp.PullUpHelper
import com.intellij.refactoring.util.RefactoringUtil
import org.jetbrains.kotlin.asJava.getRepresentativeLightMethod
import org.jetbrains.kotlin.asJava.namedUnwrappedElement
import org.jetbrains.kotlin.asJava.toLightClass
import org.jetbrains.kotlin.asJava.unwrapped
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.idea.KotlinLanguage
import org.jetbrains.kotlin.idea.codeInsight.shorten.addToShorteningWaitSet
import org.jetbrains.kotlin.idea.core.dropDefaultValue
import org.jetbrains.kotlin.idea.core.getOrCreateCompanionObject
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.idea.core.setType
import org.jetbrains.kotlin.idea.inspections.CONSTRUCTOR_VAL_VAR_MODIFIERS
import org.jetbrains.kotlin.idea.refactoring.createJavaField
import org.jetbrains.kotlin.idea.refactoring.dropOverrideKeywordIfNecessary
import org.jetbrains.kotlin.idea.refactoring.isAbstract
import org.jetbrains.kotlin.idea.refactoring.isCompanionMemberOf
import org.jetbrains.kotlin.idea.refactoring.memberInfo.KtPsiClassWrapper
import org.jetbrains.kotlin.idea.refactoring.memberInfo.toKtDeclarationWrapperAware
import org.jetbrains.kotlin.idea.refactoring.safeDelete.removeOverrideModifier
import org.jetbrains.kotlin.idea.util.anonymousObjectSuperTypeOrNull
import org.jetbrains.kotlin.idea.util.hasComments
import org.jetbrains.kotlin.idea.util.psi.patternMatching.KotlinPsiUnifier
import org.jetbrains.kotlin.idea.util.reformatted
import org.jetbrains.kotlin.lexer.KtModifierKeywordToken
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.util.getExplicitReceiverValue
import org.jetbrains.kotlin.resolve.scopes.receivers.ExpressionReceiver
import org.jetbrains.kotlin.resolve.source.getPsi
import org.jetbrains.kotlin.types.Variance
class KotlinPullUpHelper(
private val javaData: PullUpData,
private val data: KotlinPullUpData
) : PullUpHelper<MemberInfoBase<PsiMember>> {
companion object {
private val MODIFIERS_TO_LIFT_IN_SUPERCLASS = listOf(KtTokens.PRIVATE_KEYWORD)
private val MODIFIERS_TO_LIFT_IN_INTERFACE = listOf(KtTokens.PRIVATE_KEYWORD, KtTokens.PROTECTED_KEYWORD, KtTokens.INTERNAL_KEYWORD)
}
private fun KtExpression.isMovable(): Boolean {
return accept(
object : KtVisitor<Boolean, Nothing?>() {
override fun visitKtElement(element: KtElement, arg: Nothing?): Boolean {
return element.allChildren.all { (it as? KtElement)?.accept(this, arg) ?: true }
}
override fun visitKtFile(file: KtFile, data: Nothing?) = false
override fun visitSimpleNameExpression(expression: KtSimpleNameExpression, arg: Nothing?): Boolean {
val resolvedCall = expression.getResolvedCall(data.resolutionFacade.analyze(expression)) ?: return true
val receiver = (resolvedCall.getExplicitReceiverValue() as? ExpressionReceiver)?.expression
if (receiver != null && receiver !is KtThisExpression && receiver !is KtSuperExpression) return true
var descriptor: DeclarationDescriptor = resolvedCall.resultingDescriptor
if (descriptor is ConstructorDescriptor) {
descriptor = descriptor.containingDeclaration
}
// todo: local functions
if (descriptor is ValueParameterDescriptor) return true
if (descriptor is ClassDescriptor && !descriptor.isInner) return true
if (descriptor is MemberDescriptor) {
if (descriptor.source.getPsi() in propertiesToMoveInitializers) return true
descriptor = descriptor.containingDeclaration
}
return descriptor is PackageFragmentDescriptor
|| (descriptor is ClassDescriptor && DescriptorUtils.isSubclass(data.targetClassDescriptor, descriptor))
}
},
null
)
}
private fun getCommonInitializer(
currentInitializer: KtExpression?,
scope: KtBlockExpression?,
propertyDescriptor: PropertyDescriptor,
elementsToRemove: MutableSet<KtElement>
): KtExpression? {
if (scope == null) return currentInitializer
var initializerCandidate: KtExpression? = null
for (statement in scope.statements) {
statement.asAssignment()?.let body@{
val lhs = KtPsiUtil.safeDeparenthesize(it.left ?: return@body)
val receiver = (lhs as? KtQualifiedExpression)?.receiverExpression
if (receiver != null && receiver !is KtThisExpression) return@body
val resolvedCall = lhs.getResolvedCall(data.resolutionFacade.analyze(it)) ?: return@body
if (resolvedCall.resultingDescriptor != propertyDescriptor) return@body
if (initializerCandidate == null) {
if (currentInitializer == null) {
if (!statement.isMovable()) return null
initializerCandidate = statement
elementsToRemove.add(statement)
} else {
if (!KotlinPsiUnifier.DEFAULT.unify(statement, currentInitializer).isMatched) return null
initializerCandidate = currentInitializer
elementsToRemove.add(statement)
}
} else if (!KotlinPsiUnifier.DEFAULT.unify(statement, initializerCandidate).isMatched) return null
}
}
return initializerCandidate
}
private data class InitializerInfo(
val initializer: KtExpression?,
val usedProperties: Set<KtProperty>,
val usedParameters: Set<KtParameter>,
val elementsToRemove: Set<KtElement>
)
private fun getInitializerInfo(
property: KtProperty,
propertyDescriptor: PropertyDescriptor,
targetConstructor: KtElement
): InitializerInfo? {
val sourceConstructors = targetToSourceConstructors[targetConstructor] ?: return null
val elementsToRemove = LinkedHashSet<KtElement>()
val commonInitializer = sourceConstructors.fold(null as KtExpression?) { commonInitializer, constructor ->
val body = (constructor as? KtSecondaryConstructor)?.bodyExpression
getCommonInitializer(commonInitializer, body, propertyDescriptor, elementsToRemove)
}
if (commonInitializer == null) {
elementsToRemove.clear()
}
val usedProperties = LinkedHashSet<KtProperty>()
val usedParameters = LinkedHashSet<KtParameter>()
val visitor = object : KtTreeVisitorVoid() {
override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) {
val context = data.resolutionFacade.analyze(expression)
val resolvedCall = expression.getResolvedCall(context) ?: return
val receiver = (resolvedCall.getExplicitReceiverValue() as? ExpressionReceiver)?.expression
if (receiver != null && receiver !is KtThisExpression) return
when (val target = (resolvedCall.resultingDescriptor as? DeclarationDescriptorWithSource)?.source?.getPsi()) {
is KtParameter -> usedParameters.add(target)
is KtProperty -> usedProperties.add(target)
}
}
}
commonInitializer?.accept(visitor)
if (targetConstructor == ((data.targetClass as? KtClass)?.primaryConstructor ?: data.targetClass)) {
property.initializer?.accept(visitor)
}
return InitializerInfo(commonInitializer, usedProperties, usedParameters, elementsToRemove)
}
private val propertiesToMoveInitializers = with(data) {
membersToMove
.filterIsInstance<KtProperty>()
.filter {
val descriptor = memberDescriptors[it] as? PropertyDescriptor
descriptor != null && data.sourceClassContext[BindingContext.BACKING_FIELD_REQUIRED, descriptor] ?: false
}
}
private val targetToSourceConstructors = LinkedHashMap<KtElement, MutableList<KtElement>>().let { result ->
if (!data.isInterfaceTarget && data.targetClass is KtClass) {
result[data.targetClass.primaryConstructor ?: data.targetClass] = ArrayList()
data.sourceClass.accept(
object : KtTreeVisitorVoid() {
private fun processConstructorReference(expression: KtReferenceExpression, callingConstructorElement: KtElement) {
val descriptor = data.resolutionFacade.analyze(expression)[BindingContext.REFERENCE_TARGET, expression]
val constructorElement = (descriptor as? DeclarationDescriptorWithSource)?.source?.getPsi() ?: return
if (constructorElement == data.targetClass || (constructorElement as? KtConstructor<*>)?.getContainingClassOrObject() == data.targetClass) {
result.getOrPut(constructorElement as KtElement) { ArrayList() }.add(callingConstructorElement)
}
}
override fun visitSuperTypeCallEntry(specifier: KtSuperTypeCallEntry) {
val constructorRef = specifier.calleeExpression.constructorReferenceExpression ?: return
val containingClass = specifier.getStrictParentOfType<KtClassOrObject>() ?: return
val callingConstructorElement = containingClass.primaryConstructor ?: containingClass
processConstructorReference(constructorRef, callingConstructorElement)
}
override fun visitSecondaryConstructor(constructor: KtSecondaryConstructor) {
val constructorRef = constructor.getDelegationCall().calleeExpression ?: return
processConstructorReference(constructorRef, constructor)
}
}
)
}
result
}
private val targetConstructorToPropertyInitializerInfoMap = LinkedHashMap<KtElement, Map<KtProperty, InitializerInfo>>().let { result ->
for (targetConstructor in targetToSourceConstructors.keys) {
val propertyToInitializerInfo = LinkedHashMap<KtProperty, InitializerInfo>()
for (property in propertiesToMoveInitializers) {
val propertyDescriptor = data.memberDescriptors[property] as? PropertyDescriptor ?: continue
propertyToInitializerInfo[property] = getInitializerInfo(property, propertyDescriptor, targetConstructor) ?: continue
}
val unmovableProperties = RefactoringUtil.transitiveClosure(
object : RefactoringUtil.Graph<KtProperty> {
override fun getVertices() = propertyToInitializerInfo.keys
override fun getTargets(source: KtProperty) = propertyToInitializerInfo[source]?.usedProperties
}
) { !propertyToInitializerInfo.containsKey(it) }
propertyToInitializerInfo.keys.removeAll(unmovableProperties)
result[targetConstructor] = propertyToInitializerInfo
}
result
}
private var dummyField: PsiField? = null
private fun addMovedMember(newMember: KtNamedDeclaration) {
if (newMember is KtProperty) {
// Add dummy light field since PullUpProcessor won't invoke moveFieldInitializations() if no PsiFields are present
if (dummyField == null) {
val factory = JavaPsiFacade.getElementFactory(newMember.project)
val dummyField = object : LightField(
newMember.manager,
factory.createField("dummy", PsiType.BOOLEAN),
factory.createClass("Dummy")
) {
// Prevent processing by JavaPullUpHelper
override fun getLanguage() = KotlinLanguage.INSTANCE
}
javaData.movedMembers.add(dummyField)
}
}
when (newMember) {
is KtProperty, is KtNamedFunction -> {
newMember.getRepresentativeLightMethod()?.let { javaData.movedMembers.add(it) }
}
is KtClassOrObject -> {
newMember.toLightClass()?.let { javaData.movedMembers.add(it) }
}
}
}
private fun liftVisibility(declaration: KtNamedDeclaration, ignoreUsages: Boolean = false) {
val newModifier = if (data.isInterfaceTarget) KtTokens.PUBLIC_KEYWORD else KtTokens.PROTECTED_KEYWORD
val modifiersToLift = if (data.isInterfaceTarget) MODIFIERS_TO_LIFT_IN_INTERFACE else MODIFIERS_TO_LIFT_IN_SUPERCLASS
val currentModifier = declaration.visibilityModifierTypeOrDefault()
if (currentModifier !in modifiersToLift) return
if (ignoreUsages || willBeUsedInSourceClass(declaration, data.sourceClass, data.membersToMove)) {
if (newModifier != KtTokens.DEFAULT_VISIBILITY_KEYWORD) {
declaration.addModifier(newModifier)
} else {
declaration.removeModifier(currentModifier)
}
}
}
override fun setCorrectVisibility(info: MemberInfoBase<PsiMember>) {
val member = info.member.namedUnwrappedElement as? KtNamedDeclaration ?: return
if (data.isInterfaceTarget) {
member.removeModifier(KtTokens.PUBLIC_KEYWORD)
}
val modifiersToLift = if (data.isInterfaceTarget) MODIFIERS_TO_LIFT_IN_INTERFACE else MODIFIERS_TO_LIFT_IN_SUPERCLASS
if (member.visibilityModifierTypeOrDefault() in modifiersToLift) {
member.accept(
object : KtVisitorVoid() {
override fun visitNamedDeclaration(declaration: KtNamedDeclaration) {
when (declaration) {
is KtClass -> {
liftVisibility(declaration)
declaration.declarations.forEach { it.accept(this) }
}
is KtNamedFunction, is KtProperty -> {
liftVisibility(declaration, declaration == member && info.isToAbstract)
}
}
}
}
)
}
}
override fun encodeContextInfo(info: MemberInfoBase<PsiMember>) {
}
private fun fixOverrideAndGetClashingSuper(
sourceMember: KtCallableDeclaration,
targetMember: KtCallableDeclaration
): KtCallableDeclaration? {
val memberDescriptor = data.memberDescriptors[sourceMember] as CallableMemberDescriptor
if (memberDescriptor.overriddenDescriptors.isEmpty()) {
targetMember.removeOverrideModifier()
return null
}
val clashingSuperDescriptor = data.getClashingMemberInTargetClass(memberDescriptor) ?: return null
if (clashingSuperDescriptor.overriddenDescriptors.isEmpty()) {
targetMember.removeOverrideModifier()
}
return clashingSuperDescriptor.source.getPsi() as? KtCallableDeclaration
}
private fun moveSuperInterface(member: PsiNamedElement, substitutor: PsiSubstitutor) {
val realMemberPsi = (member as? KtPsiClassWrapper)?.psiClass ?: member
val classDescriptor = data.memberDescriptors[member] as? ClassDescriptor ?: return
val currentSpecifier = data.sourceClass.getSuperTypeEntryByDescriptor(classDescriptor, data.sourceClassContext) ?: return
when (data.targetClass) {
is KtClass -> {
data.sourceClass.removeSuperTypeListEntry(currentSpecifier)
addSuperTypeEntry(
currentSpecifier,
data.targetClass,
data.targetClassDescriptor,
data.sourceClassContext,
data.sourceToTargetClassSubstitutor
)
}
is PsiClass -> {
val elementFactory = JavaPsiFacade.getElementFactory(member.project)
val sourcePsiClass = data.sourceClass.toLightClass() ?: return
val superRef = sourcePsiClass.implementsList
?.referenceElements
?.firstOrNull { it.resolve()?.unwrapped == realMemberPsi }
?: return
val superTypeForTarget = substitutor.substitute(elementFactory.createType(superRef))
data.sourceClass.removeSuperTypeListEntry(currentSpecifier)
if (DescriptorUtils.isSubclass(data.targetClassDescriptor, classDescriptor)) return
val refList = if (data.isInterfaceTarget) data.targetClass.extendsList else data.targetClass.implementsList
refList?.add(elementFactory.createReferenceFromText(superTypeForTarget.canonicalText, null))
}
}
return
}
private fun removeOriginalMemberOrAddOverride(member: KtCallableDeclaration) {
if (member.isAbstract()) {
member.deleteWithCompanion()
} else {
member.addModifier(KtTokens.OVERRIDE_KEYWORD)
KtTokens.VISIBILITY_MODIFIERS.types.forEach { member.removeModifier(it as KtModifierKeywordToken) }
(member as? KtNamedFunction)?.valueParameters?.forEach { it.dropDefaultValue() }
}
}
private fun moveToJavaClass(member: KtNamedDeclaration, substitutor: PsiSubstitutor) {
if (!(data.targetClass is PsiClass && member.canMoveMemberToJavaClass(data.targetClass))) return
// TODO: Drop after PsiTypes in light elements are properly generated
if (member is KtCallableDeclaration && member.typeReference == null) {
val returnType = (data.memberDescriptors[member] as CallableDescriptor).returnType
returnType?.anonymousObjectSuperTypeOrNull()?.let { member.setType(it, false) }
}
val project = member.project
val elementFactory = JavaPsiFacade.getElementFactory(project)
val lightMethod = member.getRepresentativeLightMethod()!!
val movedMember: PsiMember = when (member) {
is KtProperty, is KtParameter -> {
val newType = substitutor.substitute(lightMethod.returnType)
val newField = createJavaField(member, data.targetClass)
newField.typeElement?.replace(elementFactory.createTypeElement(newType))
if (member.isCompanionMemberOf(data.sourceClass)) {
newField.modifierList?.setModifierProperty(PsiModifier.STATIC, true)
}
if (member is KtParameter) {
(member.parent as? KtParameterList)?.removeParameter(member)
} else {
member.deleteWithCompanion()
}
newField
}
is KtNamedFunction -> {
val newReturnType = substitutor.substitute(lightMethod.returnType)
val newParameterTypes = lightMethod.parameterList.parameters.map { substitutor.substitute(it.type) }
val objectType = PsiType.getJavaLangObject(PsiManager.getInstance(project), GlobalSearchScope.allScope(project))
val newTypeParameterBounds = lightMethod.typeParameters.map {
it.superTypes.map { type -> substitutor.substitute(type) as? PsiClassType ?: objectType }
}
val newMethod = org.jetbrains.kotlin.idea.refactoring.createJavaMethod(member, data.targetClass)
RefactoringUtil.makeMethodAbstract(data.targetClass, newMethod)
newMethod.returnTypeElement?.replace(elementFactory.createTypeElement(newReturnType))
newMethod.parameterList.parameters.forEachIndexed { i, parameter ->
parameter.typeElement?.replace(elementFactory.createTypeElement(newParameterTypes[i]))
}
newMethod.typeParameters.forEachIndexed { i, typeParameter ->
typeParameter.extendsList.referenceElements.forEachIndexed { j, referenceElement ->
referenceElement.replace(elementFactory.createReferenceElementByType(newTypeParameterBounds[i][j]))
}
}
removeOriginalMemberOrAddOverride(member)
if (!data.isInterfaceTarget && !data.targetClass.hasModifierProperty(PsiModifier.ABSTRACT)) {
data.targetClass.modifierList?.setModifierProperty(PsiModifier.ABSTRACT, true)
}
newMethod
}
else -> return
}
JavaCodeStyleManager.getInstance(project).shortenClassReferences(movedMember)
}
override fun move(info: MemberInfoBase<PsiMember>, substitutor: PsiSubstitutor) {
val member = info.member.toKtDeclarationWrapperAware() ?: return
if ((member is KtClass || member is KtPsiClassWrapper) && info.overrides != null) {
moveSuperInterface(member, substitutor)
return
}
if (data.targetClass is PsiClass) {
moveToJavaClass(member, substitutor)
return
}
val markedElements = markElements(member, data.sourceClassContext, data.sourceClassDescriptor, data.targetClassDescriptor)
val memberCopy = member.copy() as KtNamedDeclaration
fun moveClassOrObject(member: KtClassOrObject, memberCopy: KtClassOrObject): KtClassOrObject {
if (data.isInterfaceTarget) {
memberCopy.removeModifier(KtTokens.INNER_KEYWORD)
}
val movedMember = addMemberToTarget(memberCopy, data.targetClass as KtClass) as KtClassOrObject
member.deleteWithCompanion()
return movedMember
}
fun moveCallableMember(member: KtCallableDeclaration, memberCopy: KtCallableDeclaration): KtCallableDeclaration {
data.targetClass as KtClass
val movedMember: KtCallableDeclaration
val clashingSuper = fixOverrideAndGetClashingSuper(member, memberCopy)
val psiFactory = KtPsiFactory(member)
val originalIsAbstract = member.hasModifier(KtTokens.ABSTRACT_KEYWORD)
val toAbstract = when {
info.isToAbstract -> true
!data.isInterfaceTarget -> false
member is KtProperty -> member.mustBeAbstractInInterface()
else -> false
}
val classToAddTo =
if (member.isCompanionMemberOf(data.sourceClass)) data.targetClass.getOrCreateCompanionObject() else data.targetClass
if (toAbstract) {
if (!originalIsAbstract) {
makeAbstract(
memberCopy,
data.memberDescriptors[member] as CallableMemberDescriptor,
data.sourceToTargetClassSubstitutor,
data.targetClass
)
}
movedMember = doAddCallableMember(memberCopy, clashingSuper, classToAddTo)
if (member.typeReference == null) {
movedMember.typeReference?.addToShorteningWaitSet()
}
if (movedMember.nextSibling.hasComments()) {
movedMember.parent.addAfter(psiFactory.createNewLine(), movedMember)
}
removeOriginalMemberOrAddOverride(member)
} else {
movedMember = doAddCallableMember(memberCopy, clashingSuper, classToAddTo)
if (member is KtParameter && movedMember is KtParameter) {
member.valOrVarKeyword?.delete()
CONSTRUCTOR_VAL_VAR_MODIFIERS.forEach { member.removeModifier(it) }
val superEntry = data.superEntryForTargetClass
val superResolvedCall = data.targetClassSuperResolvedCall
if (superResolvedCall != null) {
val superCall = if (superEntry !is KtSuperTypeCallEntry || superEntry.valueArgumentList == null) {
superEntry!!.replaced(psiFactory.createSuperTypeCallEntry("${superEntry.text}()"))
} else superEntry
val argumentList = superCall.valueArgumentList!!
val parameterIndex = movedMember.parameterIndex()
val prevParameterDescriptor = superResolvedCall.resultingDescriptor.valueParameters.getOrNull(parameterIndex - 1)
val prevArgument =
superResolvedCall.valueArguments[prevParameterDescriptor]?.arguments?.singleOrNull() as? KtValueArgument
val newArgumentName = if (prevArgument != null && prevArgument.isNamed()) Name.identifier(member.name!!) else null
val newArgument = psiFactory.createArgument(psiFactory.createExpression(member.name!!), newArgumentName)
if (prevArgument == null) {
argumentList.addArgument(newArgument)
} else {
argumentList.addArgumentAfter(newArgument, prevArgument)
}
}
} else {
member.deleteWithCompanion()
}
}
if (originalIsAbstract && data.isInterfaceTarget) {
movedMember.removeModifier(KtTokens.ABSTRACT_KEYWORD)
}
if (movedMember.hasModifier(KtTokens.ABSTRACT_KEYWORD)) {
data.targetClass.makeAbstract()
}
return movedMember
}
try {
val movedMember = when (member) {
is KtCallableDeclaration -> moveCallableMember(member, memberCopy as KtCallableDeclaration)
is KtClassOrObject -> moveClassOrObject(member, memberCopy as KtClassOrObject)
else -> return
}
movedMember.modifierList?.reformatted()
applyMarking(movedMember, data.sourceToTargetClassSubstitutor, data.targetClassDescriptor)
addMovedMember(movedMember)
} finally {
clearMarking(markedElements)
}
}
override fun postProcessMember(member: PsiMember) {
val declaration = member.unwrapped as? KtNamedDeclaration ?: return
dropOverrideKeywordIfNecessary(declaration)
}
override fun moveFieldInitializations(movedFields: LinkedHashSet<PsiField>) {
val psiFactory = KtPsiFactory(data.sourceClass)
fun KtClassOrObject.getOrCreateClassInitializer(): KtAnonymousInitializer {
getOrCreateBody().declarations.lastOrNull { it is KtAnonymousInitializer }?.let { return it as KtAnonymousInitializer }
return addDeclaration(psiFactory.createAnonymousInitializer())
}
fun KtElement.getConstructorBodyBlock(): KtBlockExpression? {
return when (this) {
is KtClassOrObject -> {
getOrCreateClassInitializer().body
}
is KtPrimaryConstructor -> {
getContainingClassOrObject().getOrCreateClassInitializer().body
}
is KtSecondaryConstructor -> {
bodyExpression ?: add(psiFactory.createEmptyBody())
}
else -> null
} as? KtBlockExpression
}
fun KtClassOrObject.getDelegatorToSuperCall(): KtSuperTypeCallEntry? {
return superTypeListEntries.singleOrNull { it is KtSuperTypeCallEntry } as? KtSuperTypeCallEntry
}
fun addUsedParameters(constructorElement: KtElement, info: InitializerInfo) {
if (info.usedParameters.isEmpty()) return
val constructor: KtConstructor<*> = when (constructorElement) {
is KtConstructor<*> -> constructorElement
is KtClass -> constructorElement.createPrimaryConstructorIfAbsent()
else -> return
}
with(constructor.getValueParameterList()!!) {
info.usedParameters.forEach {
val newParameter = addParameter(it)
val originalType = data.sourceClassContext[BindingContext.VALUE_PARAMETER, it]!!.type
newParameter.setType(
data.sourceToTargetClassSubstitutor.substitute(originalType, Variance.INVARIANT) ?: originalType,
false
)
newParameter.typeReference!!.addToShorteningWaitSet()
}
}
targetToSourceConstructors[constructorElement]!!.forEach {
val superCall: KtCallElement? = when (it) {
is KtClassOrObject -> it.getDelegatorToSuperCall()
is KtPrimaryConstructor -> it.getContainingClassOrObject().getDelegatorToSuperCall()
is KtSecondaryConstructor -> {
if (it.hasImplicitDelegationCall()) {
it.replaceImplicitDelegationCallWithExplicit(false)
} else {
it.getDelegationCall()
}
}
else -> null
}
superCall?.valueArgumentList?.let { args ->
info.usedParameters.forEach { parameter ->
args.addArgument(psiFactory.createArgument(psiFactory.createExpression(parameter.name ?: "_")))
}
}
}
}
for ((constructorElement, propertyToInitializerInfo) in targetConstructorToPropertyInitializerInfoMap.entries) {
val properties = propertyToInitializerInfo.keys.sortedWith(
Comparator { property1, property2 ->
val info1 = propertyToInitializerInfo[property1]!!
val info2 = propertyToInitializerInfo[property2]!!
when {
property2 in info1.usedProperties -> -1
property1 in info2.usedProperties -> 1
else -> 0
}
}
)
for (oldProperty in properties) {
val info = propertyToInitializerInfo.getValue(oldProperty)
addUsedParameters(constructorElement, info)
info.initializer?.let {
val body = constructorElement.getConstructorBodyBlock()
body?.addAfter(it, body.statements.lastOrNull() ?: body.lBrace!!)
}
info.elementsToRemove.forEach { it.delete() }
}
}
}
override fun updateUsage(element: PsiElement) {
}
}
internal fun KtNamedDeclaration.deleteWithCompanion() {
val containingClass = this.containingClassOrObject
if (containingClass is KtObjectDeclaration &&
containingClass.isCompanion() &&
containingClass.declarations.size == 1 &&
containingClass.getSuperTypeList() == null
) {
containingClass.delete()
} else {
this.delete()
}
}
| apache-2.0 | becb70480c7bf4cad4000a5563ce0cbe | 47.632684 | 164 | 0.633917 | 6.586396 | false | false | false | false |
JetBrains/ideavim | vim-engine/src/main/kotlin/com/maddyhome/idea/vim/vimscript/model/commands/SetCommand.kt | 1 | 8639 | /*
* Copyright 2003-2022 The IdeaVim authors
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at
* https://opensource.org/licenses/MIT.
*/
package com.maddyhome.idea.vim.vimscript.model.commands
import com.maddyhome.idea.vim.api.ExecutionContext
import com.maddyhome.idea.vim.api.VimEditor
import com.maddyhome.idea.vim.api.injector
import com.maddyhome.idea.vim.command.OperatorArguments
import com.maddyhome.idea.vim.ex.ExException
import com.maddyhome.idea.vim.ex.ranges.Ranges
import com.maddyhome.idea.vim.helper.Msg
import com.maddyhome.idea.vim.option.ToggleOption
import com.maddyhome.idea.vim.options.OptionScope
import com.maddyhome.idea.vim.vimscript.model.ExecutionResult
import java.util.*
import kotlin.math.ceil
import kotlin.math.min
/**
* see "h :set"
*/
data class SetCommand(val ranges: Ranges, val argument: String) : Command.SingleExecution(ranges, argument) {
override val argFlags = flags(RangeFlag.RANGE_OPTIONAL, ArgumentFlag.ARGUMENT_OPTIONAL, Access.READ_ONLY)
override fun processCommand(editor: VimEditor, context: ExecutionContext, operatorArguments: OperatorArguments): ExecutionResult {
val result = parseOptionLine(editor, argument, OptionScope.GLOBAL, failOnBad = true)
return if (result) {
ExecutionResult.Success
} else {
ExecutionResult.Error
}
}
}
data class SetLocalCommand(val ranges: Ranges, val argument: String) : Command.SingleExecution(ranges, argument) {
override val argFlags = flags(RangeFlag.RANGE_OPTIONAL, ArgumentFlag.ARGUMENT_OPTIONAL, Access.READ_ONLY)
override fun processCommand(editor: VimEditor, context: ExecutionContext, operatorArguments: OperatorArguments): ExecutionResult {
return if (parseOptionLine(editor, argument, OptionScope.LOCAL(editor), failOnBad = true)) {
ExecutionResult.Success
} else {
ExecutionResult.Error
}
}
}
/**
* This parses a set of :set commands. The following types of commands are supported:
*
* * :set - show all changed options
* * :set all - show all options
* * :set all& - reset all options to default values
* * :set {option} - set option of boolean, display others
* * :set {option}? - display option
* * :set no{option} - reset boolean option
* * :set inv{option} - toggle boolean option
* * :set {option}! - toggle boolean option
* * :set {option}& - set option to default
* * :set {option}={value} - set option to new value
* * :set {option}:{value} - set option to new value
* * :set {option}+={value} - append or add to option value
* * :set {option}-={value} - remove or subtract from option value
* * :set {option}^={value} - prepend or multiply option value
*
*
* @param editor The editor the command was entered for, null if no editor - reading .ideavimrc
* @param args The :set command arguments
* @param failOnBad True if processing should stop when a bad argument is found, false if a bad argument is simply
* skipped and processing continues.
* @return True if no errors were found, false if there were any errors
*/
// todo is failOnBad used anywhere?
fun parseOptionLine(editor: VimEditor, args: String, scope: OptionScope, failOnBad: Boolean): Boolean {
// No arguments so we show changed values
val optionService = injector.optionService
when {
args.isEmpty() -> {
val changedOptions = optionService.getOptions().filter { !optionService.isDefault(scope, it) }
showOptions(editor, changedOptions.map { Pair(it, it) }, scope, true)
return true
}
args == "all" -> {
showOptions(editor, optionService.getOptions().map { Pair(it, it) }, scope, true)
return true
}
args == "all&" -> {
optionService.resetAllOptions()
return true
}
}
// We now have 1 or more option operators separator by spaces
var error: String? = null
var token = ""
val tokenizer = StringTokenizer(args)
val toShow = mutableListOf<Pair<String, String>>()
while (tokenizer.hasMoreTokens()) {
token = tokenizer.nextToken()
// See if a space has been backslashed, if no get the rest of the text
while (token.endsWith("\\")) {
token = token.substring(0, token.length - 1) + ' '
if (tokenizer.hasMoreTokens()) {
token += tokenizer.nextToken()
}
}
when {
token.endsWith("?") -> toShow.add(Pair(token.dropLast(1), token))
token.startsWith("no") -> optionService.unsetOption(scope, token.substring(2), token)
token.startsWith("inv") -> optionService.toggleOption(scope, token.substring(3), token)
token.endsWith("!") -> optionService.toggleOption(scope, token.dropLast(1), token)
token.endsWith("&") -> optionService.resetDefault(scope, token.dropLast(1), token)
else -> {
// This must be one of =, :, +=, -=, or ^=
// Look for the = or : first
var eq = token.indexOf('=')
if (eq == -1) {
eq = token.indexOf(':')
}
// No operator so only the option name was given
if (eq == -1) {
val option = optionService.getOptionByNameOrAbbr(token)
when (option) {
null -> error = Msg.unkopt
is ToggleOption -> optionService.setOption(scope, token, token)
else -> toShow.add(Pair(option.name, option.abbrev))
}
} else {
// Make sure there is an option name
if (eq > 0) {
// See if an operator before the equal sign
val op = token[eq - 1]
var end = eq
if (op in "+-^") {
end--
}
// Get option name and value after operator
val option = token.take(end)
val value = token.substring(eq + 1)
when (op) {
'+' -> optionService.appendValue(scope, option, value, token)
'-' -> optionService.removeValue(scope, option, value, token)
'^' -> optionService.prependValue(scope, option, value, token)
else -> optionService.setOptionValue(scope, option, value, token)
}
} else {
error = Msg.unkopt
}
}
}
}
if (failOnBad && error != null) {
break
}
}
// Now show all options that were individually requested
if (toShow.size > 0) {
showOptions(editor, toShow, scope, false)
}
if (error != null) {
throw ExException(injector.messages.message(error, token))
}
return true
}
private fun showOptions(editor: VimEditor, nameAndToken: Collection<Pair<String, String>>, scope: OptionScope, showIntro: Boolean) {
val optionService = injector.optionService
val optionsToShow = mutableListOf<String>()
var unknownOption: Pair<String, String>? = null
for (pair in nameAndToken) {
val myOption = optionService.getOptionByNameOrAbbr(pair.first)
if (myOption != null) {
optionsToShow.add(myOption.name)
} else {
unknownOption = pair
break
}
}
val cols = mutableListOf<String>()
val extra = mutableListOf<String>()
for (option in optionsToShow) {
val optionAsString = optionToString(scope, option)
if (optionAsString.length > 19) extra.add(optionAsString) else cols.add(optionAsString)
}
cols.sort()
extra.sort()
var width = injector.engineEditorHelper.getApproximateScreenWidth(editor)
if (width < 20) {
width = 80
}
val colCount = width / 20
val height = ceil(cols.size.toDouble() / colCount.toDouble()).toInt()
var empty = cols.size % colCount
empty = if (empty == 0) colCount else empty
val res = StringBuilder()
if (showIntro) {
res.append("--- Options ---\n")
}
for (h in 0 until height) {
for (c in 0 until colCount) {
if (h == height - 1 && c >= empty) {
break
}
var pos = c * height + h
if (c > empty) {
pos -= c - empty
}
val opt = cols[pos]
res.append(opt.padEnd(20))
}
res.append("\n")
}
for (opt in extra) {
val seg = (opt.length - 1) / width
for (j in 0..seg) {
res.append(opt, j * width, min(j * width + width, opt.length))
res.append("\n")
}
}
injector.exOutputPanel.getPanel(editor).output(res.toString())
if (unknownOption != null) {
throw ExException("E518: Unknown option: ${unknownOption.second}")
}
}
private fun optionToString(scope: OptionScope, name: String): String {
val value = injector.optionService.getOptionValue(scope, name)
return if (injector.optionService.isToggleOption(name)) {
if (value.asBoolean()) " $name" else "no$name"
} else {
"$name=$value"
}
}
| mit | d85d076497e432248e4bc730daad6e7c | 33.694779 | 132 | 0.649612 | 3.986617 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/viewmodel/activitylog/ActivityLogViewModel.kt | 1 | 32847 | package org.wordpress.android.viewmodel.activitylog
import androidx.annotation.VisibleForTesting
import androidx.core.util.Pair
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import org.wordpress.android.R
import org.wordpress.android.fluxc.model.LocalOrRemoteId.RemoteId
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.fluxc.model.activity.ActivityTypeModel
import org.wordpress.android.fluxc.store.ActivityLogStore
import org.wordpress.android.fluxc.store.ActivityLogStore.OnActivityLogFetched
import org.wordpress.android.ui.activitylog.ActivityLogNavigationEvents
import org.wordpress.android.ui.activitylog.list.ActivityLogListItem
import org.wordpress.android.ui.jetpack.JetpackCapabilitiesUseCase
import org.wordpress.android.ui.jetpack.backup.download.BackupDownloadRequestState
import org.wordpress.android.ui.jetpack.backup.download.usecases.GetBackupDownloadStatusUseCase
import org.wordpress.android.ui.jetpack.backup.download.usecases.PostDismissBackupDownloadUseCase
import org.wordpress.android.ui.jetpack.common.JetpackBackupDownloadActionState.PROGRESS
import org.wordpress.android.ui.jetpack.restore.RestoreRequestState
import org.wordpress.android.ui.jetpack.restore.usecases.GetRestoreStatusUseCase
import org.wordpress.android.ui.stats.refresh.utils.StatsDateUtils
import org.wordpress.android.ui.utils.UiString
import org.wordpress.android.ui.utils.UiString.UiStringRes
import org.wordpress.android.ui.utils.UiString.UiStringResWithParams
import org.wordpress.android.ui.utils.UiString.UiStringText
import org.wordpress.android.util.AppLog
import org.wordpress.android.util.analytics.ActivityLogTracker
import org.wordpress.android.util.extensions.toFormattedDateString
import org.wordpress.android.util.extensions.toFormattedTimeString
import org.wordpress.android.viewmodel.Event
import org.wordpress.android.viewmodel.ResourceProvider
import org.wordpress.android.viewmodel.SingleLiveEvent
import org.wordpress.android.viewmodel.activitylog.ActivityLogViewModel.FiltersUiState.FiltersHidden
import org.wordpress.android.viewmodel.activitylog.ActivityLogViewModel.FiltersUiState.FiltersShown
import java.util.Date
import javax.inject.Inject
const val ACTIVITY_LOG_REWINDABLE_ONLY_KEY = "activity_log_rewindable_only"
private const val DAY_IN_MILLIS = 1000 * 60 * 60 * 24
private const val ONE_SECOND_IN_MILLIS = 1000
private const val TIMEZONE_GMT_0 = "GMT+0"
typealias DateRange = Pair<Long, Long>
/**
* It was decided to reuse the 'Activity Log' screen instead of creating a new 'Backup' screen. This was due to the
* fact that there will be lots of code that would need to be duplicated for the new 'Backup' screen. On the other
* hand, not much more complexity would be introduced if the 'Activity Log' screen is reused (mainly some 'if/else'
* code branches here and there).
*
* However, should more 'Backup' related additions are added to the 'Activity Log' screen, then it should become a
* necessity to split those features in separate screens in order not to increase further the complexity of this
* screen's architecture.
*/
@Suppress("LargeClass")
class ActivityLogViewModel @Inject constructor(
private val activityLogStore: ActivityLogStore,
private val getRestoreStatusUseCase: GetRestoreStatusUseCase,
private val getBackupDownloadStatusUseCase: GetBackupDownloadStatusUseCase,
private val postDismissBackupDownloadUseCase: PostDismissBackupDownloadUseCase,
private val resourceProvider: ResourceProvider,
private val statsDateUtils: StatsDateUtils,
private val activityLogTracker: ActivityLogTracker,
private val jetpackCapabilitiesUseCase: JetpackCapabilitiesUseCase
) : ViewModel() {
enum class ActivityLogListStatus {
CAN_LOAD_MORE,
DONE,
ERROR,
FETCHING,
LOADING_MORE
}
private var isStarted = false
private val _events = MutableLiveData<List<ActivityLogListItem>>()
val events: LiveData<List<ActivityLogListItem>>
get() = _events
private val _eventListStatus = MutableLiveData<ActivityLogListStatus>()
val eventListStatus: LiveData<ActivityLogListStatus>
get() = _eventListStatus
private val _filtersUiState = MutableLiveData<FiltersUiState>(FiltersHidden)
val filtersUiState: LiveData<FiltersUiState>
get() = _filtersUiState
private val _emptyUiState = MutableLiveData<EmptyUiState>(EmptyUiState.ActivityLog.EmptyFilters)
val emptyUiState: LiveData<EmptyUiState> = _emptyUiState
private val _showActivityTypeFilterDialog = SingleLiveEvent<ShowActivityTypePicker>()
val showActivityTypeFilterDialog: LiveData<ShowActivityTypePicker>
get() = _showActivityTypeFilterDialog
private val _showDateRangePicker = SingleLiveEvent<ShowDateRangePicker>()
val showDateRangePicker: LiveData<ShowDateRangePicker>
get() = _showDateRangePicker
private val _moveToTop = SingleLiveEvent<Unit>()
val moveToTop: SingleLiveEvent<Unit>
get() = _moveToTop
private val _showItemDetail = SingleLiveEvent<ActivityLogListItem>()
val showItemDetail: LiveData<ActivityLogListItem>
get() = _showItemDetail
private val _showSnackbarMessage = SingleLiveEvent<String>()
val showSnackbarMessage: LiveData<String>
get() = _showSnackbarMessage
private val _navigationEvents =
MutableLiveData<Event<ActivityLogNavigationEvents>>()
val navigationEvents: LiveData<Event<ActivityLogNavigationEvents>>
get() = _navigationEvents
private val isRestoreProgressItemShown: Boolean
get() = events.value?.find {
it is ActivityLogListItem.Progress &&
it.progressType == ActivityLogListItem.Progress.Type.RESTORE
} != null
private val isBackupDownloadProgressItemShown: Boolean
get() = events.value?.find {
it is ActivityLogListItem.Progress &&
it.progressType == ActivityLogListItem.Progress.Type.BACKUP_DOWNLOAD
} != null
private val isDone: Boolean
get() = eventListStatus.value == ActivityLogListStatus.DONE
private var fetchActivitiesJob: Job? = null
private var restoreStatusJob: Job? = null
private var backupDownloadStatusJob: Job? = null
private var currentDateRangeFilter: DateRange? = null
private var currentActivityTypeFilter: List<ActivityTypeModel> = listOf()
lateinit var site: SiteModel
var rewindableOnly: Boolean = false
private var currentRestoreEvent = RestoreEvent(false)
private var currentBackupDownloadEvent = BackupDownloadEvent(displayProgress = false, displayNotice = false)
fun start(site: SiteModel, rewindableOnly: Boolean) {
if (isStarted) {
return
}
isStarted = true
this.site = site
this.rewindableOnly = rewindableOnly
reloadEvents(true)
requestEventsUpdate(false)
showFiltersIfSupported()
}
@Suppress("LongMethod", "ComplexMethod")
@VisibleForTesting
fun reloadEvents(
done: Boolean = isDone,
restoreEvent: RestoreEvent = currentRestoreEvent,
backupDownloadEvent: BackupDownloadEvent = currentBackupDownloadEvent
) {
currentRestoreEvent = restoreEvent
currentBackupDownloadEvent = backupDownloadEvent
val eventList = activityLogStore.getActivityLogForSite(
site = site,
ascending = false,
rewindableOnly = rewindableOnly
)
val items = mutableListOf<ActivityLogListItem>()
var moveToTop = false
val withRestoreProgressItem = restoreEvent.displayProgress && !restoreEvent.isCompleted
val withBackupDownloadProgressItem = backupDownloadEvent.displayProgress && !backupDownloadEvent.isCompleted
val withBackupDownloadNoticeItem = backupDownloadEvent.displayNotice
if (withRestoreProgressItem || withBackupDownloadProgressItem) {
items.add(ActivityLogListItem.Header(resourceProvider.getString(R.string.now)))
moveToTop = eventListStatus.value != ActivityLogListStatus.LOADING_MORE
}
if (withRestoreProgressItem) {
items.add(getRestoreProgressItem(restoreEvent.rewindId, restoreEvent.published))
}
if (withBackupDownloadProgressItem) {
items.add(getBackupDownloadProgressItem(backupDownloadEvent.rewindId, backupDownloadEvent.published))
}
if (withBackupDownloadNoticeItem) {
getBackupDownloadNoticeItem(backupDownloadEvent)?.let {
items.add(it)
moveToTop = true
}
}
eventList.forEach { model ->
val currentItem = ActivityLogListItem.Event(
model = model,
rewindDisabled = withRestoreProgressItem || withBackupDownloadProgressItem,
isRestoreHidden = restoreEvent.isRestoreHidden
)
val lastItem = items.lastOrNull() as? ActivityLogListItem.Event
if (lastItem == null || lastItem.formattedDate != currentItem.formattedDate) {
items.add(ActivityLogListItem.Header(currentItem.formattedDate))
}
items.add(currentItem)
}
if (eventList.isNotEmpty() && !done) {
items.add(ActivityLogListItem.Loading)
}
if (eventList.isNotEmpty() && site.hasFreePlan && done) {
items.add(ActivityLogListItem.Footer)
}
_events.value = items
if (moveToTop) {
_moveToTop.call()
}
if (restoreEvent.isCompleted) {
showRestoreFinishedMessage(restoreEvent.rewindId, restoreEvent.published)
currentRestoreEvent = RestoreEvent(false)
}
}
private fun getRestoreProgressItem(rewindId: String?, published: Date?): ActivityLogListItem.Progress {
val rewindDate = published ?: rewindId?.let { activityLogStore.getActivityLogItemByRewindId(it)?.published }
return rewindDate?.let {
ActivityLogListItem.Progress(
resourceProvider.getString(R.string.activity_log_currently_restoring_title),
resourceProvider.getString(
R.string.activity_log_currently_restoring_message,
rewindDate.toFormattedDateString(),
rewindDate.toFormattedTimeString()
),
ActivityLogListItem.Progress.Type.RESTORE
)
} ?: ActivityLogListItem.Progress(
resourceProvider.getString(R.string.activity_log_currently_restoring_title),
resourceProvider.getString(R.string.activity_log_currently_restoring_message_no_dates),
ActivityLogListItem.Progress.Type.RESTORE
)
}
private fun getBackupDownloadProgressItem(rewindId: String?, published: Date?): ActivityLogListItem.Progress {
val rewindDate = published ?: rewindId?.let { activityLogStore.getActivityLogItemByRewindId(it)?.published }
return rewindDate?.let {
ActivityLogListItem.Progress(
resourceProvider.getString(R.string.activity_log_currently_backing_up_title),
resourceProvider.getString(
R.string.activity_log_currently_backing_up_message,
rewindDate.toFormattedDateString(), rewindDate.toFormattedTimeString()
),
ActivityLogListItem.Progress.Type.BACKUP_DOWNLOAD
)
} ?: ActivityLogListItem.Progress(
resourceProvider.getString(R.string.activity_log_currently_backing_up_title),
resourceProvider.getString(R.string.activity_log_currently_backing_up_message_no_dates),
ActivityLogListItem.Progress.Type.BACKUP_DOWNLOAD
)
}
private fun getBackupDownloadNoticeItem(backupDownloadEvent: BackupDownloadEvent): ActivityLogListItem.Notice? {
val rewindDate = backupDownloadEvent.published
?: backupDownloadEvent.rewindId?.let { activityLogStore.getActivityLogItemByRewindId(it)?.published }
return rewindDate?.let {
ActivityLogListItem.Notice(
label = resourceProvider.getString(
R.string.activity_log_backup_download_notice_description_with_two_params,
rewindDate.toFormattedDateString(), rewindDate.toFormattedTimeString()
),
primaryAction = { onDownloadBackupFileClicked(backupDownloadEvent.url as String) },
secondaryAction = { dismissNoticeClicked(backupDownloadEvent.downloadId as Long) }
)
}
}
private fun showRestoreFinishedMessage(rewindId: String?, published: Date?) {
val rewindDate = published ?: rewindId?.let { activityLogStore.getActivityLogItemByRewindId(it)?.published }
if (rewindDate != null) {
_showSnackbarMessage.value =
resourceProvider.getString(
R.string.activity_log_rewind_finished_snackbar_message,
rewindDate.toFormattedDateString(),
rewindDate.toFormattedTimeString()
)
} else {
_showSnackbarMessage.value =
resourceProvider.getString(R.string.activity_log_rewind_finished_snackbar_message_no_dates)
}
}
private fun showBackupDownloadFinishedMessage(rewindId: String?) {
val rewindDate = rewindId?.let { activityLogStore.getActivityLogItemByRewindId(it)?.published }
if (rewindDate != null) {
_showSnackbarMessage.value =
resourceProvider.getString(
R.string.activity_log_backup_finished_snackbar_message,
rewindDate.toFormattedDateString(),
rewindDate.toFormattedTimeString()
)
} else {
_showSnackbarMessage.value =
resourceProvider.getString(R.string.activity_log_backup_finished_snackbar_message_no_dates)
}
}
private fun requestEventsUpdate(
loadMore: Boolean,
restoreEvent: RestoreEvent = currentRestoreEvent,
backupDownloadEvent: BackupDownloadEvent = currentBackupDownloadEvent
) {
val isLoadingMore = fetchActivitiesJob != null && eventListStatus.value == ActivityLogListStatus.LOADING_MORE
val canLoadMore = eventListStatus.value == ActivityLogListStatus.CAN_LOAD_MORE
if (loadMore && (isLoadingMore || !canLoadMore)) {
// Ignore loadMore request when already loading more items or there are no more items to load
return
}
fetchActivitiesJob?.cancel()
val newStatus = if (loadMore) ActivityLogListStatus.LOADING_MORE else ActivityLogListStatus.FETCHING
_eventListStatus.value = newStatus
val payload = ActivityLogStore.FetchActivityLogPayload(
site,
loadMore,
currentDateRangeFilter?.first?.let { Date(it) },
currentDateRangeFilter?.second?.let { Date(it) },
currentActivityTypeFilter.map { it.key }
)
fetchActivitiesJob = viewModelScope.launch {
val result = activityLogStore.fetchActivities(payload)
if (isActive) {
onActivityLogFetched(result, loadMore, restoreEvent, backupDownloadEvent)
fetchActivitiesJob = null
}
}
}
private fun onActivityLogFetched(
event: OnActivityLogFetched,
loadingMore: Boolean,
restoreEvent: RestoreEvent,
backupDownloadEvent: BackupDownloadEvent
) {
if (event.isError) {
_eventListStatus.value = ActivityLogListStatus.ERROR
AppLog.e(AppLog.T.ACTIVITY_LOG, "An error occurred while fetching the Activity log events")
return
}
if (event.rowsAffected > 0) {
reloadEvents(
done = !event.canLoadMore,
restoreEvent = restoreEvent,
backupDownloadEvent = backupDownloadEvent
)
if (!loadingMore) {
moveToTop.call()
}
if (!restoreEvent.isCompleted) queryRestoreStatus()
if (!backupDownloadEvent.isCompleted) queryBackupDownloadStatus()
}
if (event.canLoadMore) {
_eventListStatus.value = ActivityLogListStatus.CAN_LOAD_MORE
} else {
_eventListStatus.value = ActivityLogListStatus.DONE
}
}
private fun showFiltersIfSupported() {
when {
!site.hasFreePlan -> refreshFiltersUiState()
else -> {
viewModelScope.launch {
val purchasedProducts = jetpackCapabilitiesUseCase.getCachedJetpackPurchasedProducts(site.siteId)
if (purchasedProducts.backup) {
refreshFiltersUiState()
}
}
}
}
}
override fun onCleared() {
if (currentDateRangeFilter != null || currentActivityTypeFilter.isNotEmpty()) {
/**
* Clear cache when filters are not empty. Filters are not retained across sessions, therefore the data is
* not relevant when the screen is accessed next time.
*/
activityLogStore.clearActivityLogCache(site)
}
jetpackCapabilitiesUseCase.clear()
super.onCleared()
}
private fun refreshFiltersUiState() {
val (activityTypeLabel, activityTypeLabelContentDescription) = createActivityTypeFilterLabel()
val (dateRangeLabel, dateRangeLabelContentDescription) = createDateRangeFilterLabel()
_filtersUiState.value = FiltersShown(
dateRangeLabel,
dateRangeLabelContentDescription,
activityTypeLabel,
activityTypeLabelContentDescription,
currentDateRangeFilter?.let { ::onClearDateRangeFilterClicked },
currentActivityTypeFilter.takeIf { it.isNotEmpty() }?.let { ::onClearActivityTypeFilterClicked }
)
refreshEmptyUiState()
}
private fun refreshEmptyUiState() {
if (rewindableOnly) {
refreshBackupEmptyUiState()
} else {
refreshActivityLogEmptyUiState()
}
}
private fun refreshBackupEmptyUiState() {
if (currentDateRangeFilter != null) {
_emptyUiState.value = EmptyUiState.Backup.ActiveFilters
} else {
_emptyUiState.value = EmptyUiState.Backup.EmptyFilters
}
}
private fun refreshActivityLogEmptyUiState() {
if (currentDateRangeFilter != null || currentActivityTypeFilter.isNotEmpty()) {
_emptyUiState.value = EmptyUiState.ActivityLog.ActiveFilters
} else {
_emptyUiState.value = EmptyUiState.ActivityLog.EmptyFilters
}
}
private fun createDateRangeFilterLabel(): kotlin.Pair<UiString, UiString> {
return currentDateRangeFilter?.let {
val label = UiStringText(
statsDateUtils.formatDateRange(requireNotNull(it.first), requireNotNull(it.second), TIMEZONE_GMT_0)
)
kotlin.Pair(label, label)
} ?: kotlin.Pair(
UiStringRes(R.string.activity_log_date_range_filter_label),
UiStringRes(R.string.activity_log_date_range_filter_label_content_description)
)
}
private fun createActivityTypeFilterLabel(): kotlin.Pair<UiString, UiString> {
return currentActivityTypeFilter.takeIf { it.isNotEmpty() }?.let {
if (it.size == 1) {
kotlin.Pair(
UiStringText(it[0].name),
UiStringResWithParams(
R.string.activity_log_activity_type_filter_single_item_selected_content_description,
listOf(UiStringText(it[0].name), UiStringText(it[0].count.toString()))
)
)
} else {
kotlin.Pair(
UiStringResWithParams(
R.string.activity_log_activity_type_filter_active_label,
listOf(UiStringText("${it.size}"))
),
UiStringResWithParams(
R.string.activity_log_activity_type_filter_multiple_items_selected_content_description,
listOf(UiStringText("${it.size}"))
)
)
}
} ?: kotlin.Pair(
UiStringRes(R.string.activity_log_activity_type_filter_label),
UiStringRes(R.string.activity_log_activity_type_filter_no_item_selected_content_description)
)
}
fun onScrolledToBottom() {
requestEventsUpdate(true)
}
fun onPullToRefresh() {
requestEventsUpdate(false)
}
fun onItemClicked(item: ActivityLogListItem) {
if (item is ActivityLogListItem.Event) {
_showItemDetail.value = item
}
}
fun onSecondaryActionClicked(
secondaryAction: ActivityLogListItem.SecondaryAction,
item: ActivityLogListItem
): Boolean {
if (item is ActivityLogListItem.Event) {
val navigationEvent = when (secondaryAction) {
ActivityLogListItem.SecondaryAction.RESTORE -> {
ActivityLogNavigationEvents.ShowRestore(item)
}
ActivityLogListItem.SecondaryAction.DOWNLOAD_BACKUP -> {
ActivityLogNavigationEvents.ShowBackupDownload(item)
}
}
_navigationEvents.value = Event(navigationEvent)
}
return true
}
private fun onDownloadBackupFileClicked(url: String) {
activityLogTracker.trackDownloadBackupDownloadButtonClicked(rewindableOnly)
_navigationEvents.value = Event(ActivityLogNavigationEvents.DownloadBackupFile(url))
}
/**
Reload events first to remove the notice item, as it shows progress to the user. Then
trigger the dismiss (this is an optimistic call). If the dismiss fails it will show
again on the next reload.
*/
private fun dismissNoticeClicked(downloadId: Long) {
activityLogTracker.trackDownloadBackupDismissButtonClicked(rewindableOnly)
reloadEvents(backupDownloadEvent = BackupDownloadEvent(displayNotice = false, displayProgress = false))
viewModelScope.launch { postDismissBackupDownloadUseCase.dismissBackupDownload(downloadId, site) }
}
fun dateRangePickerClicked() {
activityLogTracker.trackDateRangeFilterButtonClicked(rewindableOnly)
_showDateRangePicker.value = ShowDateRangePicker(initialSelection = currentDateRangeFilter)
}
fun onDateRangeSelected(dateRange: DateRange?) {
val adjustedDateRange = dateRange?.let {
// adjust time of the end of the date range to 23:59:59
Pair(dateRange.first, dateRange.second?.let { it + DAY_IN_MILLIS - ONE_SECOND_IN_MILLIS })
}
activityLogTracker.trackDateRangeFilterSelected(dateRange, rewindableOnly)
currentDateRangeFilter = adjustedDateRange
refreshFiltersUiState()
requestEventsUpdate(false)
}
fun onClearDateRangeFilterClicked() {
activityLogTracker.trackDateRangeFilterCleared(rewindableOnly)
currentDateRangeFilter = null
refreshFiltersUiState()
requestEventsUpdate(false)
}
fun onActivityTypeFilterClicked() {
activityLogTracker.trackActivityTypeFilterButtonClicked()
_showActivityTypeFilterDialog.value = ShowActivityTypePicker(
RemoteId(site.siteId),
currentActivityTypeFilter.map { it.key },
currentDateRangeFilter
)
}
fun onActivityTypesSelected(selectedTypes: List<ActivityTypeModel>) {
activityLogTracker.trackActivityTypeFilterSelected(selectedTypes)
currentActivityTypeFilter = selectedTypes
refreshFiltersUiState()
requestEventsUpdate(false)
}
fun onClearActivityTypeFilterClicked() {
activityLogTracker.trackActivityTypeFilterCleared()
currentActivityTypeFilter = listOf()
refreshFiltersUiState()
requestEventsUpdate(false)
}
fun onQueryRestoreStatus(rewindId: String, restoreId: Long) {
queryRestoreStatus(restoreId)
showRestoreStartedMessage(rewindId)
}
private fun queryRestoreStatus(restoreId: Long? = null) {
restoreStatusJob?.cancel()
restoreStatusJob = viewModelScope.launch {
getRestoreStatusUseCase.getRestoreStatus(site, restoreId)
.collect { handleRestoreStatus(it) }
}
}
private fun handleRestoreStatus(state: RestoreRequestState) {
when (state) {
is RestoreRequestState.Multisite -> handleRestoreStatusForMultisite()
is RestoreRequestState.Progress -> handleRestoreStatusForProgress(state)
is RestoreRequestState.Complete -> handleRestoreStatusForComplete(state)
else -> Unit // Do nothing
}
}
private fun handleRestoreStatusForMultisite() {
reloadEvents(
restoreEvent = RestoreEvent(
displayProgress = false,
isRestoreHidden = true
)
)
}
private fun handleRestoreStatusForProgress(state: RestoreRequestState.Progress) {
if (!isRestoreProgressItemShown) {
reloadEvents(
restoreEvent = RestoreEvent(
displayProgress = true,
isCompleted = false,
rewindId = state.rewindId,
published = state.published
)
)
}
}
private fun handleRestoreStatusForComplete(state: RestoreRequestState.Complete) {
if (isRestoreProgressItemShown) {
requestEventsUpdate(
loadMore = false,
restoreEvent = RestoreEvent(
displayProgress = false,
isCompleted = true,
rewindId = state.rewindId,
published = state.published
)
)
}
}
private fun showRestoreStartedMessage(rewindId: String) {
activityLogStore.getActivityLogItemByRewindId(rewindId)?.published?.let {
_showSnackbarMessage.value = resourceProvider.getString(
R.string.activity_log_rewind_started_snackbar_message,
it.toFormattedDateString(),
it.toFormattedTimeString()
)
}
}
fun onQueryBackupDownloadStatus(rewindId: String, downloadId: Long, actionState: Int) {
queryBackupDownloadStatus(downloadId)
if (actionState == PROGRESS.id) {
showBackupDownloadStartedMessage(rewindId)
} else {
showBackupDownloadFinishedMessage(rewindId)
}
}
private fun queryBackupDownloadStatus(downloadId: Long? = null) {
backupDownloadStatusJob?.cancel()
backupDownloadStatusJob = viewModelScope.launch {
getBackupDownloadStatusUseCase.getBackupDownloadStatus(site, downloadId)
.collect { state -> handleBackupDownloadStatus(state) }
}
}
private fun handleBackupDownloadStatus(state: BackupDownloadRequestState) {
when (state) {
is BackupDownloadRequestState.Progress -> handleBackupDownloadStatusForProgress(state)
is BackupDownloadRequestState.Complete -> handleBackupDownloadStatusForComplete(state)
else -> Unit // Do nothing
}
}
private fun handleBackupDownloadStatusForProgress(state: BackupDownloadRequestState.Progress) {
if (!isBackupDownloadProgressItemShown) {
reloadEvents(
backupDownloadEvent = BackupDownloadEvent(
displayProgress = true,
displayNotice = false,
isCompleted = false,
rewindId = state.rewindId,
published = state.published
)
)
}
}
private fun handleBackupDownloadStatusForComplete(state: BackupDownloadRequestState.Complete) {
val backupDownloadEvent = BackupDownloadEvent(
displayProgress = false,
displayNotice = state.isValid,
isCompleted = true,
rewindId = state.rewindId,
published = state.published,
url = state.url,
validUntil = state.validUntil,
downloadId = state.downloadId
)
if (isBackupDownloadProgressItemShown) {
requestEventsUpdate(loadMore = false, backupDownloadEvent = backupDownloadEvent)
} else {
reloadEvents(backupDownloadEvent = backupDownloadEvent)
}
}
private fun showBackupDownloadStartedMessage(rewindId: String) {
activityLogStore.getActivityLogItemByRewindId(rewindId)?.published?.let {
_showSnackbarMessage.value = resourceProvider.getString(
R.string.activity_log_backup_started_snackbar_message,
it.toFormattedDateString(),
it.toFormattedTimeString()
)
}
}
data class ShowDateRangePicker(val initialSelection: DateRange?)
data class ShowActivityTypePicker(
val siteId: RemoteId,
val initialSelection: List<String>,
val dateRange: DateRange?
)
data class RestoreEvent(
val displayProgress: Boolean,
val isRestoreHidden: Boolean = false,
val isCompleted: Boolean = false,
val rewindId: String? = null,
val published: Date? = null
)
data class BackupDownloadEvent(
val displayProgress: Boolean,
val displayNotice: Boolean,
val isCompleted: Boolean = false,
val rewindId: String? = null,
val published: Date? = null,
val downloadId: Long? = null,
val url: String? = null,
val validUntil: Date? = null
)
sealed class FiltersUiState(val visibility: Boolean) {
object FiltersHidden : FiltersUiState(visibility = false)
data class FiltersShown(
val dateRangeLabel: UiString,
val dateRangeLabelContentDescription: UiString,
val activityTypeLabel: UiString,
val activityTypeLabelContentDescription: UiString,
val onClearDateRangeFilterClicked: (() -> Unit)?,
val onClearActivityTypeFilterClicked: (() -> Unit)?
) : FiltersUiState(visibility = true)
}
sealed class EmptyUiState {
abstract val emptyScreenTitle: UiString
abstract val emptyScreenSubtitle: UiString
object ActivityLog {
object EmptyFilters : EmptyUiState() {
override val emptyScreenTitle = UiStringRes(R.string.activity_log_empty_title)
override val emptyScreenSubtitle = UiStringRes(R.string.activity_log_empty_subtitle)
}
object ActiveFilters : EmptyUiState() {
override val emptyScreenTitle = UiStringRes(R.string.activity_log_active_filter_empty_title)
override val emptyScreenSubtitle = UiStringRes(R.string.activity_log_active_filter_empty_subtitle)
}
}
object Backup {
object EmptyFilters : EmptyUiState() {
override val emptyScreenTitle = UiStringRes(R.string.backup_empty_title)
override val emptyScreenSubtitle = UiStringRes(R.string.backup_empty_subtitle)
}
object ActiveFilters : EmptyUiState() {
override val emptyScreenTitle = UiStringRes(R.string.backup_active_filter_empty_title)
override val emptyScreenSubtitle = UiStringRes(R.string.backup_active_filter_empty_subtitle)
}
}
}
}
| gpl-2.0 | 2703c42c2160e258bc91fc135a226efb | 41.274131 | 119 | 0.653241 | 5.902426 | false | false | false | false |
gabfssilva/geryon | kotlin-examples/src/main/kotlin/org/geryon/examples/kotlin/SimpleServer.kt | 1 | 3482 | package org.geryon.examples.kotlin
import java.util.*
import java.util.concurrent.Executors
import org.geryon.Http.*
/**
* @author Gabriel Francisco <[email protected]>
*/
object SimpleServer {
@JvmStatic
fun main(args: Array<String>) {
//defining the expose http port
//default is 8080
port(8888)
//default response content-type
//default is text/plain
defaultContentType("application/json")
//you can define how many threads netty will use for its event loop
eventLoopThreadNumber(1)
// you can define some headers to be sent with any response
defaultHeader("X-Powered-By", "geryon")
//you can also define exception handlers for exceptions occurred on the future completion
handlerFor(Exception::class.java) { exception, request ->
internalServerError("ups, you called ${request.url()} and it seems that an exception occurred: ${exception.message}")
}
get("/hello") { r ->
val name = r.queryParameters().get("name")
// since you cannot block your handler,
// you need to return a CompletableFuture with a response, instead of only a response
supply { ok("{\"name\": \"$name\"}") }
}
//over here we are using a matcher
//a matcher is a function<request, boolean> which returns if the request
//matched the route, so, you can have the same method and path mapped
//to different routes, since you also implemented different matchers.
get("/hello/withMatcher", { r -> "1" == r.headers().get("Version") }) { r ->
val name = r.queryParameters().get("name")
// since you cannot block your handler,
// you need to return a CompletableFuture with a response, instead of only a response
supply { ok("{\"name\": \"$name\"}") }
}
get("/hello/:name") { r ->
//getting the path parameter
val name = r.pathParameters()["name"]
// since you cannot block your handler,
// you need to return a CompletableFuture with a response, instead of only a response
supply { ok("{\"name\": \"$name\"}") }
}
//this example is using matrix parameters
//matrix parameters are evaluated lazily, since getting them is more costly than other parameters
get("/hello/matrix") { r ->
//so, if the client sends a GET: http://host:port/hello;name=gabriel;age=24/matrix
//we are extracting over here name and size parameters from "hello" path.
val name = r.matrixParameters()["hello"]!!["name"]
val age = r.matrixParameters()["hello"]!!["age"]
supply { ok("{\"name\": \"$name\", \"age\":$age}") }
}
post("/hello") { r ->
val jsonBody = r.body()
// since you cannot block your handler,
// you need to return a CompletableFuture with a response, instead of only a response
supply { created("/hello/" + UUID.randomUUID().toString(), jsonBody) }
}
val singleThreadExecutor = Executors.newSingleThreadExecutor()
put("/hello") { r ->
val jsonBody = r.body()
//in this case, we are using a specific executor service to avoid blocking operations in the global executor
supply(singleThreadExecutor) { accepted(jsonBody) }
}
}
}
| mit | aa4557b0c203408dc75b1d308840d320 | 39.488372 | 129 | 0.599943 | 4.730978 | false | false | false | false |
mdaniel/intellij-community | plugins/grazie/src/main/kotlin/com/intellij/grazie/GraziePlugin.kt | 5 | 1029 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.grazie
import com.intellij.ide.plugins.IdeaPluginDescriptor
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.openapi.extensions.PluginId
import java.nio.file.Path
internal object GraziePlugin {
const val id = "tanvd.grazi"
object LanguageTool {
const val version = "5.7"
const val url = "https://resources.jetbrains.com/grazie/model/language-tool"
}
private val descriptor: IdeaPluginDescriptor
get() = PluginManagerCore.getPlugin(PluginId.getId(id))!!
val group: String
get() = GrazieBundle.message("grazie.group.name")
val settingsPageName: String
get() = GrazieBundle.message("grazie.settings.page.name")
val isBundled: Boolean
get() = descriptor.isBundled
val classLoader: ClassLoader
get() = descriptor.classLoader
val libFolder: Path
get() = descriptor.pluginPath.resolve("lib")
}
| apache-2.0 | e82e62a3d4c15ce2360a6149e6b183c9 | 29.264706 | 140 | 0.748299 | 4.13253 | false | false | false | false |
ingokegel/intellij-community | notebooks/visualization/test/org/jetbrains/plugins/notebooks/visualization/NotebookIntervalPointerTest.kt | 1 | 7597 | package org.jetbrains.plugins.notebooks.visualization
import com.intellij.mock.MockDocument
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.event.MockDocumentEvent
import com.intellij.util.EventDispatcher
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.catchThrowable
import org.assertj.core.api.Descriptable
import org.assertj.core.description.Description
import org.jetbrains.plugins.notebooks.visualization.NotebookCellLines.Interval
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@RunWith(JUnit4::class)
class NotebookIntervalPointerTest {
private val exampleIntervals = listOf(
makeIntervals(),
makeIntervals(0..1),
makeIntervals(0..1, 2..4),
makeIntervals(0..1, 2..4, 5..8),
)
@Test
fun testInitialization() {
for (intervals in exampleIntervals) {
val env = TestEnv(intervals)
env.shouldBeValid(intervals)
env.shouldBeInvalid(makeInterval(10, 10..11))
}
}
@Test
fun testAddAllIntervals() {
for (intervals in exampleIntervals) {
val env = TestEnv(listOf())
env.shouldBeInvalid(intervals)
env.changeSegment(listOf(), intervals, intervals)
env.shouldBeValid(intervals)
}
}
@Test
fun testRemoveAllIntervals() {
for (intervals in exampleIntervals) {
val env = TestEnv(intervals)
env.shouldBeValid(intervals)
env.changeSegment(intervals, listOf(), listOf())
env.shouldBeInvalid(intervals)
}
}
@Test
fun testChangeElements() {
val initialIntervals = makeIntervals(0..1, 2..4, 5..8, 9..13)
val optionsToRemove = listOf(
listOf(),
initialIntervals.subList(1, 2),
initialIntervals.subList(1, 3),
initialIntervals.subList(1, 4)
)
val optionsToAdd = listOf(
listOf(),
makeIntervals(2..10).map { it.copy(ordinal = it.ordinal + 1, type = NotebookCellLines.CellType.CODE) },
makeIntervals(2..10, 11..20).map { it.copy(ordinal = it.ordinal + 1, type = NotebookCellLines.CellType.CODE) }
)
for (toRemove in optionsToRemove) {
for (toAdd in optionsToAdd) {
val start = initialIntervals.subList(0, 1)
val end = initialIntervals.subList(1 + toRemove.size, 4)
val finalIntervals = fixOrdinalsAndOffsets(start + toAdd + end)
val env = TestEnv(initialIntervals)
val pointersToUnchangedIntervals = (start + end).map { env.pointersFactory.create(it) }
val pointersToRemovedIntervals = toRemove.map { env.pointersFactory.create(it) }
pointersToUnchangedIntervals.forEach { assertThat(it.get()).isNotNull() }
pointersToRemovedIntervals.forEach { assertThat(it.get()).isNotNull }
env.changeSegment(toRemove, toAdd, finalIntervals)
pointersToUnchangedIntervals.forEach { pointer -> assertThat(pointer.get()).isNotNull() }
pointersToRemovedIntervals.forEach { pointer -> assertThat(pointer.get()).isNull() }
env.shouldBeValid(finalIntervals)
env.shouldBeInvalid(toRemove)
}
}
}
@Test
fun testReuseInterval() {
val initialIntervals = makeIntervals(0..1, 2..19, 20..199)
for ((i, selected) in initialIntervals.withIndex()) {
val dsize = 1
val changed = selected.copy(lines = selected.lines.first..selected.lines.last + dsize)
val allIntervals = fixOrdinalsAndOffsets(initialIntervals.subList(0, i) + listOf(changed) + initialIntervals.subList(i + 1, initialIntervals.size))
val env = TestEnv(initialIntervals)
val pointers = initialIntervals.map { env.pointersFactory.create(it) }
pointers.zip(initialIntervals).forEach { (pointer, interval) -> assertThat(pointer.get()).isEqualTo(interval) }
env.changeSegment(listOf(selected), listOf(changed), allIntervals)
pointers.zip(allIntervals).forEach { (pointer, interval) -> assertThat(pointer.get()).isEqualTo(interval)}
}
}
private fun fixOrdinalsAndOffsets(intervals: List<Interval>): List<Interval> {
val result = mutableListOf<Interval>()
for ((index, interval) in intervals.withIndex()) {
val expectedOffset = result.lastOrNull()?.let { it.lines.last + 1 } ?: 0
val correctInterval =
if (interval.lines.first == expectedOffset && interval.ordinal == index)
interval
else
interval.copy(ordinal = index, lines = expectedOffset..(expectedOffset + interval.lines.last - interval.lines.first))
result.add(correctInterval)
}
return result
}
private fun makeInterval(ordinal: Int, lines: IntRange) =
Interval(ordinal, NotebookCellLines.CellType.RAW, lines, NotebookCellLines.MarkersAtLines.NO)
private fun makeIntervals(vararg lines: IntRange): List<Interval> =
lines.withIndex().map { (index, lines) -> makeInterval(index, lines) }
}
private class TestEnv(intervals: List<Interval>, val document: Document = MockDocument()) {
val notebookCellLines = MockNotebookCellLines(intervals = mutableListOf(*intervals.toTypedArray()))
val pointersFactory = NotebookIntervalPointerFactoryImpl(notebookCellLines)
fun changeSegment(old: List<Interval>, new: List<Interval>, allIntervals: List<Interval>) {
old.firstOrNull()?.let { firstOld ->
new.firstOrNull()?.let { firstNew ->
assertThat(firstOld.ordinal).isEqualTo(firstNew.ordinal)
}
}
notebookCellLines.intervals.clear()
notebookCellLines.intervals.addAll(allIntervals)
val documentEvent = MockDocumentEvent(document, 0)
val event = NotebookCellLinesEvent(documentEvent, old, old, new, new, 0)
notebookCellLines.intervalListeners.multicaster.segmentChanged(event)
}
fun shouldBeValid(interval: Interval) {
assertThat(pointersFactory.create(interval).get())
.describedAs { "pointer for ${interval} should be valid, but current pointers = ${describe(notebookCellLines.intervals)}" }
.isEqualTo(interval)
}
fun shouldBeInvalid(interval: Interval) {
val error = catchThrowable {
pointersFactory.create(interval).get()
}
assertThat(error)
.describedAs { "pointer for ${interval} should be null, but current pointers = ${describe(notebookCellLines.intervals)}" }
.isNotNull()
}
fun shouldBeValid(intervals: List<Interval>): Unit = intervals.forEach { shouldBeValid(it) }
fun shouldBeInvalid(intervals: List<Interval>): Unit = intervals.forEach { shouldBeInvalid(it) }
}
private class MockNotebookCellLines(override val intervals: MutableList<Interval> = mutableListOf()) : NotebookCellLines {
init {
checkIntervals(intervals)
}
override val intervalListeners = EventDispatcher.create(NotebookCellLines.IntervalListener::class.java)
override fun intervalsIterator(startLine: Int): ListIterator<Interval> = TODO("stub")
override val modificationStamp: Long
get() = TODO("stub")
}
private fun describe(intervals: List<Interval>): String =
intervals.joinToString(separator = ",", prefix = "[", postfix = "]")
private fun checkIntervals(intervals: List<Interval>) {
intervals.zipWithNext().forEach { (prev, next) ->
assertThat(prev.lines.last + 1).describedAs { "wrong intervals: ${describe(intervals)}" }.isEqualTo(next.lines.first)
}
intervals.withIndex().forEach { (index, interval) ->
assertThat(interval.ordinal).describedAs { "wrong interval ordinal: ${describe(intervals)}" }.isEqualTo(index)
}
}
fun <Self> Descriptable<Self>.describedAs(lazyMsg: () -> String): Self =
describedAs(object : Description() {
override fun value(): String = lazyMsg()
})
| apache-2.0 | 918671a60fe2eecc29b88bbb3c78e31f | 35.004739 | 153 | 0.710807 | 4.336187 | false | true | false | false |
ingokegel/intellij-community | platform/platform-impl/src/com/intellij/idea/StartupUtil.kt | 1 | 40319 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:JvmName("StartupUtil")
@file:Suppress("JAVA_MODULE_DOES_NOT_EXPORT_PACKAGE", "ReplacePutWithAssignment", "KDocUnresolvedReference")
package com.intellij.idea
import com.intellij.BundleBase
import com.intellij.accessibility.AccessibilityUtils
import com.intellij.diagnostic.*
import com.intellij.diagnostic.opentelemetry.TraceManager
import com.intellij.ide.*
import com.intellij.ide.customize.CommonCustomizeIDEWizardDialog
import com.intellij.ide.gdpr.ConsentOptions
import com.intellij.ide.gdpr.EndUserAgreement
import com.intellij.ide.gdpr.showDataSharingAgreement
import com.intellij.ide.gdpr.showEndUserAndDataSharingAgreements
import com.intellij.ide.instrument.WriteIntentLockInstrumenter
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.ide.ui.html.GlobalStyleSheetHolder
import com.intellij.ide.ui.laf.IdeaLaf
import com.intellij.ide.ui.laf.IntelliJLaf
import com.intellij.ide.ui.laf.darcula.DarculaLaf
import com.intellij.idea.SocketLock.ActivationStatus
import com.intellij.jna.JnaLoader
import com.intellij.openapi.application.ApplicationInfo
import com.intellij.openapi.application.ApplicationNamesInfo
import com.intellij.openapi.application.ConfigImportHelper
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.application.ex.ApplicationInfoEx
import com.intellij.openapi.application.ex.ApplicationManagerEx
import com.intellij.openapi.application.impl.AWTExceptionHandler
import com.intellij.openapi.application.impl.ApplicationImpl
import com.intellij.openapi.application.impl.ApplicationInfoImpl
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.ShutDownTracker
import com.intellij.openapi.util.SystemInfoRt
import com.intellij.openapi.util.io.win32.IdeaWin32
import com.intellij.openapi.wm.WeakFocusStackManager
import com.intellij.serviceContainer.ComponentManagerImpl
import com.intellij.ui.AppUIUtil
import com.intellij.ui.CoreIconManager
import com.intellij.ui.IconManager
import com.intellij.ui.mac.MacOSApplicationProvider
import com.intellij.ui.scale.JBUIScale
import com.intellij.util.EnvironmentUtil
import com.intellij.util.PlatformUtils
import com.intellij.util.ReflectionUtil
import com.intellij.util.lang.Java11Shim
import com.intellij.util.lang.ZipFilePool
import com.intellij.util.ui.EDT
import com.intellij.util.ui.StartupUiUtil
import com.intellij.util.ui.accessibility.ScreenReader
import kotlinx.coroutines.*
import org.jetbrains.annotations.VisibleForTesting
import org.jetbrains.io.BuiltInServer
import sun.awt.AWTAutoShutdown
import java.awt.EventQueue
import java.awt.Font
import java.awt.GraphicsEnvironment
import java.awt.Toolkit
import java.awt.dnd.DragSource
import java.io.File
import java.io.IOError
import java.io.IOException
import java.lang.invoke.MethodHandles
import java.lang.invoke.MethodType
import java.lang.management.ManagementFactory
import java.nio.channels.FileChannel
import java.nio.file.Files
import java.nio.file.InvalidPathException
import java.nio.file.Path
import java.nio.file.StandardOpenOption
import java.nio.file.attribute.PosixFileAttributeView
import java.nio.file.attribute.PosixFilePermission
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.*
import java.util.function.BiConsumer
import java.util.function.BiFunction
import java.util.function.Function
import java.util.logging.ConsoleHandler
import java.util.logging.Level
import javax.swing.*
import kotlin.coroutines.CoroutineContext
import kotlin.system.exitProcess
internal const val IDE_STARTED = "------------------------------------------------------ IDE STARTED ------------------------------------------------------"
private const val IDE_SHUTDOWN = "------------------------------------------------------ IDE SHUTDOWN ------------------------------------------------------"
@JvmField
internal var EXTERNAL_LISTENER: BiFunction<String, Array<String>, Int> = BiFunction { _, _ -> AppExitCodes.ACTIVATE_NOT_INITIALIZED }
private const val IDEA_CLASS_BEFORE_APPLICATION_PROPERTY = "idea.class.before.app"
// see `ApplicationImpl#USE_SEPARATE_WRITE_THREAD`
private const val USE_SEPARATE_WRITE_THREAD_PROPERTY = "idea.use.separate.write.thread"
private const val MAGIC_MAC_PATH = "/AppTranslocation/"
private var socketLock: SocketLock? = null
// checked - using Deferred type doesn't lead to loading this class on StartupUtil init
internal var shellEnvDeferred: Deferred<Boolean?>? = null
private set
// mainDispatcher is a sequential - use it with care
fun CoroutineScope.startApplication(args: List<String>,
appStarterDeferred: Deferred<AppStarter>,
mainScope: CoroutineScope,
busyThread: Thread) {
val appInfoDeferred = async(CoroutineName("app info") + Dispatchers.IO) {
// required for DisabledPluginsState and EUA
ApplicationInfoImpl.getShadowInstance()
}
val euaDocumentDeferred = loadEuaDocument(appInfoDeferred)
// this must happen before LaF loading
val checkGraphicsJob = checkGraphics()
val pathDeferred = async(CoroutineName("config path computing") + Dispatchers.IO) {
Pair(canonicalPath(PathManager.getConfigPath()), canonicalPath(PathManager.getSystemPath()))
}
val isHeadless = AppMode.isHeadless()
val configImportNeededDeferred = async {
val (configPath, _) = pathDeferred.await()
!isHeadless && (!Files.exists(configPath) || Files.exists(configPath.resolve(ConfigImportHelper.CUSTOM_MARKER_FILE_NAME)))
}
// this should happen before UI initialization - if we're not going to show UI (in case another IDE instance is already running),
// we shouldn't initialize AWT toolkit in order to avoid unnecessary focus stealing and space switching on macOS.
val lockSystemDirsJob = lockSystemDirs(configImportNeededDeferred = configImportNeededDeferred,
pathDeferred = pathDeferred,
args = args,
mainScope = mainScope)
val consoleLoggerJob = configureJavaUtilLogging()
launch {
LoadingState.setStrictMode()
LoadingState.errorHandler = BiConsumer { message, throwable ->
logger<LoadingState>().error(message, throwable)
}
}
val preloadLafClassesJob = preloadLafClasses()
// LookAndFeel type is not specified to avoid class loading
val initUiDeferred = async {
checkGraphicsJob?.join()
lockSystemDirsJob.join()
initUi(preloadLafClassesJob, busyThread = busyThread)
}
val zipFilePoolDeferred = async(Dispatchers.IO) {
// ZipFilePoolImpl uses Guava for Striped lock - load in parallel
val result = ZipFilePoolImpl()
ZipFilePool.POOL = result
result
}
val schedulePluginDescriptorLoading = launch {
ComponentManagerImpl.mainScope = mainScope
// plugins cannot be loaded when a config import is needed, because plugins may be added after importing
Java11Shim.INSTANCE = Java11ShimImpl()
if (!configImportNeededDeferred.await()) {
PluginManagerCore.scheduleDescriptorLoading(mainScope, zipFilePoolDeferred)
}
}
// system dirs checking must happen after locking system dirs
val checkSystemDirJob = checkSystemDirs(lockSystemDirsJob, pathDeferred)
// log initialization must happen only after locking the system directory
val logDeferred = setupLogger(consoleLoggerJob, checkSystemDirJob)
val showEuaIfNeededJob = showEuaIfNeeded(euaDocumentDeferred, initUiDeferred)
val patchHtmlStyleJob = if (isHeadless) null else patchHtmlStyle(initUiDeferred)
shellEnvDeferred = async(CoroutineName("environment loading") + Dispatchers.IO) {
EnvironmentUtil.loadEnvironment()
}
if (!isHeadless) {
showSplashIfNeeded(initUiDeferred, showEuaIfNeededJob, appInfoDeferred, args)
// must happen after initUi
updateFrameClassAndWindowIconAndPreloadSystemFonts(initUiDeferred)
}
if (java.lang.Boolean.getBoolean("idea.enable.coroutine.dump")) {
launch(CoroutineName("coroutine debug probes init")) {
enableCoroutineDump()
}
}
loadSystemLibsAndLogInfoAndInitMacApp(logDeferred, appInfoDeferred, initUiDeferred, args)
val telemetryInitJob = launch {
appInfoDeferred.join()
runActivity("opentelemetry configuration") {
TraceManager.init()
}
}
val isInternal = java.lang.Boolean.getBoolean(ApplicationManagerEx.IS_INTERNAL_PROPERTY)
if (isInternal) {
launch(CoroutineName("assert on missed keys enabling")) {
BundleBase.assertOnMissedKeys(true)
}
}
launch(CoroutineName("disposer debug mode enabling if needed")) {
if (isInternal || Disposer.isDebugDisposerOn()) {
Disposer.setDebugMode(true)
}
}
val appDeferred = async {
// logging must be initialized before creating application
val log = logDeferred.await()
if (!configImportNeededDeferred.await()) {
runPreAppClass(log, args)
}
// we must wait for UI before creating application and before AppStarter.start (some appStarter dialogs) - EDT thread is required
runActivity("prepare ui waiting") {
initUiDeferred.join()
}
val app = runActivity("app instantiation") {
ApplicationImpl(isInternal, AppMode.isHeadless(), AppMode.isCommandLine(), EDT.getEventDispatchThread())
}
runActivity("telemetry waiting") {
telemetryInitJob.join()
}
app to patchHtmlStyleJob
}
mainScope.launch {
// required for appStarter.prepareStart
appInfoDeferred.join()
val appStarter = runActivity("main class loading waiting") {
appStarterDeferred.await()
}
appStarter.prepareStart(args)
// before config importing and license check
showEuaIfNeededJob.join()
if (!isHeadless && configImportNeededDeferred.await()) {
initUiDeferred.join()
val imported = importConfig(
args = args,
log = logDeferred.await(),
appStarter = appStarterDeferred.await(),
agreementShown = showEuaIfNeededJob,
)
if (imported) {
PluginManagerCore.scheduleDescriptorLoading(mainScope, zipFilePoolDeferred)
}
}
// must be scheduled before starting app
schedulePluginDescriptorLoading.join()
// with main dispatcher (appStarter uses runBlocking - block main thread and not some coroutine thread)
appStarter.start(args, appDeferred)
}
}
private fun CoroutineScope.loadSystemLibsAndLogInfoAndInitMacApp(logDeferred: Deferred<Logger>,
appInfoDeferred: Deferred<ApplicationInfoEx>,
initUiDeferred: Job,
args: List<String>) {
launch {
// this must happen after locking system dirs
val log = logDeferred.await()
runActivity("system libs setup") {
setupSystemLibraries()
}
withContext(Dispatchers.IO) {
runActivity("system libs loading") {
JnaLoader.load(log)
if (SystemInfoRt.isWindows) {
IdeaWin32.isAvailable()
}
}
}
val appInfo = appInfoDeferred.await()
launch(CoroutineName("essential IDE info logging") + Dispatchers.IO) {
logEssentialInfoAboutIde(log, appInfo, args)
}
if (!AppMode.isHeadless() && SystemInfoRt.isMac) {
// JNA and Swing are used - invoke only after both are loaded
initUiDeferred.join()
launch(CoroutineName("mac app init")) {
MacOSApplicationProvider.initApplication(log)
}
}
}
}
private fun CoroutineScope.showSplashIfNeeded(initUiDeferred: Deferred<Any>,
showEuaIfNeededJob: Deferred<Boolean>,
appInfoDeferred: Deferred<ApplicationInfoEx>,
args: List<String>) {
if (AppMode.isLightEdit()) {
return
}
launch {
// A splash instance must not be created before base LaF is created.
// It is important on Linux, where GTK LaF must be initialized (to properly set up the scale factor).
// https://youtrack.jetbrains.com/issue/IDEA-286544
initUiDeferred.join()
// before showEuaIfNeededJob to prepare during showing EUA dialog
val runnable = prepareSplash(appInfoDeferred, args) ?: return@launch
showEuaIfNeededJob.join()
withContext(SwingDispatcher) {
runnable.run()
}
}
}
private fun CoroutineScope.patchHtmlStyle(initUiJob: Deferred<Any>): Job {
return launch {
initUiJob.join()
withContext(SwingDispatcher) {
runActivity("html style patching") {
// patch html styles
val uiDefaults = UIManager.getDefaults()
// create a separate copy for each case
val globalStyleSheet = GlobalStyleSheetHolder.getGlobalStyleSheet()
uiDefaults.put("javax.swing.JLabel.userStyleSheet", globalStyleSheet)
uiDefaults.put("HTMLEditorKit.jbStyleSheet", globalStyleSheet)
runActivity("global styleSheet updating") {
GlobalStyleSheetHolder.updateGlobalSwingStyleSheet()
}
}
}
}
}
private suspend fun prepareSplash(appInfoDeferred: Deferred<ApplicationInfoEx>, args: List<String>): Runnable? {
var showSplash = false
for (arg in args) {
if (CommandLineArgs.SPLASH == arg) {
showSplash = true
break
}
else if (CommandLineArgs.NO_SPLASH == arg) {
return null
}
}
// products may specify `splash` VM property; `nosplash` is deprecated and should be checked first
if (!showSplash &&
(java.lang.Boolean.getBoolean(CommandLineArgs.NO_SPLASH) || !java.lang.Boolean.getBoolean(CommandLineArgs.SPLASH))) {
return null
}
val appInfo = appInfoDeferred.await()
return runActivity("splash preparation") {
SplashManager.scheduleShow(appInfo)
}
}
private fun CoroutineScope.checkGraphics(): Job? {
if (AppMode.isHeadless()) {
return null
}
return launch {
runActivity("graphics environment checking") {
if (GraphicsEnvironment.isHeadless()) {
StartupErrorReporter.showMessage(BootstrapBundle.message("bootstrap.error.title.startup.error"),
BootstrapBundle.message("bootstrap.error.message.no.graphics.environment"), true)
exitProcess(AppExitCodes.NO_GRAPHICS)
}
}
}
}
/** Called via reflection from [WindowsCommandLineProcessor.processWindowsLauncherCommandLine]. */
@Suppress("unused")
fun processWindowsLauncherCommandLine(currentDirectory: String, args: Array<String>): Int {
return EXTERNAL_LISTENER.apply(currentDirectory, args)
}
internal val isUsingSeparateWriteThread: Boolean
get() = java.lang.Boolean.getBoolean(USE_SEPARATE_WRITE_THREAD_PROPERTY)
// called by the app after startup
@Synchronized
fun addExternalInstanceListener(processor: Function<List<String>, Future<CliResult>>) {
if (socketLock == null) {
throw AssertionError("Not initialized yet")
}
socketLock!!.setCommandProcessor(processor)
}
// used externally by TeamCity plugin (as TeamCity cannot use modern API to support old IDE versions)
@Synchronized
@Deprecated("")
fun getServer(): BuiltInServer? = socketLock?.getServer()
@Synchronized
fun getServerFutureAsync(): Deferred<BuiltInServer?> = socketLock?.serverFuture ?: CompletableDeferred(value = null)
// On startup 2 dialogs must be shown:
// - gdpr agreement
// - eu(l)a
private fun CoroutineScope.loadEuaDocument(appInfoDeferred: Deferred<ApplicationInfoEx>): Deferred<Any?>? {
if (AppMode.isHeadless()) {
return null
}
return async(CoroutineName("eua document") + Dispatchers.IO) {
val vendorAsProperty = System.getProperty("idea.vendor.name", "")
if (if (vendorAsProperty.isEmpty()) !appInfoDeferred.await().isVendorJetBrains else vendorAsProperty != "JetBrains") {
null
}
else {
val document = runActivity("eua getting") { EndUserAgreement.getLatestDocument() }
if (runActivity("eua is accepted checking") { document.isAccepted }) null else document
}
}
}
private fun runPreAppClass(log: Logger, args: List<String>) {
val classBeforeAppProperty = System.getProperty(IDEA_CLASS_BEFORE_APPLICATION_PROPERTY) ?: return
runActivity("pre app class running") {
try {
val aClass = AppStarter::class.java.classLoader.loadClass(classBeforeAppProperty)
MethodHandles.lookup()
.findStatic(aClass, "invoke", MethodType.methodType(Void.TYPE, Array<String>::class.java))
.invoke(args.toTypedArray())
}
catch (e: Exception) {
log.error("Failed pre-app class init for class $classBeforeAppProperty", e)
}
}
}
private suspend fun importConfig(args: List<String>,
log: Logger,
appStarter: AppStarter,
agreementShown: Deferred<Boolean>): Boolean {
var activity = StartUpMeasurer.startActivity("screen reader checking")
try {
withContext(SwingDispatcher) { AccessibilityUtils.enableScreenReaderSupportIfNecessary() }
}
catch (e: Throwable) {
log.error(e)
}
activity = activity.endAndStart("config importing")
appStarter.beforeImportConfigs()
val newConfigDir = PathManager.getConfigDir()
val veryFirstStartOnThisComputer = agreementShown.await()
withContext(SwingDispatcher) {
if (UIManager.getLookAndFeel() !is IntelliJLaf) {
UIManager.setLookAndFeel(IntelliJLaf())
}
ConfigImportHelper.importConfigsTo(veryFirstStartOnThisComputer, newConfigDir, args, log)
}
appStarter.importFinished(newConfigDir)
activity.end()
return !PlatformUtils.isRider() || ConfigImportHelper.isConfigImported()
}
// return type (LookAndFeel) is not specified to avoid class loading
private suspend fun initUi(preloadLafClassesJob: Job, busyThread: Thread): Any {
// calls `sun.util.logging.PlatformLogger#getLogger` - it takes enormous time (up to 500 ms)
// only non-logging tasks can be executed before `setupLogger`
val activityQueue = StartUpMeasurer.startActivity("base LaF preparation")
val isHeadless = AppMode.isHeadless()
coroutineScope {
launch {
checkHiDPISettings()
blockATKWrapper()
@Suppress("SpellCheckingInspection")
System.setProperty("sun.awt.noerasebackground", "true")
activityQueue.startChild("awt toolkit creating").let { activity ->
Toolkit.getDefaultToolkit()
activity.end()
}
}
// IdeaLaF uses AllIcons - icon manager must be activated
if (!isHeadless) {
launch(CoroutineName("icon manager activation")) {
IconManager.activate(CoreIconManager())
}
}
launch(CoroutineName("IdeEventQueue class preloading")) {
val classLoader = AppStarter::class.java.classLoader
// preload class not in EDT
Class.forName(IdeEventQueue::class.java.name, true, classLoader)
}
}
preloadLafClassesJob.join()
// SwingDispatcher must be used after Toolkit init
val baseLaF = withContext(SwingDispatcher) {
activityQueue.end()
// we don't need Idea LaF to show splash, but we do need some base LaF to compute system font data (see below for what)
var activity = StartUpMeasurer.startActivity("base LaF creation")
val baseLaF = DarculaLaf.createBaseLaF()
activity = activity.endAndStart("base LaF initialization")
// LaF is useless until initialized (`getDefaults` "should only be invoked ... after `initialize` has been invoked.")
baseLaF.initialize()
// to compute the system scale factor on non-macOS (JRE HiDPI is not enabled), we need to know system font data,
// and to compute system font data we need to know `Label.font` UI default (that's why we compute base LaF first)
activity = activity.endAndStart("system font data initialization")
if (!isHeadless) {
JBUIScale.getSystemFontData {
runActivity("base LaF defaults getting") { baseLaF.defaults }
}
activity = activity.endAndStart("scale initialization")
JBUIScale.scale(1f)
}
StartUpMeasurer.setCurrentState(LoadingState.BASE_LAF_INITIALIZED)
activity = activity.endAndStart("awt thread busy notification")
/*
Make EDT to always persist while the main thread is alive. Otherwise, it's possible to have EDT being
terminated by [AWTAutoShutdown], which will break a `ReadMostlyRWLock` instance.
[AWTAutoShutdown.notifyThreadBusy(Thread)] will put the main thread into the thread map,
and thus will effectively disable auto shutdown behavior for this application.
*/
AWTAutoShutdown.getInstance().notifyThreadBusy(busyThread)
activity.end()
patchSystem(isHeadless)
baseLaF
}
if (isUsingSeparateWriteThread) {
runActivity("Write Intent Lock UI class transformer loading") {
WriteIntentLockInstrumenter.instrument()
}
}
DarculaLaf.setPreInitializedBaseLaf(baseLaF)
return baseLaF
}
private fun CoroutineScope.preloadLafClasses(): Job {
val classLoader = AppStarter::class.java.classLoader
return launch(CoroutineName("LaF class preloading")) {
// preload class not in EDT
Class.forName(DarculaLaf::class.java.name, true, classLoader)
Class.forName(IdeaLaf::class.java.name, true, classLoader)
Class.forName(JBUIScale::class.java.name, true, classLoader)
}
}
/*
* The method should be called before `Toolkit#initAssistiveTechnologies`, which is called from `Toolkit#getDefaultToolkit`.
*/
private fun blockATKWrapper() {
// the registry must not be used here, because this method is called before application loading
@Suppress("SpellCheckingInspection")
if (!SystemInfoRt.isLinux || !java.lang.Boolean.parseBoolean(System.getProperty("linux.jdk.accessibility.atkwrapper.block", "true"))) {
return
}
val activity = StartUpMeasurer.startActivity("atk wrapper blocking")
if (ScreenReader.isEnabled(ScreenReader.ATK_WRAPPER)) {
// Replacing `AtkWrapper` with a dummy `Object`. It'll be instantiated & garbage collected right away, a NOP.
System.setProperty("javax.accessibility.assistive_technologies", "java.lang.Object")
Logger.getInstance(StartupUiUtil::class.java).info(ScreenReader.ATK_WRAPPER + " is blocked, see IDEA-149219")
}
activity.end()
}
private fun CoroutineScope.showEuaIfNeeded(euaDocumentDeferred: Deferred<Any?>?, initUiJob: Deferred<Any>): Deferred<Boolean> {
return async {
if (euaDocumentDeferred == null) {
return@async true
}
val euaDocument = euaDocumentDeferred.await()
initUiJob.join()
runActivity("eua showing") {
val document = euaDocument as EndUserAgreement.Document?
withContext(Dispatchers.IO) {
EndUserAgreement.updateCachedContentToLatestBundledVersion()
}
if (document != null) {
withContext(SwingDispatcher) {
UIManager.setLookAndFeel(IntelliJLaf())
showEndUserAndDataSharingAgreements(document)
}
true
}
else if (ConsentOptions.needToShowUsageStatsConsent()) {
withContext(SwingDispatcher) {
UIManager.setLookAndFeel(IntelliJLaf())
showDataSharingAgreement()
}
false
}
else {
false
}
}
}
}
/** Do not use it. For start-up code only. */
internal object SwingDispatcher : CoroutineDispatcher() {
override fun isDispatchNeeded(context: CoroutineContext): Boolean = !EventQueue.isDispatchThread()
override fun dispatch(context: CoroutineContext, block: Runnable): Unit = EventQueue.invokeLater(block)
override fun toString() = "Swing"
}
private fun CoroutineScope.updateFrameClassAndWindowIconAndPreloadSystemFonts(initUiDeferred: Job) {
launch {
initUiDeferred.join()
launch(CoroutineName("system fonts loading") + Dispatchers.IO) {
// forces loading of all system fonts; the following statement alone might not do it (see JBR-1825)
Font("N0nEx1st5ntF0nt", Font.PLAIN, 1).family
// caches available font family names for the default locale to speed up editor reopening (see `ComplementaryFontsRegistry`)
GraphicsEnvironment.getLocalGraphicsEnvironment().availableFontFamilyNames
}
if (!SystemInfoRt.isWindows && !SystemInfoRt.isMac) {
launch(CoroutineName("frame class updating")) {
try {
val toolkit = Toolkit.getDefaultToolkit()
val aClass = toolkit.javaClass
if (aClass.name == "sun.awt.X11.XToolkit") {
val field = ReflectionUtil.findAssignableField(aClass, null, "awtAppClassName")
field.set(toolkit, AppUIUtil.getFrameClass())
}
}
catch (ignore: Exception) {
}
}
}
launch(CoroutineName("update window icon")) {
// `updateWindowIcon` should be called after `initUiJob`, because it uses computed system font data for scale context
if (!AppUIUtil.isWindowIconAlreadyExternallySet() && !PluginManagerCore.isRunningFromSources()) {
// most of the time is consumed by loading SVG and can be done in parallel
AppUIUtil.updateWindowIcon(JOptionPane.getRootFrame())
}
}
// preload cursors used by drag-n-drop AWT subsystem, run on SwingDispatcher to avoid a possible deadlock - see RIDER-80810
launch(CoroutineName("DnD setup") + SwingDispatcher) {
DragSource.getDefaultDragSource()
}
launch(SwingDispatcher) {
WeakFocusStackManager.getInstance()
}
}
}
private fun CoroutineScope.configureJavaUtilLogging(): Job {
return launch(CoroutineName("console logger configuration")) {
val rootLogger = java.util.logging.Logger.getLogger("")
if (rootLogger.handlers.isEmpty()) {
rootLogger.level = Level.WARNING
val consoleHandler = ConsoleHandler()
consoleHandler.level = Level.WARNING
rootLogger.addHandler(consoleHandler)
}
}
}
@VisibleForTesting
fun checkHiDPISettings() {
if (!java.lang.Boolean.parseBoolean(System.getProperty("hidpi", "true"))) {
// suppress JRE-HiDPI mode
System.setProperty("sun.java2d.uiScale.enabled", "false")
}
}
private fun CoroutineScope.checkSystemDirs(lockSystemDirJob: Job, pathDeferred: Deferred<Pair<Path, Path>>): Job {
return launch {
lockSystemDirJob.join()
val (configPath, systemPath) = pathDeferred.await()
runActivity("system dirs checking") {
if (!doCheckSystemDirs(configPath, systemPath)) {
exitProcess(AppExitCodes.DIR_CHECK_FAILED)
}
}
}
}
private suspend fun doCheckSystemDirs(configPath: Path, systemPath: Path): Boolean {
if (configPath == systemPath) {
StartupErrorReporter.showMessage(BootstrapBundle.message("bootstrap.error.title.invalid.config.or.system.path"),
BootstrapBundle.message("bootstrap.error.message.config.0.and.system.1.paths.must.be.different",
PathManager.PROPERTY_CONFIG_PATH,
PathManager.PROPERTY_SYSTEM_PATH), true)
return false
}
return withContext(Dispatchers.IO) {
val logPath = Path.of(PathManager.getLogPath()).normalize()
val tempPath = Path.of(PathManager.getTempPath()).normalize()
listOf(
async {
checkDirectory(directory = configPath,
kind = "Config",
property = PathManager.PROPERTY_CONFIG_PATH,
checkWrite = true,
checkLock = true,
checkExec = false)
},
async {
checkDirectory(directory = systemPath,
kind = "System",
property = PathManager.PROPERTY_SYSTEM_PATH,
checkWrite = true,
checkLock = true,
checkExec = false)
},
async {
checkDirectory(directory = logPath,
kind = "Log",
property = PathManager.PROPERTY_LOG_PATH,
checkWrite = !logPath.startsWith(systemPath),
checkLock = false,
checkExec = false)
},
async {
checkDirectory(directory = tempPath,
kind = "Temp",
property = PathManager.PROPERTY_SYSTEM_PATH,
checkWrite = !tempPath.startsWith(systemPath),
checkLock = false,
checkExec = SystemInfoRt.isUnix && !SystemInfoRt.isMac)
}
).awaitAll().all { it }
}
}
private fun checkDirectory(directory: Path,
kind: String,
property: String,
checkWrite: Boolean,
checkLock: Boolean,
checkExec: Boolean): Boolean {
var problem = "bootstrap.error.message.check.ide.directory.problem.cannot.create.the.directory"
var reason = "bootstrap.error.message.check.ide.directory.possible.reason.path.is.incorrect"
var tempFile: Path? = null
try {
if (!Files.isDirectory(directory)) {
problem = "bootstrap.error.message.check.ide.directory.problem.cannot.create.the.directory"
reason = "bootstrap.error.message.check.ide.directory.possible.reason.directory.is.read.only.or.the.user.lacks.necessary.permissions"
Files.createDirectories(directory)
}
if (checkWrite || checkLock || checkExec) {
problem = "bootstrap.error.message.check.ide.directory.problem.the.ide.cannot.create.a.temporary.file.in.the.directory"
reason = "bootstrap.error.message.check.ide.directory.possible.reason.directory.is.read.only.or.the.user.lacks.necessary.permissions"
tempFile = directory.resolve("ij${Random().nextInt(Int.MAX_VALUE)}.tmp")
Files.writeString(tempFile, "#!/bin/sh\nexit 0", StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE)
if (checkLock) {
problem = "bootstrap.error.message.check.ide.directory.problem.the.ide.cannot.create.a.lock.in.directory"
reason = "bootstrap.error.message.check.ide.directory.possible.reason.the.directory.is.located.on.a.network.disk"
FileChannel.open(tempFile, EnumSet.of(StandardOpenOption.WRITE)).use { channel ->
channel.tryLock().use { lock ->
if (lock == null) {
throw IOException("File is locked")
}
}
}
}
else if (checkExec) {
problem = "bootstrap.error.message.check.ide.directory.problem.the.ide.cannot.execute.test.script"
reason = "bootstrap.error.message.check.ide.directory.possible.reason.partition.is.mounted.with.no.exec.option"
Files.getFileAttributeView(tempFile!!, PosixFileAttributeView::class.java)
.setPermissions(EnumSet.of(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE, PosixFilePermission.OWNER_EXECUTE))
val exitCode = ProcessBuilder(tempFile.toAbsolutePath().toString()).start().waitFor()
if (exitCode != 0) {
throw IOException("Unexpected exit value: $exitCode")
}
}
}
return true
}
catch (e: Exception) {
val title = BootstrapBundle.message("bootstrap.error.title.invalid.ide.directory.type.0.directory", kind)
val advice = if (SystemInfoRt.isMac && PathManager.getSystemPath().contains(MAGIC_MAC_PATH)) {
BootstrapBundle.message("bootstrap.error.message.invalid.ide.directory.trans.located.macos.directory.advice")
}
else {
BootstrapBundle.message("bootstrap.error.message.invalid.ide.directory.ensure.the.modified.property.0.is.correct", property)
}
val message = BootstrapBundle.message(
"bootstrap.error.message.invalid.ide.directory.problem.0.possible.reason.1.advice.2.location.3.exception.class.4.exception.message.5",
BootstrapBundle.message(problem), BootstrapBundle.message(reason), advice, directory, e.javaClass.name, e.message)
StartupErrorReporter.showMessage(title, message, true)
return false
}
finally {
if (tempFile != null) {
try {
Files.deleteIfExists(tempFile)
}
catch (ignored: Exception) {
}
}
}
}
// returns `true` when `checkConfig` is requested and config import is needed
private fun CoroutineScope.lockSystemDirs(configImportNeededDeferred: Job,
pathDeferred: Deferred<Pair<Path, Path>>,
args: List<String>,
mainScope: CoroutineScope): Job {
if (socketLock != null) {
throw AssertionError("Already initialized")
}
return launch(Dispatchers.IO) {
val (configPath, systemPath) = pathDeferred.await()
configImportNeededDeferred.join()
runActivity("system dirs locking") {
// this check must be performed before system directories are locked
socketLock = SocketLock(configPath, systemPath)
val status = socketLock!!.lockAndTryActivate(args = args, mainScope = mainScope)
when (status.first) {
ActivationStatus.NO_INSTANCE -> {
ShutDownTracker.getInstance().registerShutdownTask {
synchronized(AppStarter::class.java) {
socketLock!!.dispose()
socketLock = null
}
}
}
ActivationStatus.ACTIVATED -> {
val result = status.second!!
println(result.message ?: "Already running")
exitProcess(result.exitCode)
}
ActivationStatus.CANNOT_ACTIVATE -> {
val message = BootstrapBundle.message("bootstrap.error.message.only.one.instance.of.0.can.be.run.at.a.time",
ApplicationNamesInfo.getInstance().productName)
StartupErrorReporter.showMessage(BootstrapBundle.message("bootstrap.error.title.too.many.instances"), message, true)
exitProcess(AppExitCodes.INSTANCE_CHECK_FAILED)
}
}
}
}
}
private fun CoroutineScope.setupLogger(consoleLoggerJob: Job, checkSystemDirJob: Job): Deferred<Logger> {
return async {
consoleLoggerJob.join()
checkSystemDirJob.join()
runActivity("file logger configuration") {
try {
Logger.setFactory(LoggerFactory())
}
catch (e: Exception) {
e.printStackTrace()
}
val log = Logger.getInstance(AppStarter::class.java)
log.info(IDE_STARTED)
ShutDownTracker.getInstance().registerShutdownTask { log.info(IDE_SHUTDOWN) }
if (java.lang.Boolean.parseBoolean(System.getProperty("intellij.log.stdout", "true"))) {
System.setOut(PrintStreamLogger("STDOUT", System.out))
System.setErr(PrintStreamLogger("STDERR", System.err))
}
log
}
}
}
@Suppress("SpellCheckingInspection")
private fun setupSystemLibraries() {
val ideTempPath = PathManager.getTempPath()
if (System.getProperty("jna.tmpdir") == null) {
// to avoid collisions and work around no-exec /tmp
System.setProperty("jna.tmpdir", ideTempPath)
}
if (System.getProperty("jna.nosys") == null) {
// prefer bundled JNA dispatcher lib
System.setProperty("jna.nosys", "true")
}
if (SystemInfoRt.isWindows && System.getProperty("winp.folder.preferred") == null) {
System.setProperty("winp.folder.preferred", ideTempPath)
}
if (System.getProperty("pty4j.tmpdir") == null) {
System.setProperty("pty4j.tmpdir", ideTempPath)
}
if (System.getProperty("pty4j.preferred.native.folder") == null) {
System.setProperty("pty4j.preferred.native.folder", Path.of(PathManager.getLibPath(), "pty4j-native").toAbsolutePath().toString())
}
}
private fun logEssentialInfoAboutIde(log: Logger, appInfo: ApplicationInfo, args: List<String>) {
val buildDate = SimpleDateFormat("dd MMM yyyy HH:mm", Locale.US).format(appInfo.buildDate.time)
log.info("IDE: ${ApplicationNamesInfo.getInstance().fullProductName} (build #${appInfo.build.asString()}, $buildDate)")
log.info("OS: ${SystemInfoRt.OS_NAME} (${SystemInfoRt.OS_VERSION}, ${System.getProperty("os.arch")})")
log.info("JRE: ${System.getProperty("java.runtime.version", "-")} (${System.getProperty("java.vendor", "-")})")
log.info("JVM: ${System.getProperty("java.vm.version", "-")} (${System.getProperty("java.vm.name", "-")})")
log.info("PID: ${ProcessHandle.current().pid()}")
if (SystemInfoRt.isXWindow) {
log.info("desktop: ${System.getenv("XDG_CURRENT_DESKTOP")}")
}
ManagementFactory.getRuntimeMXBean().inputArguments?.let {
log.info("JVM options: $it")
}
log.info("args: ${args.joinToString(separator = " ")}")
log.info("library path: ${System.getProperty("java.library.path")}")
log.info("boot library path: ${System.getProperty("sun.boot.library.path")}")
logEnvVar(log, "_JAVA_OPTIONS")
logEnvVar(log, "JDK_JAVA_OPTIONS")
logEnvVar(log, "JAVA_TOOL_OPTIONS")
log.info(
"""locale=${Locale.getDefault()} JNU=${System.getProperty("sun.jnu.encoding")} file.encoding=${System.getProperty("file.encoding")}
${PathManager.PROPERTY_CONFIG_PATH}=${logPath(PathManager.getConfigPath())}
${PathManager.PROPERTY_SYSTEM_PATH}=${logPath(PathManager.getSystemPath())}
${PathManager.PROPERTY_PLUGINS_PATH}=${logPath(PathManager.getPluginsPath())}
${PathManager.PROPERTY_LOG_PATH}=${logPath(PathManager.getLogPath())}"""
)
val cores = Runtime.getRuntime().availableProcessors()
val pool = ForkJoinPool.commonPool()
log.info("CPU cores: $cores; ForkJoinPool.commonPool: $pool; factory: ${pool.factory}")
}
private fun logEnvVar(log: Logger, variable: String) {
val value = System.getenv(variable)
if (value != null) {
log.info("$variable=$value")
}
}
private fun logPath(path: String): String {
try {
val configured = Path.of(path)
val real = configured.toRealPath()
if (configured != real) {
return "$path -> $real"
}
}
catch (ignored: IOException) {
}
catch (ignored: InvalidPathException) {
}
return path
}
fun runStartupWizard() {
val stepsDialogName = ApplicationInfoImpl.getShadowInstance().welcomeWizardDialog ?: return
try {
val dialogClass = Class.forName(stepsDialogName)
val ctor = dialogClass.getConstructor(AppStarter::class.java)
(ctor.newInstance(null) as CommonCustomizeIDEWizardDialog).showIfNeeded()
}
catch (e: Throwable) {
StartupErrorReporter.showMessage(BootstrapBundle.message("bootstrap.error.title.configuration.wizard.failed"), e)
return
}
PluginManagerCore.invalidatePlugins()
PluginManagerCore.scheduleDescriptorLoading(ComponentManagerImpl.mainScope!!)
}
// the method must be called on EDT
private fun patchSystem(isHeadless: Boolean) {
var activity = StartUpMeasurer.startActivity("event queue replacing")
// replace system event queue
IdeEventQueue.getInstance()
if (!isHeadless && "true" == System.getProperty("idea.check.swing.threading")) {
activity = activity.endAndStart("repaint manager set")
RepaintManager.setCurrentManager(AssertiveRepaintManager())
}
// do not crash AWT on exceptions
AWTExceptionHandler.register()
activity.end()
}
fun canonicalPath(path: String): Path {
return try {
// `toRealPath` doesn't restore a canonical file name on case-insensitive UNIX filesystems
Path.of(File(path).canonicalPath)
}
catch (ignore: IOException) {
val file = Path.of(path)
try {
file.toAbsolutePath()
}
catch (ignored: IOError) {
}
file.normalize()
}
}
interface AppStarter {
fun prepareStart(args: List<String>) {}
/* called from IDE init thread */
suspend fun start(args: List<String>, appDeferred: Deferred<Any>)
/* called from IDE init thread */
fun beforeImportConfigs() {}
/* called from IDE init thread */
fun importFinished(newConfigDir: Path) {}
}
class Java11ShimImpl : Java11Shim() {
override fun <K : Any, V : Any> copyOf(map: Map<out K, V>): Map<K, V> = java.util.Map.copyOf(map)
override fun <E : Any> copyOf(collection: Set<E>): Set<E> = java.util.Set.copyOf(collection)
override fun <E : Any> copyOfCollection(collection: Collection<E>): List<E> = java.util.List.copyOf(collection)
}
| apache-2.0 | e0a38377ca6880b9f02f83adefbad586 | 37.731028 | 157 | 0.695305 | 4.677921 | false | true | false | false |
kelsos/mbrc | app/src/main/kotlin/com/kelsos/mbrc/repository/data/LocalGenreDataSource.kt | 1 | 2695 | package com.kelsos.mbrc.repository.data
import com.kelsos.mbrc.data.db.RemoteDatabase
import com.kelsos.mbrc.data.library.Genre
import com.kelsos.mbrc.data.library.Genre_Table
import com.kelsos.mbrc.di.modules.AppDispatchers
import com.kelsos.mbrc.extensions.escapeLike
import com.raizlabs.android.dbflow.kotlinextensions.database
import com.raizlabs.android.dbflow.kotlinextensions.delete
import com.raizlabs.android.dbflow.kotlinextensions.from
import com.raizlabs.android.dbflow.kotlinextensions.modelAdapter
import com.raizlabs.android.dbflow.kotlinextensions.select
import com.raizlabs.android.dbflow.kotlinextensions.where
import com.raizlabs.android.dbflow.list.FlowCursorList
import com.raizlabs.android.dbflow.sql.language.OperatorGroup.clause
import com.raizlabs.android.dbflow.sql.language.SQLite
import com.raizlabs.android.dbflow.structure.database.transaction.FastStoreModelTransaction
import kotlinx.coroutines.withContext
import javax.inject.Inject
class LocalGenreDataSource
@Inject constructor(private val dispatchers: AppDispatchers) : LocalDataSource<Genre> {
override suspend fun deleteAll() = withContext(dispatchers.db) {
delete(Genre::class).execute()
}
override suspend fun saveAll(list: List<Genre>) = withContext(dispatchers.db) {
val adapter = modelAdapter<Genre>()
val transaction = FastStoreModelTransaction.insertBuilder(adapter)
.addAll(list)
.build()
database<RemoteDatabase>().executeTransaction(transaction)
}
override suspend fun loadAllCursor(): FlowCursorList<Genre> = withContext(dispatchers.db) {
val query = (select from Genre::class).orderBy(Genre_Table.genre, true)
return@withContext FlowCursorList.Builder(Genre::class.java).modelQueriable(query).build()
}
override suspend fun search(term: String): FlowCursorList<Genre> = withContext(dispatchers.db) {
val query = (select from Genre::class where Genre_Table.genre.like("%${term.escapeLike()}%"))
.orderBy(Genre_Table.genre, true)
return@withContext FlowCursorList.Builder(Genre::class.java).modelQueriable(query).build()
}
override suspend fun isEmpty(): Boolean = withContext(dispatchers.db) {
return@withContext SQLite.selectCountOf().from(Genre::class.java).longValue() == 0L
}
override suspend fun count(): Long = withContext(dispatchers.db) {
return@withContext SQLite.selectCountOf().from(Genre::class.java).longValue()
}
override suspend fun removePreviousEntries(epoch: Long) {
withContext(dispatchers.io) {
SQLite.delete()
.from(Genre::class.java)
.where(clause(Genre_Table.date_added.lessThan(epoch)).or(Genre_Table.date_added.isNull))
.execute()
}
}
}
| gpl-3.0 | b43dfadbe95e25ba204fb0084a753d9d | 40.461538 | 98 | 0.775139 | 4.237421 | false | false | false | false |
micolous/metrodroid | src/commonMain/kotlin/au/id/micolous/metrodroid/transit/nextfare/record/NextfareConfigRecord.kt | 1 | 2111 | /*
* NextfareConfigRecord.kt
*
* Copyright 2016-2019 Michael Farrell <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package au.id.micolous.metrodroid.transit.nextfare.record
import au.id.micolous.metrodroid.multi.Log
import au.id.micolous.metrodroid.multi.Parcelable
import au.id.micolous.metrodroid.multi.Parcelize
import au.id.micolous.metrodroid.time.MetroTimeZone
import au.id.micolous.metrodroid.time.Timestamp
import au.id.micolous.metrodroid.util.ImmutableByteArray
import au.id.micolous.metrodroid.util.hexString
/**
* Represents a configuration record on Nextfare MFC.
* https://github.com/micolous/metrodroid/wiki/Cubic-Nextfare-MFC
*/
@Parcelize
class NextfareConfigRecord (val ticketType: Int,
val expiry: Timestamp): NextfareRecord, Parcelable {
companion object {
private const val TAG = "NextfareConfigRecord"
fun recordFromBytes(input: ImmutableByteArray, timeZone: MetroTimeZone): NextfareConfigRecord {
//if (input[0] != 0x01) throw new AssertionError();
// Expiry date
val record = NextfareConfigRecord(
expiry = NextfareRecord.unpackDate(input, 4, timeZone),
// Treat ticket type as little-endian
ticketType = input.byteArrayToIntReversed(8, 2)
)
Log.d(TAG, "Ticket type = ${record.ticketType.hexString}, expires ${record.expiry}")
return record
}
}
}
| gpl-3.0 | e20d07b80623182dbab7330ab39d98c0 | 35.396552 | 103 | 0.703932 | 4.379668 | false | true | false | false |
milosmns/Timecrypt | Android/app/src/main/java/co/timecrypt/android/activities/ReadMessageActivity.kt | 1 | 6013 | package co.timecrypt.android.activities
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.support.v4.text.util.LinkifyCompat
import android.support.v7.app.AppCompatActivity
import android.text.util.Linkify
import android.util.Log
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.Toast
import co.timecrypt.android.R
import co.timecrypt.android.v2.api.TimecryptController
import kotlinx.android.synthetic.main.activity_read_message.*
/**
* An activity that handles displaying (and unlocking) for one Timecrypt message.
*/
class ReadMessageActivity : AppCompatActivity(), View.OnClickListener {
@Suppress("PrivatePropertyName")
private val TAG = ReadMessageActivity::class.simpleName!!
companion object {
const val KEY_MESSAGE_ID = "MESSAGE_ID"
}
private var controller: TimecryptController? = null
private var messageId: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// check preconditions, must find a message ID
val extras = intent.extras
val uri = intent.data
if (extras == null && uri == null) {
Log.e(TAG, "No URL data provided")
finish()
return
}
messageId = extras?.getString(KEY_MESSAGE_ID, null) ?: parseMessageUrl(uri)
if (messageId == null) {
Log.e(TAG, "No message ID provided")
finish()
return
}
setContentView(R.layout.activity_read_message)
// activity is ready, create business logic components
controller = TimecryptController(TimecryptController.Companion.DEFAULT_API_URL)
controller?.lockCheck(this, messageId!!, lockCheckListener)
// setup initial Views
progressOverlay.visibility = View.VISIBLE
listOf(buttonCancel, buttonCreateNew, buttonUnlock).forEach {
it.setOnClickListener(this)
}
}
/**
* Tries to find the message ID by parsing the given [Uri].
*
* @param url An Intent [Uri] that represents the message link
*/
private fun parseMessageUrl(url: Uri?): String? {
try {
if (url == null) return null
val query = url.query ?: return null
query.split("&").forEach {
val param = it.split("=")
if (param[0].trim() == "c" || param[0].trim() == "id") {
return param[1].trim()
}
}
return null
} catch (t: Throwable) {
return null
}
}
override fun onClick(view: View) {
when (view.id) {
buttonCancel.id -> {
stopReading()
finish()
}
buttonCreateNew.id -> {
startActivity(Intent(this, CreateMessageActivity::class.java))
finish()
}
buttonUnlock.id -> {
currentFocus?.let {
val inputManager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
inputManager.hideSoftInputFromWindow(it.windowToken, 0)
}
progressOverlay.visibility = View.VISIBLE
readMessagePassword.visibility = View.GONE
buttonUnlock.visibility = View.GONE
controller?.read(this, messageId!!, readMessagePassword.text.toString(), readCompleteListener)
readMessagePassword.setText("")
readInformation.text = ""
}
}
}
/**
* Used to listen for changes from the [TimecryptController.lockCheck] operation.
*/
private val lockCheckListener = object : TimecryptController.LockCheckListener {
override fun onLockCheckCompleted(locked: Boolean) {
if (locked) {
progressOverlay.visibility = View.GONE
readMessagePassword.visibility = View.VISIBLE
buttonUnlock.visibility = View.VISIBLE
readInformation.text = getString(R.string.read_locked)
} else {
controller?.read(this@ReadMessageActivity, messageId!!, null, readCompleteListener)
}
}
override fun onLockCheckFailed(message: String) {
Log.e(TAG, message)
progressOverlay.visibility = View.GONE
Toast.makeText(this@ReadMessageActivity, message, Toast.LENGTH_LONG).show()
finish()
}
}
/**
* Used to listen for changes from the [TimecryptController.read] operation.
*/
private val readCompleteListener = object : TimecryptController.ReadCompleteListener {
override fun onReadComplete(text: String, title: String?, destructDate: String, views: Int) {
progressOverlay.visibility = View.GONE
buttonCreateNew.visibility = View.VISIBLE
val viewsCount = resources.getQuantityString(R.plurals.views_left, views, views)
readInformation.text = getString(R.string.read_info, viewsCount, destructDate)
// append title on top if present
var finalText = text
title?.let {
finalText = "- $it -\n\n$finalText"
}
readMessageText.text = finalText
LinkifyCompat.addLinks(readMessageText, Linkify.WEB_URLS)
readMessageText.visibility = View.VISIBLE
}
override fun onReadFailed(message: String) {
Log.e(TAG, message)
progressOverlay.visibility = View.GONE
Toast.makeText(this@ReadMessageActivity, message, Toast.LENGTH_LONG).show()
finish()
}
}
private fun stopReading() {
controller?.stopAll()
progressOverlay.visibility = View.GONE
}
override fun onStop() {
super.onStop()
stopReading()
}
}
| apache-2.0 | a6b54ffac3494973f92aa59377a72c69 | 33.959302 | 110 | 0.609513 | 4.908571 | false | false | false | false |
abertschi/ad-free | app/src/main/java/ch/abertschi/adfree/detector/NotificationActionDetector.kt | 1 | 828 | /*
* Ad Free
* Copyright (c) 2017 by abertschi, www.abertschi.ch
* See the file "LICENSE" for the full license governing this code.
*/
package ch.abertschi.adfree.detector
/**
* Created by abertschi on 17.04.17.
*
* Detector which checks for number of control buttons
*/
class NotificationActionDetector : AbstractSpStatusBarDetector() {
override fun canHandle(payload: AdPayload): Boolean =
super.canHandle(payload) && payload?.statusbarNotification?.notification?.actions != null
override fun flagAsAdvertisement(payload: AdPayload): Boolean =
payload.statusbarNotification.notification.actions.size <= 3
override fun getMeta(): AdDetectorMeta = AdDetectorMeta(
"Notification actions", "spotify generic inspection of notification actions",
category = "Spotify"
)
} | apache-2.0 | 483772262f673810ab74b46d9ab33d2c | 29.703704 | 97 | 0.725845 | 4.5 | false | false | false | false |
google/android-fhir | datacapture/src/test/java/com/google/android/fhir/datacapture/views/QuestionnaireItemCheckBoxGroupViewHolderFactoryTest.kt | 1 | 15274 | /*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.fhir.datacapture.views
import android.view.ViewGroup
import android.widget.CheckBox
import android.widget.FrameLayout
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.view.children
import com.google.android.fhir.datacapture.ChoiceOrientationTypes
import com.google.android.fhir.datacapture.EXTENSION_CHOICE_ORIENTATION_URL
import com.google.android.fhir.datacapture.EXTENSION_OPTION_EXCLUSIVE_URL
import com.google.android.fhir.datacapture.R
import com.google.android.fhir.datacapture.validation.Invalid
import com.google.android.fhir.datacapture.validation.NotValidated
import com.google.common.truth.Truth.assertThat
import org.hl7.fhir.r4.model.BooleanType
import org.hl7.fhir.r4.model.CodeType
import org.hl7.fhir.r4.model.Coding
import org.hl7.fhir.r4.model.Extension
import org.hl7.fhir.r4.model.Questionnaire
import org.hl7.fhir.r4.model.QuestionnaireResponse
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
@RunWith(RobolectricTestRunner::class)
class QuestionnaireItemCheckBoxGroupViewHolderFactoryTest {
private val parent =
FrameLayout(
RuntimeEnvironment.getApplication().apply { setTheme(R.style.Theme_Material3_DayNight) }
)
private val viewHolder = QuestionnaireItemCheckBoxGroupViewHolderFactory.create(parent)
@Test
fun bind_shouldSetQuestionHeader() {
viewHolder.bind(
QuestionnaireItemViewItem(
Questionnaire.QuestionnaireItemComponent().apply {
repeats = true
text = "Question?"
},
QuestionnaireResponse.QuestionnaireResponseItemComponent(),
validationResult = NotValidated,
answersChangedCallback = { _, _, _ -> },
)
)
assertThat(viewHolder.itemView.findViewById<TextView>(R.id.question).text.toString())
.isEqualTo("Question?")
}
@Test
fun bind_vertical_shouldCreateCheckBoxButtons() {
val questionnaire =
Questionnaire.QuestionnaireItemComponent().apply {
repeats = true
addExtension(
EXTENSION_CHOICE_ORIENTATION_URL,
CodeType(ChoiceOrientationTypes.VERTICAL.extensionCode)
)
addAnswerOption(
Questionnaire.QuestionnaireItemAnswerOptionComponent().apply {
value = Coding().apply { display = "Coding 1" }
}
)
addAnswerOption(
Questionnaire.QuestionnaireItemAnswerOptionComponent().apply {
value = Coding().apply { display = "Coding 2" }
}
)
}
viewHolder.bind(
QuestionnaireItemViewItem(
questionnaire,
QuestionnaireResponse.QuestionnaireResponseItemComponent(),
validationResult = NotValidated,
answersChangedCallback = { _, _, _ -> },
)
)
val checkBoxGroup = viewHolder.itemView.findViewById<ConstraintLayout>(R.id.checkbox_group)
val children = checkBoxGroup.children.asIterable().filterIsInstance<CheckBox>()
children.forEachIndexed { index, view ->
assertThat(view.text).isEqualTo(questionnaire.answerOption[index].valueCoding.display)
assertThat(view.layoutParams.width).isEqualTo(ViewGroup.LayoutParams.MATCH_PARENT)
}
}
@Test
fun bind_horizontal_shouldCreateCheckBoxButtons() {
val questionnaire =
Questionnaire.QuestionnaireItemComponent().apply {
repeats = true
addExtension(
EXTENSION_CHOICE_ORIENTATION_URL,
CodeType(ChoiceOrientationTypes.HORIZONTAL.extensionCode)
)
addAnswerOption(
Questionnaire.QuestionnaireItemAnswerOptionComponent().apply {
value = Coding().apply { display = "Coding 1" }
}
)
addAnswerOption(
Questionnaire.QuestionnaireItemAnswerOptionComponent().apply {
value = Coding().apply { display = "Coding 2" }
}
)
}
viewHolder.bind(
QuestionnaireItemViewItem(
questionnaire,
QuestionnaireResponse.QuestionnaireResponseItemComponent(),
validationResult = NotValidated,
answersChangedCallback = { _, _, _ -> },
)
)
val checkBoxGroup = viewHolder.itemView.findViewById<ConstraintLayout>(R.id.checkbox_group)
val children = checkBoxGroup.children.asIterable().filterIsInstance<CheckBox>()
children.forEachIndexed { index, view ->
assertThat(view.text).isEqualTo(questionnaire.answerOption[index].valueCoding.display)
assertThat(view.layoutParams.width).isEqualTo(ViewGroup.LayoutParams.WRAP_CONTENT)
}
}
@Test
fun bind_noAnswer_shouldLeaveCheckButtonsUnchecked() {
viewHolder.bind(
QuestionnaireItemViewItem(
Questionnaire.QuestionnaireItemComponent().apply {
repeats = true
addAnswerOption(
Questionnaire.QuestionnaireItemAnswerOptionComponent().apply {
value = Coding().apply { display = "Coding 1" }
}
)
},
QuestionnaireResponse.QuestionnaireResponseItemComponent(),
validationResult = NotValidated,
answersChangedCallback = { _, _, _ -> },
)
)
val checkBoxGroup = viewHolder.itemView.findViewById<ConstraintLayout>(R.id.checkbox_group)
val checkBox = checkBoxGroup.getChildAt(1) as CheckBox
assertThat(checkBox.isChecked).isFalse()
}
@Test
fun bind_answer_shouldSetCheckBoxButton() {
viewHolder.bind(
QuestionnaireItemViewItem(
Questionnaire.QuestionnaireItemComponent().apply {
repeats = true
addAnswerOption(
Questionnaire.QuestionnaireItemAnswerOptionComponent().apply {
value =
Coding().apply {
code = "code 1"
display = "Coding 1"
}
}
)
},
QuestionnaireResponse.QuestionnaireResponseItemComponent().apply {
addAnswer(
QuestionnaireResponse.QuestionnaireResponseItemAnswerComponent().apply {
value =
Coding().apply {
code = "code 1"
display = "Coding 1"
}
}
)
},
validationResult = NotValidated,
answersChangedCallback = { _, _, _ -> },
)
)
val checkBoxGroup = viewHolder.itemView.findViewById<ConstraintLayout>(R.id.checkbox_group)
val checkBox = checkBoxGroup.getChildAt(1) as CheckBox
assertThat(checkBox.isChecked).isTrue()
}
@Test
fun click_shouldAddQuestionnaireResponseItemAnswer() {
var answerHolder: List<QuestionnaireResponse.QuestionnaireResponseItemAnswerComponent>? = null
val questionnaireItemViewItem =
QuestionnaireItemViewItem(
Questionnaire.QuestionnaireItemComponent().apply {
repeats = true
addAnswerOption(
Questionnaire.QuestionnaireItemAnswerOptionComponent().apply {
value =
Coding().apply {
code = "code 1"
display = "Coding 1"
}
}
)
},
QuestionnaireResponse.QuestionnaireResponseItemComponent(),
validationResult = NotValidated,
answersChangedCallback = { _, _, answers -> answerHolder = answers },
)
viewHolder.bind(questionnaireItemViewItem)
val checkBoxGroup = viewHolder.itemView.findViewById<ConstraintLayout>(R.id.checkbox_group)
val checkBox = checkBoxGroup.getChildAt(1) as CheckBox
checkBox.performClick()
assertThat(answerHolder!!.single().valueCoding.display).isEqualTo("Coding 1")
}
@Test
fun optionExclusiveAnswerOption_click_deselectsOtherAnswerOptions() {
var answerHolder: List<QuestionnaireResponse.QuestionnaireResponseItemAnswerComponent>? = null
val questionnaireItemViewItem =
QuestionnaireItemViewItem(
Questionnaire.QuestionnaireItemComponent().apply {
repeats = true
addAnswerOption(
Questionnaire.QuestionnaireItemAnswerOptionComponent().apply {
value =
Coding().apply {
code = "code-1"
display = "display-1"
}
extension = listOf(Extension(EXTENSION_OPTION_EXCLUSIVE_URL, BooleanType(true)))
}
)
addAnswerOption(
Questionnaire.QuestionnaireItemAnswerOptionComponent().apply {
value =
Coding().apply {
code = "code-2"
display = "display-2"
}
}
)
},
QuestionnaireResponse.QuestionnaireResponseItemComponent(),
validationResult = NotValidated,
answersChangedCallback = { _, _, answers -> answerHolder = answers },
)
viewHolder.bind(questionnaireItemViewItem)
val checkBoxGroup = viewHolder.itemView.findViewById<ConstraintLayout>(R.id.checkbox_group)
(checkBoxGroup.getChildAt(2) as CheckBox).performClick()
(checkBoxGroup.getChildAt(1) as CheckBox).performClick()
assertThat(answerHolder!!.single().valueCoding.display).isEqualTo("display-1")
}
@Test
fun answerOption_click_deselectsOptionExclusiveAnswerOption() {
var answerHolder: List<QuestionnaireResponse.QuestionnaireResponseItemAnswerComponent>? = null
val questionnaireItemViewItem =
QuestionnaireItemViewItem(
Questionnaire.QuestionnaireItemComponent().apply {
repeats = true
addAnswerOption(
Questionnaire.QuestionnaireItemAnswerOptionComponent().apply {
value =
Coding().apply {
code = "code-1"
display = "display-1"
}
extension = listOf(Extension(EXTENSION_OPTION_EXCLUSIVE_URL, BooleanType(true)))
}
)
addAnswerOption(
Questionnaire.QuestionnaireItemAnswerOptionComponent().apply {
value =
Coding().apply {
code = "code-2"
display = "display-2"
}
}
)
},
QuestionnaireResponse.QuestionnaireResponseItemComponent(),
validationResult = NotValidated,
answersChangedCallback = { _, _, answers -> answerHolder = answers },
)
viewHolder.bind(questionnaireItemViewItem)
val checkBoxGroup = viewHolder.itemView.findViewById<ConstraintLayout>(R.id.checkbox_group)
(checkBoxGroup.getChildAt(1) as CheckBox).performClick()
(checkBoxGroup.getChildAt(2) as CheckBox).performClick()
assertThat(answerHolder!!.single().valueCoding.display).isEqualTo("display-2")
}
@Test
fun click_shouldRemoveQuestionnaireResponseItemAnswer() {
var answerHolder: List<QuestionnaireResponse.QuestionnaireResponseItemAnswerComponent>? = null
val questionnaireItemViewItem =
QuestionnaireItemViewItem(
Questionnaire.QuestionnaireItemComponent().apply {
repeats = true
answerValueSet = "http://coding-value-set-url"
},
QuestionnaireResponse.QuestionnaireResponseItemComponent().apply {
addAnswer(
QuestionnaireResponse.QuestionnaireResponseItemAnswerComponent().apply {
value =
Coding().apply {
code = "code 1"
display = "Coding 1"
}
}
)
},
resolveAnswerValueSet = {
if (it == "http://coding-value-set-url") {
listOf(
Questionnaire.QuestionnaireItemAnswerOptionComponent().apply {
value =
Coding().apply {
code = "code 1"
display = "Coding 1"
}
}
)
} else {
emptyList()
}
},
validationResult = NotValidated,
answersChangedCallback = { _, _, answers -> answerHolder = answers },
)
viewHolder.bind(questionnaireItemViewItem)
val checkBoxGroup = viewHolder.itemView.findViewById<ConstraintLayout>(R.id.checkbox_group)
val checkBox = checkBoxGroup.getChildAt(1) as CheckBox
checkBox.performClick()
assertThat(answerHolder).isEmpty()
}
@Test
fun displayValidationResult_error_shouldShowErrorMessage() {
viewHolder.bind(
QuestionnaireItemViewItem(
Questionnaire.QuestionnaireItemComponent().apply {
repeats = true
required = true
},
QuestionnaireResponse.QuestionnaireResponseItemComponent(),
validationResult = Invalid(listOf("Missing answer for required field.")),
answersChangedCallback = { _, _, _ -> },
)
)
assertThat(viewHolder.itemView.findViewById<TextView>(R.id.error_text_at_header).text)
.isEqualTo("Missing answer for required field.")
}
@Test
fun displayValidationResult_noError_shouldShowNoErrorMessage() {
viewHolder.bind(
QuestionnaireItemViewItem(
Questionnaire.QuestionnaireItemComponent().apply {
repeats = true
required = true
addAnswerOption(
Questionnaire.QuestionnaireItemAnswerOptionComponent().apply {
value = Coding().apply { display = "display" }
}
)
},
QuestionnaireResponse.QuestionnaireResponseItemComponent().apply {
addAnswer(
QuestionnaireResponse.QuestionnaireResponseItemAnswerComponent().apply {
value = Coding().apply { display = "display" }
}
)
},
validationResult = NotValidated,
answersChangedCallback = { _, _, _ -> },
)
)
assertThat(viewHolder.itemView.findViewById<TextView>(R.id.error_text_at_header).text.isEmpty())
.isTrue()
}
@Test
fun bind_readOnly_shouldDisableView() {
viewHolder.bind(
QuestionnaireItemViewItem(
Questionnaire.QuestionnaireItemComponent().apply {
repeats = true
readOnly = true
addAnswerOption(
Questionnaire.QuestionnaireItemAnswerOptionComponent().apply {
value = Coding().apply { display = "Coding 1" }
}
)
},
QuestionnaireResponse.QuestionnaireResponseItemComponent(),
validationResult = NotValidated,
answersChangedCallback = { _, _, _ -> },
)
)
assertThat(
(viewHolder.itemView.findViewById<ConstraintLayout>(R.id.checkbox_group).getChildAt(1)
as CheckBox)
.isEnabled
)
.isFalse()
}
}
| apache-2.0 | 39aac102755fd224a9be50c7741a0c79 | 34.52093 | 100 | 0.645411 | 5.709907 | false | false | false | false |
cqjjjzr/Gensokyo | src/main/kotlin/charlie/gensokyo/LayoutExtension.kt | 1 | 2073 | @file:JvmName("Gensokyo")
@file:JvmMultifileClass
package charlie.gensokyo
import java.awt.BorderLayout
import java.awt.Container
import java.awt.GridLayout
import java.awt.IllegalComponentStateException
import javax.swing.JComponent
import javax.swing.JDialog
import javax.swing.JFrame
import javax.swing.JLabel
inline val Container.abstractLayout: Unit get() { layout = null }
inline val JFrame.abstractLayout: Unit get() = contentPane.abstractLayout
inline val JDialog.abstractLayout: Unit get() = contentPane.abstractLayout
inline val Container.borderLayout: Unit get() { layout = BorderLayout() }
inline val JFrame.borderLayout: Unit get() = contentPane.abstractLayout
inline val JDialog.borderLayout: Unit get() = contentPane.abstractLayout
inline fun Container.gridLayout(block: GridLayoutHelper.() -> Unit) {
layout = BorderLayout()
removeAll()
add(GridLayoutHelper().apply(block))
}
inline fun JFrame.gridLayout(block: GridLayoutHelper.() -> Unit) = contentPane.gridLayout(block)
inline fun JDialog.gridLayout(block: GridLayoutHelper.() -> Unit) = contentPane.gridLayout(block)
class GridLayoutHelper: JComponent() {
private var rowIndex = -1
private var columnIndex = 0
private var firstRowInserted = false
fun row(block: GridLayoutHelper.() -> Unit) {
if (firstRowInserted)
(layout as GridLayout).rows++
columnIndex = 0
rowIndex++
block()
firstRowInserted = true
}
val gap: Unit get() {
JLabel().apply {
[email protected](this)
add(this)
}
}
internal fun ensureColumns() {
if (++columnIndex > (layout as GridLayout).columns) {
if (!firstRowInserted)
(layout as GridLayout).columns++
else throw IllegalComponentStateException("columns of row under the first row is more than the first row. add gaps. ")
}
}
private fun beforeAddingComponent(comp: JComponent) = ensureColumns()
init {
layout = GridLayout()
}
} | apache-2.0 | a53775e7a4fc5e3aface2363d47d9f2e | 30.424242 | 130 | 0.698987 | 4.690045 | false | false | false | false |
pureal-code/pureal-os | traits/src/net/pureal/traits/math/RealPrimitive.kt | 1 | 647 | package net.pureal.traits.math
import java.math.BigInteger
public trait RealPrimitive : Real {
val value: InternalReal
override fun toString() = "real(\"${value.toMathematicalString()}\")"
override fun approximate() = value
override fun equals(other: Any?): Boolean {
return when (other) {
is RealPrimitive -> value == other.value
is Real -> false
is Number -> value == other
else -> false
}
}
override fun minus(): Real = real(-value)
override val isPositive: Boolean get() = value > 0
override val isZero: Boolean get() = value equals 0
}
| bsd-3-clause | 1484dc6105b6fbd7dfb8c33fff7aa7de | 22.107143 | 73 | 0.607419 | 4.556338 | false | false | false | false |
dbrant/apps-android-wikipedia | app/src/main/java/org/wikipedia/descriptions/DescriptionEditReviewView.kt | 1 | 3386 | package org.wikipedia.descriptions
import android.content.Context
import android.net.Uri
import android.util.AttributeSet
import android.view.LayoutInflater
import androidx.constraintlayout.widget.ConstraintLayout
import org.wikipedia.databinding.ViewDescriptionEditReviewBinding
import org.wikipedia.descriptions.DescriptionEditLicenseView.Companion.ARG_NOTICE_ARTICLE_DESCRIPTION
import org.wikipedia.descriptions.DescriptionEditLicenseView.Companion.ARG_NOTICE_DEFAULT
import org.wikipedia.descriptions.DescriptionEditLicenseView.Companion.ARG_NOTICE_IMAGE_CAPTION
import org.wikipedia.suggestededits.PageSummaryForEdit
import org.wikipedia.util.L10nUtil
import org.wikipedia.util.StringUtil
import org.wikipedia.views.ViewUtil
class DescriptionEditReviewView constructor(context: Context, attrs: AttributeSet? = null) : ConstraintLayout(context, attrs) {
private val binding = ViewDescriptionEditReviewBinding.inflate(LayoutInflater.from(context), this)
val isShowing: Boolean
get() = visibility == VISIBLE
fun show() {
visibility = VISIBLE
}
fun hide() {
visibility = GONE
}
fun setSummary(summaryForEdit: PageSummaryForEdit, description: String, captionReview: Boolean) {
L10nUtil.setConditionalLayoutDirection(this, summaryForEdit.lang)
if (captionReview) {
setGalleryReviewView(summaryForEdit, description)
binding.licenseView.buildLicenseNotice(ARG_NOTICE_IMAGE_CAPTION)
} else {
setDescriptionReviewView(summaryForEdit, description)
binding.licenseView.buildLicenseNotice(if (summaryForEdit.description.isNullOrEmpty()) ARG_NOTICE_ARTICLE_DESCRIPTION else ARG_NOTICE_DEFAULT,
summaryForEdit.lang)
}
}
private fun setDescriptionReviewView(summaryForEdit: PageSummaryForEdit, description: String) {
binding.galleryContainer.visibility = GONE
binding.articleTitle.text = StringUtil.fromHtml(summaryForEdit.displayTitle)
binding.articleSubtitle.text = description
binding.articleExtract.text = StringUtil.fromHtml(summaryForEdit.extractHtml)
if (summaryForEdit.thumbnailUrl.isNullOrBlank()) {
binding.articleImage.visibility = GONE
binding.articleExtract.maxLines = ARTICLE_EXTRACT_MAX_LINE_WITHOUT_IMAGE
} else {
binding.articleImage.visibility = VISIBLE
binding.articleImage.loadImage(Uri.parse(summaryForEdit.getPreferredSizeThumbnailUrl()))
binding.articleExtract.maxLines = ARTICLE_EXTRACT_MAX_LINE_WITH_IMAGE
}
}
private fun setGalleryReviewView(summaryForEdit: PageSummaryForEdit, description: String) {
binding.articleContainer.visibility = GONE
binding.indicatorDivider.visibility = GONE
binding.galleryDescriptionText.text = StringUtil.fromHtml(description)
if (summaryForEdit.thumbnailUrl.isNullOrBlank()) {
binding.galleryImage.visibility = GONE
} else {
binding.galleryImage.visibility = VISIBLE
ViewUtil.loadImage(binding.galleryImage, summaryForEdit.getPreferredSizeThumbnailUrl())
}
binding.licenseView.darkLicenseView()
}
companion object {
const val ARTICLE_EXTRACT_MAX_LINE_WITH_IMAGE = 5
const val ARTICLE_EXTRACT_MAX_LINE_WITHOUT_IMAGE = 15
}
}
| apache-2.0 | 1f950a955a6ef6ff78c3ba854937c33c | 43.552632 | 154 | 0.743946 | 5.130303 | false | false | false | false |
google/ground-android | ground/src/main/java/com/google/android/ground/persistence/remote/firestore/schema/SurveyConverter.kt | 1 | 2503 | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.ground.persistence.remote.firestore.schema
import com.google.android.ground.model.Survey
import com.google.android.ground.model.basemap.BaseMap
import com.google.android.ground.model.job.Job
import com.google.android.ground.persistence.remote.DataStoreException
import com.google.android.ground.persistence.remote.firestore.schema.JobConverter.toJob
import com.google.common.collect.ImmutableList
import com.google.common.collect.ImmutableMap
import com.google.firebase.firestore.DocumentSnapshot
import java.net.MalformedURLException
import java.net.URL
import timber.log.Timber
/** Converts between Firestore documents and [Survey] instances. */
internal object SurveyConverter {
@Throws(DataStoreException::class)
fun toSurvey(doc: DocumentSnapshot): Survey {
val pd =
DataStoreException.checkNotNull(doc.toObject(SurveyDocument::class.java), "surveyDocument")
val jobMap = ImmutableMap.builder<String, Job>()
if (pd.jobs != null) {
pd.jobs.forEach { (id: String, obj: JobNestedObject) -> jobMap.put(id, toJob(id, obj)) }
}
val baseMaps = ImmutableList.builder<BaseMap>()
if (pd.baseMaps != null) {
convertOfflineBaseMapSources(pd, baseMaps)
}
return Survey(
doc.id,
pd.title.orEmpty(),
pd.description.orEmpty(),
jobMap.build(),
baseMaps.build(),
ImmutableMap.copyOf(pd.acl)
)
}
private fun convertOfflineBaseMapSources(
pd: SurveyDocument,
builder: ImmutableList.Builder<BaseMap>
) {
for ((url) in pd.baseMaps!!) {
if (url == null) {
Timber.d("Skipping base map source in survey with missing URL")
continue
}
try {
builder.add(BaseMap(URL(url), BaseMap.typeFromExtension(url)))
} catch (e: MalformedURLException) {
Timber.d("Skipping base map source in survey with malformed URL")
}
}
}
}
| apache-2.0 | a23f42e333a19917924fa594630a5292 | 32.373333 | 97 | 0.717938 | 4.030596 | false | false | false | false |
mdanielwork/intellij-community | plugins/stream-debugger/src/com/intellij/debugger/streams/lib/impl/StreamExLibrarySupportProvider.kt | 6 | 1577 | // Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.debugger.streams.lib.impl
import com.intellij.debugger.streams.lib.LibrarySupport
import com.intellij.debugger.streams.lib.LibrarySupportProvider
import com.intellij.debugger.streams.psi.impl.JavaChainTransformerImpl
import com.intellij.debugger.streams.psi.impl.JavaStreamChainBuilder
import com.intellij.debugger.streams.psi.impl.PackageChainDetector
import com.intellij.debugger.streams.trace.TraceExpressionBuilder
import com.intellij.debugger.streams.trace.dsl.impl.DslImpl
import com.intellij.debugger.streams.trace.dsl.impl.java.JavaStatementFactory
import com.intellij.debugger.streams.trace.impl.JavaTraceExpressionBuilder
import com.intellij.debugger.streams.wrapper.StreamChainBuilder
import com.intellij.openapi.project.Project
/**
* @author Vitaliy.Bibaev
*/
class StreamExLibrarySupportProvider : LibrarySupportProvider {
private val librarySupport = StreamExLibrarySupport()
private val javaDsl = DslImpl(JavaStatementFactory())
override fun getLanguageId(): String = "JAVA"
override fun getLibrarySupport(): LibrarySupport = librarySupport
override fun getExpressionBuilder(project: Project): TraceExpressionBuilder =
JavaTraceExpressionBuilder(project, librarySupport.createHandlerFactory(javaDsl), javaDsl)
override fun getChainBuilder(): StreamChainBuilder =
JavaStreamChainBuilder(JavaChainTransformerImpl(), PackageChainDetector.forJavaStreams("one.util.streamex"))
} | apache-2.0 | db60094eb28f3a2b1a73cb4732d19b66 | 49.903226 | 140 | 0.837032 | 4.571014 | false | false | false | false |
ngthtung2805/dalatlaptop | app/src/main/java/com/tungnui/abccomputer/activity/CartListActivity.kt | 1 | 4255 | package com.tungnui.abccomputer.activity
import android.app.Activity
import android.content.Context
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.MenuItem
import android.view.View
import com.travijuu.numberpicker.library.Enums.ActionEnum
import com.tungnui.abccomputer.R
import com.tungnui.abccomputer.adapter.CartListAdapter
import com.tungnui.abccomputer.adapter.CartRecyclerInterface
import com.tungnui.abccomputer.data.sqlite.*
import com.tungnui.abccomputer.listeners.OnSingleClickListener
import com.tungnui.abccomputer.models.Cart
import com.tungnui.abccomputer.utils.ActivityUtils
import com.tungnui.abccomputer.utils.formatPrice
import kotlinx.android.synthetic.main.activity_cart_list.*
import com.tungnui.abccomputer.R.id.cartList
import com.tungnui.abccomputer.R.string.quantity
import android.R.attr.name
import com.tungnui.abccomputer.SettingsMy
import com.tungnui.abccomputer.data.constant.AppConstants
import com.tungnui.abccomputer.models.LineItem
class CartListActivity : BaseActivity() {
// initialize variables
private var mContext: Context? = null
private var mActivity: Activity? = null
private var cartListAdapter: CartListAdapter? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
initVariables()
initView()
loadCartData()
initLister()
}
private fun initVariables() {
mContext = applicationContext
mActivity = this@CartListActivity
}
private fun initView() {
setContentView(R.layout.activity_cart_list)
initToolbar()
enableBackButton()
setToolbarTitle(getString(R.string.cart_list))
initLoader()
// init RecyclerView
rvCartList?.setHasFixedSize(true)
rvCartList?.layoutManager = LinearLayoutManager(this)
cartListAdapter = CartListAdapter(object :CartRecyclerInterface{
override fun onQuantityChange(cart: Cart, quantity: Int, actionEnum: ActionEnum) {
cart.id?.let{applicationContext.DbHelper.updateCartQuantity(it,quantity)}
loadCartData()
}
override fun onProductDelete(cart: Cart) {
cart.id?.let { applicationContext.DbHelper.deleteCart(it) }
loadCartData()
}
override fun onProductSelect(productId: Int) {
/* if (activity is MainActivity)
(activity as MainActivity).onProductSelected(productId)*/
}
})
rvCartList?.adapter = cartListAdapter
}
private fun initLister() {
btnOrder.setOnClickListener(object : OnSingleClickListener() {
override fun onSingleClick(v: View) {
val user = SettingsMy.getActiveUser()
if(user == null)
ActivityUtils.instance.invokeLoginAndOrder(this@CartListActivity)
else
ActivityUtils.instance.invokeOrderShipping(this@CartListActivity)
}
})
}
private fun setCartVisibility(visible: Boolean) {
if (visible) {
cart_empty.visibility = View.GONE
cart_recycler.visibility = View.VISIBLE
cart_footer.visibility = View.VISIBLE
} else {
cartListAdapter?.cleatCart()
cart_empty.visibility = View.VISIBLE
cart_recycler.visibility = View.GONE
cart_footer.visibility = View.GONE
}
}
private fun loadCartData() {
val carts = applicationContext.DbHelper.getAllCart();
if (carts.isEmpty()) {
setCartVisibility(false)
} else {
cartListAdapter?.refreshItems(carts);
cart_footer_price.text =applicationContext.DbHelper.totalCart().toString().formatPrice();
setCartVisibility(true)
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> {
finish()
return true
}
else -> return super.onOptionsItemSelected(item)
}
}
}
| mit | eaf34d927e945e52a26ac4c0d693be4b | 32.503937 | 101 | 0.662515 | 4.907728 | false | false | false | false |
ilya-g/intellij-markdown | src/org/intellij/markdown/parser/markerblocks/impl/ListItemMarkerBlock.kt | 2 | 1957 | package org.intellij.markdown.parser.markerblocks.impl
import org.intellij.markdown.IElementType
import org.intellij.markdown.MarkdownElementTypes
import org.intellij.markdown.parser.LookaheadText
import org.intellij.markdown.parser.ProductionHolder
import org.intellij.markdown.parser.constraints.MarkdownConstraints
import org.intellij.markdown.parser.markerblocks.MarkdownParserUtil
import org.intellij.markdown.parser.markerblocks.MarkerBlock
import org.intellij.markdown.parser.markerblocks.MarkerBlockImpl
public class ListItemMarkerBlock(myConstraints: MarkdownConstraints,
marker: ProductionHolder.Marker) : MarkerBlockImpl(myConstraints, marker) {
override fun allowsSubBlocks(): Boolean = true
override fun isInterestingOffset(pos: LookaheadText.Position): Boolean = pos.char == '\n'
override fun getDefaultAction(): MarkerBlock.ClosingAction {
return MarkerBlock.ClosingAction.DONE
}
override fun calcNextInterestingOffset(pos: LookaheadText.Position): Int {
return pos.nextLineOffset ?: -1
}
override fun doProcessToken(pos: LookaheadText.Position, currentConstraints: MarkdownConstraints): MarkerBlock.ProcessingResult {
assert(pos.char == '\n')
val eolN = MarkdownParserUtil.calcNumberOfConsequentEols(pos, constraints)
if (eolN >= 3) {
return MarkerBlock.ProcessingResult.DEFAULT
}
val nonemptyPos = MarkdownParserUtil.getFirstNonWhitespaceLinePos(pos, eolN)
?: return MarkerBlock.ProcessingResult.DEFAULT
val nextLineConstraints = MarkdownConstraints.fromBase(nonemptyPos, constraints)
if (!nextLineConstraints.extendsPrev(constraints)) {
return MarkerBlock.ProcessingResult.DEFAULT
}
return MarkerBlock.ProcessingResult.CANCEL
}
override fun getDefaultNodeType(): IElementType {
return MarkdownElementTypes.LIST_ITEM
}
}
| apache-2.0 | ad8957e3f8c399c5c6bb0eda54ecbbc0 | 40.638298 | 133 | 0.751661 | 5.361644 | false | false | false | false |
TheMrMilchmann/lwjgl3 | modules/lwjgl/openxr/src/templates/kotlin/openxr/XRBinding.kt | 4 | 6962 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package openxr
import org.lwjgl.generator.*
import openxr.XRFunctionType.*
import java.io.*
private val NativeClass.capName: String
get() = if (templateName.startsWith(prefix)) {
if (prefix == "XR")
"OpenXR${templateName.substring(2)}"
else
templateName
} else {
"${prefixTemplate}_$templateName"
}
private enum class XRFunctionType {
PROC,
GLOBAL,
INSTANCE
}
private val Func.type: XRFunctionType
get() = when {
name == "xrGetInstanceProcAddr" -> PROC // dlsym/GetProcAddress
parameters[0].nativeType !is WrappedPointerType -> GLOBAL // xrGetInstanceProcAddr: XR_NULL_HANDLE
else -> INSTANCE // xrGetDeviceProcAddr: instance handle
}
private val Func.isInstanceFunction get() = type === INSTANCE && !has<Macro>()
private val EXTENSION_NAME = "[A-Za-z0-9_]+".toRegex()
private fun getFunctionDependencyExpression(func: Func) = func.get<DependsOn>()
.reference
.let { expression ->
if (EXTENSION_NAME.matches(expression))
"ext.contains(\"$expression\")"
else
expression
}
private fun PrintWriter.printCheckFunctions(
nativeClass: NativeClass,
commands: Map<String, Int>,
dependencies: LinkedHashMap<String, Int>,
filter: (Func) -> Boolean
) {
print("checkFunctions(provider, caps, new int[] {")
nativeClass.printPointers(this, { func ->
val index = commands[func.name]
if (func.has<DependsOn>()) {
"flag${dependencies[getFunctionDependencyExpression(func)]} + $index"
} else{
index.toString()
}
}, filter)
print("},")
nativeClass.printPointers(this, { "\"${it.name}\"" }, filter)
print(")")
}
val XR_BINDING_INSTANCE = Generator.register(object : APIBinding(Module.OPENXR, "XRCapabilities", APICapabilities.PARAM_CAPABILITIES) {
override fun shouldCheckFunctionAddress(function: Func): Boolean = function.nativeClass.templateName != "XR10"
override fun generateFunctionAddress(writer: PrintWriter, function: Func) {
writer.print("$t${t}long $FUNCTION_ADDRESS = ")
writer.println(if (function.has<Capabilities>())
"${function.get<Capabilities>().expression}.${function.name};"
else
"${function.getParams { it.nativeType is WrappedPointerType }.first().name}.getCapabilities().${function.name};"
)
}
private fun PrintWriter.checkExtensionFunctions(nativeClass: NativeClass, commands: Map<String, Int>) {
val capName = nativeClass.capName
print("""
private static boolean check_${nativeClass.templateName}(FunctionProvider provider, long[] caps, java.util.Set<String> ext) {
if (!ext.contains("$capName")) {
return false;
}""")
val dependencies = nativeClass.functions
.filter { it.isInstanceFunction && it.has<DependsOn>() }
.map(::getFunctionDependencyExpression)
.foldIndexed(LinkedHashMap<String, Int>()) { index, map, expression ->
if (!map.containsKey(expression)) {
map[expression] = index
}
map
}
if (dependencies.isNotEmpty()) {
println()
dependencies.forEach { (expression, index) ->
print("\n$t${t}int flag$index = $expression ? 0 : Integer.MIN_VALUE;")
}
}
print("\n\n$t${t}return ")
printCheckFunctions(nativeClass, commands, dependencies) { it.isInstanceFunction }
println(" || reportMissing(\"XR\", \"$capName\");")
println("$t}")
}
init {
javaImport("static org.lwjgl.system.Checks.*")
documentation = "Defines the capabilities of an OpenXR {@code XrInstance}."
}
override fun PrintWriter.generateJava() {
generateJavaPreamble()
println("@SuppressWarnings(\"SimplifiableIfStatement\")")
println("public class XRCapabilities {")
val classes = super.getClasses("XR")
val instanceCommands = LinkedHashMap<String, Int>()
classes.asSequence()
.filter { it.hasNativeFunctions }
.forEach {
val functions = it.functions.asSequence()
.filter { cmd ->
if (cmd.isInstanceFunction) {
if (!instanceCommands.contains(cmd.name)) {
instanceCommands[cmd.name] = instanceCommands.size
return@filter true
}
}
false
}
.joinToString(",\n$t$t") { cmd -> cmd.name }
if (functions.isNotEmpty()) {
println("\n$t// ${it.templateName}")
println("${t}public final long")
println("$t$t$functions;")
}
}
println(
"""
/** The OpenXR API version number. */
public final long apiVersion;
"""
)
classes
.forEach {
println(it.getCapabilityJavadoc())
println("${t}public final boolean ${it.capName};")
}
print(
"""
XRCapabilities(FunctionProvider provider, long apiVersion, Set<String> ext) {
this.apiVersion = apiVersion;
long[] caps = new long[${instanceCommands.size}];
"""
)
classes.forEach {
val capName = it.capName
if (it.functions.any { func -> func.isInstanceFunction }) {
print("\n$t$t$capName = check_${it.templateName}(provider, caps, ext);")
} else {
print("\n$t$t$capName = ext.contains(\"$capName\");")
}
}
println()
instanceCommands.forEach { (it, index) ->
print("\n$t$t$it = caps[$index];")
}
print(
"""
}
""")
for (extension in classes) {
if (extension.functions.any { it.isInstanceFunction }) {
checkExtensionFunctions(extension, instanceCommands)
}
}
println("\n}")
}
})
// DSL Extensions
val GlobalCommand = Capabilities("XR.getGlobalCommands()")
fun String.nativeClassXR(
templateName: String,
type: String,
prefix: String = "XR",
prefixMethod: String = prefix.lowercase(),
postfix: String = "",
init: (NativeClass.() -> Unit)? = null
): NativeClass {
check(type == "instance")
return nativeClass(
Module.OPENXR,
templateName,
prefix = prefix,
prefixMethod = prefixMethod,
postfix = postfix,
binding = XR_BINDING_INSTANCE,
init = init
)
} | bsd-3-clause | 70b8f14c759d5f348a9ffa0e75cf1568 | 30.506787 | 135 | 0.559897 | 4.871938 | false | false | false | false |
Zeyad-37/RxRedux | core/src/main/java/com/zeyad/rxredux/core/v2/RxReduxViewModel.kt | 1 | 10030 | package com.zeyad.rxredux.core.v2
import android.util.Log
import androidx.lifecycle.*
import io.reactivex.BackpressureStrategy
import io.reactivex.Flowable
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import io.reactivex.subjects.PublishSubject
import org.reactivestreams.Subscriber
import java.util.concurrent.TimeUnit
import kotlin.properties.Delegates.observable
const val ARG_STATE = "arg_state"
class AsyncOutcomeFlowable(val flowable: Flowable<RxOutcome>) : Flowable<RxOutcome>() {
override fun subscribeActual(s: Subscriber<in RxOutcome>?) = Unit
}
data class InputOutcomeStream(val input: Input, val outcomes: Flowable<RxOutcome>)
internal object EmptyInput : Input()
open class RxOutcome(open var input: Input = EmptyInput)
object EmptyOutcome : RxOutcome()
private data class RxProgress(val progress: Progress) : RxOutcome()
internal data class RxError(var error: Error) : RxOutcome() {
override var input: Input = EmptyInput
set(value) {
error = error.copy(input = value)
field = value
}
}
abstract class RxReduxViewModel<I : Input, R : Result, S : State, E : Effect>(
private val reducer: Reducer<S, R>,
private val inputHandler: InputHandler<I, S>,
private val savedStateHandle: SavedStateHandle?,
) : ViewModel() {
private data class RxState<S>(val state: S) : RxOutcome()
internal data class RxEffect<E>(val effect: E) : RxOutcome()
internal data class RxResult<R>(val result: R) : RxOutcome()
private lateinit var disposable: Disposable
private lateinit var currentState: S
private var viewModelListener: ViewModelListener<S, E>? = null
set(value) {
value?.states?.invoke(currentState)
field = value
}
private var progress: Progress by observable(Progress(false, EmptyInput),
{ _, oldValue, newValue ->
if (newValue != oldValue) notifyProgressChanged(newValue)
})
private val inputs: PublishSubject<I> = PublishSubject.create()
private val throttledInputs: PublishSubject<I> = PublishSubject.create()
private val debouncedInputs: PublishSubject<I> = PublishSubject.create()
private val trackingListener: TrackingListener<I, R, S, E> = this.initTracking()
private val loggingListener: LoggingListener<I, R, S, E> = this.initLogging()
fun bind(initialState: S, inputs: () -> Observable<I>): RxReduxViewModel<I, R, S, E> {
currentState = savedStateHandle?.get(ARG_STATE) ?: initialState
bindInputs(inputs)
return this
}
fun observe(lifecycleOwner: LifecycleOwner, init: ViewModelListenerHelper<S, E>.() -> Unit) {
val helper = ViewModelListenerHelper<S, E>()
helper.init()
viewModelListener = helper
removeObservers(lifecycleOwner)
}
/**
* Input source provider. By default it returns empty
* It can be overwritten to provide other inputs into the stream
*/
fun inputSource(): Observable<I> = Observable.empty()
fun process(input: I, inputStrategy: InputStrategy = InputStrategy.NONE) = when (inputStrategy) {
InputStrategy.NONE -> inputs
InputStrategy.THROTTLE -> throttledInputs
InputStrategy.DEBOUNCE -> debouncedInputs
}.onNext(input)
fun log(): LoggingListenerHelper<I, R, S, E>.() -> Unit = {
inputs { Log.d(this@RxReduxViewModel::class.simpleName, " - Input: $it") }
progress { Log.d(this@RxReduxViewModel::class.simpleName, " - Progress: $it") }
results { Log.d(this@RxReduxViewModel::class.simpleName, " - Result: $it") }
effects { Log.d(this@RxReduxViewModel::class.simpleName, " - Effect: $it") }
states { Log.d(this@RxReduxViewModel::class.simpleName, " - State: $it") }
}
fun track(): TrackingListenerHelper<I, R, S, E>.() -> Unit = { /*empty*/ }
private fun bindInputs(inputs: () -> Observable<I>) {
val outcome = createOutcomes(inputs)
val stateResult = outcome.filter { it is RxResult<*> }.map { it as RxResult<R> }
.scan(RxState(currentState)) { state: RxState<S>, result: RxResult<R> ->
RxState(reducer.reduce(state.state, result.result)).apply { input = result.input }
}.doOnNext {
trackState(it.state, it.input as I)
logState(it.state)
}
disposable = Flowable.merge(outcome.filter { it !is RxResult<*> }, stateResult)
.observeOn(AndroidSchedulers.mainThread())
.map {
trackEvents(it)
logEvents(it)
handleResult(it)
}.subscribe()
}
private fun createOutcomes(inputs: () -> Observable<I>): Flowable<RxOutcome> {
val streamsToProcess = Observable.merge(
inputs(), inputSource(), this.inputs, //throttledInputs.throttle(InputStrategy.THROTTLE.interval),
debouncedInputs.debounce(InputStrategy.DEBOUNCE.interval, TimeUnit.MILLISECONDS)
).observeOn(Schedulers.computation())
.toFlowable(BackpressureStrategy.BUFFER)
.doOnNext {
trackInput(it)
logInput(it)
}.map { InputOutcomeStream(it, inputHandler.handleInputs(it, currentState)) }
.share()
val asyncOutcomes = streamsToProcess.filter { it.outcomes is AsyncOutcomeFlowable }
.map { it.copy(outcomes = (it.outcomes as AsyncOutcomeFlowable).flowable) }
.flatMap { processInputOutcomeStream(it) }
val sequentialOutcomes = streamsToProcess.filter { it.outcomes !is AsyncOutcomeFlowable }
.concatMap { processInputOutcomeStream(it) }
return Flowable.merge(asyncOutcomes, sequentialOutcomes)
}
private fun processInputOutcomeStream(inputOutcomeStream: InputOutcomeStream): Flowable<RxOutcome> {
val result = inputOutcomeStream.outcomes
.map { it.apply { input = inputOutcomeStream.input } }
.onErrorReturn { createRxError(it, inputOutcomeStream.input as I) }
return if (inputOutcomeStream.input.showProgress.not()) {
result
} else {
result.startWith(RxProgress(Progress(isLoading = true, input = inputOutcomeStream.input)))
}
}
private fun trackEvents(event: RxOutcome) {
when (event) {
is RxProgress -> trackingListener.progress(event.progress)
is RxEffect<*> -> trackingListener.effects(event.effect as E, event.input as I)
is RxError -> trackingListener.errors(event.error)
is RxResult<*> -> trackingListener.results(event.result as R, event.input as I)
}
}
private fun logEvents(event: RxOutcome) {
when (event) {
is RxProgress -> loggingListener.progress(event.progress)
is RxEffect<*> -> loggingListener.effects(event.effect as E)
is RxError -> loggingListener.errors(event.error)
is RxResult<*> -> loggingListener.results(event.result as R)
}
}
private fun trackInput(input: I) = trackingListener.inputs(input)
private fun logInput(input: I) = loggingListener.inputs(input)
private fun trackState(state: S, input: I) = trackingListener.states(state, input)
private fun logState(state: S) = loggingListener.states(state)
private fun createRxError(throwable: Throwable, input: I): RxError =
RxError(Error(throwable.message.orEmpty(), throwable, input)).apply { this.input = input }
private fun handleResult(result: RxOutcome) {
if (result is RxProgress) {
notifyProgressChanged(result.progress)
} else {
dismissProgressDependingOnInput(result.input as I)
}
when (result) {
is RxError -> notifyError(result.error)
is RxEffect<*> -> notifyEffect(result.effect as E)
is RxState<*> -> {
saveState(result.state as S)
notifyNewState(result.state)
}
}
}
private fun dismissProgressDependingOnInput(input: I?) {
if (input?.showProgress == true) {
notifyProgressChanged(Progress(false, input))
}
}
private fun notifyProgressChanged(progress: Progress) = viewModelListener?.progress?.invoke(progress)
private fun notifyEffect(effect: E) = viewModelListener?.effects?.invoke(effect)
private fun notifyError(error: Error) = viewModelListener?.errors?.invoke(error)
private fun notifyNewState(state: S) {
currentState = state
viewModelListener?.states?.invoke(state)
}
private fun initTracking(): TrackingListener<I, R, S, E> {
val trackingListenerHelper = TrackingListenerHelper<I, R, S, E>()
val init: TrackingListenerHelper<I, R, S, E>.() -> Unit = track()
trackingListenerHelper.init()
return trackingListenerHelper
}
private fun initLogging(): LoggingListener<I, R, S, E> {
val loggingListenerHelper = LoggingListenerHelper<I, R, S, E>()
val init: LoggingListenerHelper<I, R, S, E>.() -> Unit = log()
loggingListenerHelper.init()
return loggingListenerHelper
}
private fun saveState(state: S) = savedStateHandle?.set(ARG_STATE, state) ?: Unit
private fun removeObservers(lifecycleOwner: LifecycleOwner) =
lifecycleOwner.lifecycle.addObserver(object : LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
fun onDestroy() {
unBind()
lifecycleOwner.lifecycle.removeObserver(this)
}
})
override fun onCleared() = unBind()
private fun unBind() {
viewModelListener = null
disposable.dispose()
}
}
| apache-2.0 | b24c901cb63d6d21dd8ecb82e70c1360 | 39.443548 | 114 | 0.646361 | 4.66946 | false | false | false | false |
paplorinc/intellij-community | jps/jps-builders/testSrc/org/jetbrains/jps/builders/java/MockPackageFacadeBuilder.kt | 11 | 8131 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.jps.builders.java
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.io.FileUtilRt
import com.intellij.openapi.util.text.StringUtil
import com.intellij.util.containers.MultiMap
import com.intellij.util.io.EnumeratorStringDescriptor
import com.intellij.util.io.directoryContent
import com.intellij.util.io.java.AccessModifier
import com.intellij.util.io.java.ClassFileBuilder
import com.intellij.util.io.java.classFile
import gnu.trove.THashSet
import org.jetbrains.jps.ModuleChunk
import org.jetbrains.jps.builders.DirtyFilesHolder
import org.jetbrains.jps.builders.storage.StorageProvider
import org.jetbrains.jps.incremental.BuilderCategory
import org.jetbrains.jps.incremental.CompileContext
import org.jetbrains.jps.incremental.ModuleBuildTarget
import org.jetbrains.jps.incremental.ModuleLevelBuilder
import org.jetbrains.jps.incremental.storage.AbstractStateStorage
import org.jetbrains.jps.incremental.storage.PathStringDescriptor
import org.jetbrains.jps.model.java.LanguageLevel
import org.jetbrains.org.objectweb.asm.ClassReader
import java.io.File
import java.util.*
import java.util.regex.Pattern
/**
* Mock builder which produces class file from several source files to test that our build infrastructure handle such cases properly.
*
* The builder processes *.p file, generates empty class for each such file and generates 'PackageFacade' class for each package
* which references all classes from that package. Package name is derived from 'package <name>;' statement from a file or set to empty
* if no such statement is found
*
* @author nik
*/
class MockPackageFacadeGenerator : ModuleLevelBuilder(BuilderCategory.SOURCE_PROCESSOR) {
override fun build(context: CompileContext,
chunk: ModuleChunk,
dirtyFilesHolder: DirtyFilesHolder<JavaSourceRootDescriptor, ModuleBuildTarget>,
outputConsumer: ModuleLevelBuilder.OutputConsumer): ModuleLevelBuilder.ExitCode {
val filesToCompile = MultiMap.createLinked<ModuleBuildTarget, File>()
dirtyFilesHolder.processDirtyFiles { target, file, root ->
if (isCompilable(file)) {
filesToCompile.putValue(target, file)
}
true
}
val allFilesToCompile = ArrayList(filesToCompile.values())
if (allFilesToCompile.isEmpty() && chunk.targets.all { dirtyFilesHolder.getRemovedFiles(it).all { !isCompilable(File(it)) } }) return ModuleLevelBuilder.ExitCode.NOTHING_DONE
if (JavaBuilderUtil.isCompileJavaIncrementally(context)) {
val logger = context.loggingManager.projectBuilderLogger
if (logger.isEnabled) {
if (!filesToCompile.isEmpty) {
logger.logCompiledFiles(allFilesToCompile, "MockPackageFacadeGenerator", "Compiling files:")
}
}
}
val mappings = context.projectDescriptor.dataManager.mappings
val callback = JavaBuilderUtil.getDependenciesRegistrar(context)
fun generateClass(packageName: String, className: String, target: ModuleBuildTarget, sources: Collection<String>,
allSources: Collection<String>, content: (ClassFileBuilder.() -> Unit)? = null) {
val fullClassName = StringUtil.getQualifiedName(packageName, className)
directoryContent {
classFile(fullClassName) {
javaVersion = LanguageLevel.JDK_1_6
if (content != null) {
content()
}
}
}.generate(target.outputDir!!)
val outputFile = File(target.outputDir, "${fullClassName.replace('.', '/')}.class")
outputConsumer.registerOutputFile(target, outputFile, sources)
callback.associate(fullClassName, allSources, ClassReader(outputFile.readBytes()))
}
for (target in chunk.targets) {
val packagesStorage = context.projectDescriptor.dataManager.getStorage(target, PACKAGE_CACHE_STORAGE_PROVIDER)
for (file in filesToCompile[target]) {
val sources = listOf(file.absolutePath)
generateClass(getPackageName(file), FileUtil.getNameWithoutExtension(file), target, sources, sources)
}
val packagesToGenerate = LinkedHashMap<String, MutableList<File>>()
filesToCompile[target].forEach {
val currentName = getPackageName(it)
if (currentName !in packagesToGenerate) packagesToGenerate[currentName] = ArrayList()
packagesToGenerate[currentName]!!.add(it)
val oldName = packagesStorage.getState(it.absolutePath)
if (oldName != null && oldName != currentName && oldName !in packagesToGenerate) {
packagesToGenerate[oldName] = ArrayList()
}
}
val packagesFromDeletedFiles = dirtyFilesHolder.getRemovedFiles(target).filter { isCompilable(File(it)) }.map { packagesStorage.getState(it) }.filterNotNull()
packagesFromDeletedFiles.forEach {
if (it !in packagesToGenerate) {
packagesToGenerate[it] = ArrayList()
}
}
val getParentFile: (File) -> File = { it.parentFile }
val dirsToCheck = filesToCompile[target].mapTo(THashSet(FileUtil.FILE_HASHING_STRATEGY), getParentFile)
packagesFromDeletedFiles.flatMap {
mappings.getClassSources(mappings.getName(StringUtil.getQualifiedName(it, "PackageFacade"))) ?: emptyList()
}.map(getParentFile).filterNotNullTo(dirsToCheck)
for ((packageName, dirtyFiles) in packagesToGenerate) {
val files = dirsToCheck.map { it.listFiles() }.filterNotNull().flatMap { it.toList() }.filter { isCompilable(it) && packageName == getPackageName(it) }
if (files.isEmpty()) continue
val classNames = files.map { FileUtilRt.getNameWithoutExtension(it.name) }.sorted()
val dirtySource = dirtyFiles.map { it.absolutePath }
val allSources = files.map { it.absolutePath }
generateClass(packageName, "PackageFacade", target, dirtySource, allSources) {
for (fileName in classNames) {
val fieldClass = StringUtil.getQualifiedName(packageName, fileName)
field(StringUtil.decapitalize(fileName), fieldClass, AccessModifier.PUBLIC)
}
}
for (source in dirtySource) {
packagesStorage.update(FileUtil.toSystemIndependentName(source), packageName)
}
}
}
JavaBuilderUtil.registerFilesToCompile(context, allFilesToCompile)
JavaBuilderUtil.registerSuccessfullyCompiled(context, allFilesToCompile)
return ModuleLevelBuilder.ExitCode.OK
}
override fun getCompilableFileExtensions(): List<String> {
return listOf("p")
}
override fun getPresentableName(): String {
return "Mock Package Facade Generator"
}
companion object {
private val PACKAGE_CACHE_STORAGE_PROVIDER = object : StorageProvider<AbstractStateStorage<String, String>>() {
override fun createStorage(targetDataDir: File): AbstractStateStorage<String, String> {
val storageFile = File(targetDataDir, "mockPackageFacade/packages")
return object : AbstractStateStorage<String, String>(storageFile, PathStringDescriptor(), EnumeratorStringDescriptor()) {
}
}
}
private fun getPackageName(sourceFile: File): String {
val text = String(FileUtil.loadFileText(sourceFile))
val matcher = Pattern.compile("\\p{javaWhitespace}*package\\p{javaWhitespace}+([^;]*);.*").matcher(text)
if (matcher.matches()) {
return matcher.group(1)
}
return ""
}
private fun isCompilable(file: File): Boolean {
return FileUtilRt.extensionEquals(file.name, "p")
}
}
} | apache-2.0 | 64f248b376f841f09665f0b8158e531e | 44.177778 | 178 | 0.725003 | 4.791397 | false | false | false | false |
google/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/KotlinChangeInfo.kt | 2 | 27198 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.refactoring.changeSignature
import com.intellij.lang.Language
import com.intellij.lang.java.JavaLanguage
import com.intellij.openapi.util.UserDataHolder
import com.intellij.openapi.util.UserDataHolderBase
import com.intellij.psi.*
import com.intellij.psi.search.searches.OverridingMethodsSearch
import com.intellij.refactoring.changeSignature.*
import com.intellij.refactoring.util.CanonicalTypes
import com.intellij.usageView.UsageInfo
import com.intellij.util.VisibilityUtil
import org.jetbrains.kotlin.asJava.getRepresentativeLightMethod
import org.jetbrains.kotlin.asJava.toLightMethods
import org.jetbrains.kotlin.asJava.unwrapped
import org.jetbrains.kotlin.builtins.isNonExtensionFunctionType
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.descriptors.DescriptorVisibilities
import org.jetbrains.kotlin.descriptors.DescriptorVisibility
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.idea.KotlinLanguage
import org.jetbrains.kotlin.idea.base.facet.platform.platform
import org.jetbrains.kotlin.idea.base.psi.unquoteKotlinIdentifier
import org.jetbrains.kotlin.idea.caches.resolve.util.getJavaOrKotlinMemberDescriptor
import org.jetbrains.kotlin.idea.j2k.j2k
import org.jetbrains.kotlin.idea.refactoring.changeSignature.KotlinMethodDescriptor.Kind
import org.jetbrains.kotlin.idea.refactoring.changeSignature.usages.KotlinCallableDefinitionUsage
import org.jetbrains.kotlin.idea.refactoring.changeSignature.usages.KotlinCallerUsage
import org.jetbrains.kotlin.idea.resolve.ResolutionFacade
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.load.java.JvmAbi
import org.jetbrains.kotlin.platform.jvm.isJvm
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.isIdentifier
import org.jetbrains.kotlin.psi.psiUtil.quoteIfNeeded
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.jvm.annotations.findJvmOverloadsAnnotation
import org.jetbrains.kotlin.resolve.source.getPsi
import org.jetbrains.kotlin.types.isError
import org.jetbrains.kotlin.types.typeUtil.isUnit
import org.jetbrains.kotlin.utils.keysToMap
open class KotlinChangeInfo(
val methodDescriptor: KotlinMethodDescriptor,
private var name: String = methodDescriptor.name,
var newReturnTypeInfo: KotlinTypeInfo = KotlinTypeInfo(true, methodDescriptor.baseDescriptor.returnType),
var newVisibility: DescriptorVisibility = methodDescriptor.visibility,
parameterInfos: List<KotlinParameterInfo> = methodDescriptor.parameters,
receiver: KotlinParameterInfo? = methodDescriptor.receiver,
val context: PsiElement,
primaryPropagationTargets: Collection<PsiElement> = emptyList(),
var checkUsedParameters: Boolean = false,
) : ChangeInfo, UserDataHolder by UserDataHolderBase() {
private val innerChangeInfo: MutableList<KotlinChangeInfo> = mutableListOf()
fun registerInnerChangeInfo(changeInfo: KotlinChangeInfo) {
innerChangeInfo += changeInfo
}
private class JvmOverloadSignature(
val method: PsiMethod,
val mandatoryParams: Set<KtParameter>,
val defaultValues: Set<KtExpression>
) {
fun constrainBy(other: JvmOverloadSignature): JvmOverloadSignature {
return JvmOverloadSignature(
method,
mandatoryParams.intersect(other.mandatoryParams),
defaultValues.intersect(other.defaultValues)
)
}
}
private val originalReturnTypeInfo = methodDescriptor.returnTypeInfo
private val originalReceiverTypeInfo = methodDescriptor.receiver?.originalTypeInfo
var receiverParameterInfo: KotlinParameterInfo? = receiver
set(value) {
if (value != null && value !in newParameters) {
newParameters.add(value)
}
field = value
}
private val newParameters = parameterInfos.toMutableList()
private val originalPsiMethods = method.toLightMethods()
private val originalParameters = (method as? KtFunction)?.valueParameters ?: emptyList()
private val originalSignatures = makeSignatures(originalParameters, originalPsiMethods, { it }, { it.defaultValue })
private val oldNameToParameterIndex: Map<String, Int> by lazy {
val map = HashMap<String, Int>()
val parameters = methodDescriptor.baseDescriptor.valueParameters
parameters.indices.forEach { i -> map[parameters[i].name.asString()] = i }
map
}
private val isParameterSetOrOrderChangedLazy: Boolean by lazy {
val signatureParameters = getNonReceiverParameters()
methodDescriptor.receiver != receiverParameterInfo ||
signatureParameters.size != methodDescriptor.parametersCount ||
signatureParameters.indices.any { i -> signatureParameters[i].oldIndex != i }
}
private var isPrimaryMethodUpdated: Boolean = false
private var javaChangeInfos: List<JavaChangeInfo>? = null
var originalToCurrentMethods: Map<PsiMethod, PsiMethod> = emptyMap()
private set
val parametersToRemove: BooleanArray
get() {
val originalReceiver = methodDescriptor.receiver
val hasReceiver = methodDescriptor.receiver != null
val receiverShift = if (hasReceiver) 1 else 0
val toRemove = BooleanArray(receiverShift + methodDescriptor.parametersCount) { true }
if (hasReceiver) {
toRemove[0] = receiverParameterInfo == null && hasReceiver && originalReceiver !in getNonReceiverParameters()
}
for (parameter in newParameters) {
parameter.oldIndex.takeIf { it >= 0 }?.let { oldIndex ->
toRemove[receiverShift + oldIndex] = false
}
}
return toRemove
}
fun getOldParameterIndex(oldParameterName: String): Int? = oldNameToParameterIndex[oldParameterName]
override fun isParameterTypesChanged(): Boolean = true
override fun isParameterNamesChanged(): Boolean = true
override fun isParameterSetOrOrderChanged(): Boolean = isParameterSetOrOrderChangedLazy
fun getNewParametersCount(): Int = newParameters.size
fun hasAppendedParametersOnly(): Boolean {
val oldParamCount = originalBaseFunctionDescriptor.valueParameters.size
return newParameters.asSequence().withIndex().all { (i, p) -> if (i < oldParamCount) p.oldIndex == i else p.isNewParameter }
}
override fun getNewParameters(): Array<KotlinParameterInfo> = newParameters.toTypedArray()
fun getNonReceiverParametersCount(): Int = newParameters.size - (if (receiverParameterInfo != null) 1 else 0)
fun getNonReceiverParameters(): List<KotlinParameterInfo> {
methodDescriptor.baseDeclaration.let { if (it is KtProperty || it is KtParameter) return emptyList() }
return receiverParameterInfo?.let { receiver -> newParameters.filter { it != receiver } } ?: newParameters
}
fun setNewParameter(index: Int, parameterInfo: KotlinParameterInfo) {
newParameters[index] = parameterInfo
}
@JvmOverloads
fun addParameter(parameterInfo: KotlinParameterInfo, atIndex: Int = -1) {
if (atIndex >= 0) {
newParameters.add(atIndex, parameterInfo)
} else {
newParameters.add(parameterInfo)
}
}
fun removeParameter(index: Int) {
val parameterInfo = newParameters.removeAt(index)
if (parameterInfo == receiverParameterInfo) {
receiverParameterInfo = null
}
}
fun clearParameters() {
newParameters.clear()
receiverParameterInfo = null
}
fun hasParameter(parameterInfo: KotlinParameterInfo): Boolean =
parameterInfo in newParameters
override fun isGenerateDelegate(): Boolean = false
override fun getNewName(): String = name.takeIf { it != "<no name provided>" }?.quoteIfNeeded() ?: name
fun setNewName(value: String) {
name = value
}
override fun isNameChanged(): Boolean = name != methodDescriptor.name
fun isVisibilityChanged(): Boolean = newVisibility != methodDescriptor.visibility
override fun getMethod(): PsiElement {
return methodDescriptor.method
}
override fun isReturnTypeChanged(): Boolean = !newReturnTypeInfo.isEquivalentTo(originalReturnTypeInfo)
fun isReceiverTypeChanged(): Boolean {
val receiverInfo = receiverParameterInfo ?: return originalReceiverTypeInfo != null
return originalReceiverTypeInfo == null || !receiverInfo.currentTypeInfo.isEquivalentTo(originalReceiverTypeInfo)
}
override fun getLanguage(): Language = KotlinLanguage.INSTANCE
var propagationTargetUsageInfos: List<UsageInfo> = ArrayList()
private set
var primaryPropagationTargets: Collection<PsiElement> = emptyList()
set(value) {
field = value
val result = LinkedHashSet<UsageInfo>()
fun add(element: PsiElement) {
element.unwrapped?.let {
val usageInfo = when (it) {
is KtNamedFunction, is KtConstructor<*>, is KtClassOrObject ->
KotlinCallerUsage(it as KtNamedDeclaration)
is PsiMethod ->
CallerUsageInfo(it, true, true)
else ->
return
}
result.add(usageInfo)
}
}
for (caller in value) {
add(caller)
OverridingMethodsSearch.search(caller.getRepresentativeLightMethod() ?: continue).forEach(::add)
}
propagationTargetUsageInfos = result.toList()
}
init {
this.primaryPropagationTargets = primaryPropagationTargets
}
private fun renderReturnTypeIfNeeded(): String? {
val typeInfo = newReturnTypeInfo
if (kind != Kind.FUNCTION) return null
if (typeInfo.type?.isUnit() == true) return null
return typeInfo.render()
}
fun getNewSignature(inheritedCallable: KotlinCallableDefinitionUsage<PsiElement>): String {
val buffer = StringBuilder()
val isCustomizedVisibility = newVisibility != DescriptorVisibilities.DEFAULT_VISIBILITY
if (kind == Kind.PRIMARY_CONSTRUCTOR) {
buffer.append(newName)
if (isCustomizedVisibility) {
buffer.append(' ').append(newVisibility).append(" constructor ")
}
} else {
if (!DescriptorUtils.isLocal(inheritedCallable.originalCallableDescriptor) && isCustomizedVisibility) {
buffer.append(newVisibility).append(' ')
}
buffer.append(if (kind == Kind.SECONDARY_CONSTRUCTOR) KtTokens.CONSTRUCTOR_KEYWORD else KtTokens.FUN_KEYWORD).append(' ')
if (kind == Kind.FUNCTION) {
receiverParameterInfo?.let {
val typeInfo = it.currentTypeInfo
if (typeInfo.type != null && typeInfo.type.isNonExtensionFunctionType) {
buffer.append("(${typeInfo.render()})")
} else {
buffer.append(typeInfo.render())
}
buffer.append('.')
}
buffer.append(newName)
}
}
buffer.append(getNewParametersSignature(inheritedCallable))
renderReturnTypeIfNeeded()?.let { buffer.append(": ").append(it) }
return buffer.toString()
}
fun getNewParametersSignature(inheritedCallable: KotlinCallableDefinitionUsage<*>): String {
return "(" + getNewParametersSignatureWithoutParentheses(inheritedCallable) + ")"
}
fun getNewParametersSignatureWithoutParentheses(
inheritedCallable: KotlinCallableDefinitionUsage<*>
): String {
val signatureParameters = getNonReceiverParameters()
val isLambda = inheritedCallable.declaration is KtFunctionLiteral
if (isLambda && signatureParameters.size == 1 && !signatureParameters[0].requiresExplicitType(inheritedCallable)) {
return signatureParameters[0].getDeclarationSignature(0, inheritedCallable).text
}
return signatureParameters.indices.joinToString(separator = ", ") { i ->
signatureParameters[i].getDeclarationSignature(i, inheritedCallable).text
}
}
fun renderReceiverType(inheritedCallable: KotlinCallableDefinitionUsage<*>): String? {
val receiverTypeText = receiverParameterInfo?.currentTypeInfo?.render() ?: return null
val typeSubstitutor = inheritedCallable.typeSubstitutor ?: return receiverTypeText
val currentBaseFunction = inheritedCallable.baseFunction.currentCallableDescriptor ?: return receiverTypeText
val receiverType = currentBaseFunction.extensionReceiverParameter!!.type
if (receiverType.isError) return receiverTypeText
return receiverType.renderTypeWithSubstitution(typeSubstitutor, receiverTypeText, false)
}
fun renderReturnType(inheritedCallable: KotlinCallableDefinitionUsage<*>): String {
val defaultRendering = newReturnTypeInfo.render()
val typeSubstitutor = inheritedCallable.typeSubstitutor ?: return defaultRendering
val currentBaseFunction = inheritedCallable.baseFunction.currentCallableDescriptor ?: return defaultRendering
val returnType = currentBaseFunction.returnType!!
if (returnType.isError) return defaultRendering
return returnType.renderTypeWithSubstitution(typeSubstitutor, defaultRendering, false)
}
fun primaryMethodUpdated() {
isPrimaryMethodUpdated = true
javaChangeInfos = null
for (info in innerChangeInfo) {
info.primaryMethodUpdated()
}
}
private fun <Parameter> makeSignatures(
parameters: List<Parameter>,
psiMethods: List<PsiMethod>,
getPsi: (Parameter) -> KtParameter,
getDefaultValue: (Parameter) -> KtExpression?
): List<JvmOverloadSignature> {
val defaultValueCount = parameters.count { getDefaultValue(it) != null }
if (psiMethods.size != defaultValueCount + 1) return emptyList()
val mandatoryParams = parameters.toMutableList()
val defaultValues = ArrayList<KtExpression>()
return psiMethods.map { method ->
JvmOverloadSignature(method, mandatoryParams.asSequence().map(getPsi).toSet(), defaultValues.toSet()).apply {
val param = mandatoryParams.removeLast { getDefaultValue(it) != null } ?: return@apply
defaultValues.add(getDefaultValue(param)!!)
}
}
}
private fun <T> MutableList<T>.removeLast(condition: (T) -> Boolean): T? {
val index = indexOfLast(condition)
return if (index >= 0) removeAt(index) else null
}
fun getOrCreateJavaChangeInfos(): List<JavaChangeInfo>? {
fun initCurrentSignatures(currentPsiMethods: List<PsiMethod>): List<JvmOverloadSignature> {
val parameterInfoToPsi = methodDescriptor.original.parameters.zip(originalParameters).toMap()
val dummyParameter = KtPsiFactory(method).createParameter("dummy")
return makeSignatures(
parameters = newParameters,
psiMethods = currentPsiMethods,
getPsi = { parameterInfoToPsi[it] ?: dummyParameter },
getDefaultValue = { it.defaultValue },
)
}
fun matchOriginalAndCurrentMethods(currentPsiMethods: List<PsiMethod>): Map<PsiMethod, PsiMethod> {
if (!(isPrimaryMethodUpdated && originalBaseFunctionDescriptor is FunctionDescriptor && originalBaseFunctionDescriptor.findJvmOverloadsAnnotation() != null)) {
return (originalPsiMethods.zip(currentPsiMethods)).toMap()
}
if (originalPsiMethods.isEmpty() || currentPsiMethods.isEmpty()) return emptyMap()
currentPsiMethods.singleOrNull()?.let { method -> return originalPsiMethods.keysToMap { method } }
val currentSignatures = initCurrentSignatures(currentPsiMethods)
return originalSignatures.associateBy({ it.method }) { originalSignature ->
var constrainedCurrentSignatures = currentSignatures.map { it.constrainBy(originalSignature) }
val maxMandatoryCount = constrainedCurrentSignatures.maxOf { it.mandatoryParams.size }
constrainedCurrentSignatures = constrainedCurrentSignatures.filter { it.mandatoryParams.size == maxMandatoryCount }
val maxDefaultCount = constrainedCurrentSignatures.maxOf { it.defaultValues.size }
constrainedCurrentSignatures.last { it.defaultValues.size == maxDefaultCount }.method
}
}
/*
* When primaryMethodUpdated is false, changes to the primary Kotlin declaration are already confirmed, but not yet applied.
* It means that originalPsiMethod has already expired, but new one can't be created until Kotlin declaration is updated
* (signified by primaryMethodUpdated being true). It means we can't know actual PsiType, visibility, etc.
* to use in JavaChangeInfo. However they are not actually used at this point since only parameter count and order matters here
* So we resort to this hack and pass around "default" type (void) and visibility (package-local)
*/
fun createJavaChangeInfo(
originalPsiMethod: PsiMethod,
currentPsiMethod: PsiMethod,
newName: String,
newReturnType: PsiType?,
newParameters: Array<ParameterInfoImpl>
): JavaChangeInfo? {
if (!newName.unquoteKotlinIdentifier().isIdentifier()) return null
val newVisibility = if (isPrimaryMethodUpdated)
VisibilityUtil.getVisibilityModifier(currentPsiMethod.modifierList)
else
PsiModifier.PACKAGE_LOCAL
val propagationTargets = primaryPropagationTargets.asSequence()
.mapNotNull { it.getRepresentativeLightMethod() }
.toSet()
val javaChangeInfo = ChangeSignatureProcessor(
method.project,
originalPsiMethod,
false,
newVisibility,
newName,
CanonicalTypes.createTypeWrapper(newReturnType ?: PsiType.VOID),
newParameters,
arrayOf<ThrownExceptionInfo>(),
propagationTargets,
emptySet()
).changeInfo
javaChangeInfo.updateMethod(currentPsiMethod)
return javaChangeInfo
}
fun getJavaParameterInfos(
originalPsiMethod: PsiMethod,
currentPsiMethod: PsiMethod,
newParameterList: List<KotlinParameterInfo>
): MutableList<ParameterInfoImpl> {
val defaultValuesToSkip = newParameterList.size - currentPsiMethod.parameterList.parametersCount
val defaultValuesToRetain = newParameterList.count { it.defaultValue != null } - defaultValuesToSkip
val oldIndices = newParameterList.map { it.oldIndex }.toIntArray()
// TODO: Ugly code, need to refactor Change Signature data model
var defaultValuesRemained = defaultValuesToRetain
for (param in newParameterList) {
if (param.isNewParameter || param.defaultValue == null || defaultValuesRemained-- > 0) continue
newParameterList.asSequence()
.withIndex()
.filter { it.value.oldIndex >= param.oldIndex }
.toList()
.forEach { oldIndices[it.index]-- }
}
defaultValuesRemained = defaultValuesToRetain
val oldParameterCount = originalPsiMethod.parameterList.parametersCount
var indexInCurrentPsiMethod = 0
return newParameterList.asSequence().withIndex().mapNotNullTo(ArrayList()) map@{ pair ->
val (i, info) = pair
if (info.defaultValue != null && defaultValuesRemained-- <= 0) return@map null
val oldIndex = oldIndices[i]
val javaOldIndex = when {
methodDescriptor.receiver == null -> oldIndex
info == methodDescriptor.receiver -> 0
oldIndex >= 0 -> oldIndex + 1
else -> -1
}
if (javaOldIndex >= oldParameterCount) return@map null
val type = if (isPrimaryMethodUpdated)
currentPsiMethod.parameterList.parameters[indexInCurrentPsiMethod++].type
else
PsiType.VOID
val defaultValue = info.defaultValueForCall ?: info.defaultValue
ParameterInfoImpl(javaOldIndex, info.name, type, defaultValue?.text ?: "")
}
}
fun createJavaChangeInfoForFunctionOrGetter(
originalPsiMethod: PsiMethod,
currentPsiMethod: PsiMethod,
isGetter: Boolean
): JavaChangeInfo? {
val newParameterList = listOfNotNull(receiverParameterInfo) + getNonReceiverParameters()
val newJavaParameters = getJavaParameterInfos(originalPsiMethod, currentPsiMethod, newParameterList).toTypedArray()
val newName = if (isGetter) JvmAbi.getterName(newName) else newName
return createJavaChangeInfo(originalPsiMethod, currentPsiMethod, newName, currentPsiMethod.returnType, newJavaParameters)
}
fun createJavaChangeInfoForSetter(originalPsiMethod: PsiMethod, currentPsiMethod: PsiMethod): JavaChangeInfo? {
val newJavaParameters = getJavaParameterInfos(originalPsiMethod, currentPsiMethod, listOfNotNull(receiverParameterInfo))
val oldIndex = if (methodDescriptor.receiver != null) 1 else 0
val parameters = currentPsiMethod.parameterList.parameters
if (isPrimaryMethodUpdated) {
val newIndex = if (receiverParameterInfo != null) 1 else 0
val setterParameter = parameters[newIndex]
newJavaParameters.add(ParameterInfoImpl(oldIndex, setterParameter.name, setterParameter.type))
} else {
if (receiverParameterInfo != null) {
if (newJavaParameters.isEmpty()) {
newJavaParameters.add(ParameterInfoImpl(oldIndex, "receiver", PsiType.VOID))
}
}
if (oldIndex < parameters.size) {
val setterParameter = parameters[oldIndex]
newJavaParameters.add(ParameterInfoImpl(oldIndex, setterParameter.name, setterParameter.type))
}
}
val newName = JvmAbi.setterName(newName)
return createJavaChangeInfo(originalPsiMethod, currentPsiMethod, newName, PsiType.VOID, newJavaParameters.toTypedArray())
}
if (!(method.containingFile as KtFile).platform.isJvm()) return null
if (javaChangeInfos == null) {
val method = method
originalToCurrentMethods = matchOriginalAndCurrentMethods(method.toLightMethods())
javaChangeInfos = originalToCurrentMethods.entries.mapNotNull {
val (originalPsiMethod, currentPsiMethod) = it
when (method) {
is KtFunction, is KtClassOrObject ->
createJavaChangeInfoForFunctionOrGetter(originalPsiMethod, currentPsiMethod, false)
is KtProperty, is KtParameter -> {
val accessorName = originalPsiMethod.name
when {
JvmAbi.isGetterName(accessorName) ->
createJavaChangeInfoForFunctionOrGetter(originalPsiMethod, currentPsiMethod, true)
JvmAbi.isSetterName(accessorName) ->
createJavaChangeInfoForSetter(originalPsiMethod, currentPsiMethod)
else -> null
}
}
else -> null
}
}
}
return javaChangeInfos
}
}
val KotlinChangeInfo.originalBaseFunctionDescriptor: CallableDescriptor
get() = methodDescriptor.baseDescriptor
val KotlinChangeInfo.kind: Kind get() = methodDescriptor.kind
val KotlinChangeInfo.oldName: String?
get() = (methodDescriptor.method as? KtFunction)?.name
fun KotlinChangeInfo.getAffectedCallables(): Collection<UsageInfo> = methodDescriptor.affectedCallables + propagationTargetUsageInfos
fun ChangeInfo.toJetChangeInfo(
originalChangeSignatureDescriptor: KotlinMethodDescriptor,
resolutionFacade: ResolutionFacade
): KotlinChangeInfo {
val method = method as PsiMethod
val functionDescriptor = method.getJavaOrKotlinMemberDescriptor(resolutionFacade) as CallableDescriptor
val parameterDescriptors = functionDescriptor.valueParameters
//noinspection ConstantConditions
val originalParameterDescriptors = originalChangeSignatureDescriptor.baseDescriptor.valueParameters
val newParameters = newParameters.withIndex().map { pair ->
val (i, info) = pair
val oldIndex = info.oldIndex
val currentType = parameterDescriptors[i].type
val defaultValueText = info.defaultValue
val defaultValueExpr =
when {
info is KotlinAwareJavaParameterInfoImpl -> info.kotlinDefaultValue
language.`is`(JavaLanguage.INSTANCE) && !defaultValueText.isNullOrEmpty() -> {
PsiElementFactory.getInstance(method.project).createExpressionFromText(defaultValueText, null).j2k()
}
else -> null
}
val parameterType = if (oldIndex >= 0) originalParameterDescriptors[oldIndex].type else currentType
val originalKtParameter = originalParameterDescriptors.getOrNull(oldIndex)?.source?.getPsi() as? KtParameter
val valOrVar = originalKtParameter?.valOrVarKeyword?.toValVar() ?: KotlinValVar.None
KotlinParameterInfo(
callableDescriptor = functionDescriptor,
originalIndex = oldIndex,
name = info.name,
originalTypeInfo = KotlinTypeInfo(false, parameterType),
defaultValueForCall = defaultValueExpr,
valOrVar = valOrVar
).apply {
currentTypeInfo = KotlinTypeInfo(false, currentType)
}
}
return KotlinChangeInfo(
originalChangeSignatureDescriptor,
newName,
KotlinTypeInfo(true, functionDescriptor.returnType),
functionDescriptor.visibility,
newParameters,
null,
method
)
}
| apache-2.0 | a1ce02632c877d9ce3af935752e951bd | 43.441176 | 171 | 0.670123 | 6.242369 | false | false | false | false |
google/intellij-community | plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/PackageSearchUI.kt | 1 | 17311 | /*******************************************************************************
* Copyright 2000-2022 JetBrains s.r.o. and contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.jetbrains.packagesearch.intellij.plugin.ui
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.Presentation
import com.intellij.openapi.actionSystem.ex.CustomComponentAction
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.ui.ExperimentalUI
import com.intellij.ui.Gray
import com.intellij.ui.JBColor
import com.intellij.util.ui.JBEmptyBorder
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.JBValue
import com.intellij.util.ui.StartupUiUtil
import com.intellij.util.ui.UIUtil
import com.intellij.util.ui.components.BorderLayoutPanel
import com.jetbrains.packagesearch.intellij.plugin.ui.components.BrowsableLinkLabel
import com.jetbrains.packagesearch.intellij.plugin.ui.util.ScalableUnits
import com.jetbrains.packagesearch.intellij.plugin.ui.util.ScaledPixels
import com.jetbrains.packagesearch.intellij.plugin.ui.util.scaled
import org.jetbrains.annotations.Nls
import java.awt.CardLayout
import java.awt.Color
import java.awt.Component
import java.awt.Dimension
import java.awt.FlowLayout
import java.awt.Rectangle
import java.awt.event.ActionEvent
import javax.swing.AbstractAction
import javax.swing.BorderFactory
import javax.swing.BoxLayout
import javax.swing.Icon
import javax.swing.JCheckBox
import javax.swing.JComponent
import javax.swing.JLabel
import javax.swing.JMenuItem
import javax.swing.JPanel
import javax.swing.JScrollPane
import javax.swing.JTextField
import javax.swing.KeyStroke
import javax.swing.Scrollable
object PackageSearchUI {
internal object Colors {
val border = JBColor.border()
val separator = JBUI.CurrentTheme.CustomFrameDecorations.separatorForeground()
private val mainBackground: Color = JBColor.namedColor("Plugins.background", UIUtil.getListBackground())
val infoLabelForeground: Color = JBColor.namedColor("Label.infoForeground", JBColor(Gray._120, Gray._135))
val headerBackground = mainBackground
val sectionHeaderBackground = JBColor.namedColor("Plugins.SectionHeader.background", 0xF7F7F7, 0x3C3F41)
val panelBackground
get() = if (isNewUI) JBColor.namedColor("Panel.background") else mainBackground
interface StatefulColor {
fun background(isSelected: Boolean, isHover: Boolean): Color
fun foreground(isSelected: Boolean, isHover: Boolean): Color
}
object PackagesTable : StatefulColor {
override fun background(isSelected: Boolean, isHover: Boolean) =
when {
isSelected -> tableSelectedBackground
isHover -> tableHoverBackground
else -> tableBackground
}
override fun foreground(isSelected: Boolean, isHover: Boolean) =
when {
isSelected -> tableSelectedForeground
else -> tableForeground
}
private val tableBackground = JBColor.namedColor("Table.background")
private val tableForeground = JBColor.namedColor("Table.foreground")
private val tableHoverBackground
get() = color(
propertyName = "PackageSearch.SearchResult.hoverBackground",
newUILight = 0x2C3341, newUIDark = 0xDBE1EC,
oldUILight = 0xF2F5F9, oldUIDark = 0x4C5052
)
private val tableSelectedBackground = JBColor.namedColor("Table.selectionBackground")
private val tableSelectedForeground = JBColor.namedColor("Table.selectionForeground")
object SearchResult : StatefulColor {
override fun background(isSelected: Boolean, isHover: Boolean) =
when {
isSelected -> searchResultSelectedBackground
isHover -> searchResultHoverBackground
else -> searchResultBackground
}
override fun foreground(isSelected: Boolean, isHover: Boolean) =
when {
isSelected -> searchResultSelectedForeground
else -> searchResultForeground
}
private val searchResultBackground
get() = color(
propertyName = "PackageSearch.SearchResult.background",
newUILight = 0xE8EEFA, newUIDark = 0x1C2433,
oldUILight = 0xE4FAFF, oldUIDark = 0x3F4749
)
private val searchResultForeground = tableForeground
private val searchResultSelectedBackground = tableSelectedBackground
private val searchResultSelectedForeground = tableSelectedForeground
private val searchResultHoverBackground
get() = color(
propertyName = "PackageSearch.SearchResult.hoverBackground",
newUILight = 0xDBE1EC, newUIDark = 0x2C3341,
oldUILight = 0xF2F5F9, oldUIDark = 0x4C5052
)
object Tag : StatefulColor {
override fun background(isSelected: Boolean, isHover: Boolean) =
when {
isSelected -> searchResultTagSelectedBackground
isHover -> searchResultTagHoverBackground
else -> searchResultTagBackground
}
override fun foreground(isSelected: Boolean, isHover: Boolean) =
when {
isSelected -> searchResultTagSelectedForeground
else -> searchResultTagForeground
}
private val searchResultTagBackground
get() = color(
propertyName = "PackageSearch.SearchResult.PackageTag.background",
newUILight = 0xD5DBE6, newUIDark = 0x2E3643,
oldUILight = 0xD2E6EB, oldUIDark = 0x4E5658
)
private val searchResultTagForeground
get() = color(
propertyName = "PackageSearch.SearchResult.PackageTag.foreground",
newUILight = 0x000000, newUIDark = 0xDFE1E5,
oldUILight = 0x000000, oldUIDark = 0x8E8F8F
)
private val searchResultTagHoverBackground
get() = color(
propertyName = "PackageSearch.SearchResult.PackageTag.hoverBackground",
newUILight = 0xC9CFD9, newUIDark = 0x3D4350,
oldUILight = 0xBFD0DB, oldUIDark = 0x55585B
)
private val searchResultTagSelectedBackground
get() = color(
propertyName = "PackageSearch.SearchResult.PackageTag.selectedBackground",
newUILight = 0xA0BDF8, newUIDark = 0x375FAD,
oldUILight = 0x4395E2, oldUIDark = 0x2F65CA
)
private val searchResultTagSelectedForeground
get() = color(
propertyName = "PackageSearch.SearchResult.PackageTag.selectedForeground",
newUILight = 0x000000, newUIDark = 0x1E1F22,
oldUILight = 0xFFFFFF, oldUIDark = 0xBBBBBB
)
}
}
object Tag : StatefulColor {
override fun background(isSelected: Boolean, isHover: Boolean) =
when {
isSelected -> tagSelectedBackground
isHover -> tagHoverBackground
else -> tagBackground
}
override fun foreground(isSelected: Boolean, isHover: Boolean) =
when {
isSelected -> tagSelectedForeground
else -> tagForeground
}
private val tagBackground
get() = color(
propertyName = "PackageSearch.PackageTag.background",
newUILight = 0xDFE1E5, newUIDark = 0x43454A,
oldUILight = 0xEBEBEB, oldUIDark = 0x4C4E50
)
private val tagForeground
get() = color(
propertyName = "PackageSearch.PackageTag.foreground",
newUILight = 0x5A5D6B, newUIDark = 0x9DA0A8,
oldUILight = 0x000000, oldUIDark = 0x9C9C9C
)
private val tagHoverBackground
get() = color(
propertyName = "PackageSearch.PackageTag.hoverBackground",
newUILight = 0xF7F8FA, newUIDark = 0x4A4C4E,
oldUILight = 0xC9D2DB, oldUIDark = 0x55585B
)
private val tagSelectedBackground
get() = color(
propertyName = "PackageSearch.PackageTag.selectedBackground",
newUILight = 0x88ADF7, newUIDark = 0x43454A,
oldUILight = 0x4395E2, oldUIDark = 0x2F65CA
)
private val tagSelectedForeground
get() = color(
propertyName = "PackageSearch.PackageTag.selectedForeground",
newUILight = 0x000000, newUIDark = 0x9DA0A8,
oldUILight = 0xFFFFFF, oldUIDark = 0xBBBBBB
)
}
}
object InfoBanner {
val background = JBUI.CurrentTheme.Banner.INFO_BACKGROUND
val border = JBUI.CurrentTheme.Banner.INFO_BORDER_COLOR
}
private fun color(
propertyName: String? = null,
newUILight: Int,
newUIDark: Int,
oldUILight: Int,
oldUIDark: Int
) =
if (propertyName != null) {
JBColor.namedColor(
propertyName,
if (isNewUI) newUILight else oldUILight,
if (isNewUI) newUIDark else oldUIDark
)
} else {
JBColor(
if (isNewUI) newUILight else oldUILight,
if (isNewUI) newUIDark else oldUIDark
)
}
}
internal val mediumHeaderHeight = JBValue.Float(30f)
internal val smallHeaderHeight = JBValue.Float(24f)
val isNewUI
get() = ExperimentalUI.isNewUI()
@Suppress("MagicNumber") // Thanks, Swing
internal fun headerPanel(init: BorderLayoutPanel.() -> Unit) = object : BorderLayoutPanel() {
init {
border = JBEmptyBorder(2, 0, 2, 12)
init()
}
override fun getBackground() = Colors.headerBackground
}
internal fun cardPanel(cards: List<JPanel> = emptyList(), backgroundColor: Color = Colors.panelBackground, init: JPanel.() -> Unit) =
object : JPanel() {
init {
layout = CardLayout()
cards.forEach { add(it) }
init()
}
override fun getBackground() = backgroundColor
}
internal fun borderPanel(backgroundColor: Color = Colors.panelBackground, init: BorderLayoutPanel.() -> Unit) =
object : BorderLayoutPanel() {
init {
init()
}
override fun getBackground() = backgroundColor
}
internal fun boxPanel(axis: Int = BoxLayout.Y_AXIS, backgroundColor: Color = Colors.panelBackground, init: JPanel.() -> Unit) =
object : JPanel() {
init {
layout = BoxLayout(this, axis)
init()
}
override fun getBackground() = backgroundColor
}
internal fun flowPanel(backgroundColor: Color = Colors.panelBackground, init: JPanel.() -> Unit) = object : JPanel() {
init {
layout = FlowLayout(FlowLayout.LEFT)
init()
}
override fun getBackground() = backgroundColor
}
fun checkBox(@Nls title: String, init: JCheckBox.() -> Unit = {}) = object : JCheckBox(title) {
init {
init()
}
override fun getBackground() = Colors.panelBackground
}
fun textField(init: JTextField.() -> Unit): JTextField = JTextField().apply {
init()
}
internal fun menuItem(@Nls title: String, icon: Icon?, handler: () -> Unit): JMenuItem {
if (icon != null) {
return JMenuItem(title, icon).apply { addActionListener { handler() } }
}
return JMenuItem(title).apply { addActionListener { handler() } }
}
fun createLabel(@Nls text: String? = null, init: JLabel.() -> Unit = {}) = JLabel().apply {
font = StartupUiUtil.getLabelFont()
if (text != null) this.text = text
init()
}
internal fun createLabelWithLink(init: BrowsableLinkLabel.() -> Unit = {}) = BrowsableLinkLabel().apply {
font = StartupUiUtil.getLabelFont()
init()
}
internal fun getTextColorPrimary(isSelected: Boolean = false): Color = when {
isSelected -> JBColor.lazy { UIUtil.getListSelectionForeground(true) }
else -> JBColor.lazy { UIUtil.getListForeground() }
}
internal fun getTextColorSecondary(isSelected: Boolean = false): Color = when {
isSelected -> getTextColorPrimary(true)
else -> Colors.infoLabelForeground
}
internal fun setHeight(component: JComponent, @ScalableUnits height: Int, keepWidth: Boolean = false) {
setHeightPreScaled(component, height.scaled(), keepWidth)
}
internal fun setHeightPreScaled(component: JComponent, @ScaledPixels height: Int, keepWidth: Boolean = false) {
component.apply {
preferredSize = Dimension(if (keepWidth) preferredSize.width else 0, height)
minimumSize = Dimension(if (keepWidth) minimumSize.width else 0, height)
maximumSize = Dimension(if (keepWidth) maximumSize.width else Int.MAX_VALUE, height)
}
}
internal fun verticalScrollPane(c: Component) = object : JScrollPane(
VerticalScrollPanelWrapper(c),
VERTICAL_SCROLLBAR_AS_NEEDED,
HORIZONTAL_SCROLLBAR_NEVER
) {
init {
border = BorderFactory.createEmptyBorder()
viewport.background = Colors.panelBackground
}
}
internal fun overrideKeyStroke(c: JComponent, stroke: String, action: () -> Unit) = overrideKeyStroke(c, stroke, stroke, action)
internal fun overrideKeyStroke(c: JComponent, key: String, stroke: String, action: () -> Unit) {
val inputMap = c.getInputMap(JComponent.WHEN_FOCUSED)
inputMap.put(KeyStroke.getKeyStroke(stroke), key)
c.actionMap.put(
key,
object : AbstractAction() {
override fun actionPerformed(arg: ActionEvent) {
action()
}
}
)
}
private class VerticalScrollPanelWrapper(content: Component) : JPanel(), Scrollable {
init {
layout = BoxLayout(this, BoxLayout.Y_AXIS)
add(content)
}
override fun getPreferredScrollableViewportSize(): Dimension = preferredSize
override fun getScrollableUnitIncrement(visibleRect: Rectangle, orientation: Int, direction: Int) = 10
override fun getScrollableBlockIncrement(visibleRect: Rectangle, orientation: Int, direction: Int) = 100
override fun getScrollableTracksViewportWidth() = true
override fun getScrollableTracksViewportHeight() = false
override fun getBackground() = Colors.panelBackground
}
}
internal class ComponentActionWrapper(private val myComponentCreator: () -> JComponent) : DumbAwareAction(), CustomComponentAction {
override fun createCustomComponent(presentation: Presentation, place: String) = myComponentCreator()
override fun actionPerformed(e: AnActionEvent) {
// No-op
}
}
internal fun JComponent.updateAndRepaint() {
invalidate()
repaint()
}
| apache-2.0 | 30a49484c2593915ebb7dd2ee0586ee4 | 38.704128 | 137 | 0.584599 | 5.62228 | false | false | false | false |
google/intellij-community | platform/workspaceModel/storage/gen/com/intellij/workspaceModel/storage/bridgeEntities/api/FacetEntityImpl.kt | 1 | 15360 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.workspaceModel.storage.bridgeEntities.api
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.PersistentEntityId
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.EntityLink
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.SoftLinkable
import com.intellij.workspaceModel.storage.impl.UsedClassesCollector
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.extractOneToManyParent
import com.intellij.workspaceModel.storage.impl.indices.WorkspaceMutableIndex
import com.intellij.workspaceModel.storage.impl.updateOneToManyParentOfChild
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class FacetEntityImpl(val dataSource: FacetEntityData) : FacetEntity, WorkspaceEntityBase() {
companion object {
internal val MODULE_CONNECTION_ID: ConnectionId = ConnectionId.create(ModuleEntity::class.java, FacetEntity::class.java,
ConnectionId.ConnectionType.ONE_TO_MANY, false)
internal val UNDERLYINGFACET_CONNECTION_ID: ConnectionId = ConnectionId.create(FacetEntity::class.java, FacetEntity::class.java,
ConnectionId.ConnectionType.ONE_TO_MANY, true)
val connections = listOf<ConnectionId>(
MODULE_CONNECTION_ID,
UNDERLYINGFACET_CONNECTION_ID,
)
}
override val name: String
get() = dataSource.name
override val module: ModuleEntity
get() = snapshot.extractOneToManyParent(MODULE_CONNECTION_ID, this)!!
override val facetType: String
get() = dataSource.facetType
override val configurationXmlTag: String?
get() = dataSource.configurationXmlTag
override val moduleId: ModuleId
get() = dataSource.moduleId
override val underlyingFacet: FacetEntity?
get() = snapshot.extractOneToManyParent(UNDERLYINGFACET_CONNECTION_ID, this)
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: FacetEntityData?) : ModifiableWorkspaceEntityBase<FacetEntity>(), FacetEntity.Builder {
constructor() : this(FacetEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity FacetEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isEntitySourceInitialized()) {
error("Field WorkspaceEntity#entitySource should be initialized")
}
if (!getEntityData().isNameInitialized()) {
error("Field FacetEntity#name should be initialized")
}
if (_diff != null) {
if (_diff.extractOneToManyParent<WorkspaceEntityBase>(MODULE_CONNECTION_ID, this) == null) {
error("Field FacetEntity#module should be initialized")
}
}
else {
if (this.entityLinks[EntityLink(false, MODULE_CONNECTION_ID)] == null) {
error("Field FacetEntity#module should be initialized")
}
}
if (!getEntityData().isFacetTypeInitialized()) {
error("Field FacetEntity#facetType should be initialized")
}
if (!getEntityData().isModuleIdInitialized()) {
error("Field FacetEntity#moduleId should be initialized")
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
// Relabeling code, move information from dataSource to this builder
override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) {
dataSource as FacetEntity
this.entitySource = dataSource.entitySource
this.name = dataSource.name
this.facetType = dataSource.facetType
this.configurationXmlTag = dataSource.configurationXmlTag
this.moduleId = dataSource.moduleId
if (parents != null) {
this.module = parents.filterIsInstance<ModuleEntity>().single()
this.underlyingFacet = parents.filterIsInstance<FacetEntity>().singleOrNull()
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override var name: String
get() = getEntityData().name
set(value) {
checkModificationAllowed()
getEntityData().name = value
changedProperty.add("name")
}
override var module: ModuleEntity
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToManyParent(MODULE_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false,
MODULE_CONNECTION_ID)]!! as ModuleEntity
}
else {
this.entityLinks[EntityLink(false, MODULE_CONNECTION_ID)]!! as ModuleEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) {
// Setting backref of the list
if (value is ModifiableWorkspaceEntityBase<*>) {
val data = (value.entityLinks[EntityLink(true, MODULE_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this
value.entityLinks[EntityLink(true, MODULE_CONNECTION_ID)] = data
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) {
_diff.updateOneToManyParentOfChild(MODULE_CONNECTION_ID, this, value)
}
else {
// Setting backref of the list
if (value is ModifiableWorkspaceEntityBase<*>) {
val data = (value.entityLinks[EntityLink(true, MODULE_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this
value.entityLinks[EntityLink(true, MODULE_CONNECTION_ID)] = data
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(false, MODULE_CONNECTION_ID)] = value
}
changedProperty.add("module")
}
override var facetType: String
get() = getEntityData().facetType
set(value) {
checkModificationAllowed()
getEntityData().facetType = value
changedProperty.add("facetType")
}
override var configurationXmlTag: String?
get() = getEntityData().configurationXmlTag
set(value) {
checkModificationAllowed()
getEntityData().configurationXmlTag = value
changedProperty.add("configurationXmlTag")
}
override var moduleId: ModuleId
get() = getEntityData().moduleId
set(value) {
checkModificationAllowed()
getEntityData().moduleId = value
changedProperty.add("moduleId")
}
override var underlyingFacet: FacetEntity?
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToManyParent(UNDERLYINGFACET_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false,
UNDERLYINGFACET_CONNECTION_ID)] as? FacetEntity
}
else {
this.entityLinks[EntityLink(false, UNDERLYINGFACET_CONNECTION_ID)] as? FacetEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) {
// Setting backref of the list
if (value is ModifiableWorkspaceEntityBase<*>) {
val data = (value.entityLinks[EntityLink(true, UNDERLYINGFACET_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this
value.entityLinks[EntityLink(true, UNDERLYINGFACET_CONNECTION_ID)] = data
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) {
_diff.updateOneToManyParentOfChild(UNDERLYINGFACET_CONNECTION_ID, this, value)
}
else {
// Setting backref of the list
if (value is ModifiableWorkspaceEntityBase<*>) {
val data = (value.entityLinks[EntityLink(true, UNDERLYINGFACET_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this
value.entityLinks[EntityLink(true, UNDERLYINGFACET_CONNECTION_ID)] = data
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(false, UNDERLYINGFACET_CONNECTION_ID)] = value
}
changedProperty.add("underlyingFacet")
}
override fun getEntityData(): FacetEntityData = result ?: super.getEntityData() as FacetEntityData
override fun getEntityClass(): Class<FacetEntity> = FacetEntity::class.java
}
}
class FacetEntityData : WorkspaceEntityData.WithCalculablePersistentId<FacetEntity>(), SoftLinkable {
lateinit var name: String
lateinit var facetType: String
var configurationXmlTag: String? = null
lateinit var moduleId: ModuleId
fun isNameInitialized(): Boolean = ::name.isInitialized
fun isFacetTypeInitialized(): Boolean = ::facetType.isInitialized
fun isModuleIdInitialized(): Boolean = ::moduleId.isInitialized
override fun getLinks(): Set<PersistentEntityId<*>> {
val result = HashSet<PersistentEntityId<*>>()
result.add(moduleId)
return result
}
override fun index(index: WorkspaceMutableIndex<PersistentEntityId<*>>) {
index.index(this, moduleId)
}
override fun updateLinksIndex(prev: Set<PersistentEntityId<*>>, index: WorkspaceMutableIndex<PersistentEntityId<*>>) {
// TODO verify logic
val mutablePreviousSet = HashSet(prev)
val removedItem_moduleId = mutablePreviousSet.remove(moduleId)
if (!removedItem_moduleId) {
index.index(this, moduleId)
}
for (removed in mutablePreviousSet) {
index.remove(this, removed)
}
}
override fun updateLink(oldLink: PersistentEntityId<*>, newLink: PersistentEntityId<*>): Boolean {
var changed = false
val moduleId_data = if (moduleId == oldLink) {
changed = true
newLink as ModuleId
}
else {
null
}
if (moduleId_data != null) {
moduleId = moduleId_data
}
return changed
}
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<FacetEntity> {
val modifiable = FacetEntityImpl.Builder(null)
modifiable.allowModifications {
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
modifiable.entitySource = this.entitySource
}
modifiable.changedProperty.clear()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): FacetEntity {
return getCached(snapshot) {
val entity = FacetEntityImpl(this)
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
entity
}
}
override fun persistentId(): PersistentEntityId<*> {
return FacetId(name, facetType, moduleId)
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return FacetEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return FacetEntity(name, facetType, moduleId, entitySource) {
this.configurationXmlTag = [email protected]
this.module = parents.filterIsInstance<ModuleEntity>().single()
this.underlyingFacet = parents.filterIsInstance<FacetEntity>().singleOrNull()
}
}
override fun getRequiredParents(): List<Class<out WorkspaceEntity>> {
val res = mutableListOf<Class<out WorkspaceEntity>>()
res.add(ModuleEntity::class.java)
return res
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as FacetEntityData
if (this.entitySource != other.entitySource) return false
if (this.name != other.name) return false
if (this.facetType != other.facetType) return false
if (this.configurationXmlTag != other.configurationXmlTag) return false
if (this.moduleId != other.moduleId) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as FacetEntityData
if (this.name != other.name) return false
if (this.facetType != other.facetType) return false
if (this.configurationXmlTag != other.configurationXmlTag) return false
if (this.moduleId != other.moduleId) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + name.hashCode()
result = 31 * result + facetType.hashCode()
result = 31 * result + configurationXmlTag.hashCode()
result = 31 * result + moduleId.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
result = 31 * result + name.hashCode()
result = 31 * result + facetType.hashCode()
result = 31 * result + configurationXmlTag.hashCode()
result = 31 * result + moduleId.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
collector.add(ModuleId::class.java)
collector.sameForAllEntities = true
}
}
| apache-2.0 | d22f7ea703b14319dd1507ddf915abae | 36.739558 | 154 | 0.680273 | 5.309367 | false | false | false | false |
google/intellij-community | jvm/jvm-analysis-kotlin-tests/testSrc/com/intellij/codeInspection/tests/kotlin/test/junit/KotlinJUnitMalformedDeclarationInspectionTest.kt | 2 | 46210 | package com.intellij.codeInspection.tests.kotlin.test.junit
import com.intellij.codeInspection.tests.ULanguage
import com.intellij.codeInspection.tests.test.junit.JUnitMalformedDeclarationInspectionTestBase
import com.intellij.openapi.module.Module
import com.intellij.openapi.roots.ContentEntry
import com.intellij.openapi.roots.ModifiableRootModel
import com.intellij.testFramework.LightProjectDescriptor
import com.intellij.testFramework.PsiTestUtil
import com.intellij.util.PathUtil
import java.io.File
class KotlinJUnitMalformedDeclarationInspectionTest : JUnitMalformedDeclarationInspectionTestBase() {
override fun getProjectDescriptor(): LightProjectDescriptor = object : JUnitProjectDescriptor(sdkLevel) {
override fun configureModule(module: Module, model: ModifiableRootModel, contentEntry: ContentEntry) {
super.configureModule(module, model, contentEntry)
val jar = File(PathUtil.getJarPathForClass(JvmStatic::class.java))
PsiTestUtil.addLibrary(model, "kotlin-stdlib", jar.parent, jar.name)
}
}
/* Malformed extensions */
fun `test malformed extension no highlighting`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class A {
@org.junit.jupiter.api.extension.RegisterExtension
val myRule5 = Rule5()
class Rule5 : org.junit.jupiter.api.extension.Extension { }
}
""".trimIndent())
}
fun `test malformed extension highlighting`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class A {
@org.junit.jupiter.api.extension.RegisterExtension
val <warning descr="'A.Rule5' should implement 'org.junit.jupiter.api.extension.Extension'">myRule5</warning> = Rule5()
class Rule5 { }
}
""".trimIndent())
}
/* Malformed nested class */
fun `test malformed nested no highlighting`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class A {
@org.junit.jupiter.api.Nested
inner class B { }
}
""".trimIndent())
}
fun `test malformed nested class highlighting`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class A {
@org.junit.jupiter.api.Nested
class <warning descr="Only non-static nested classes can serve as '@Nested' test classes">B</warning> { }
}
""".trimIndent())
}
/* Malformed parameterized */
fun `test malformed parameterized no highlighting`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
enum class TestEnum { FIRST, SECOND, THIRD }
class ValueSourcesTest {
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.ValueSource(ints = [1])
fun testWithIntValues(i: Int) { }
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.ValueSource(longs = [1L])
fun testWithIntValues(i: Long) { }
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.ValueSource(doubles = [0.5])
fun testWithDoubleValues(d: Double) { }
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.ValueSource(strings = [""])
fun testWithStringValues(s: String) { }
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.ValueSource(strings = ["foo"])
fun implicitParameter(argument: String, testReporter: org.junit.jupiter.api.TestInfo) { }
@org.junit.jupiter.api.extension.ExtendWith(org.junit.jupiter.api.extension.TestExecutionExceptionHandler::class)
annotation class RunnerExtension { }
@RunnerExtension
abstract class AbstractValueSource { }
class ValueSourcesWithCustomProvider : AbstractValueSource() {
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.ValueSource(ints = [1])
fun testWithIntValues(i: Int, fromExtension: String) { }
}
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.ValueSource(strings = ["FIRST"])
fun implicitConversionEnum(e: TestEnum) { }
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.ValueSource(strings = ["1"])
fun implicitConversionString(i: Int) { }
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.ValueSource(strings = ["title"])
fun implicitConversionClass(book: Book) { }
class Book(val title: String) { }
}
class MethodSource {
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.MethodSource("stream")
fun simpleStream(x: Int, y: Int) { System.out.println("${'$'}x, ${'$'}y") }
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.MethodSource("iterable")
fun simpleIterable(x: Int, y: Int) { System.out.println("${'$'}x, ${'$'}y") }
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.MethodSource(value = ["stream", "iterator", "iterable"])
fun parametersArray(x: Int, y: Int) { System.out.println("${'$'}x, ${'$'}y") }
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.MethodSource(value = ["stream", "iterator"])
fun implicitValueArray(x: Int, y: Int) { System.out.println("${'$'}x, ${'$'}y") }
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.MethodSource(value = ["argumentsArrayProvider"])
fun argumentsArray(x: Int, s: String) { System.out.println("${'$'}x, ${'$'}s") }
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.MethodSource(value = ["anyArrayProvider"])
fun anyArray(x: Int, s: String) { System.out.println("${'$'}x, ${'$'}s") }
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.MethodSource(value = ["any2DArrayProvider"])
fun any2DArray(x: Int, s: String) { System.out.println("${'$'}x, ${'$'}s") }
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.MethodSource("intStreamProvider")
fun intStream(x: Int) { System.out.println(x) }
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.MethodSource("intStreamProvider")
fun injectTestReporter(x: Int, testReporter: org.junit.jupiter.api.TestReporter) {
System.out.println("${'$'}x, ${'$'}testReporter")
}
companion object {
@JvmStatic
fun stream(): java.util.stream.Stream<org.junit.jupiter.params.provider.Arguments>? { return null }
@JvmStatic
fun iterable(): Iterable<org.junit.jupiter.params.provider.Arguments>? { return null }
@JvmStatic
fun argumentsArrayProvider(): Array<org.junit.jupiter.params.provider.Arguments> {
return arrayOf(org.junit.jupiter.params.provider.Arguments.of(1, "one"))
}
@JvmStatic
fun anyArrayProvider(): Array<Any> { return arrayOf(org.junit.jupiter.params.provider.Arguments.of(1, "one")) }
@JvmStatic
fun any2DArrayProvider(): Array<Array<Any>> { return arrayOf(arrayOf(1, "s")) }
@JvmStatic
fun intStreamProvider(): java.util.stream.IntStream? { return null }
}
}
@org.junit.jupiter.api.TestInstance(org.junit.jupiter.api.TestInstance.Lifecycle.PER_CLASS)
class TestWithMethodSource {
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.MethodSource("getParameters")
public fun shouldExecuteWithParameterizedMethodSource(arguments: String) { }
public fun getParameters(): java.util.stream.Stream<String> { return java.util.Arrays.asList( "Another execution", "Last execution").stream() }
}
class EnumSource {
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.EnumSource(names = ["FIRST"])
fun runTest(value: TestEnum) { }
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.EnumSource(
value = TestEnum::class,
names = ["regexp-value"],
mode = org.junit.jupiter.params.provider.EnumSource.Mode.MATCH_ALL
)
fun disable() { }
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.EnumSource(value = TestEnum::class, names = ["SECOND", "FIRST"/*, "commented"*/])
fun array() { }
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.EnumSource(TestEnum::class)
fun testWithEnumSourceCorrect(value: TestEnum) { }
}
class CsvSource {
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.CsvSource(value = ["src, 1"])
fun testWithCsvSource(first: String, second: Int) { }
}
class NullSource {
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.NullSource
fun testWithNullSrc(o: Any) { }
}
class EmptySource {
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.EmptySource
fun testFooSet(input: Set<String>) {}
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.EmptySource
fun testFooList(input: List<String>) {}
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.EmptySource
fun testFooMap(input: Map<String, String>) {}
}
""".trimIndent()
)
}
fun `test malformed parameterized value source wrong type`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class ValueSourcesTest {
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.ValueSource(booleans = [
<warning descr="No implicit conversion found to convert 'boolean' to 'int'">false</warning>
])
fun testWithBooleanSource(argument: Int) { }
}
""".trimIndent())
}
fun `test malformed parameterized enum source wrong type`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
enum class TestEnum { FIRST, SECOND, THIRD }
class ValueSourcesTest {
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.EnumSource(<warning descr="No implicit conversion found to convert 'TestEnum' to 'int'">TestEnum::class</warning>)
fun testWithEnumSource(i: Int) { }
}
""".trimIndent())
}
fun `test malformed parameterized multiple types`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class ValueSourcesTest {
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.<warning descr="Exactly one type of input must be provided">ValueSource</warning>(
ints = [1], strings = ["str"]
)
fun testWithMultipleValues(i: Int) { }
}
""".trimIndent())
}
fun `test malformed parameterized no value defined`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class ValueSourcesTest {
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.<warning descr="No value source is defined">ValueSource</warning>()
fun testWithNoValues(i: Int) { }
}
""".trimIndent())
}
fun `test malformed parameterized no argument defined`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class ValueSourcesTest {
@org.junit.jupiter.params.ParameterizedTest
<warning descr="'@NullSource' cannot provide an argument to method because method doesn't have parameters">@org.junit.jupiter.params.provider.NullSource</warning>
fun testWithNullSrcNoParam() {}
}
""".trimIndent())
}
fun `test method source in another class`() {
myFixture.addFileToProject("SampleTest.kt", """"
open class SampleTest {
companion object {
@kotlin.jvm.JvmStatic
fun squares() : List<org.junit.jupiter.params.provider.Arguments> {
return listOf(
org.junit.jupiter.params.provider.Arguments.of(1, 1)
)
}
}
}""".trimIndent())
myFixture.testHighlighting(ULanguage.JAVA, """
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
class MethodSourceUsage {
@ParameterizedTest
@MethodSource("SampleTest#squares")
void testSquares(int input, int expected) {}
}
""".trimIndent())
}
fun `test malformed parameterized value source multiple parameters`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class ValueSourcesTest {
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.ValueSource(strings = ["foo"])
fun <warning descr="Multiple parameters are not supported by this source">testWithMultipleParams</warning>(argument: String, i: Int) { }
}
""".trimIndent())
}
fun `test malformed parameterized and test annotation defined`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class ValueSourcesTest {
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.ValueSource(ints = [1])
@org.junit.jupiter.api.Test
fun <warning descr="Suspicious combination of '@Test' and '@ParameterizedTest'">testWithTestAnnotation</warning>(i: Int) { }
}
""".trimIndent())
}
fun `test malformed parameterized and value source defined`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class ValueSourcesTest {
@org.junit.jupiter.params.provider.ValueSource(ints = [1])
@org.junit.jupiter.api.Test
fun <warning descr="Suspicious combination of '@ValueSource' and '@Test'">testWithTestAnnotationNoParameterized</warning>(i: Int) { }
}
""".trimIndent())
}
fun `test malformed parameterized no argument source provided`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class ValueSourcesTest {
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.ArgumentsSources()
fun <warning descr="No sources are provided, the suite would be empty">emptyArgs</warning>(param: String) { }
}
""".trimIndent())
}
fun `test malformed parameterized method source should be static`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class ValueSourcesTest {
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.MethodSource("<warning descr="Method source 'a' must be static">a</warning>")
fun foo(param: String) { }
fun a(): Array<String> { return arrayOf("a", "b") }
}
""".trimIndent())
}
fun `test malformed parameterized method source should have no parameters`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class ValueSourcesTest {
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.MethodSource("<warning descr="Method source 'a' should have no parameters">a</warning>")
fun foo(param: String) { }
companion object {
@JvmStatic
fun a(i: Int): Array<String> { return arrayOf("a", i.toString()) }
}
}
""".trimIndent())
}
fun `test malformed parameterized method source wrong return type`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class ValueSourcesTest {
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.MethodSource(
"<warning descr="Method source 'a' must have one of the following return types: 'Stream<?>', 'Iterator<?>', 'Iterable<?>' or 'Object[]'">a</warning>"
)
fun foo(param: String) { }
companion object {
@JvmStatic
fun a(): Any { return arrayOf("a", "b") }
}
}
""".trimIndent())
}
fun `test malformed parameterized method source not found`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class ValueSourcesTest {
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.MethodSource("<warning descr="Cannot resolve target method source: 'a'">a</warning>")
fun foo(param: String) { }
}
""".trimIndent())
}
fun `test malformed parameterized enum source unresolvable entry`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class EnumSourceTest {
private enum class Foo { AAA, AAX, BBB }
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.EnumSource(
value = Foo::class,
names = ["<warning descr="Can't resolve 'enum' constant reference.">invalid-value</warning>"],
mode = org.junit.jupiter.params.provider.EnumSource.Mode.INCLUDE
)
fun invalid() { }
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.EnumSource(
value = Foo::class,
names = ["<warning descr="Can't resolve 'enum' constant reference.">invalid-value</warning>"]
)
fun invalidDefault() { }
}
""".trimIndent())
}
fun `test malformed parameterized add test instance quick fix`() {
myFixture.testQuickFix(ULanguage.KOTLIN, """
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.Arguments
import org.junit.jupiter.params.provider.MethodSource
import java.util.stream.Stream;
class Test {
private fun parameters(): Stream<Arguments>? { return null; }
@MethodSource("param<caret>eters")
@ParameterizedTest
fun foo(param: String) { }
}
""".trimIndent(), """
import org.junit.jupiter.api.TestInstance
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.Arguments
import org.junit.jupiter.params.provider.MethodSource
import java.util.stream.Stream;
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class Test {
private fun parameters(): Stream<Arguments>? { return null; }
@MethodSource("param<caret>eters")
@ParameterizedTest
fun foo(param: String) { }
}
""".trimIndent(), "Annotate as @TestInstance")
}
fun `test malformed parameterized introduce method source quick fix`() {
myFixture.testQuickFix(ULanguage.KOTLIN, """
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.MethodSource
class Test {
@MethodSource("para<caret>meters")
@ParameterizedTest
fun foo(param: String) { }
}
""".trimIndent(), """
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.Arguments
import org.junit.jupiter.params.provider.MethodSource
import java.util.stream.Stream
class Test {
@MethodSource("parameters")
@ParameterizedTest
fun foo(param: String) { }
companion object {
@JvmStatic
fun parameters(): Stream<Arguments> {
TODO("Not yet implemented")
}
}
}
""".trimIndent(), "Add method 'parameters' to 'Test'")
}
fun `test malformed parameterized create csv source quick fix`() {
val file = myFixture.addFileToProject("CsvFile.kt", """
class CsvFile {
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.CsvFileSource(resources = "two-<caret>column.txt")
fun testWithCsvFileSource(first: String, second: Int) { }
}
""".trimIndent())
myFixture.configureFromExistingVirtualFile(file.virtualFile)
val intention = myFixture.findSingleIntention("Create file two-column.txt")
assertNotNull(intention)
myFixture.launchAction(intention)
assertNotNull(myFixture.findFileInTempDir("two-column.txt"))
}
/* Malformed repeated test*/
fun `test malformed repeated test no highlighting`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
object WithRepeated {
@org.junit.jupiter.api.RepeatedTest(1)
fun repeatedTestNoParams() { }
@org.junit.jupiter.api.RepeatedTest(1)
fun repeatedTestWithRepetitionInfo(repetitionInfo: org.junit.jupiter.api.RepetitionInfo) { }
@org.junit.jupiter.api.BeforeEach
fun config(repetitionInfo: org.junit.jupiter.api.RepetitionInfo) { }
}
class WithRepeatedAndCustomNames {
@org.junit.jupiter.api.RepeatedTest(value = 1, name = "{displayName} {currentRepetition}/{totalRepetitions}")
fun repeatedTestWithCustomName() { }
}
class WithRepeatedAndTestInfo {
@org.junit.jupiter.api.BeforeEach
fun beforeEach(testInfo: org.junit.jupiter.api.TestInfo, repetitionInfo: org.junit.jupiter.api.RepetitionInfo) {}
@org.junit.jupiter.api.RepeatedTest(1)
fun repeatedTestWithTestInfo(testInfo: org.junit.jupiter.api.TestInfo) { }
@org.junit.jupiter.api.AfterEach
fun afterEach(testInfo: org.junit.jupiter.api.TestInfo, repetitionInfo: org.junit.jupiter.api.RepetitionInfo) {}
}
class WithRepeatedAndTestReporter {
@org.junit.jupiter.api.BeforeEach
fun beforeEach(testReporter: org.junit.jupiter.api.TestReporter, repetitionInfo: org.junit.jupiter.api.RepetitionInfo) {}
@org.junit.jupiter.api.RepeatedTest(1)
fun repeatedTestWithTestInfo(testReporter: org.junit.jupiter.api.TestReporter) { }
@org.junit.jupiter.api.AfterEach
fun afterEach(testReporter: org.junit.jupiter.api.TestReporter, repetitionInfo: org.junit.jupiter.api.RepetitionInfo) {}
}
""".trimIndent())
}
fun `test malformed repeated test combination of @Test and @RepeatedTest`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class WithRepeatedAndTests {
@org.junit.jupiter.api.Test
@org.junit.jupiter.api.RepeatedTest(1)
fun <warning descr="Suspicious combination of '@Test' and '@RepeatedTest'">repeatedTestAndTest</warning>() { }
}
""".trimIndent())
}
fun `test malformed repeated test with injected RepeatedInfo for @Test method`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class WithRepeatedInfoAndTest {
@org.junit.jupiter.api.BeforeEach
fun beforeEach(repetitionInfo: org.junit.jupiter.api.RepetitionInfo) { }
@org.junit.jupiter.api.Test
fun <warning descr="Method 'nonRepeated' annotated with '@Test' should not declare parameter 'repetitionInfo'">nonRepeated</warning>(repetitionInfo: org.junit.jupiter.api.RepetitionInfo) { }
}
""".trimIndent() )
}
fun `test malformed repeated test with injected RepetitionInfo for @BeforeAll method`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class WithBeforeEach {
companion object {
@JvmStatic
@org.junit.jupiter.api.BeforeAll
fun <warning descr="Method 'beforeAllWithRepetitionInfo' annotated with '@BeforeAll' should not declare parameter 'repetitionInfo'">beforeAllWithRepetitionInfo</warning>(repetitionInfo: org.junit.jupiter.api.RepetitionInfo) { }
}
}
""".trimIndent())
}
fun `test malformed repeated test with non-positive repetitions`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class WithRepeated {
@org.junit.jupiter.api.RepeatedTest(<warning descr="The number of repetitions must be greater than zero">-1</warning>)
fun repeatedTestNegative() { }
@org.junit.jupiter.api.RepeatedTest(<warning descr="The number of repetitions must be greater than zero">0</warning>)
fun repeatedTestBoundaryZero() { }
}
""".trimIndent())
}
/* Malformed before after */
fun `test malformed before highlighting`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class MainTest {
@org.junit.Before
fun <warning descr="Method 'before' annotated with '@Before' should be of type 'void' and not declare parameter 'i'">before</warning>(i: Int): String { return "${'$'}i" }
}
""".trimIndent())
}
fun `test malformed before each highlighting`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class MainTest {
@org.junit.jupiter.api.BeforeEach
fun <warning descr="Method 'beforeEach' annotated with '@BeforeEach' should be of type 'void' and not declare parameter 'i'">beforeEach</warning>(i: Int): String { return "" }
}
""".trimIndent())
}
fun `test malformed before each remove private quickfix`() {
myFixture.testQuickFix(ULanguage.KOTLIN, """
class MainTest {
@org.junit.jupiter.api.BeforeEach
private fun bef<caret>oreEach() { }
}
""".trimIndent(), """
import org.junit.jupiter.api.BeforeEach
class MainTest {
@BeforeEach
fun bef<caret>oreEach(): Unit { }
}
""".trimIndent(), "Fix 'beforeEach' method signature")
}
fun `test malformed before class no highlighting`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class BeforeClassStatic {
companion object {
@JvmStatic
@org.junit.BeforeClass
fun beforeClass() { }
}
}
@org.junit.jupiter.api.TestInstance(org.junit.jupiter.api.TestInstance.Lifecycle.PER_CLASS)
class BeforeAllTestInstancePerClass {
@org.junit.jupiter.api.BeforeAll
fun beforeAll() { }
}
class BeforeAllStatic {
companion object {
@JvmStatic
@org.junit.jupiter.api.BeforeAll
fun beforeAll() { }
}
}
class TestParameterResolver : org.junit.jupiter.api.extension.ParameterResolver {
override fun supportsParameter(
parameterContext: org.junit.jupiter.api.extension.ParameterContext,
extensionContext: org.junit.jupiter.api.extension.ExtensionContext
): Boolean = true
override fun resolveParameter(
parameterContext: org.junit.jupiter.api.extension.ParameterContext,
extensionContext: org.junit.jupiter.api.extension.ExtensionContext
): Any = ""
}
@org.junit.jupiter.api.extension.ExtendWith(TestParameterResolver::class)
class ParameterResolver {
companion object {
@JvmStatic
@org.junit.jupiter.api.BeforeAll
fun beforeAll(foo: String) { println(foo) }
}
}
@org.junit.jupiter.api.extension.ExtendWith(value = [TestParameterResolver::class])
class ParameterResolverArray {
companion object {
@JvmStatic
@org.junit.jupiter.api.BeforeAll
fun beforeAll(foo: String) { println(foo) }
}
}
@org.junit.jupiter.api.extension.ExtendWith(TestParameterResolver::class)
open class AbstractTest { }
class TestImplementation: AbstractTest() {
@org.junit.jupiter.api.BeforeEach
fun beforeEach(valueBox : String){ }
}
@org.junit.jupiter.api.extension.ExtendWith(TestParameterResolver::class)
annotation class CustomTestAnnotation
@CustomTestAnnotation
class MetaParameterResolver {
companion object {
@JvmStatic
@org.junit.jupiter.api.BeforeAll
fun beforeAll(foo: String) { println(foo) }
}
}
""".trimIndent())
}
fun `test malformed before class method that is non-static`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class MainTest {
@org.junit.BeforeClass
fun <warning descr="Method 'beforeClass' annotated with '@BeforeClass' should be static">beforeClass</warning>() { }
}
""".trimIndent())
}
fun `test malformed before class method that is not private`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class MainTest {
companion object {
@JvmStatic
@org.junit.BeforeClass
private fun <warning descr="Method 'beforeClass' annotated with '@BeforeClass' should be public">beforeClass</warning>() { }
}
}
""".trimIndent())
}
fun `test malformed before class method that has parameters`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class MainTest {
companion object {
@JvmStatic
@org.junit.BeforeClass
fun <warning descr="Method 'beforeClass' annotated with '@BeforeClass' should not declare parameter 'i'">beforeClass</warning>(i: Int) { System.out.println(i) }
}
}
""".trimIndent())
}
fun `test malformed before class method with a non void return type`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class MainTest {
companion object {
@JvmStatic
@org.junit.BeforeClass
fun <warning descr="Method 'beforeClass' annotated with '@BeforeClass' should be of type 'void'">beforeClass</warning>(): String { return "" }
}
}
""".trimIndent())
}
fun `test malformed before all method that is non-static`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class MainTest {
@org.junit.jupiter.api.BeforeAll
fun <warning descr="Method 'beforeAll' annotated with '@BeforeAll' should be static">beforeAll</warning>() { }
}
""".trimIndent())
}
fun `test malformed before all method that is not private`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class MainTest {
companion object {
@JvmStatic
@org.junit.jupiter.api.BeforeAll
private fun <warning descr="Method 'beforeAll' annotated with '@BeforeAll' should be public">beforeAll</warning>() { }
}
}
""".trimIndent())
}
fun `test malformed before all method that has parameters`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class MainTest {
companion object {
@JvmStatic
@org.junit.jupiter.api.BeforeAll
fun <warning descr="Method 'beforeAll' annotated with '@BeforeAll' should not declare parameter 'i'">beforeAll</warning>(i: Int) { System.out.println(i) }
}
}
""".trimIndent())
}
fun `test malformed before all method with a non void return type`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class MainTest {
companion object {
@JvmStatic
@org.junit.jupiter.api.BeforeAll
fun <warning descr="Method 'beforeAll' annotated with '@BeforeAll' should be of type 'void'">beforeAll</warning>(): String { return "" }
}
}
""".trimIndent())
}
fun `test malformed before all quickfix`() {
myFixture.testQuickFix(ULanguage.KOTLIN, """
import org.junit.jupiter.api.BeforeAll
class MainTest {
@BeforeAll
fun before<caret>All(i: Int): String { return "" }
}
""".trimIndent(), """
import org.junit.jupiter.api.BeforeAll
class MainTest {
companion object {
@JvmStatic
@BeforeAll
fun beforeAll(): Unit {
return ""
}
}
}
""".trimIndent(), "Fix 'beforeAll' method signature")
}
/* Malformed datapoint(s) */
fun `test malformed datapoint no highlighting`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class Test {
companion object {
@JvmField
@org.junit.experimental.theories.DataPoint
val f1: Any? = null
}
}
""".trimIndent())
}
fun `test malformed datapoint non-static highlighting`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class Test {
@JvmField
@org.junit.experimental.theories.DataPoint
val <warning descr="Field 'f1' annotated with '@DataPoint' should be static">f1</warning>: Any? = null
}
""".trimIndent())
}
fun `test malformed datapoint non-public highlighting`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class Test {
companion object {
@JvmStatic
@org.junit.experimental.theories.DataPoint
private val <warning descr="Field 'f1' annotated with '@DataPoint' should be public">f1</warning>: Any? = null
}
}
""".trimIndent())
}
fun `test malformed datapoint field highlighting`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class Test {
@org.junit.experimental.theories.DataPoint
private val <warning descr="Field 'f1' annotated with '@DataPoint' should be static and public">f1</warning>: Any? = null
}
""".trimIndent())
}
fun `test malformed datapoint method highlighting`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class Test {
@org.junit.experimental.theories.DataPoint
private fun <warning descr="Method 'f1' annotated with '@DataPoint' should be static and public">f1</warning>(): Any? = null
}
""".trimIndent())
}
fun `test malformed datapoints method highlighting`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class Test {
@org.junit.experimental.theories.DataPoints
private fun <warning descr="Method 'f1' annotated with '@DataPoints' should be static and public">f1</warning>(): Any? = null
}
""".trimIndent())
}
fun `test malformed datapoint make field public quickfix`() {
myFixture.testQuickFix(ULanguage.KOTLIN, """
class Test {
companion object {
@org.junit.experimental.theories.DataPoint
val f<caret>1: Any? = null
}
}
""".trimIndent(), """
class Test {
companion object {
@JvmField
@org.junit.experimental.theories.DataPoint
val f1: Any? = null
}
}
""".trimIndent(), "Fix 'f1' field signature")
}
fun `test malformed datapoint make field public and static quickfix`() {
myFixture.testQuickFix(ULanguage.KOTLIN, """
class Test {
@org.junit.experimental.theories.DataPoint
val f<caret>1: Any? = null
}
""".trimIndent(), """
class Test {
companion object {
@JvmField
@org.junit.experimental.theories.DataPoint
val f1: Any? = null
}
}
""".trimIndent(), "Fix 'f1' field signature")
}
fun `test malformed datapoint make method public and static quickfix`() {
myFixture.testQuickFix(ULanguage.KOTLIN, """
class Test {
@org.junit.experimental.theories.DataPoint
private fun f<caret>1(): Any? = null
}
""".trimIndent(), """
class Test {
companion object {
@JvmStatic
@org.junit.experimental.theories.DataPoint
fun f1(): Any? = null
}
}
""".trimIndent(), "Fix 'f1' method signature")
}
/* Malformed setup/teardown */
fun `test malformed setup no highlighting`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class C : junit.framework.TestCase() {
override fun setUp() { }
}
""".trimIndent())
}
fun `test malformed setup highlighting`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class C : junit.framework.TestCase() {
private fun <warning descr="Method 'setUp' should be a non-private, non-static, have no parameters and be of type void">setUp</warning>(i: Int) { System.out.println(i) }
}
""".trimIndent())
}
fun `test malformed setup quickfix`() {
myFixture.testQuickFix(ULanguage.KOTLIN, """
class C : junit.framework.TestCase() {
private fun set<caret>Up(i: Int) { }
}
""".trimIndent(), """
class C : junit.framework.TestCase() {
fun setUp(): Unit { }
}
""".trimIndent(), "Fix 'setUp' method signature")
}
/* Malformed rule */
fun `test malformed rule field non-public highlighting`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class SomeTestRule : org.junit.rules.TestRule {
override fun apply(base: org.junit.runners.model.Statement, description: org.junit.runner.Description): org.junit.runners.model.Statement = base
}
class PrivateRule {
@org.junit.Rule
var <warning descr="Field 'x' annotated with '@Rule' should be public">x</warning> = SomeTestRule()
}
""".trimIndent())
}
fun `test malformed rule object inherited rule highlighting`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class SomeTestRule : org.junit.rules.TestRule {
override fun apply(base: org.junit.runners.model.Statement, description: org.junit.runner.Description): org.junit.runners.model.Statement = base
}
object OtherRule : org.junit.rules.TestRule {
override fun apply(base: org.junit.runners.model.Statement, description: org.junit.runner.Description): org.junit.runners.model.Statement = base
}
object ObjRule {
@org.junit.Rule
private var <warning descr="Field 'x' annotated with '@Rule' should be non-static and public">x</warning> = SomeTestRule()
}
class ClazzRule {
@org.junit.Rule
fun x() = OtherRule
@org.junit.Rule
fun <warning descr="Method 'y' annotated with '@Rule' should be of type 'org.junit.rules.TestRule'">y</warning>() = 0
@org.junit.Rule
public fun z() = object : org.junit.rules.TestRule {
override fun apply(base: org.junit.runners.model.Statement, description: org.junit.runner.Description): org.junit.runners.model.Statement = base
}
@org.junit.Rule
public fun <warning descr="Method 'a' annotated with '@Rule' should be of type 'org.junit.rules.TestRule'">a</warning>() = object { }
}
""".trimIndent())
}
fun `test malformed rule method static highlighting`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class SomeTestRule : org.junit.rules.TestRule {
override fun apply(base: org.junit.runners.model.Statement, description: org.junit.runner.Description): org.junit.runners.model.Statement = base
}
class PrivateRule {
@org.junit.Rule
private fun <warning descr="Method 'x' annotated with '@Rule' should be public">x</warning>() = SomeTestRule()
}
""".trimIndent())
}
fun `test malformed rule method non TestRule type highlighting`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class PrivateRule {
@org.junit.Rule
fun <warning descr="Method 'x' annotated with '@Rule' should be of type 'org.junit.rules.TestRule'">x</warning>() = 0
}
""".trimIndent())
}
fun `test malformed class rule field highlighting`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class SomeTestRule : org.junit.rules.TestRule {
override fun apply(base: org.junit.runners.model.Statement, description: org.junit.runner.Description): org.junit.runners.model.Statement = base
}
object PrivateClassRule {
@org.junit.ClassRule
private var <warning descr="Field 'x' annotated with '@ClassRule' should be public">x</warning> = SomeTestRule()
@org.junit.ClassRule
private var <warning descr="Field 'y' annotated with '@ClassRule' should be public and be of type 'org.junit.rules.TestRule'">y</warning> = 0
}
""".trimIndent())
}
fun `test malformed rule make field public quickfix`() {
myFixture.testQuickFix(ULanguage.KOTLIN, """
class PrivateRule {
@org.junit.Rule
var x<caret> = 0
}
""".trimIndent(), """
class PrivateRule {
@JvmField
@org.junit.Rule
var x = 0
}
""".trimIndent(), "Fix 'x' field signature")
}
fun `test malformed class rule make field public quickfix`() {
myFixture.testQuickFix(ULanguage.KOTLIN, """
class SomeTestRule : org.junit.rules.TestRule {
override fun apply(base: org.junit.runners.model.Statement, description: org.junit.runner.Description): org.junit.runners.model.Statement = base
}
object PrivateClassRule {
@org.junit.ClassRule
private var x<caret> = SomeTestRule()
}
""".trimIndent(), """
class SomeTestRule : org.junit.rules.TestRule {
override fun apply(base: org.junit.runners.model.Statement, description: org.junit.runner.Description): org.junit.runners.model.Statement = base
}
object PrivateClassRule {
@JvmField
@org.junit.ClassRule
var x = SomeTestRule()
}
""".trimIndent(), "Fix 'x' field signature")
}
/* Malformed test */
fun `test malformed test for JUnit 3 highlighting`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
public class JUnit3TestMethodIsPublicVoidNoArg : junit.framework.TestCase() {
fun testOne() { }
public fun <warning descr="Method 'testTwo' should be a public, non-static, have no parameters and be of type void">testTwo</warning>(): Int { return 2 }
public fun <warning descr="Method 'testFour' should be a public, non-static, have no parameters and be of type void">testFour</warning>(i: Int) { println(i) }
public fun testFive() { }
private fun testSix(i: Int) { println(i) } //ignore when method doesn't look like test anymore
companion object {
@JvmStatic
public fun <warning descr="Method 'testThree' should be a public, non-static, have no parameters and be of type void">testThree</warning>() { }
}
}
""".trimIndent())
}
fun `test malformed test for JUnit 4 highlighting`() {
myFixture.addClass("""
package mockit;
public @interface Mocked { }
""".trimIndent())
myFixture.testHighlighting(ULanguage.KOTLIN, """
public class JUnit4TestMethodIsPublicVoidNoArg {
@org.junit.Test fun testOne() { }
@org.junit.Test public fun <warning descr="Method 'testTwo' annotated with '@Test' should be of type 'void'">testTwo</warning>(): Int { return 2 }
@org.junit.Test public fun <warning descr="Method 'testFour' annotated with '@Test' should not declare parameter 'i'">testFour</warning>(i: Int) { }
@org.junit.Test public fun testFive() { }
@org.junit.Test public fun testMock(@mockit.Mocked s: String) { }
companion object {
@JvmStatic
@org.junit.Test public fun <warning descr="Method 'testThree' annotated with '@Test' should be non-static">testThree</warning>() { }
}
}
""".trimIndent())
}
fun `test malformed test for JUnit 4 runWith highlighting`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
@org.junit.runner.RunWith(org.junit.runner.Runner::class)
class JUnit4RunWith {
@org.junit.Test public fun <warning descr="Method 'testMe' annotated with '@Test' should be of type 'void' and not declare parameter 'i'">testMe</warning>(i: Int): Int { return -1 }
}
""".trimIndent())
}
/* Malformed suite */
fun `test malformed suite no highlighting`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class Junit3Suite : junit.framework.TestCase() {
companion object {
@JvmStatic
fun suite() = junit.framework.TestSuite()
}
}
""".trimIndent())
}
fun `test malformed suite highlighting`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class Junit3Suite : junit.framework.TestCase() {
fun <warning descr="Method 'suite' should be a non-private, static and have no parameters">suite</warning>() = junit.framework.TestSuite()
}
""".trimIndent())
}
fun `test malformed suite quickfix`() {
myFixture.testQuickFix(ULanguage.KOTLIN, """
class Junit3Suite : junit.framework.TestCase() {
fun sui<caret>te() = junit.framework.TestSuite()
}
""".trimIndent(), """
class Junit3Suite : junit.framework.TestCase() {
companion object {
@JvmStatic
fun suite() = junit.framework.TestSuite()
}
}
""".trimIndent(), "Fix 'suite' method signature")
}
/* Suspending test function */
fun `test malformed suspending test JUnit 3 function`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class JUnit3Test : junit.framework.TestCase() {
suspend fun <warning descr="Method 'testFoo' should not be a suspending function">testFoo</warning>() { }
}
""".trimIndent())
}
fun `test malformed suspending test JUnit 4 function`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class JUnit4Test {
@org.junit.Test
suspend fun <warning descr="Method 'testFoo' annotated with '@Test' should not be a suspending function">testFoo</warning>() { }
}
""".trimIndent())
}
fun `test malformed suspending test JUnit 5 function`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class JUnit5Test {
@org.junit.jupiter.api.Test
suspend fun <warning descr="Method 'testFoo' annotated with '@Test' should not be a suspending function">testFoo</warning>() { }
}
""".trimIndent())
}
} | apache-2.0 | f586894798c27ea5b558d833ac99affd | 39.288579 | 237 | 0.640338 | 4.616384 | false | true | false | false |
JetBrains/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/declarations/ConvertMemberToExtensionIntention.kt | 1 | 15403 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.intentions.declarations
import com.intellij.codeInsight.FileModificationService
import com.intellij.codeInsight.intention.LowPriorityAction
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.ScrollType
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiMethodCallExpression
import com.intellij.psi.PsiReferenceExpression
import com.intellij.psi.PsiWhiteSpace
import com.intellij.psi.codeStyle.JavaCodeStyleManager
import com.intellij.psi.search.searches.ReferencesSearch
import com.intellij.util.SmartList
import org.jetbrains.kotlin.asJava.toLightMethods
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingRangeIntention
import org.jetbrains.kotlin.idea.core.*
import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.getReturnTypeReference
import org.jetbrains.kotlin.idea.references.KtReference
import org.jetbrains.kotlin.idea.util.*
import org.jetbrains.kotlin.idea.util.application.isUnitTestMode
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.*
import org.jetbrains.kotlin.types.Variance
import org.jetbrains.kotlin.utils.addIfNotNull
private val LOG = Logger.getInstance(ConvertMemberToExtensionIntention::class.java)
class ConvertMemberToExtensionIntention : SelfTargetingRangeIntention<KtCallableDeclaration>(
KtCallableDeclaration::class.java,
KotlinBundle.lazyMessage("convert.member.to.extension")
), LowPriorityAction {
private fun isApplicable(element: KtCallableDeclaration): Boolean {
val classBody = element.parent as? KtClassBody ?: return false
if (classBody.parent !is KtClass) return false
if (element.receiverTypeReference != null) return false
if (element.hasModifier(KtTokens.OVERRIDE_KEYWORD)) return false
when (element) {
is KtProperty -> if (element.hasInitializer() || element.hasDelegate()) return false
is KtSecondaryConstructor -> return false
}
return true
}
override fun applicabilityRange(element: KtCallableDeclaration): TextRange? {
if (!element.withExpectedActuals().all { it is KtCallableDeclaration && isApplicable(it) }) return null
return (element.nameIdentifier ?: return null).textRange
}
override fun startInWriteAction() = false
//TODO: local class
override fun applyTo(element: KtCallableDeclaration, editor: Editor?) {
if (!FileModificationService.getInstance().preparePsiElementForWrite(element)) return
var allowExpected = true
element.liftToExpected()?.actualsForExpected()?.let {
if (it.isEmpty()) {
allowExpected = askIfExpectedIsAllowed(element.containingKtFile)
}
}
val (extension, bodyTypeToSelect) = createExtensionCallableAndPrepareBodyToSelect(element, allowExpected)
runWriteAction {
editor?.apply {
unblockDocument()
if (extension.isValid) {
if (bodyTypeToSelect != GeneratedBodyType.NOTHING) {
val bodyToSelect = getBodyForSelection(extension, bodyTypeToSelect)
if (bodyToSelect != null) {
val range = bodyToSelect.textRange
moveCaret(range.startOffset, ScrollType.CENTER)
val parent = bodyToSelect.parent
val lastSibling =
if (parent is KtBlockExpression)
parent.rBrace?.siblings(forward = false, withItself = false)?.first { it !is PsiWhiteSpace }
else
bodyToSelect.siblings(forward = true, withItself = false).lastOrNull()
val endOffset = lastSibling?.endOffset ?: range.endOffset
selectionModel.setSelection(range.startOffset, endOffset)
} else {
LOG.error("Extension created with new method body but this body was not found after document commit. Extension text: \"${extension.text}\"")
moveCaret(extension.textOffset, ScrollType.CENTER)
}
} else {
moveCaret(extension.textOffset, ScrollType.CENTER)
}
} else {
LOG.error("Extension invalidated during document commit. Extension text \"${extension.text}\"")
}
}
}
}
private fun getBodyForSelection(extension: KtCallableDeclaration, bodyTypeToSelect: GeneratedBodyType): KtExpression? {
fun selectBody(declaration: KtDeclarationWithBody): KtExpression? {
if (!declaration.hasBody()) return extension
return declaration.bodyExpression?.let {
(it as? KtBlockExpression)?.statements?.singleOrNull() ?: it
}
}
return when (bodyTypeToSelect) {
GeneratedBodyType.FUNCTION -> (extension as? KtFunction)?.let { selectBody(it) }
GeneratedBodyType.GETTER -> (extension as? KtProperty)?.getter?.let { selectBody(it) }
GeneratedBodyType.SETTER -> (extension as? KtProperty)?.setter?.let { selectBody(it) }
else -> null
}
}
private enum class GeneratedBodyType {
NOTHING,
FUNCTION,
SETTER,
GETTER
}
private fun processSingleDeclaration(
element: KtCallableDeclaration,
allowExpected: Boolean
): Pair<KtCallableDeclaration, GeneratedBodyType> {
val descriptor = element.unsafeResolveToDescriptor()
val containingClass = descriptor.containingDeclaration as ClassDescriptor
val isEffectivelyExpected = allowExpected && element.isExpectDeclaration()
val file = element.containingKtFile
val project = file.project
val outermostParent = KtPsiUtil.getOutermostParent(element, file, false)
val ktFilesToAddImports = LinkedHashSet<KtFile>()
val javaCallsToFix = SmartList<PsiMethodCallExpression>()
for (ref in ReferencesSearch.search(element)) {
when (ref) {
is KtReference -> {
val refFile = ref.element.containingKtFile
if (refFile != file) {
ktFilesToAddImports.add(refFile)
}
}
is PsiReferenceExpression -> javaCallsToFix.addIfNotNull(ref.parent as? PsiMethodCallExpression)
}
}
val typeParameterList = newTypeParameterList(element)
val psiFactory = KtPsiFactory(project)
val (extension, bodyTypeToSelect) =
runWriteAction {
val extension = file.addAfter(element, outermostParent) as KtCallableDeclaration
file.addAfter(psiFactory.createNewLine(), outermostParent)
file.addAfter(psiFactory.createNewLine(), outermostParent)
element.delete()
extension.setReceiverType(containingClass.defaultType)
if (typeParameterList != null) {
if (extension.typeParameterList != null) {
extension.typeParameterList!!.replace(typeParameterList)
} else {
extension.addBefore(typeParameterList, extension.receiverTypeReference)
extension.addBefore(psiFactory.createWhiteSpace(), extension.receiverTypeReference)
}
}
extension.modifierList?.getModifier(KtTokens.PROTECTED_KEYWORD)?.delete()
extension.modifierList?.getModifier(KtTokens.ABSTRACT_KEYWORD)?.delete()
extension.modifierList?.getModifier(KtTokens.OPEN_KEYWORD)?.delete()
extension.modifierList?.getModifier(KtTokens.FINAL_KEYWORD)?.delete()
if (isEffectivelyExpected && !extension.hasExpectModifier()) {
extension.addModifier(KtTokens.EXPECT_KEYWORD)
}
var bodyTypeToSelect = GeneratedBodyType.NOTHING
val bodyText = getFunctionBodyTextFromTemplate(
project,
if (extension is KtFunction) TemplateKind.FUNCTION else TemplateKind.PROPERTY_INITIALIZER,
extension.name,
extension.getReturnTypeReference()?.text ?: "Unit",
extension.containingClassOrObject?.fqName
)
when (extension) {
is KtFunction -> {
if (!extension.hasBody() && !isEffectivelyExpected) {
//TODO: methods in PSI for setBody
extension.add(psiFactory.createBlock(bodyText))
bodyTypeToSelect = GeneratedBodyType.FUNCTION
}
}
is KtProperty -> {
val templateProperty =
psiFactory.createDeclaration<KtProperty>("var v: Any\nget()=$bodyText\nset(value){\n$bodyText\n}")
if (!isEffectivelyExpected) {
val templateGetter = templateProperty.getter!!
val templateSetter = templateProperty.setter!!
var getter = extension.getter
if (getter == null) {
getter = extension.addAfter(templateGetter, extension.typeReference) as KtPropertyAccessor
extension.addBefore(psiFactory.createNewLine(), getter)
bodyTypeToSelect = GeneratedBodyType.GETTER
} else if (!getter.hasBody()) {
getter = getter.replace(templateGetter) as KtPropertyAccessor
bodyTypeToSelect = GeneratedBodyType.GETTER
}
if (extension.isVar) {
var setter = extension.setter
if (setter == null) {
setter = extension.addAfter(templateSetter, getter) as KtPropertyAccessor
extension.addBefore(psiFactory.createNewLine(), setter)
if (bodyTypeToSelect == GeneratedBodyType.NOTHING) {
bodyTypeToSelect = GeneratedBodyType.SETTER
}
} else if (!setter.hasBody()) {
setter.replace(templateSetter) as KtPropertyAccessor
if (bodyTypeToSelect == GeneratedBodyType.NOTHING) {
bodyTypeToSelect = GeneratedBodyType.SETTER
}
}
}
}
}
}
extension to bodyTypeToSelect
}
if (ktFilesToAddImports.isNotEmpty()) {
val newDescriptor = extension.unsafeResolveToDescriptor()
val importInsertHelper = ImportInsertHelper.getInstance(project)
for (ktFileToAddImport in ktFilesToAddImports) {
importInsertHelper.importDescriptor(ktFileToAddImport, newDescriptor)
}
}
if (javaCallsToFix.isNotEmpty()) {
val lightMethod = extension.toLightMethods().first()
for (javaCallToFix in javaCallsToFix) {
javaCallToFix.methodExpression.qualifierExpression?.let {
val argumentList = javaCallToFix.argumentList
argumentList.addBefore(it, argumentList.expressions.firstOrNull())
}
val newRef = javaCallToFix.methodExpression.bindToElement(lightMethod)
JavaCodeStyleManager.getInstance(project).shortenClassReferences(newRef)
}
}
return extension to bodyTypeToSelect
}
private fun askIfExpectedIsAllowed(file: KtFile): Boolean {
if (isUnitTestMode()) {
return file.allChildren.any { it is PsiComment && it.text.trim() == "// ALLOW_EXPECT_WITHOUT_ACTUAL" }
}
return Messages.showYesNoDialog(
KotlinBundle.message("do.you.want.to.make.new.extension.an.expected.declaration"),
text,
Messages.getQuestionIcon()
) == Messages.YES
}
private fun createExtensionCallableAndPrepareBodyToSelect(
element: KtCallableDeclaration,
allowExpected: Boolean = true
): Pair<KtCallableDeclaration, GeneratedBodyType> {
val expectedDeclaration = element.liftToExpected() as? KtCallableDeclaration
if (expectedDeclaration != null) {
element.withExpectedActuals().filterIsInstance<KtCallableDeclaration>().forEach {
if (it != element) {
processSingleDeclaration(it, allowExpected)
}
}
}
val classVisibility = element.containingClass()?.visibilityModifierType()
val (extension, bodyTypeToSelect) = processSingleDeclaration(element, allowExpected)
if (classVisibility != null && extension.visibilityModifier() == null) {
runWriteAction {
extension.addModifier(classVisibility)
}
}
return extension to bodyTypeToSelect
}
private fun newTypeParameterList(member: KtCallableDeclaration): KtTypeParameterList? {
val classElement = member.parent.parent as KtClass
val classParams = classElement.typeParameters
if (classParams.isEmpty()) return null
val allTypeParameters = classParams + member.typeParameters
val text = allTypeParameters.joinToString(",", "<", ">") { it.textWithoutVariance() }
return KtPsiFactory(member.project).createDeclaration<KtFunction>("fun $text foo()").typeParameterList
}
private fun KtTypeParameter.textWithoutVariance(): String {
if (variance == Variance.INVARIANT) return text
val copied = this.copy() as KtTypeParameter
copied.modifierList?.getModifier(KtTokens.OUT_KEYWORD)?.delete()
copied.modifierList?.getModifier(KtTokens.IN_KEYWORD)?.delete()
return copied.text
}
companion object {
fun convert(element: KtCallableDeclaration): KtCallableDeclaration =
ConvertMemberToExtensionIntention().createExtensionCallableAndPrepareBodyToSelect(element).first
}
} | apache-2.0 | 70fe5eb4727c68b24635200ddcda69bf | 45.11976 | 168 | 0.614945 | 6.195897 | false | false | false | false |
square/okhttp | okhttp/src/jvmMain/kotlin/okhttp3/internal/connection/FailedPlan.kt | 2 | 1535 | /*
* Copyright (C) 2022 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp3.internal.connection
/**
* Used when we were unsuccessful in the planning phase of a connection:
*
* * A DNS lookup failed
* * The configuration is incapable of carrying the request, such as when the client is configured
* to use `H2_PRIOR_KNOWLEDGE` but the URL's scheme is `https:`.
* * Preemptive proxy authentication failed.
*
* Planning failures are not necessarily fatal. For example, even if we can't DNS lookup the first
* proxy in a list, looking up a subsequent one may succeed.
*/
internal class FailedPlan(e: Throwable) : RoutePlanner.Plan {
val result = RoutePlanner.ConnectResult(plan = this, throwable = e)
override val isReady = false
override fun connectTcp() = result
override fun connectTlsEtc() = result
override fun handleSuccess() = error("unexpected call")
override fun cancel() = error("unexpected cancel")
override fun retry() = error("unexpected retry")
}
| apache-2.0 | 9ef457c5734e59def43489272eae466e | 34.697674 | 99 | 0.730293 | 4.137466 | false | false | false | false |
chrislo27/RhythmHeavenRemixEditor2 | desktop/src/main/kotlin/io/github/chrislo27/rhre3/desktop/Arguments.kt | 2 | 3866 | package io.github.chrislo27.rhre3.desktop
import com.beust.jcommander.Parameter
class Arguments {
@Parameter(names = ["--help", "-h", "-?"], description = "Prints this usage menu.", help = true)
var printHelp: Boolean = false
// -----------------------------------------------------------
@Parameter(names = ["--force-lazy-sound-load"], description = "Forces lazy-loaded sounds to be loaded when initialized.")
var lazySoundsForceLoad: Boolean = false
@Parameter(names = ["--fps"], description = "Manually sets the target FPS. Will always be at least 30.")
var fps: Int = 60
@Parameter(names = ["--log-missing-localizations"], description = "Logs any missing localizations. Other locales are checked against the default properties file.")
var logMissingLocalizations: Boolean = false
@Parameter(names = ["--skip-git"], description = "Skips checking the online Git repository for the SFX Database completely. This is overridden by --force-git-check.")
var skipGit: Boolean = false
@Parameter(names = ["--force-git-fetch"], description = "Forces a fetch for the online Git repository for the SFX Database.")
var forceGitFetch: Boolean = false
@Parameter(names = ["--force-git-check"], description = "Forces checking the online Git repository for the SFX Database.")
var forceGitCheck: Boolean = false
@Parameter(names = ["--verify-sfxdb"], description = "Verifies and reports warnings/errors for the entire SFX Database after loading.")
var verifySfxdb: Boolean = false
@Parameter(names = ["--no-analytics"], description = "Disables sending of analytics and crash reports.")
var noAnalytics: Boolean = false
@Parameter(names = ["--no-online-counter"], description = "Disables the online user count feature.")
var noOnlineCounter: Boolean = false
@Parameter(names = ["--output-generated-datamodels"], description = "Writes out games that are generated internally in JSON format to console on start-up.")
var outputGeneratedDatamodels: Boolean = false
@Parameter(names = ["--output-custom-sfx"], description = "Writes out custom SFX that don't have data.json (i.e.: just sound files in a folder) in JSON format to console on start-up.")
var outputCustomSfx: Boolean = false
@Parameter(names = ["--show-tapalong-markers"], description = "Shows tapalong tap markers by default.")
var showTapalongMarkers: Boolean = false
@Parameter(names = ["--midi-recording"], description = "Enables MIDI recording, a hidden feature. Using a MIDI device while the remix is playing will write notes to the remix.")
var midiRecording: Boolean = false
@Parameter(names = ["--portable-mode"], description = "Puts the `.rhre3/` folder and preferences locally next to the RHRE.jar file.")
var portableMode: Boolean = false
@Parameter(names = ["--disable-custom-sounds"], description = "Disables loading of custom sounds.")
var disableCustomSounds: Boolean = false
@Parameter(names = ["--trigger-update-screen"], description = "Triggers the \"new version available\" screen on startup. Requires that the latest version be known, however.")
var triggerUpdateScreen: Boolean = false
// -----------------------------------------------------------
@Parameter(names = ["--immmediate-anniversary"], hidden = true)
var eventImmediateAnniversary: Boolean = false
@Parameter(names = ["--immmediate-anniversary-like-new"], hidden = true)
var eventImmediateAnniversaryLikeNew: Boolean = false
@Parameter(names = ["--immmediate-xmas"], hidden = true)
var eventImmediateXmas: Boolean = false
// -----------------------------------------------------------
@Parameter(names = ["--lc"], hidden = true)
var lc: String? = null
} | gpl-3.0 | 7f4306378b836736e189bd02e9d6f55a | 51.972603 | 188 | 0.658303 | 4.703163 | false | false | false | false |
NeatoRobotics/neato-sdk-android | Neato-SDK/neato-sdk-android/src/main/java/com/neatorobotics/sdk/android/robotservices/scheduling/SchedulingAdvanced2Service.kt | 1 | 3555 | /*
* Copyright (c) 2019.
* Neato Robotics Inc.
*/
package com.neatorobotics.sdk.android.robotservices.scheduling
import android.util.Log
import com.neatorobotics.sdk.android.clients.Resource
import com.neatorobotics.sdk.android.clients.nucleo.Nucleo
import com.neatorobotics.sdk.android.clients.nucleo.json.NucleoJSONParser
import com.neatorobotics.sdk.android.models.Robot
import com.neatorobotics.sdk.android.models.RobotSchedule
import com.neatorobotics.sdk.android.models.ScheduleEvent
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import java.util.ArrayList
class SchedulingAdvanced2Service : SchedulingService() {
override val cleaningModeSupported: Boolean
get() = true
override val singleZoneSupported: Boolean
get() = false
override val multipleZoneSupported: Boolean
get() = true
override suspend fun getSchedule(robot: Robot): Resource<RobotSchedule> {
val result = nucleoRepository.executeCommand(robot, JSONObject(Nucleo.GET_ROBOT_SCHEDULE_COMMAND))
return when(result.status) {
Resource.Status.SUCCESS -> Resource.success(NucleoJSONParser.parseSchedule(result.data))
else -> Resource.error(result.code, result.message)
}
}
override suspend fun setSchedule(robot: Robot, schedule: RobotSchedule): Resource<Boolean> {
val command = Nucleo.SET_SCHEDULE_COMMAND.replace("EVENTS_PLACEHOLDER", "events:" + convertEventsToJSON(schedule.events, true))
val result = nucleoRepository.executeCommand(robot, JSONObject(command))
return when(result.status) {
Resource.Status.SUCCESS -> Resource.success(true)
else -> Resource.error(result.code, result.message)
}
}
private fun convertEventsToJSON(events: ArrayList<ScheduleEvent>, toSendToTheRobot: Boolean): String {
val array = JSONArray()
for (i in events.indices) {
array.put(convertEventToJSON(events[i], toSendToTheRobot))
}
return array.toString()
}
fun convertEventToJSON(event: ScheduleEvent, toSendToTheRobot: Boolean = false): JSONObject? {
val json = JSONObject()
try {
json.put("mode", event.mode.value)
json.put("day", event.day)
json.put("startTime", event.startTime)
if (toSendToTheRobot) {
if (event.boundaryIds?.size != null && event.boundaryIds?.size!! > 0) {
val ids = JSONArray()
for(b in event.boundaryIds!!) ids.put(b)
json.put("boundaryIds", ids)
}
} else {
if (event.boundaryIds?.size != null && event.boundaryIds?.size!! > 0) {
val boundaries = JSONArray()
for((id, name) in event.boundaryIds!!.zip(event.boundaryNames!!)) {
val b = JSONObject().apply {
put("id", id)
put("name", name)
}
boundaries.put(b)
}
json.put("boundaries", boundaries)
}
if (!event.mapId.isNullOrEmpty()) {
json.put("mapId", event.mapId)
}
}
} catch (e: JSONException) {
Log.e(TAG, "Exception", e)
return null
}
return json
}
companion object {
private const val TAG = "SchedulingAdv2Service"
}
}
| mit | 58e89f55b3ee80fc536047727e3c7ee1 | 35.27551 | 135 | 0.607032 | 4.551857 | false | false | false | false |
BrianErikson/PushLocal-Desktop | src/main/PushLocal.kt | 1 | 4150 | package main
import common.OsUtils
import javafx.application.Application
import javafx.application.Platform
import javafx.beans.property.SimpleStringProperty
import javafx.collections.FXCollections
import javafx.collections.ObservableList
import javafx.fxml.FXMLLoader
import javafx.scene.Node
import javafx.stage.Stage
import network.client.NetClient
import ui.StageController
import ui.debugmenu.DebugMenu
import ui.notification.NotificationController
import java.awt.*
import java.io.IOException
import java.util.ArrayList
/**
* Created by brian on 8/29/15.
*/
class PushLocal : Application() {
var trayIcon: TrayIcon? = null
val icon: Image = Toolkit.getDefaultToolkit().getImage(javaClass.getResource("/PL.png"))
private val filteredNotifications: ObservableList<String> = FXCollections.observableArrayList<String>()
private val stageController: StageController = StageController()
private val notificationNodes: ArrayList<Node> = ArrayList()
private val logger = SimpleStringProperty("Application initializing...")
private var netClient: NetClient? = null
init {
singleton = this;
}
@Throws(Exception::class)
override fun start(primaryStage: Stage) {
addToSystemTray()
primaryStage.close() // Get rid of useless init stage
stageController.stage = DebugMenu(filteredNotifications, logger, 1024, 768, notificationNodes)
stageController.stage?.icons?.add(javafx.scene.image.Image("PL.png"))
stageController.showStage()
log("Application initialized")
if (trayIcon != null)
trayIcon!!.addActionListener { e -> Platform.runLater { stageController.showStage() } }
netClient = NetClient(this)
netClient!!.isDaemon = true
netClient!!.start()
postNotification("PushLocal.Desktop", "Test", "First Line", "Second Line")
}
private fun addToSystemTray() {
if (SystemTray.isSupported()) {
val systemTray = SystemTray.getSystemTray()
trayIcon = TrayIcon(icon, "Push Local")
trayIcon!!.isImageAutoSize = true
try {
systemTray.add(trayIcon)
} catch (e: AWTException) {
log(e.message as String)
}
}
}
@Synchronized fun log(text: String) {
Platform.runLater { logger.value = logger.valueSafe + "\n" + text }
}
// main & TCP thread
@Synchronized @Throws(IOException::class)
fun postNotification(origin: String, title: String, text: String, subText: String) {
var filtered = false
for (s in filteredNotifications) {
if (s.contains(origin))
filtered = true
}
if (!filtered) {
OsUtils.postNotification(title, text, subText)
var loader: FXMLLoader = FXMLLoader(javaClass.getResource("/notification.fxml"))
val notification = loader.load<Node>()
val controller = loader.getController<NotificationController>()
controller.origin = origin
controller.setTitle(title)
controller.setText(text)
controller.setSubText(if (subText.contains("null")) "" else subText)
notificationNodes.add(notification)
if (stageController.stage is DebugMenu) {
println("Is intance of debugMenu")
Platform.runLater { (stageController.stage as DebugMenu).addNotification(notification) }
}
}
}
fun addFilteredNotification(origin: String) {
filteredNotifications.add(origin)
}
@Throws(Exception::class)
override fun stop() {
super.stop()
netClient?.dispose()
if (trayIcon != null)
SystemTray.getSystemTray().remove(trayIcon)
}
companion object {
var singleton : PushLocal? = null
get() {
return field
}
set(value) {
if (singleton == null) {
field = value
}
}
@JvmStatic fun main(args: Array<String>) {
launch(PushLocal::class.java)
}
}
}
| apache-2.0 | a15ae12def3fac2fc934217cf648fc20 | 31.170543 | 107 | 0.637349 | 4.797688 | false | false | false | false |
allotria/intellij-community | plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/worktree/WorkspaceModuleImporter.kt | 2 | 8560 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.idea.maven.importing.worktree
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.workspaceModel.ide.getInstance
import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager
import com.intellij.workspaceModel.storage.WorkspaceEntityStorageBuilder
import com.intellij.workspaceModel.storage.bridgeEntities.*
import org.jetbrains.idea.maven.importing.MavenFoldersImporter
import org.jetbrains.idea.maven.importing.MavenModelUtil
import org.jetbrains.idea.maven.model.MavenArtifact
import org.jetbrains.idea.maven.model.MavenConstants
import org.jetbrains.idea.maven.project.MavenProject
import org.jetbrains.idea.maven.project.MavenProjectsManager
import org.jetbrains.idea.maven.project.MavenProjectsTree
import org.jetbrains.idea.maven.project.SupportedRequestType
import org.jetbrains.jps.model.java.JavaResourceRootType
import org.jetbrains.jps.model.java.JavaSourceRootType
import org.jetbrains.jps.model.serialization.JpsModelSerializerExtension
import org.jetbrains.jps.model.serialization.module.JpsModuleSourceRootPropertiesSerializer
class WorkspaceModuleImporter(private val project: Project,
private val mavenProject: MavenProject,
private val projectsTree: MavenProjectsTree,
private val diff: WorkspaceEntityStorageBuilder) {
private val virtualFileManager: VirtualFileUrlManager = VirtualFileUrlManager.getInstance(project)
private lateinit var moduleEntity: ModuleEntity
fun importModule() {
val dependencies = collectDependencies();
moduleEntity = diff.addModuleEntity(mavenProject.displayName, dependencies, MavenExternalSource.INSTANCE)
val contentRootEntity = diff.addContentRootEntity(virtualFileManager.fromPath(mavenProject.directory), emptyList(), emptyList(),
moduleEntity)
importFolders(contentRootEntity)
importLanguageLevel();
}
private fun importLanguageLevel() {
}
private fun collectDependencies(): List<ModuleDependencyItem> {
val dependencyTypes = MavenProjectsManager.getInstance(project).importingSettings.dependencyTypesAsSet;
dependencyTypes.addAll(mavenProject.getDependencyTypesFromImporters(SupportedRequestType.FOR_IMPORT))
return listOf(ModuleDependencyItem.ModuleSourceDependency,
ModuleDependencyItem.InheritedSdkDependency) +
mavenProject.dependencies.filter { dependencyTypes.contains(it.type) }.mapNotNull(this::createDependency)
}
private fun createDependency(artifact: MavenArtifact): ModuleDependencyItem? {
val depProject = projectsTree.findProject(artifact.mavenId)
if (depProject == null) {
if (artifact.scope == "system") {
return createSystemDependency(artifact)
}
if (artifact.type == "bundle") {
return addBundleDependency(artifact)
}
return createLibraryDependency(artifact)
}
if (depProject === mavenProject) {
return null
}
if (projectsTree.isIgnored(depProject)) {
TODO()
}
return createModuleDependency(artifact, depProject)
}
private fun addBundleDependency(artifact: MavenArtifact): ModuleDependencyItem? {
val newArtifact = MavenArtifact(
artifact.groupId,
artifact.artifactId,
artifact.version,
artifact.baseVersion,
"jar",
artifact.classifier,
artifact.scope,
artifact.isOptional,
"jar",
null,
mavenProject.getLocalRepository(),
false, false
);
return createLibraryDependency(newArtifact);
}
private fun createSystemDependency(artifact: MavenArtifact): ModuleDependencyItem.Exportable.LibraryDependency {
assert(MavenConstants.SCOPE_SYSTEM == artifact.scope)
val roots = ArrayList<LibraryRoot>()
roots.add(LibraryRoot(virtualFileManager.fromUrl(MavenModelUtil.getArtifactUrlForClassifierAndExtension(artifact, null, null)),
LibraryRootTypeId.COMPILED))
val libraryTableId = LibraryTableId.ModuleLibraryTableId(moduleId = ModuleId(mavenProject.displayName)); //(ModuleId(moduleEntity.name))
diff.addLibraryEntity(artifact.libraryName, libraryTableId,
roots,
emptyList(), MavenExternalSource.INSTANCE)
return ModuleDependencyItem.Exportable.LibraryDependency(LibraryId(artifact.libraryName, libraryTableId), false,
toEntityScope(artifact.scope))
}
private fun createModuleDependency(artifact: MavenArtifact, depProject: MavenProject): ModuleDependencyItem {
val isTestJar = MavenConstants.TYPE_TEST_JAR == artifact.type || "tests" == artifact.classifier
return ModuleDependencyItem.Exportable.ModuleDependency(ModuleId(depProject.displayName), false,
toEntityScope(artifact.scope), isTestJar)
}
private fun createLibraryDependency(artifact: MavenArtifact): ModuleDependencyItem.Exportable.LibraryDependency {
assert(MavenConstants.SCOPE_SYSTEM != artifact.scope)
if (!libraryExists(artifact)) {
addLibraryToProjectTable(artifact)
}
val libraryTableId = LibraryTableId.ProjectLibraryTableId; //(ModuleId(moduleEntity.name))
return ModuleDependencyItem.Exportable.LibraryDependency(LibraryId(artifact.libraryName, libraryTableId), false,
toEntityScope(artifact.scope))
}
private fun libraryExists(artifact: MavenArtifact): Boolean {
return diff.entities(LibraryEntity::class.java).any { it.name == artifact.libraryName }
}
private fun addLibraryToProjectTable(artifact: MavenArtifact): LibraryEntity {
val roots = ArrayList<LibraryRoot>()
roots.add(LibraryRoot(virtualFileManager.fromUrl(MavenModelUtil.getArtifactUrlForClassifierAndExtension(artifact, null, null)),
LibraryRootTypeId.COMPILED))
roots.add(
LibraryRoot(virtualFileManager.fromUrl(MavenModelUtil.getArtifactUrlForClassifierAndExtension(artifact, "javadoc", "jar")),
JAVADOC_TYPE))
roots.add(
LibraryRoot(virtualFileManager.fromUrl(MavenModelUtil.getArtifactUrlForClassifierAndExtension(artifact, "sources", "jar")),
LibraryRootTypeId.SOURCES))
val libraryTableId = LibraryTableId.ProjectLibraryTableId; //(ModuleId(moduleEntity.name))
return diff.addLibraryEntity(artifact.libraryName, libraryTableId,
roots,
emptyList(), MavenExternalSource.INSTANCE)
}
private fun importFolders(contentRootEntity: ContentRootEntity) {
MavenFoldersImporter.getSourceFolders(mavenProject).forEach { entry ->
val serializer = (JpsModelSerializerExtension.getExtensions()
.flatMap { it.moduleSourceRootPropertiesSerializers }
.firstOrNull { it.type == entry.value }) as? JpsModuleSourceRootPropertiesSerializer
?: error("Module source root type ${entry}.value is not registered as JpsModelSerializerExtension")
val sourceRootEntity = diff.addSourceRootEntity(contentRootEntity,
virtualFileManager.fromUrl(VfsUtilCore.pathToUrl(entry.key)),
entry.value.isForTests,
serializer.typeId,
MavenExternalSource.INSTANCE)
when (entry.value) {
is JavaSourceRootType -> diff.addJavaSourceRootEntity(sourceRootEntity, false, "")
is JavaResourceRootType -> diff.addJavaResourceRootEntity(sourceRootEntity, false, "")
else -> TODO()
}
}
}
fun toEntityScope(mavenScope: String): ModuleDependencyItem.DependencyScope {
if (MavenConstants.SCOPE_RUNTIME == mavenScope) return ModuleDependencyItem.DependencyScope.RUNTIME
if (MavenConstants.SCOPE_TEST == mavenScope) return ModuleDependencyItem.DependencyScope.TEST
return if (MavenConstants.SCOPE_PROVIDED == mavenScope) ModuleDependencyItem.DependencyScope.PROVIDED else ModuleDependencyItem.DependencyScope.COMPILE
}
companion object {
internal val JAVADOC_TYPE: LibraryRootTypeId = LibraryRootTypeId("JAVADOC")
}
} | apache-2.0 | 1a2758f71787c812d580c20b8777e5ef | 46.826816 | 155 | 0.717523 | 5.875086 | false | false | false | false |
ursjoss/sipamato | public/public-entity/src/main/kotlin/ch/difty/scipamato/publ/entity/Keyword.kt | 2 | 358 | package ch.difty.scipamato.publ.entity
data class Keyword(
val id: Int = 0,
val keywordId: Int = 0,
val langCode: String? = null,
val name: String? = null,
val searchOverride: String? = null,
) : PublicDbEntity {
val displayValue: String? get() = name
companion object {
private const val serialVersionUID = 1L
}
}
| gpl-3.0 | e2d9f4bb9552e794b6b9a85731e34f85 | 21.375 | 47 | 0.639665 | 3.808511 | false | false | false | false |
allotria/intellij-community | plugins/git4idea/src/git4idea/stash/ui/GitStashTree.kt | 2 | 7068 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package git4idea.stash.ui
import com.intellij.dvcs.ui.RepositoryChangesBrowserNode
import com.intellij.ide.DataManager
import com.intellij.ide.IdeBundle
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.DataKey
import com.intellij.openapi.actionSystem.IdeActions
import com.intellij.openapi.actionSystem.ex.ActionUtil
import com.intellij.openapi.actionSystem.ex.ActionUtil.performActionDumbAwareWithCallbacks
import com.intellij.openapi.components.service
import com.intellij.openapi.project.Project
import com.intellij.openapi.vcs.VcsException
import com.intellij.openapi.vcs.changes.ui.*
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.ui.SimpleTextAttributes
import com.intellij.util.Processor
import com.intellij.vcs.log.Hash
import git4idea.i18n.GitBundle
import git4idea.repo.GitRepositoryManager
import git4idea.stash.GitStashCache
import git4idea.stash.GitStashTracker
import git4idea.stash.GitStashTrackerListener
import git4idea.stash.ui.GitStashUi.Companion.GIT_STASH_UI_PLACE
import git4idea.ui.StashInfo
import org.jetbrains.annotations.NonNls
import java.util.stream.Stream
import javax.swing.event.TreeExpansionEvent
import javax.swing.event.TreeExpansionListener
import javax.swing.event.TreeSelectionEvent
import javax.swing.tree.TreePath
import kotlin.streams.toList
class GitStashTree(project: Project, parentDisposable: Disposable) : ChangesTree(project, false, false) {
private val stashTracker get() = project.service<GitStashTracker>()
private val stashCache get() = project.service<GitStashCache>()
init {
isKeepTreeState = true
isScrollToSelection = false
setEmptyText(GitBundle.message("stash.empty.text"))
doubleClickHandler = Processor { e ->
val diffAction = ActionManager.getInstance().getAction(IdeActions.ACTION_SHOW_DIFF_COMMON)
val dataContext = DataManager.getInstance().getDataContext(this)
val event = AnActionEvent.createFromAnAction(diffAction, e, GIT_STASH_UI_PLACE, dataContext)
val isEnabled = ActionUtil.lastUpdateAndCheckDumb(diffAction, event, true)
if (isEnabled) performActionDumbAwareWithCallbacks(diffAction, event)
isEnabled
}
project.messageBus.connect(parentDisposable).subscribe(GitStashCache.GIT_STASH_LOADED, object : GitStashCache.StashLoadedListener {
override fun stashLoaded(root: VirtualFile, hash: Hash) {
rebuildTree()
}
})
stashTracker.addListener(object : GitStashTrackerListener {
override fun stashesUpdated() {
rebuildTree()
}
}, parentDisposable)
addTreeExpansionListener(object : TreeExpansionListener {
override fun treeExpanded(event: TreeExpansionEvent) {
loadStash(event.path)
}
override fun treeCollapsed(event: TreeExpansionEvent) = Unit
})
addTreeSelectionListener { event: TreeSelectionEvent ->
loadStash(event.path)
}
}
private fun loadStash(treePath: TreePath) {
val node = treePath.lastPathComponent as? ChangesBrowserNode<*> ?: return
val stashInfo = node.userObject as? StashInfo ?: return
stashCache.loadStashData(stashInfo)
}
override fun rebuildTree() {
val modelBuilder = TreeModelBuilder(project, groupingSupport.grouping)
val stashesMap = stashTracker.stashes
for ((root, stashesList) in stashesMap) {
val rootNode = if (stashesMap.size > 1) {
createRootNode(root).also { modelBuilder.insertSubtreeRoot(it) }
}
else {
modelBuilder.myRoot
}
when (stashesList) {
is GitStashTracker.Stashes.Error -> {
modelBuilder.insertErrorNode(stashesList.error, rootNode)
}
is GitStashTracker.Stashes.Loaded -> {
for (stash in stashesList.stashes) {
val stashNode = StashInfoChangesBrowserNode(stash)
modelBuilder.insertSubtreeRoot(stashNode, rootNode)
when (val stashData = stashCache.getCachedStashData(stash)) {
is GitStashCache.StashData.ChangeList -> {
modelBuilder.insertChanges(stashData.changeList.changes, stashNode)
}
is GitStashCache.StashData.Error -> {
modelBuilder.insertErrorNode(stashData.error, stashNode)
}
null -> {
modelBuilder.insertSubtreeRoot(ChangesBrowserStringNode(IdeBundle.message("treenode.loading")), stashNode)
}
}
}
}
}
}
updateTreeModel(modelBuilder.build())
}
private fun createRootNode(root: VirtualFile): ChangesBrowserNode<*> {
val repository = GitRepositoryManager.getInstance(project).getRepositoryForRootQuick(root)
?: return ChangesBrowserNode.createFile(project, root)
return RepositoryChangesBrowserNode(repository)
}
private fun TreeModelBuilder.insertErrorNode(error: VcsException, parent: ChangesBrowserNode<*>) {
val errorNode = ChangesBrowserStringNode(error.localizedMessage, SimpleTextAttributes.ERROR_ATTRIBUTES)
insertSubtreeRoot(errorNode, parent)
}
override fun resetTreeState() {
expandDefaults()
}
override fun installGroupingSupport(): ChangesGroupingSupport {
val groupingSupport = object : ChangesGroupingSupport(myProject, this, false) {
override fun isAvailable(groupingKey: String): Boolean {
return groupingKey != REPOSITORY_GROUPING && super.isAvailable(groupingKey)
}
}
installGroupingSupport(this, groupingSupport, GROUPING_PROPERTY_NAME, *DEFAULT_GROUPING_KEYS)
return groupingSupport
}
override fun getData(dataId: String): Any? {
if (STASH_INFO.`is`(dataId)) return selectedStashes().toList()
if (GIT_STASH_TREE_FLAG.`is`(dataId)) return true
return VcsTreeModelData.getData(myProject, this, dataId) ?: super.getData(dataId)
}
private fun selectedStashes(): Stream<StashInfo> {
return VcsTreeModelData.selected(this).userObjectsStream(StashInfo::class.java)
}
class StashInfoChangesBrowserNode(private val stash: StashInfo) : ChangesBrowserNode<StashInfo>(stash) {
override fun render(renderer: ChangesBrowserNodeRenderer, selected: Boolean, expanded: Boolean, hasFocus: Boolean) {
renderer.append(stash.stash, SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES)
renderer.append(": ")
stash.branch?.let {
renderer.append(it, SimpleTextAttributes.REGULAR_ITALIC_ATTRIBUTES)
renderer.append(": ")
}
renderer.append(stash.message)
}
override fun getTextPresentation(): String = stash.stash
override fun shouldExpandByDefault() = false
}
companion object {
val GIT_STASH_TREE_FLAG = DataKey.create<Boolean>("GitStashTreeFlag")
@NonNls
private const val GROUPING_PROPERTY_NAME = "GitStash.ChangesTree.GroupingKeys"
}
} | apache-2.0 | 59ffa352bf8f477982f9aa3c63cce0b2 | 38.713483 | 140 | 0.738257 | 4.782138 | false | false | false | false |
udevbe/westford | compositor/src/main/kotlin/org/westford/nativ/libbcm_host/Libbcm_host.kt | 3 | 4550 | /*
* Westford Wayland Compositor.
* Copyright (C) 2016 Erik De Rijcke
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.westford.nativ.libbcm_host
import org.freedesktop.jaccall.Lib
import org.freedesktop.jaccall.Ptr
import javax.inject.Singleton
@Singleton @Lib("bcm_host") class Libbcm_host {
external fun bcm_host_init()
external fun vc_dispmanx_display_get_info(display: Int,
@Ptr pinfo: Long): Int
/**
* Opens a display on the given device
* @param device c
* *
* *
* @return
*/
external fun vc_dispmanx_display_open(device: Int): Int
/**
* Start a new update, DISPMANX_NO_HANDLE on error
* @param priority
* *
* *
* @return
*/
external fun vc_dispmanx_update_start(priority: Int): Int
/**
* Add an elment to a display as part of an update
*/
external fun vc_dispmanx_element_add(update: Int,
display: Int,
layer: Int,
@Ptr dest_rect: Long,
src: Int,
@Ptr src_rect: Long,
protection: Int,
@Ptr alpha: Long,
@Ptr clamp: Long,
transform: Int): Int
/**
* End an update and wait for it to complete
*/
external fun vc_dispmanx_update_submit_sync(update: Int): Int
external fun vc_dispmanx_rect_set(@Ptr rect: Long,
x_offset: Int,
y_offset: Int,
width: Int,
height: Int): Int
external fun graphics_get_display_size(display_number: Int,
@Ptr width: Long,
@Ptr height: Long): Int
companion object {
val DISPMANX_ID_MAIN_LCD = 0
val DISPMANX_ID_AUX_LCD = 1
val DISPMANX_ID_HDMI = 2
val DISPMANX_ID_SDTV = 3
val DISPMANX_ID_FORCE_LCD = 4
val DISPMANX_ID_FORCE_TV = 5
val DISPMANX_ID_FORCE_OTHER = 6/* non-default display */
val DISPMANX_PROTECTION_MAX = 0x0f
val DISPMANX_PROTECTION_NONE = 0
val DISPMANX_PROTECTION_HDCP = 11
val DISPMANX_FLAGS_ALPHA_FROM_SOURCE = 0
val DISPMANX_FLAGS_ALPHA_FIXED_ALL_PIXELS = 1
val DISPMANX_FLAGS_ALPHA_FIXED_NON_ZERO = 2
val DISPMANX_FLAGS_ALPHA_FIXED_EXCEED_0X07 = 3
val DISPMANX_FLAGS_ALPHA_PREMULT = 1 shl 16
val DISPMANX_FLAGS_ALPHA_MIX = 1 shl 17
val DISPMANX_NO_ROTATE = 0
val DISPMANX_ROTATE_90 = 1
val DISPMANX_ROTATE_180 = 2
val DISPMANX_ROTATE_270 = 3
val DISPMANX_FLIP_HRIZ = 1 shl 16
val DISPMANX_FLIP_VERT = 1 shl 17
/* invert left/right images */
val DISPMANX_STEREOSCOPIC_INVERT = 1 shl 19
/* extra flags for controlling 3d duplication behaviour */
val DISPMANX_STEREOSCOPIC_NONE = 0 shl 20
val DISPMANX_STEREOSCOPIC_MONO = 1 shl 20
val DISPMANX_STEREOSCOPIC_SBS = 2 shl 20
val DISPMANX_STEREOSCOPIC_TB = 3 shl 20
val DISPMANX_STEREOSCOPIC_MASK = 15 shl 20
/* extra flags for controlling snapshot behaviour */
val DISPMANX_SNAPSHOT_NO_YUV = 1 shl 24
val DISPMANX_SNAPSHOT_NO_RGB = 1 shl 25
val DISPMANX_SNAPSHOT_FILL = 1 shl 26
val DISPMANX_SNAPSHOT_SWAP_RED_BLUE = 1 shl 27
val DISPMANX_SNAPSHOT_PACK = 1 shl 28
val VCOS_DISPLAY_INPUT_FORMAT_INVALID = 0
val VCOS_DISPLAY_INPUT_FORMAT_RGB888 = 1
val VCOS_DISPLAY_INPUT_FORMAT_RGB565 = 2
}
}
| agpl-3.0 | 66d84d2ef0bb34c61d50d27c4061f347 | 33.732824 | 75 | 0.561099 | 4.421769 | false | false | false | false |
JetBrains/teamcity-dnx-plugin | plugin-dotnet-agent/src/main/kotlin/jetbrains/buildServer/dotcover/CoverageFilterProviderImpl.kt | 1 | 4268 | package jetbrains.buildServer.dotcover
import jetbrains.buildServer.agent.runner.ParameterType
import jetbrains.buildServer.agent.runner.ParametersService
import jetbrains.buildServer.dotnet.CoverageConstants
import java.util.*
class CoverageFilterProviderImpl(
private val _parametersService: ParametersService,
private val _coverageFilterConverter: DotCoverFilterConverter)
: CoverageFilterProvider {
override val filters: Sequence<CoverageFilter>
get() {
val filters = ArrayList<CoverageFilter>()
_parametersService.tryGetParameter(ParameterType.Runner, CoverageConstants.PARAM_DOTCOVER_FILTERS)?.let {
for (filter in _coverageFilterConverter.convert(it).map { toModuleFilter(it) }) {
filters.add(filter)
}
}
if (filters.size == 0) {
filters.addAll(0, DefaultIncludeFilters)
}
addAdditionalAnyFilterWhenHasOutdatedAnyFilter(filters, CoverageFilter.CoverageFilterType.Include)
addAdditionalAnyFilterWhenHasOutdatedAnyFilter(filters, CoverageFilter.CoverageFilterType.Exclude)
filters.addAll(DefaultExcludeFilters)
return filters.asSequence()
}
override val attributeFilters: Sequence<CoverageFilter>
get() = sequence {
_parametersService.tryGetParameter(ParameterType.Runner, CoverageConstants.PARAM_DOTCOVER_ATTRIBUTE_FILTERS)?.let {
for (filter in _coverageFilterConverter.convert(it).map { toAttributeFilter(it) }) {
if (filter.type == CoverageFilter.CoverageFilterType.Exclude && CoverageFilter.Any != filter.classMask) {
yield(filter)
}
}
}
yieldAll(DefaultExcludeAttributeFilters)
}
private fun addAdditionalAnyFilterWhenHasOutdatedAnyFilter(filters: MutableList<CoverageFilter>, type: CoverageFilter.CoverageFilterType) {
val outdatedFilter = CoverageFilter(type, CoverageFilter.Any, "*.*", CoverageFilter.Any, CoverageFilter.Any)
val additionalFilter = CoverageFilter(type, CoverageFilter.Any, CoverageFilter.Any, CoverageFilter.Any, CoverageFilter.Any)
val anyIncludeFilter = filters.indexOf(outdatedFilter)
if (anyIncludeFilter >= 0) {
filters.add(anyIncludeFilter, additionalFilter)
}
}
private fun getMask(mask: String, defaultMask: String): String {
if (CoverageFilter.Any == mask) {
return defaultMask
}
return mask
}
private fun toModuleFilter(filter: CoverageFilter): CoverageFilter {
return CoverageFilter(
filter.type,
CoverageFilter.Any,
getMask(filter.moduleMask, filter.defaultMask),
filter.classMask,
filter.functionMask)
}
private fun toAttributeFilter(filter: CoverageFilter): CoverageFilter {
return CoverageFilter(
filter.type,
CoverageFilter.Any,
CoverageFilter.Any,
getMask(filter.classMask, filter.defaultMask),
CoverageFilter.Any)
}
companion object {
internal val DefaultIncludeFilters = listOf(CoverageFilter(CoverageFilter.CoverageFilterType.Include, CoverageFilter.Any, CoverageFilter.Any, CoverageFilter.Any, CoverageFilter.Any))
internal val DefaultExcludeFilters = listOf(
CoverageFilter(CoverageFilter.CoverageFilterType.Exclude, CoverageFilter.Any, "TeamCity.VSTest.TestAdapter", CoverageFilter.Any, CoverageFilter.Any),
CoverageFilter(CoverageFilter.CoverageFilterType.Exclude, CoverageFilter.Any, "TeamCity.MSBuild.Logger", CoverageFilter.Any, CoverageFilter.Any),
CoverageFilter(CoverageFilter.CoverageFilterType.Exclude, CoverageFilter.Any, CoverageFilter.Any, "AutoGeneratedProgram", CoverageFilter.Any))
internal val DefaultExcludeAttributeFilters = listOf(
CoverageFilter(CoverageFilter.CoverageFilterType.Exclude, CoverageFilter.Any, CoverageFilter.Any, "System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute", CoverageFilter.Any))
}
} | apache-2.0 | 8d93355fc019fcbb83f8ca0b419f8f39 | 46.966292 | 202 | 0.686739 | 5.638045 | false | false | false | false |
zdary/intellij-community | plugins/ide-features-trainer/src/training/learn/lesson/general/SingleLineCommentLesson.kt | 3 | 1936 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package training.learn.lesson.general
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiElement
import training.dsl.LessonContext
import training.dsl.LessonSample
import training.dsl.TaskRuntimeContext
import training.learn.LessonsBundle
import training.learn.course.KLesson
class SingleLineCommentLesson(private val sample: LessonSample)
: KLesson("Comment line", LessonsBundle.message("comment.line.lesson.name")) {
override val lessonContent: LessonContext.() -> Unit
get() = {
fun TaskRuntimeContext.countCommentedLines(): Int =
calculateComments(PsiDocumentManager.getInstance(project).getPsiFile(editor.document)!!)
prepareSample(sample)
actionTask("CommentByLineComment") {
LessonsBundle.message("comment.line.comment.any.line", action(it))
}
task("CommentByLineComment") {
text(LessonsBundle.message("comment.line.uncomment.that.line", action(it)))
trigger(it, { countCommentedLines() }, { _, now -> now == 0 })
test { actions("EditorUp", it) }
}
task("CommentByLineComment") {
text(LessonsBundle.message("comment.line.comment.several.lines", action(it)))
trigger(it, { countCommentedLines() }, { before, now -> now >= before + 2 })
test { actions("EditorDownWithSelection", "EditorDownWithSelection", it) }
}
}
private fun calculateComments(psiElement: PsiElement): Int {
return when {
psiElement is PsiComment -> 1
psiElement.children.isEmpty() -> 0
else -> {
var result = 0
for (astChild in psiElement.node.getChildren(null)) {
val psiChild = astChild.psi
result += calculateComments(psiChild)
}
result
}
}
}
}
| apache-2.0 | 3b4b9174901401137aa394d4dab97c72 | 36.230769 | 140 | 0.68905 | 4.440367 | false | false | false | false |
googlecodelabs/android-performance | benchmarking/app/src/main/java/com/example/macrobenchmark_codelab/ui/home/cart/CartViewModel.kt | 1 | 3502 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.macrobenchmark_codelab.ui.home.cart
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.example.macrobenchmark_codelab.R
import com.example.macrobenchmark_codelab.model.OrderLine
import com.example.macrobenchmark_codelab.model.SnackRepo
import com.example.macrobenchmark_codelab.model.SnackbarManager
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
/**
* Holds the contents of the cart and allows changes to it.
*
* TODO: Move data to Repository so it can be displayed and changed consistently throughout the app.
*/
class CartViewModel(
private val snackbarManager: SnackbarManager,
snackRepository: SnackRepo
) : ViewModel() {
private val _orderLines: MutableStateFlow<List<OrderLine>> =
MutableStateFlow(snackRepository.getCart())
val orderLines: StateFlow<List<OrderLine>> get() = _orderLines
// Logic to show errors every few requests
private var requestCount = 0
private fun shouldRandomlyFail(): Boolean = ++requestCount % 5 == 0
fun increaseSnackCount(snackId: Long) {
if (!shouldRandomlyFail()) {
val currentCount = _orderLines.value.first { it.snack.id == snackId }.count
updateSnackCount(snackId, currentCount + 1)
} else {
snackbarManager.showMessage(R.string.cart_increase_error)
}
}
fun decreaseSnackCount(snackId: Long) {
if (!shouldRandomlyFail()) {
val currentCount = _orderLines.value.first { it.snack.id == snackId }.count
if (currentCount == 1) {
// remove snack from cart
removeSnack(snackId)
} else {
// update quantity in cart
updateSnackCount(snackId, currentCount - 1)
}
} else {
snackbarManager.showMessage(R.string.cart_decrease_error)
}
}
fun removeSnack(snackId: Long) {
_orderLines.value = _orderLines.value.filter { it.snack.id != snackId }
}
private fun updateSnackCount(snackId: Long, count: Int) {
_orderLines.value = _orderLines.value.map {
if (it.snack.id == snackId) {
it.copy(count = count)
} else {
it
}
}
}
/**
* Factory for CartViewModel that takes SnackbarManager as a dependency
*/
companion object {
fun provideFactory(
snackbarManager: SnackbarManager = SnackbarManager,
snackRepository: SnackRepo = SnackRepo
): ViewModelProvider.Factory = object : ViewModelProvider.Factory {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return CartViewModel(snackbarManager, snackRepository) as T
}
}
}
}
| apache-2.0 | d38475e8eba928bf73c366e849e73f18 | 34.734694 | 100 | 0.661622 | 4.790698 | false | false | false | false |
FirebaseExtended/mlkit-material-android | app/src/main/java/com/google/firebase/ml/md/kotlin/barcodedetection/BarcodeResultFragment.kt | 1 | 3416 | /*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.firebase.ml.md.kotlin.barcodedetection
import android.content.DialogInterface
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import com.google.firebase.ml.md.R
import com.google.firebase.ml.md.kotlin.camera.WorkflowModel
import com.google.firebase.ml.md.kotlin.camera.WorkflowModel.WorkflowState
/** Displays the bottom sheet to present barcode fields contained in the detected barcode. */
class BarcodeResultFragment : BottomSheetDialogFragment() {
override fun onCreateView(
layoutInflater: LayoutInflater,
viewGroup: ViewGroup?,
bundle: Bundle?
): View {
val view = layoutInflater.inflate(R.layout.barcode_bottom_sheet, viewGroup)
val arguments = arguments
val barcodeFieldList: ArrayList<BarcodeField> =
if (arguments?.containsKey(ARG_BARCODE_FIELD_LIST) == true) {
arguments.getParcelableArrayList(ARG_BARCODE_FIELD_LIST) ?: ArrayList()
} else {
Log.e(TAG, "No barcode field list passed in!")
ArrayList()
}
view.findViewById<RecyclerView>(R.id.barcode_field_recycler_view).apply {
setHasFixedSize(true)
layoutManager = LinearLayoutManager(activity)
adapter = BarcodeFieldAdapter(barcodeFieldList)
}
return view
}
override fun onDismiss(dialogInterface: DialogInterface) {
activity?.let {
// Back to working state after the bottom sheet is dismissed.
ViewModelProviders.of(it).get<WorkflowModel>(WorkflowModel::class.java)
.setWorkflowState(WorkflowState.DETECTING)
}
super.onDismiss(dialogInterface)
}
companion object {
private const val TAG = "BarcodeResultFragment"
private const val ARG_BARCODE_FIELD_LIST = "arg_barcode_field_list"
fun show(fragmentManager: FragmentManager, barcodeFieldArrayList: ArrayList<BarcodeField>) {
val barcodeResultFragment = BarcodeResultFragment()
barcodeResultFragment.arguments = Bundle().apply {
putParcelableArrayList(ARG_BARCODE_FIELD_LIST, barcodeFieldArrayList)
}
barcodeResultFragment.show(fragmentManager, TAG)
}
fun dismiss(fragmentManager: FragmentManager) {
(fragmentManager.findFragmentByTag(TAG) as BarcodeResultFragment?)?.dismiss()
}
}
}
| apache-2.0 | 32c0a7b4887949004958db55417394ae | 37.818182 | 100 | 0.702869 | 4.915108 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/typealias/typeAliasConstructorForArray.kt | 3 | 348 | typealias BoolArray = Array<Boolean>
typealias IArray = IntArray
typealias MyArray<T> = Array<T>
fun box(): String {
val ba = BoolArray(1) { true }
if (!ba[0]) return "Fail #1"
val ia = IArray(1) { 42 }
if (ia[0] != 42) return "Fail #2"
val ma = MyArray<Int>(1) { 42 }
if (ma[0] != 42) return "Fail #2"
return "OK"
} | apache-2.0 | 1c20158ac06dc2d027dda1f201ba977e | 20.8125 | 37 | 0.571839 | 2.829268 | false | false | false | false |
AndroidX/androidx | external/paparazzi/paparazzi/src/main/java/app/cash/paparazzi/internal/PaparazziJson.kt | 3 | 1905 | /*
* Copyright (C) 2019 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package app.cash.paparazzi.internal
import app.cash.paparazzi.Snapshot
import app.cash.paparazzi.TestName
import com.squareup.moshi.FromJson
import com.squareup.moshi.JsonAdapter
import com.squareup.moshi.Moshi
import com.squareup.moshi.ToJson
import com.squareup.moshi.Types
import com.squareup.moshi.adapters.Rfc3339DateJsonAdapter
import java.util.Date
internal object PaparazziJson {
val moshi = Moshi.Builder()
.add(Date::class.java, Rfc3339DateJsonAdapter())
.add(this)
.build()!!
val listOfShotsAdapter: JsonAdapter<List<Snapshot>> =
moshi
.adapter<List<Snapshot>>(
Types.newParameterizedType(List::class.java, Snapshot::class.java)
)
.indent(" ")
val listOfStringsAdapter: JsonAdapter<List<String>> =
moshi
.adapter<List<String>>(
Types.newParameterizedType(List::class.java, String::class.java)
)
.indent(" ")
@ToJson
fun testNameToJson(testName: TestName): String {
return "${testName.packageName}.${testName.className}#${testName.methodName}"
}
@FromJson
fun testNameFromJson(json: String): TestName {
val regex = Regex("(.*)\\.([^.]*)#([^.]*)")
val (packageName, className, methodName) = regex.matchEntire(json)!!.destructured
return TestName(packageName, className, methodName)
}
}
| apache-2.0 | e3ab859d8bba108a04f164a26421b958 | 31.288136 | 85 | 0.71811 | 4.114471 | false | true | false | false |
AndroidX/androidx | compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/pager/Pager.kt | 3 | 21124 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.foundation.pager
import androidx.compose.animation.core.AnimationSpec
import androidx.compose.animation.core.DecayAnimationSpec
import androidx.compose.animation.core.LinearOutSlowInEasing
import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.calculateTargetValue
import androidx.compose.animation.core.spring
import androidx.compose.animation.core.tween
import androidx.compose.animation.rememberSplineBasedDecay
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.gestures.FlingBehavior
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.gestures.ScrollScope
import androidx.compose.foundation.gestures.snapping.SnapFlingBehavior
import androidx.compose.foundation.gestures.snapping.SnapLayoutInfoProvider
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyList
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.Stable
import androidx.compose.runtime.remember
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalLayoutDirection
import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.flow.drop
import kotlinx.coroutines.flow.filter
/**
* A Pager that scrolls horizontally. Pages are lazily placed in accordance to the available
* viewport size. You can use [beyondBoundsPageCount] to place more pages before and after the
* visible pages.
* @param pageCount The number of pages this Pager will contain
* @param modifier A modifier instance to be applied to this Pager outer layout
* @param state The state to control this pager
* @param contentPadding a padding around the whole content. This will add padding for the
* content after it has been clipped, which is not possible via [modifier] param. You can use it
* to add a padding before the first page or after the last one. Use [pageSpacing] to add spacing
* between the pages.
* @param pageSize Use this to change how the pages will look like inside this pager.
* @param beyondBoundsPageCount Pages to load before and after the list of visible
* pages. Note: Be aware that using a large value for [beyondBoundsPageCount] will cause a lot of
* pages to be composed, measured and placed which will defeat the purpose of using Lazy loading.
* This should be used as an optimization to pre-load a couple of pages before and after the visible
* ones.
* @param pageSpacing The amount of space to be used to separate the pages in this Pager
* @param verticalAlignment How pages are aligned vertically in this Pager.
* @param flingBehavior The [FlingBehavior] to be used for post scroll gestures.
* @param userScrollEnabled whether the scrolling via the user gestures or accessibility actions
* is allowed. You can still scroll programmatically using [PagerState.scroll] even when it is
* disabled.
* @param reverseLayout reverse the direction of scrolling and layout.
* @param pageContent This Pager's page Composable.
*/
@Composable
@ExperimentalFoundationApi
internal fun HorizontalPager(
pageCount: Int,
modifier: Modifier = Modifier,
state: PagerState = rememberPagerState(),
contentPadding: PaddingValues = PaddingValues(0.dp),
pageSize: PageSize = PageSize.Fill,
beyondBoundsPageCount: Int = 0,
pageSpacing: Dp = 0.dp,
verticalAlignment: Alignment.Vertical = Alignment.CenterVertically,
flingBehavior: SnapFlingBehavior = PagerDefaults.flingBehavior(state = state),
userScrollEnabled: Boolean = true,
reverseLayout: Boolean = false,
pageContent: @Composable (page: Int) -> Unit
) {
Pager(
modifier = modifier,
state = state,
pageCount = pageCount,
pageSpacing = pageSpacing,
userScrollEnabled = userScrollEnabled,
orientation = Orientation.Horizontal,
verticalAlignment = verticalAlignment,
reverseLayout = reverseLayout,
contentPadding = contentPadding,
beyondBoundsPageCount = beyondBoundsPageCount,
pageSize = pageSize,
flingBehavior = flingBehavior,
pageContent = pageContent
)
}
/**
* A Pager that scrolls vertically. Tha backing mechanism for this is a LazyList, therefore
* pages are lazily placed in accordance to the available viewport size. You can use
* [beyondBoundsPageCount] to place more pages before and after the visible pages.
*
* @param pageCount The number of pages this Pager will contain
* @param modifier A modifier instance to be apply to this Pager outer layout
* @param state The state to control this pager
* @param contentPadding a padding around the whole content. This will add padding for the
* content after it has been clipped, which is not possible via [modifier] param. You can use it
* to add a padding before the first page or after the last one. Use [pageSpacing] to add spacing
* between the pages.
* @param pageSize Use this to change how the pages will look like inside this pager.
* @param beyondBoundsPageCount Pages to load before and after the list of visible
* pages. Note: Be aware that using a large value for [beyondBoundsPageCount] will cause a lot of
* pages to be composed, measured and placed which will defeat the purpose of using Lazy loading.
* This should be used as an optimization to pre-load a couple of pages before and after the visible
* ones.
* @param pageSpacing The amount of space to be used to separate the pages in this Pager
* @param horizontalAlignment How pages are aligned horizontally in this Pager.
* @param flingBehavior The [FlingBehavior] to be used for post scroll gestures.
* @param userScrollEnabled whether the scrolling via the user gestures or accessibility actions
* is allowed. You can still scroll programmatically using [PagerState.scroll] even when it is
* disabled.
* @param reverseLayout reverse the direction of scrolling and layout.
* @param pageContent This Pager's page Composable.
*/
@Composable
@ExperimentalFoundationApi
internal fun VerticalPager(
pageCount: Int,
modifier: Modifier = Modifier,
state: PagerState = rememberPagerState(),
contentPadding: PaddingValues = PaddingValues(0.dp),
pageSize: PageSize = PageSize.Fill,
beyondBoundsPageCount: Int = 0,
pageSpacing: Dp = 0.dp,
horizontalAlignment: Alignment.Horizontal = Alignment.CenterHorizontally,
flingBehavior: SnapFlingBehavior = PagerDefaults.flingBehavior(state = state),
userScrollEnabled: Boolean = true,
reverseLayout: Boolean = false,
pageContent: @Composable (page: Int) -> Unit
) {
Pager(
modifier = modifier,
state = state,
pageCount = pageCount,
pageSpacing = pageSpacing,
horizontalAlignment = horizontalAlignment,
userScrollEnabled = userScrollEnabled,
orientation = Orientation.Vertical,
reverseLayout = reverseLayout,
contentPadding = contentPadding,
beyondBoundsPageCount = beyondBoundsPageCount,
pageSize = pageSize,
flingBehavior = flingBehavior,
pageContent = pageContent
)
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
internal fun Pager(
modifier: Modifier,
state: PagerState,
pageCount: Int,
pageSize: PageSize,
pageSpacing: Dp,
orientation: Orientation,
beyondBoundsPageCount: Int,
verticalAlignment: Alignment.Vertical = Alignment.CenterVertically,
horizontalAlignment: Alignment.Horizontal = Alignment.CenterHorizontally,
contentPadding: PaddingValues,
flingBehavior: SnapFlingBehavior,
userScrollEnabled: Boolean,
reverseLayout: Boolean,
pageContent: @Composable (page: Int) -> Unit
) {
require(beyondBoundsPageCount >= 0) {
"beyondBoundsPageCount should be greater than or equal to 0, " +
"you selected $beyondBoundsPageCount"
}
val isVertical = orientation == Orientation.Vertical
val density = LocalDensity.current
val layoutDirection = LocalLayoutDirection.current
val calculatedContentPaddings = remember(contentPadding, orientation, layoutDirection) {
calculateContentPaddings(
contentPadding,
orientation,
layoutDirection
)
}
val pagerFlingBehavior = remember(flingBehavior, state) {
PagerWrapperFlingBehavior(flingBehavior, state)
}
LaunchedEffect(density, state, pageSpacing) {
with(density) { state.pageSpacing = pageSpacing.roundToPx() }
}
LaunchedEffect(state) {
snapshotFlow { state.isScrollInProgress }
.filter { !it }
.drop(1) // Initial scroll is false
.collect { state.updateOnScrollStopped() }
}
BoxWithConstraints(modifier = modifier) {
val mainAxisSize = if (isVertical) constraints.maxHeight else constraints.maxWidth
// Calculates how pages are shown across the main axis
val pageAvailableSize = remember(
density,
mainAxisSize,
pageSpacing,
calculatedContentPaddings
) {
with(density) {
val pageSpacingPx = pageSpacing.roundToPx()
val contentPaddingPx = calculatedContentPaddings.roundToPx()
with(pageSize) {
density.calculateMainAxisPageSize(
mainAxisSize - contentPaddingPx,
pageSpacingPx
)
}.toDp()
}
}
val horizontalAlignmentForSpacedArrangement =
if (!reverseLayout) Alignment.Start else Alignment.End
val verticalAlignmentForSpacedArrangement =
if (!reverseLayout) Alignment.Top else Alignment.Bottom
LazyList(
modifier = Modifier,
state = state.lazyListState,
contentPadding = contentPadding,
flingBehavior = pagerFlingBehavior,
horizontalAlignment = horizontalAlignment,
horizontalArrangement = Arrangement.spacedBy(
pageSpacing,
horizontalAlignmentForSpacedArrangement
),
verticalArrangement = Arrangement.spacedBy(
pageSpacing,
verticalAlignmentForSpacedArrangement
),
verticalAlignment = verticalAlignment,
isVertical = isVertical,
reverseLayout = reverseLayout,
userScrollEnabled = userScrollEnabled,
beyondBoundsItemCount = beyondBoundsPageCount
) {
items(pageCount) {
val pageMainAxisSizeModifier = if (isVertical) {
Modifier.height(pageAvailableSize)
} else {
Modifier.width(pageAvailableSize)
}
Box(
modifier = Modifier.then(pageMainAxisSizeModifier),
contentAlignment = Alignment.Center
) {
pageContent(it)
}
}
}
}
}
private fun calculateContentPaddings(
contentPadding: PaddingValues,
orientation: Orientation,
layoutDirection: LayoutDirection
): Dp {
val startPadding = if (orientation == Orientation.Vertical) {
contentPadding.calculateTopPadding()
} else {
contentPadding.calculateLeftPadding(layoutDirection)
}
val endPadding = if (orientation == Orientation.Vertical) {
contentPadding.calculateBottomPadding()
} else {
contentPadding.calculateRightPadding(layoutDirection)
}
return startPadding + endPadding
}
/**
* This is used to determine how Pages are laid out in [Pager]. By changing the size of the pages
* one can change how many pages are shown.
*/
@ExperimentalFoundationApi
internal interface PageSize {
/**
* Based on [availableSpace] pick a size for the pages
* @param availableSpace The amount of space the pages in this Pager can use.
* @param pageSpacing The amount of space used to separate pages.
*/
fun Density.calculateMainAxisPageSize(availableSpace: Int, pageSpacing: Int): Int
/**
* Pages take up the whole Pager size.
*/
@ExperimentalFoundationApi
object Fill : PageSize {
override fun Density.calculateMainAxisPageSize(availableSpace: Int, pageSpacing: Int): Int {
return availableSpace
}
}
/**
* Multiple pages in a viewport
* @param pageSize A fixed size for pages
*/
@ExperimentalFoundationApi
class Fixed(val pageSize: Dp) : PageSize {
override fun Density.calculateMainAxisPageSize(availableSpace: Int, pageSpacing: Int): Int {
return pageSize.roundToPx()
}
}
}
@ExperimentalFoundationApi
internal object PagerDefaults {
/**
* @param state The [PagerState] that controls the which to which this FlingBehavior will
* be applied to.
* @param pagerSnapDistance A way to control the snapping destination for this [Pager].
* The default behavior will result in any fling going to the next page in the direction of the
* fling (if the fling has enough velocity, otherwise we'll bounce back). Use
* [PagerSnapDistance.atMost] to define a maximum number of pages this [Pager] is allowed to
* fling after scrolling is finished and fling has started.
* @param lowVelocityAnimationSpec The animation spec used to approach the target offset. When
* the fling velocity is not large enough. Large enough means large enough to naturally decay.
* @param highVelocityAnimationSpec The animation spec used to approach the target offset. When
* the fling velocity is large enough. Large enough means large enough to naturally decay.
* @param snapAnimationSpec The animation spec used to finally snap to the position.
*
* @return An instance of [FlingBehavior] that will perform Snapping to the next page. The
* animation will be governed by the post scroll velocity and we'll use either
* [lowVelocityAnimationSpec] or [highVelocityAnimationSpec] to approach the snapped position
* and the last step of the animation will be performed by [snapAnimationSpec].
*/
@Composable
fun flingBehavior(
state: PagerState,
pagerSnapDistance: PagerSnapDistance = PagerSnapDistance.atMost(1),
lowVelocityAnimationSpec: AnimationSpec<Float> = tween(easing = LinearOutSlowInEasing),
highVelocityAnimationSpec: DecayAnimationSpec<Float> = rememberSplineBasedDecay(),
snapAnimationSpec: AnimationSpec<Float> = spring(stiffness = Spring.StiffnessMediumLow),
): SnapFlingBehavior {
val density = LocalDensity.current
return remember(
lowVelocityAnimationSpec,
highVelocityAnimationSpec,
snapAnimationSpec,
pagerSnapDistance,
density
) {
val snapLayoutInfoProvider =
SnapLayoutInfoProvider(state, pagerSnapDistance, highVelocityAnimationSpec)
SnapFlingBehavior(
snapLayoutInfoProvider = snapLayoutInfoProvider,
lowVelocityAnimationSpec = lowVelocityAnimationSpec,
highVelocityAnimationSpec = highVelocityAnimationSpec,
snapAnimationSpec = snapAnimationSpec,
density = density
)
}
}
}
/**
* [PagerSnapDistance] defines the way the [Pager] will treat the distance between the current
* page and the page where it will settle.
*/
@ExperimentalFoundationApi
@Stable
internal interface PagerSnapDistance {
/** Provides a chance to change where the [Pager] fling will settle.
*
* @param startPage The current page right before the fling starts.
* @param suggestedTargetPage The proposed target page where this fling will stop. This target
* will be the page that will be correctly positioned (snapped) after naturally decaying with
* [velocity] using a [DecayAnimationSpec].
* @param velocity The initial fling velocity.
* @param pageSize The page size for this [Pager].
* @param pageSpacing The spacing used between pages.
*
* @return An updated target page where to settle. Note that this value needs to be between 0
* and the total count of pages in this pager. If an invalid value is passed, the pager will
* coerce within the valid values.
*/
fun calculateTargetPage(
startPage: Int,
suggestedTargetPage: Int,
velocity: Float,
pageSize: Int,
pageSpacing: Int
): Int
companion object {
/**
* Limits the maximum number of pages that can be flung per fling gesture.
* @param pages The maximum number of extra pages that can be flung at once.
*/
fun atMost(pages: Int): PagerSnapDistance {
require(pages >= 0) {
"pages should be greater than or equal to 0. You have used $pages."
}
return PagerSnapDistanceMaxPages(pages)
}
}
}
/**
* Limits the maximum number of pages that can be flung per fling gesture.
* @param pagesLimit The maximum number of extra pages that can be flung at once.
*/
@OptIn(ExperimentalFoundationApi::class)
internal class PagerSnapDistanceMaxPages(private val pagesLimit: Int) : PagerSnapDistance {
override fun calculateTargetPage(
startPage: Int,
suggestedTargetPage: Int,
velocity: Float,
pageSize: Int,
pageSpacing: Int,
): Int {
return suggestedTargetPage.coerceIn(startPage - pagesLimit, startPage + pagesLimit)
}
override fun equals(other: Any?): Boolean {
return if (other is PagerSnapDistanceMaxPages) {
this.pagesLimit == other.pagesLimit
} else {
false
}
}
override fun hashCode(): Int {
return pagesLimit.hashCode()
}
}
@OptIn(ExperimentalFoundationApi::class)
private fun SnapLayoutInfoProvider(
pagerState: PagerState,
pagerSnapDistance: PagerSnapDistance,
decayAnimationSpec: DecayAnimationSpec<Float>
): SnapLayoutInfoProvider {
return object : SnapLayoutInfoProvider by SnapLayoutInfoProvider(
lazyListState = pagerState.lazyListState,
positionInLayout = SnapAlignmentStartToStart
) {
override fun Density.calculateApproachOffset(initialVelocity: Float): Float {
val effectivePageSize = pagerState.pageSize + pagerState.pageSpacing
val initialOffset = pagerState.currentPageOffset * effectivePageSize
val animationOffset =
decayAnimationSpec.calculateTargetValue(0f, initialVelocity)
val startPage = pagerState.currentPage
val startPageOffset = startPage * effectivePageSize
val targetOffset =
(startPageOffset + initialOffset + animationOffset) / effectivePageSize
val targetPage = targetOffset.toInt()
val correctedTargetPage = pagerSnapDistance.calculateTargetPage(
startPage,
targetPage,
initialVelocity,
pagerState.pageSize,
pagerState.pageSpacing
).coerceIn(0, pagerState.pageCount)
val finalOffset = (correctedTargetPage - startPage) * effectivePageSize
return (finalOffset - initialOffset)
}
}
}
@OptIn(ExperimentalFoundationApi::class)
private class PagerWrapperFlingBehavior(
val originalFlingBehavior: SnapFlingBehavior,
val pagerState: PagerState
) : FlingBehavior {
override suspend fun ScrollScope.performFling(initialVelocity: Float): Float {
return with(originalFlingBehavior) {
performFling(initialVelocity) { remainingScrollOffset ->
pagerState.snapRemainingScrollOffset = remainingScrollOffset
}
}
}
} | apache-2.0 | e537b04bab8135a350a78d4203db203b | 39.703276 | 100 | 0.703891 | 5.434525 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.