repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Biacode/escommons | escommons-persistence/src/main/kotlin/org/biacode/escommons/persistence/repository/impl/AbstractEsRepository.kt | 1 | 5474 | package org.biacode.escommons.persistence.repository.impl
import org.biacode.escommons.core.model.document.AbstractEsDocument
import org.biacode.escommons.core.model.document.DocumentConstants
import org.biacode.escommons.persistence.repository.EsRepository
import org.biacode.escommons.toolkit.component.JsonComponent
import org.biacode.escommons.toolkit.component.SearchResponseComponent
import org.elasticsearch.action.bulk.BulkRequest
import org.elasticsearch.action.delete.DeleteRequest
import org.elasticsearch.action.get.GetRequest
import org.elasticsearch.action.get.MultiGetRequest
import org.elasticsearch.action.index.IndexRequest
import org.elasticsearch.client.RequestOptions
import org.elasticsearch.client.RestHighLevelClient
import org.elasticsearch.common.xcontent.XContentType
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.core.GenericTypeResolver
import org.springframework.stereotype.Component
import org.springframework.util.Assert
import java.util.*
/**
* Created by Arthur Asatryan.
* Date: 7/14/17
* Time: 3:37 PM
*/
@Component
abstract class AbstractEsRepository<T : AbstractEsDocument> : EsRepository<T> {
//region Dependencies
@Autowired
private lateinit var jsonComponent: JsonComponent
@Autowired
private lateinit var esCommonsRestClient: RestHighLevelClient
@Autowired
private lateinit var searchResponseComponent: SearchResponseComponent
//endregion
//region Protected methods
protected val clazz: Class<T>
//endregion
//region Constructors
init {
LOGGER.debug("Initializing - {}", javaClass.canonicalName)
this.clazz = GenericTypeResolver.resolveTypeArgument(javaClass, AbstractEsRepository::class.java) as Class<T>
}
//endregion
//region Abstract Methods
fun getDocumentType(): String = "_doc"
//endregion
//region Concrete methods
override fun save(document: T, indexName: String): Boolean {
val indexRequest = IndexRequest(indexName)
.id(document.id)
.source(jsonComponent.serialize(document), XContentType.JSON)
val index = esCommonsRestClient.index(indexRequest, RequestOptions.DEFAULT)
return index.shardInfo.failed <= 0
}
override fun save(documents: List<T>, indexName: String): Boolean {
if (documents.isEmpty()) {
return false
}
val bulkRequest = BulkRequest()
documents.forEach {
val indexRequest = IndexRequest(indexName)
.id(it.id)
.source(jsonComponent.serialize(it), XContentType.JSON)
bulkRequest.add(indexRequest)
}
return !esCommonsRestClient.bulk(bulkRequest, RequestOptions.DEFAULT).hasFailures()
}
override fun delete(id: String, indexName: String): Boolean {
val deleteRequest = DeleteRequest(indexName).id(id)
return esCommonsRestClient.delete(deleteRequest, RequestOptions.DEFAULT).shardInfo.failed <= 0
}
override fun delete(ids: List<String>, indexName: String): Boolean {
val bulkRequest = BulkRequest()
ids.forEach {
val deleteRequest = DeleteRequest(indexName).id(it)
bulkRequest.add(deleteRequest)
}
return esCommonsRestClient.bulk(bulkRequest, RequestOptions.DEFAULT).hasFailures()
}
override fun findById(id: String, indexName: String): Optional<T> {
val getResponse = esCommonsRestClient.get(GetRequest(indexName, id), RequestOptions.DEFAULT)
return if (!getResponse.isExists) {
Optional.empty()
} else Optional.of(searchResponseComponent.document(getResponse, clazz))
}
override fun findByIds(ids: List<String>, indexName: String): List<T> {
val multiGetRequest = MultiGetRequest()
ids.forEach { multiGetRequest.add(indexName, it) }
val multiGetResponse = esCommonsRestClient.mget(multiGetRequest, RequestOptions.DEFAULT)
return multiGetResponse.responses.filter { it.response.isExists }.map { jsonComponent.deserializeFromString(it.response.sourceAsString, clazz) }
}
protected fun stringValues(vararg values: Any): Array<out Any> {
Assert.notNull(values, "The string values should not be null")
return Arrays.stream(values).map { this.stringValue(it) }.toArray()
}
protected fun stringValue(value: Any): String {
Assert.notNull(value, "The string value should not be null")
return value.toString()
}
protected fun dateValue(date: Any): String {
Assert.notNull(date, "The date value should not be null")
return if (date is Date) DocumentConstants.DATE_FORMAT.format(date) else date.toString()
}
protected fun dateTimeValue(date: Any): String {
Assert.notNull(date, "The date value should not be null")
return if (date is Date) DocumentConstants.DATE_TIME_FORMAT.format(date) else date.toString()
}
protected fun decimalValue(decimal: Any): String {
Assert.notNull(decimal, "The decimal value should not be null")
return decimal.toString()
}
protected fun documentType(): String = DOCUMENT_TYPE
//endregion
//region Companion object
companion object {
private val LOGGER = LoggerFactory.getLogger(AbstractEsRepository::class.java)
private const val DOCUMENT_TYPE = "_doc"
}
//endregion
}
| mit | e9bb04ad160638ec2ce5bc75ec209359 | 37.27972 | 152 | 0.71593 | 4.580753 | false | false | false | false |
andrei-heidelbacher/algostorm | algostorm-systems/src/main/kotlin/com/andreihh/algostorm/systems/graphics2d/TileSet.kt | 1 | 10112 | /*
* Copyright (c) 2017 Andrei Heidelbacher <[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 com.andreihh.algostorm.systems.graphics2d
import com.andreihh.algostorm.core.drivers.graphics2d.Bitmap
import com.andreihh.algostorm.core.drivers.io.Resource
import kotlin.properties.Delegates
/**
* A tile set used for rendering.
*
* Tiles are indexed starting from `0`, increasing from left to right and then
* Tiles are indexed starting from `0`, increasing from left to right and then
* from top to bottom.
*
* @property name the name of this tile set
* @property image the resource of the image represented by this tile set
* @property tileWidth the width of each tile in this tile set in pixels
* @property tileHeight the height of each tile in this tile set in pixels
* @property margin the margin in pixels
* @property spacing the spacing between adjacent tiles in pixels
* @property columns the number of tiles per row
* @property tileCount the number of tiles present in this tile set
* @property animations the named animations in this tile set
* @throws IllegalArgumentException if [tileWidth], [tileHeight], [columns] or
* [tileCount] are not positive or if [margin] or [spacing] are negative or if
* the specified offsets, tile sizes and tile count don't match the image
* dimensions or if [animations] contains animation frames with tile ids not in
* the range `0..tileCount - 1` or if [animations] contains empty frame
* sequences
*/
data class TileSet(
val name: String,
val image: Image,
val tileWidth: Int,
val tileHeight: Int,
val margin: Int = 0,
val spacing: Int = 0,
val animations: Map<String, List<Frame>> = emptyMap()
) {
companion object {
/** Whether this tile id is flipped horizontally. */
val Int.isFlippedHorizontally: Boolean get() = and(0x40000000) != 0
/** Whether this tile id is flipped vertically. */
val Int.isFlippedVertically: Boolean get() = and(0x20000000) != 0
/** Whether this tile id is flipped diagonally. */
val Int.isFlippedDiagonally: Boolean get() = and(0x10000000) != 0
val Int.flags: Int get() = and(0x70000000)
fun Int.applyFlags(flags: Int): Int = xor(flags.flags)
/** Flips this tile id horizontally. */
fun Int.flipHorizontally(): Int = xor(0x40000000)
/** Flips this tile id vertically. */
fun Int.flipVertically(): Int = xor(0x20000000)
/** Flips this tile id diagonally. */
fun Int.flipDiagonally(): Int = xor(0x10000000)
/** Clears all flag bits. */
fun Int.clearFlags(): Int = and(0x0FFFFFFF)
fun tileSet(init: Builder.() -> Unit): TileSet =
Builder().apply(init).build()
}
/**
* Meta-data associated to an image.
*
* @property source the bitmap resource
* @property width the width in pixels of this image
* @property height the height in pixels of this image
* @throws IllegalArgumentException if [width] or [height] are not positive
*/
data class Image(
val source: Resource<Bitmap>,
val width: Int,
val height: Int
) {
init {
require(width > 0) { "'$source': width '$width' must be positive!" }
require(height > 0) {
"'$source': height '$height' must be positive!"
}
}
}
/**
* A frame within an animation.
*
* @property tileId the id of the tile used for this frame
* @property duration the duration of this frame in milliseconds
* @throws IllegalArgumentException if [tileId] is negative or if
* [duration] is not positive
*/
data class Frame(val tileId: Int, val duration: Int) {
init {
require(tileId >= 0) { "Tile id '$tileId' can't be negative!" }
require(duration > 0) { "Duration '$duration' must be positive!" }
}
}
/**
* A rectangle projected over an image at the specified location.
*
* @property image the source image
* @property x the horizontal coordinate in pixels of the top-left corner of
* this viewport
* @property y the vertical coordinate in pixels of the top-left corner of
* this viewport (positive is down)
* @property width the width in pixels of this viewport
* @property height the height in pixels of this viewport
* @throws IllegalArgumentException if [width] or [height] are negative or
* if this viewport is not entirely contained within the image
*/
data class Viewport(
val image: Image,
val x: Int,
val y: Int,
val width: Int,
val height: Int
) {
init {
require(width >= 0) { "'$this': width '$width' can't be negative!" }
require(height >= 0) {
"'$this': height '$height' can't be negative!"
}
require(0 <= x && x + width <= image.width) {
"'$this' exceeds horizontal image bounds '(0, ${image.width})'!"
}
require(0 <= y && y + height <= image.height) {
"'$this' exceeds vertical image bounds '(0, ${image.height})'!"
}
}
override fun toString(): String =
"${image.source}[$x, $y, ${x + width}, ${y + height}]"
}
class Builder {
lateinit var name: String
private lateinit var image: Image
var tileWidth: Int by Delegates.notNull()
var tileHeight: Int by Delegates.notNull()
var margin: Int = 0
var spacing: Int = 0
private val animations = hashMapOf<String, List<Frame>>()
fun image(init: ImageBuilder.() -> Unit) {
image = ImageBuilder().apply(init).build()
}
fun animation(name: String, init: AnimationBuilder.() -> Unit) {
animations[name] = AnimationBuilder().apply(init).build()
}
fun build(): TileSet = TileSet(
name = name,
image = image,
tileWidth = tileWidth,
tileHeight = tileHeight,
margin = margin,
spacing = spacing,
animations = animations.toMap()
)
}
class ImageBuilder {
lateinit var source: String
var width: Int by Delegates.notNull()
var height: Int by Delegates.notNull()
fun build(): Image = Image(Resource(source), width, height)
}
class AnimationBuilder {
private val frames = arrayListOf<Frame>()
fun frame(tileId: Int, duration: Int) {
frames += Frame(tileId, duration)
}
fun build(): List<Frame> = frames.toList()
}
private fun checkAnimation(animationName: String, frames: List<Frame>) {
require(frames.isNotEmpty()) {
"'$name': animation '$animationName' can't have empty frame sequence!"
}
for ((tileId, _) in frames) {
require(tileId in 0 until tileCount) {
val range = "0..${tileCount - 1}"
"'$name': tile id '$tileId' in animation '$animationName' must be in $range!"
}
}
}
private val columns: Int
get() = (image.width - 2 * margin + spacing) / (tileWidth + spacing)
private val rows: Int
get() = (image.height - 2 * margin + spacing) / (tileHeight + spacing)
val tileCount: Int
get() = columns * rows
init {
require(tileWidth > 0) {
"'$name': tile width '$tileWidth' must be positive!"
}
require(tileHeight > 0) {
"'$name': tile height '$tileHeight' must be positive!"
}
require(margin >= 0) { "'$this': margin '$margin' can't be negative!" }
require(spacing >= 0) {
"'$name': spacing '$spacing' can't be negative!"
}
require(columns > 0) { "'$this': columns '$columns' must be positive!" }
require(tileCount > 0) {
"'$name': tile count '$tileCount' must be positive!"
}
val reqW = 2 * margin - spacing + columns * (tileWidth + spacing)
val reqH = 2 * margin - spacing + rows * (tileHeight + spacing)
val src = image.source
require(reqW == image.width) {
"'$name': image '$src' width '${image.width}' must be '$reqW'!"
}
require(reqH == image.height) {
"'$name': image '$src' height '${image.height}' must be '$reqH'!"
}
for ((animationName, frames) in animations) {
checkAnimation(animationName, frames)
}
}
/**
* Returns a viewport corresponding to the given tile id by applying the
* appropriate margin and spacing offsets.
*
* @param tileId the id of the requested tile
* @return the viewport associated to the requested tile
* @throws IndexOutOfBoundsException if the given [tileId] is negative or if
* it is greater than or equal to [tileCount]
*/
fun getViewport(tileId: Int): Viewport {
if (tileId !in 0 until tileCount) {
throw IndexOutOfBoundsException(
"Tile id '$tileId' must be in 0..${tileCount - 1}!"
)
}
return Viewport(
image = image,
x = margin + (tileId % columns) * (tileWidth + spacing),
y = margin + (tileId / columns) * (tileHeight + spacing),
width = tileWidth,
height = tileHeight
)
}
}
| apache-2.0 | b78b28a2475cce93ed7f2d41547a63b8 | 35.374101 | 93 | 0.594838 | 4.386985 | false | false | false | false |
owncloud/android | owncloudDomain/src/main/java/com/owncloud/android/domain/camerauploads/model/FolderBackUpConfiguration.kt | 2 | 1613 | /**
* ownCloud Android client application
*
* @author Abel García de Prada
* Copyright (C) 2021 ownCloud GmbH.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
*
* 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 com.owncloud.android.domain.camerauploads.model
data class FolderBackUpConfiguration(
val accountName: String,
val behavior: Behavior,
val sourcePath: String,
val uploadPath: String,
val wifiOnly: Boolean,
val chargingOnly: Boolean,
val lastSyncTimestamp: Long,
val name: String,
) {
val isPictureUploads get() = name == pictureUploadsName
val isVideoUploads get() = name == videoUploadsName
companion object {
const val pictureUploadsName = "Picture uploads"
const val videoUploadsName = "Video uploads"
}
enum class Behavior {
MOVE, COPY;
companion object {
fun fromString(string: String): Behavior {
return if (string.equals("MOVE", ignoreCase = true)) {
MOVE
} else {
COPY
}
}
}
}
}
| gpl-2.0 | 3fac2e31594aa7247b98f02eb459770d | 29.415094 | 72 | 0.654467 | 4.579545 | false | false | false | false |
cuebyte/rendition | src/main/kotlin/moe/cuebyte/rendition/type/columnType.kt | 1 | 553 | package moe.cuebyte.rendition.type
import moe.cuebyte.rendition.IncompleteColumn
fun bool(default: Boolean = false) = IncompleteColumn(Boolean::class.java, default)
fun string(default: String = "") = IncompleteColumn(String::class.java, default)
fun int(default: Int = 0) = IncompleteColumn(Int::class.java, default)
fun long(default: Long = 0L) = IncompleteColumn(Long::class.java, default)
fun float(default: Float = 0f) = IncompleteColumn(Float::class.java, default)
fun double(default: Double = 0.0) = IncompleteColumn(Double::class.java, default) | lgpl-3.0 | 29a5eb3ce744352bd40c4a2ea994e4be | 54.4 | 83 | 0.768535 | 3.567742 | false | false | false | false |
jksiezni/xpra-client | xpra-client-android/src/main/java/com/github/jksiezni/xpra/connection/ActiveConnectionFragment.kt | 1 | 4513 | /*
* Copyright (C) 2020 Jakub Ksiezniak
*
* 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 com.github.jksiezni.xpra.connection
import android.os.Bundle
import android.view.LayoutInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.github.jksiezni.xpra.client.AndroidXpraWindow
import com.github.jksiezni.xpra.client.ConnectionEventListener
import com.github.jksiezni.xpra.view.Intents
import com.github.jksiezni.xpra.client.ServiceBinderFragment
import com.github.jksiezni.xpra.config.ServerDetails
import com.github.jksiezni.xpra.databinding.ActiveConnectionFragmentBinding
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.addTo
import java.io.IOException
/**
*
*/
class ActiveConnectionFragment : Fragment() {
private var _binding: ActiveConnectionFragmentBinding? = null
private val binding get() = _binding!!
private val service by lazy { ServiceBinderFragment.obtain(activity) }
private val disposables = CompositeDisposable()
private val connectionListener = object : ConnectionEventListener {
override fun onConnected(serverDetails: ServerDetails) {
// do nothing
}
override fun onDisconnected(serverDetails: ServerDetails) {
exit()
}
override fun onConnectionError(serverDetails: ServerDetails, e: IOException) {
exit()
}
}
init {
setHasOptionsMenu(true)
}
override fun onStart() {
super.onStart()
service.whenXpraAvailable { api ->
api.registerConnectionListener(connectionListener)
if (!api.isConnected) {
exit()
}
}
}
override fun onStop() {
super.onStop()
service.whenXpraAvailable { api ->
api.unregisterConnectionListener(connectionListener)
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
_binding = ActiveConnectionFragmentBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
val adapter = TasksAdapter(binding.emptyView)
adapter.onClickAction.subscribe { item ->
val intent = Intents.createXpraIntent(requireContext(), item.windowId)
startActivity(intent)
}.addTo(disposables)
binding.windowsRecyclerView.adapter = adapter
service.whenXpraAvailable { api ->
api.xpraClient.getWindowsLiveData().observe(viewLifecycleOwner) { windows ->
val items = windows.map {
val androidWindow = it as AndroidXpraWindow
TaskItem(it.id, it.title, androidWindow.iconDrawable)
}
adapter.submitList(items)
}
}
binding.createCommandBtn.setOnClickListener {
StartCommandDialogFragment().showNow(childFragmentManager, StartCommandDialogFragment.TAG)
}
}
override fun onDestroyView() {
super.onDestroyView()
disposables.clear()
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
service.whenXpraAvailable { api ->
activity?.title = api.connectionDetails?.name
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
android.R.id.home -> {
exit()
true
}
else -> false
}
}
private fun exit() {
parentFragmentManager.popBackStack()
}
} | gpl-3.0 | 591d6a4628667849327439323473f47b | 31.948905 | 115 | 0.668513 | 4.795962 | false | false | false | false |
wordpress-mobile/WordPress-FluxC-Android | example/src/test/java/org/wordpress/android/fluxc/wc/order/WCOrderListDescriptorTest.kt | 1 | 4873 | package org.wordpress.android.fluxc.wc.order
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
import org.junit.runners.Parameterized.Parameters
import org.mockito.kotlin.mock
import org.mockito.kotlin.whenever
import org.wordpress.android.fluxc.list.ListDescriptorUnitTestCase
import org.wordpress.android.fluxc.list.post.LIST_DESCRIPTOR_TEST_FIRST_MOCK_SITE_LOCAL_SITE_ID
import org.wordpress.android.fluxc.list.post.LIST_DESCRIPTOR_TEST_QUERY_1
import org.wordpress.android.fluxc.list.post.LIST_DESCRIPTOR_TEST_QUERY_2
import org.wordpress.android.fluxc.list.post.LIST_DESCRIPTOR_TEST_SECOND_MOCK_SITE_LOCAL_SITE_ID
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.fluxc.model.WCOrderListDescriptor
private typealias WCOrderListDescriptorTestCase = ListDescriptorUnitTestCase<WCOrderListDescriptor>
@RunWith(Parameterized::class)
internal class WCOrderListDescriptorTest(
private val testCase: WCOrderListDescriptorTestCase
) {
companion object {
@JvmStatic
@Parameters
fun testCases(): List<WCOrderListDescriptorTestCase> {
val mockSite = mock<SiteModel>()
val mockSite2 = mock<SiteModel>()
whenever(mockSite.id).thenReturn(LIST_DESCRIPTOR_TEST_FIRST_MOCK_SITE_LOCAL_SITE_ID)
whenever(mockSite2.id).thenReturn(LIST_DESCRIPTOR_TEST_SECOND_MOCK_SITE_LOCAL_SITE_ID)
return listOf(
// Same site
WCOrderListDescriptorTestCase(
typeIdentifierReason = "Same sites should have same type identifier",
uniqueIdentifierReason = "Same sites should have same unique identifier",
descriptor1 = WCOrderListDescriptor(site = mockSite),
descriptor2 = WCOrderListDescriptor(site = mockSite),
shouldHaveSameTypeIdentifier = true,
shouldHaveSameUniqueIdentifier = true
),
// Different site
WCOrderListDescriptorTestCase(
typeIdentifierReason = "Different sites should have different type identifiers",
uniqueIdentifierReason = "Different sites should have different unique identifiers",
descriptor1 = WCOrderListDescriptor(site = mockSite),
descriptor2 = WCOrderListDescriptor(site = mockSite2),
shouldHaveSameTypeIdentifier = false,
shouldHaveSameUniqueIdentifier = false
),
// Different status filters
WCOrderListDescriptorTestCase(
typeIdentifierReason = "Different status filters should have same type identifiers",
uniqueIdentifierReason = "Different status filters should have different " +
"unique identifiers",
descriptor1 = WCOrderListDescriptor(
site = mockSite,
statusFilter = LIST_DESCRIPTOR_TEST_QUERY_1
),
descriptor2 = WCOrderListDescriptor(
site = mockSite,
statusFilter = LIST_DESCRIPTOR_TEST_QUERY_2
),
shouldHaveSameTypeIdentifier = true,
shouldHaveSameUniqueIdentifier = false
),
// Different search query
WCOrderListDescriptorTestCase(
typeIdentifierReason = "Different search queries should have same type identifiers",
uniqueIdentifierReason = "Different search queries should have different " +
"unique identifiers",
descriptor1 = WCOrderListDescriptor(
site = mockSite,
searchQuery = LIST_DESCRIPTOR_TEST_QUERY_1
),
descriptor2 = WCOrderListDescriptor(
site = mockSite,
statusFilter = LIST_DESCRIPTOR_TEST_QUERY_2
),
shouldHaveSameTypeIdentifier = true,
shouldHaveSameUniqueIdentifier = false
)
)
}
}
@Test
fun `test type identifier`() {
testCase.testTypeIdentifier()
}
@Test
fun `test unique identifier`() {
testCase.testUniqueIdentifier()
}
}
| gpl-2.0 | a2d3d4b6909d7a370dfd1bfe9819837a | 50.294737 | 112 | 0.56536 | 6.271557 | false | true | false | false |
Ekito/koin | koin-projects/koin-core/src/test/java/org/koin/core/CoroutinesTest.kt | 1 | 1570 | package org.koin.core
import kotlinx.coroutines.*
import org.junit.Assert
import org.junit.Test
import org.koin.Simple
import org.koin.core.context.startKoin
import org.koin.core.context.stopKoin
import org.koin.dsl.module
import org.koin.test.getInstanceFactory
import kotlin.random.Random
class CoroutinesTest {
@Test
fun `KoinApp with coroutines gets`() = runBlocking {
val app = startKoin {
modules(
module {
single { Simple.ComponentA() }
single { Simple.ComponentB(get()) }
single { Simple.ComponentC(get()) }
})
}
val koin = app.koin
val jobs = arrayListOf<Deferred<*>>()
jobs.add(async {
randomSleep()
koin.get<Simple.ComponentA>()
})
jobs.add(async {
randomSleep()
koin.get<Simple.ComponentB>()
})
jobs.add(async {
randomSleep()
koin.get<Simple.ComponentC>()
})
jobs.awaitAll()
val a = app.getInstanceFactory(Simple.ComponentA::class)!!
val b = app.getInstanceFactory(Simple.ComponentA::class)!!
val c = app.getInstanceFactory(Simple.ComponentA::class)!!
Assert.assertTrue(a.isCreated())
Assert.assertTrue(b.isCreated())
Assert.assertTrue(c.isCreated())
stopKoin()
}
private suspend fun randomSleep() {
val timer = Random.nextLong(MAX_TIME)
println("thread sleep $timer")
delay(timer)
}
} | apache-2.0 | 72264898a4f45a4e5c81732b59732f2c | 26.086207 | 66 | 0.579618 | 4.485714 | false | true | false | false |
NordicSemiconductor/Android-nRF-Toolbox | profile_uart/src/main/java/no/nordicsemi/android/uart/view/UARTContentView.kt | 1 | 2619 | /*
* Copyright (c) 2022, Nordic Semiconductor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific prior
* written permission.
*
* 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
* HOLDER 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 no.nordicsemi.android.uart.view
import androidx.compose.foundation.layout.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import no.nordicsemi.android.theme.Card
import no.nordicsemi.android.uart.data.UARTData
@Composable
internal fun UARTContentView(
state: UARTData,
onEvent: (UARTViewEvent) -> Unit
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier
.padding(16.dp)
.fillMaxSize()
) {
Card(
modifier = Modifier
.weight(1f)
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(start = 16.dp, top = 16.dp, end = 16.dp)
) {
OutputSection(state.displayMessages, onEvent)
}
}
Spacer(modifier = Modifier.size(16.dp))
InputSection(onEvent = onEvent)
}
}
| bsd-3-clause | 555fd38e73f361f7e004dbc3121b3328 | 35.887324 | 89 | 0.705231 | 4.619048 | false | false | false | false |
http4k/http4k | src/docs/guide/howto/attach_context_to_a_request/lens_key_example.kt | 1 | 1802 | package guide.howto.attach_context_to_a_request
import org.http4k.core.Filter
import org.http4k.core.HttpHandler
import org.http4k.core.Method.GET
import org.http4k.core.Request
import org.http4k.core.RequestContexts
import org.http4k.core.Response
import org.http4k.core.Status.Companion.OK
import org.http4k.core.then
import org.http4k.core.with
import org.http4k.filter.ServerFilters
import org.http4k.lens.RequestContextKey
import org.http4k.lens.RequestContextLens
fun main() {
data class SharedState(val message: String)
fun AddState(key: RequestContextLens<SharedState>) = Filter { next ->
{
// "modify" the request like any other Lens
next(it.with(key of SharedState("hello there")))
}
}
fun PrintState(key: RequestContextLens<SharedState>): HttpHandler = { request ->
// we can just extract the Lens state from the request like any other standard Lens
println(key(request))
Response(OK)
}
// this is the shared RequestContexts object - it holds the bag of state for each request and
// tidies up afterwards.
val contexts = RequestContexts()
// this Lens is the key we use to set and get the type-safe state. By using this, we gain
// typesafety and the guarantee that there will be no clash of keys.
// RequestContextKeys can be required, optional, or defaulted, as per the standard Lens mechanism.
val key = RequestContextKey.required<SharedState>(contexts)
// The first Filter is required to initialise the bag of state.
// The second Filter modifies the bag.
// The handler just prints out the state.
val app = ServerFilters.InitialiseRequestContext(contexts)
.then(AddState(key))
.then(PrintState(key))
app(Request(GET, "/hello"))
}
| apache-2.0 | 936d0a42df2fea3c74cd27e1c0a2de09 | 35.77551 | 102 | 0.717536 | 3.969163 | false | false | false | false |
http4k/http4k | http4k-core/src/main/kotlin/org/http4k/core/Http4k.kt | 1 | 543 | package org.http4k.core
import org.http4k.routing.RoutingHttpHandler
typealias HttpHandler = (Request) -> Response
fun interface Filter : (HttpHandler) -> HttpHandler {
companion object
}
val Filter.Companion.NoOp: Filter get() = Filter { next -> { next(it) } }
fun Filter.then(next: Filter): Filter = Filter { this(next(it)) }
fun Filter.then(next: HttpHandler): HttpHandler = this(next).let { http -> { http(it) } }
fun Filter.then(routingHttpHandler: RoutingHttpHandler): RoutingHttpHandler = routingHttpHandler.withFilter(this)
| apache-2.0 | ef5f469d5b16702608bb0f34e2bac09a | 30.941176 | 113 | 0.73849 | 3.693878 | false | false | false | false |
loloof64/BasicChessEndGamesTrainer | app/src/main/java/com/loloof64/android/basicchessendgamestrainer/MainActivity.kt | 1 | 2143 | package com.loloof64.android.basicchessendgamestrainer
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.loloof64.android.basicchessendgamestrainer.ui.theme.BasicChessEndgamesTheme
import com.loloof64.android.chessboard.ui.ChessBoard
import com.loloof64.android.chessboard.ui.ChessBoardParameters
import com.loloof64.android.chessboard.ui.ChessBoardParametersBuilder
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
BasicChessEndgamesTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colors.background
) {
Greeting("Android")
}
}
}
}
}
@Composable
fun Greeting(name: String) {
Text(text = "Hello $name!")
}
@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
BasicChessEndgamesTheme {
Greeting("Android")
}
}
@Preview
@Composable
fun ChessBoardPreview() {
val boardParameters = ChessBoardParametersBuilder()
.setTotalSizeTo(300.dp)
.build()
Row(
modifier = Modifier.fillMaxSize(),
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically
) {
ChessBoard(parameters = boardParameters)
}
} | gpl-3.0 | 7db854b17c75abe4c8d45bbc5f30f7e8 | 30.529412 | 86 | 0.729818 | 4.418557 | false | false | false | false |
yamamotoj/workshop-jb | src/v_collections/I_Partition_.kt | 8 | 482 | package v_collections
fun example8() {
val numbers = listOf(1, 3, -4, 2, -11)
//the details (how multi-assignment works) were explained in 'Conventions' task earlier
val (positive, negative) = numbers.partition { it > 0 }
positive == listOf(1, 3, 2)
negative == listOf(-4, -11)
}
fun Shop.getCustomersWithMoreUndeliveredOrdersThanDelivered(): Set<Customer> {
// Return customers who have more undelivered orders than delivered
todoCollectionTask()
}
| mit | 848dc348b5d3d4b3fa5fb50b4ec6d4cc | 29.125 | 91 | 0.697095 | 4.05042 | false | false | false | false |
openhab/openhab.android | mobile/src/main/java/org/openhab/habdroid/ui/activity/Oh3UiWebViewFragment.kt | 1 | 1253 | /*
* Copyright (c) 2010-2022 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.habdroid.ui.activity
import okhttp3.HttpUrl
import org.openhab.habdroid.R
import org.openhab.habdroid.ui.MainActivity
class Oh3UiWebViewFragment : AbstractWebViewFragment() {
override val titleRes = R.string.mainmenu_openhab_oh3_ui
override val multiServerTitleRes = R.string.mainmenu_openhab_oh3_ui_on_server
override val errorMessageRes = R.string.oh3_ui_error
override val urlToLoad = "/"
override val urlForError = "/"
override val lockDrawer = true
override val shortcutIcon = R.mipmap.ic_shortcut_oh3_ui
override val shortcutAction = MainActivity.ACTION_OH3_UI_SELECTED
override fun modifyUrl(orig: HttpUrl): HttpUrl {
if (orig.host == "myopenhab.org") {
return orig.newBuilder()
.host("home.myopenhab.org")
.build()
}
return orig
}
}
| epl-1.0 | 15ab14510fca56f1f1040e7e2cefcdc8 | 31.973684 | 81 | 0.703113 | 3.867284 | false | false | false | false |
juumixx/weartodo | todo/src/main/kotlin/io/github/juumixx/todo/Todo.kt | 1 | 4961 | package io.github.juumixx.todo
import org.joda.time.LocalDateTime
import org.joda.time.format.DateTimeFormat
class Todo(txt: String? = null) {
val tasks = ArrayList<Task>()
init {
txt?.let {
tasks.addAll(read(it))
}
}
fun readLine(line: String) {
if (line.isNotBlank()) {
tasks.add(Task(line))
}
}
fun read(txt: String) = txt.split("\n").filter(String::isNotBlank).map { Task(it) }.toMutableList()
fun contexts() = tasks.flatMap { task -> task.contexts }.toSortedSet()
fun projects() = tasks.flatMap { task -> task.projects }.toSortedSet()
fun context(name: String) = tasks.filter { task -> task.contexts.contains(name) }
fun contextString(name: String) = context(name).map(Task::toString).joinToString("\n")
override fun toString() = tasks.map(Task::toString).joinToString("\n")
}
data class Task(val txt: String) {
companion object {
private val COMPLETED = Regex("^x\\s+(.+)")
private val PRIORITY = Regex("^\\(([A-Z])\\)\\s+(.+)")
private val COMPLETION_DATE = Regex("^x\\s+([0-9]{4}-[0-9]{2}-[0-9]{2})\\s+([0-9]{4}-[0-9]{2}-[0-9]{2})\\s+(.+)")
private val CREATION_DATE = Regex("^(\\([A-Z]\\)\\s+)?([0-9]{4}-[0-9]{2}-[0-9]{2})\\s+(.+)")
private val CREATION_DATE_COMPLETED = Regex("^x\\s+([0-9]{4}-[0-9]{2}-[0-9]{2})\\s+(.+)")
private val PROJECT = Regex("\\+(\\S+)")
private val CONTEXT = Regex("@(\\S+)")
private val TAG = Regex("([^\\s:]+):([^\\s:]+)")
val DATE_STRING = "yyyy-MM-dd"
val DATE_FORMAT = DateTimeFormat.forPattern(DATE_STRING)!!
}
private val trim = txt.trim()
val completed = COMPLETED.matches(trim)
val priority = PRIORITY.matchEntire(trim)?.groupValues?.get(1)
val completionDate: LocalDateTime?
val creationDate: LocalDateTime?
val content: String
val projects = ArrayList<String>()
val contexts = ArrayList<String>()
val tags = ArrayList<Pair<String, String>>()
init {
if (completed) {
val completionMatch = COMPLETION_DATE.matchEntire(trim)
if (completionMatch != null) {
completionDate = completionMatch.groupValues[1].let { LocalDateTime.parse(it, DATE_FORMAT) }
creationDate = completionMatch.groupValues[2].let { LocalDateTime.parse(it, DATE_FORMAT) }
content = completionMatch.groupValues[3]
} else {
val creationMatch = CREATION_DATE_COMPLETED.matchEntire(trim)
if (creationMatch != null) {
completionDate = null
creationDate = creationMatch.groupValues[1].let { LocalDateTime.parse(it, DATE_FORMAT) }
content = creationMatch.groupValues[2]
} else {
completionDate = null
creationDate = null
content = COMPLETED.matchEntire(trim)!!.groupValues[1]
}
}
} else {
completionDate = null
val creationMatch = CREATION_DATE.matchEntire(trim)
if (creationMatch != null) {
creationDate = creationMatch.groupValues[2].let { LocalDateTime.parse(it, DATE_FORMAT) }
content = creationMatch.groupValues[3]
} else {
creationDate = null
val priorityMatch = PRIORITY.matchEntire(trim)
if (priorityMatch != null) {
content = priorityMatch.groupValues[2]
} else {
content = trim
}
}
}
content.split(" ").forEach { checkSpecial(it) }
}
override fun toString(): String {
val sb = StringBuilder()
if (completed) {
sb.append("x ")
} else if (priority != null) {
sb.append("($priority) ")
}
if (completionDate != null) {
sb.append("${completionDate.toString(DATE_FORMAT)} ")
}
if (creationDate != null) {
sb.append("${creationDate.toString(DATE_FORMAT)} ")
}
sb.append(content)
return sb.toString()
}
private fun checkSpecial(word: String): Boolean {
if (word.isBlank()) {
return false
}
val projectMatch = PROJECT.matchEntire(word)
if (projectMatch != null) {
projects.add(projectMatch.groupValues[1])
return false
}
val contextMatch = CONTEXT.matchEntire(word)
if (contextMatch != null) {
contexts.add(contextMatch.groupValues[1])
return false
}
val tagMatch = TAG.matchEntire(word)
if (tagMatch != null) {
val key = tagMatch.groupValues[1]
val value = tagMatch.groupValues[2]
tags.add(Pair(key, value))
return false
}
return true
}
} | mit | 82dd29913df4d392702666982aa3a459 | 36.308271 | 121 | 0.547269 | 4.258369 | false | false | false | false |
ankidroid/Anki-Android | AnkiDroid/src/main/java/com/ichi2/utils/AndroidUiUtils.kt | 1 | 2492 | /*
* Copyright (c) 2020 David Allison <[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 com.ichi2.utils
import android.app.UiModeManager
import android.content.Context
import android.content.res.Configuration
import android.view.View
import android.view.Window
import android.view.WindowManager
import android.view.inputmethod.InputMethodManager
import androidx.core.content.ContextCompat
object AndroidUiUtils {
fun isRunningOnTv(context: Context?): Boolean {
val uiModeManager = ContextCompat.getSystemService(context!!, UiModeManager::class.java)
?: return false
return uiModeManager.currentModeType == Configuration.UI_MODE_TYPE_TELEVISION
}
/**
* This method is used for setting the focus on an EditText which is used in a dialog
* and for opening the keyboard.
* @param view The EditText which requires the focus to be set.
* @param window The window where the view is present.
*/
fun setFocusAndOpenKeyboard(view: View, window: Window) {
view.requestFocus()
window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE)
}
/**
* Focuses on View and opens the soft keyboard.
* @param view The View which requires the focus to be set (typically an EditText).
* @param runnable The Optional Runnable that will be executed at the end.
*/
fun setFocusAndOpenKeyboard(view: View, runnable: Runnable? = null) {
// Required on some Android 9, 10 devices to show keyboard: https://stackoverflow.com/a/7784904
view.postDelayed({
view.requestFocus()
val imm = view.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT)
runnable?.run()
}, 200)
}
}
| gpl-3.0 | 8aea369689923f262dda8a35cd17d531 | 41.237288 | 104 | 0.718299 | 4.45 | false | false | false | false |
moove-it/fakeit | library/src/main/java/com/mooveit/library/providers/CoffeeProviderImpl.kt | 1 | 864 | package com.mooveit.library.providers
import com.mooveit.library.Fakeit.Companion.fakeit
import com.mooveit.library.providers.base.BaseProvider
import com.mooveit.library.providers.definition.CoffeeProvider
class CoffeeProviderImpl : BaseProvider(), CoffeeProvider {
override fun blendName(): String = getValue("blend_name", { fakeit!!.fetch("coffee.blend_name") })
override fun origin(): String {
val country = getValue("country", { fakeit!!.fetch("coffee.country") })
val country_formatted = country.replace(" ", "_").toLowerCase()
return country + ", " + getValue("regions", { fakeit!!.fetch("coffee.regions.$country_formatted") })
}
override fun variety(): String = getValue("variety", { fakeit!!.fetch("coffee.variety") })
override fun notes(): String = getValue("notes", { fakeit!!.fetch("coffee.notes") })
} | mit | 4fcee012539c8576034242d44e620db1 | 42.25 | 108 | 0.697917 | 4.277228 | false | false | false | false |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/server/service/user/LanternUserStorage.kt | 1 | 6511 | /*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.service.user
import com.google.gson.stream.JsonReader
import com.google.gson.stream.JsonWriter
import org.lanternpowered.api.data.persistence.DataContainer
import org.lanternpowered.api.data.persistence.DataQuery
import org.lanternpowered.api.data.persistence.DataView
import org.lanternpowered.api.service.user.UserStorage
import org.lanternpowered.api.util.optional.orNull
import org.lanternpowered.server.LanternGame
import org.lanternpowered.server.data.persistence.json.JsonDataFormat
import org.lanternpowered.server.data.persistence.nbt.NbtStreamUtils
import org.lanternpowered.server.util.SafeIO
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import java.util.UUID
import java.util.concurrent.locks.ReentrantReadWriteLock
import kotlin.concurrent.read
import kotlin.concurrent.write
class LanternUserStorage(
private val uniqueId: UUID,
private val directory: Path
) : UserStorage {
companion object {
val DATA_DIRECTORY: Path = Paths.get("playerdata")
val ADVANCEMENTS_DATA_DIRECTORY: Path = Paths.get("advancements")
val STATISTICS_DATA_DIRECTORY: Path = Paths.get("stats")
val SPONGE_DATA_DIRECTORY: Path = Paths.get("data", "sponge")
val ADVANCEMENTS: DataQuery = DataQuery.of("Advancements")
val STATISTICS: DataQuery = DataQuery.of("Statistics")
val EXTENDED_SPONGE_DATA: DataQuery = DataQuery.of("ExtendedSpongeData")
private fun getDataPath(uniqueId: UUID): Path = DATA_DIRECTORY.resolve("${uniqueId.toString().toLowerCase()}.dat")
fun exists(uniqueId: UUID, directory: Path): Boolean = Files.exists(directory.resolve(getDataPath(uniqueId)))
}
override fun getUniqueId(): UUID = this.uniqueId
private val lock = ReentrantReadWriteLock()
private val dataPath: Path
get() = this.directory.resolve(getDataPath(this.uniqueId))
private val spongeDataPath: Path
get() = this.directory.resolve(SPONGE_DATA_DIRECTORY).resolve("${uniqueId.toString().toLowerCase()}.dat")
private val advancementsPath: Path
get() = this.directory.resolve(ADVANCEMENTS_DATA_DIRECTORY).resolve("${uniqueId.toString().toLowerCase()}.json")
private val statisticsPath: Path
get() = this.directory.resolve(STATISTICS_DATA_DIRECTORY).resolve("${uniqueId.toString().toLowerCase()}.json")
override val exists: Boolean
get() = Files.exists(this.dataPath)
override fun load(): DataContainer? = this.lock.read { this.load0() }
private fun load0(): DataContainer? {
var data: DataContainer? = null
val dataPath = this.dataPath
if (Files.exists(dataPath)) {
data = Files.newInputStream(dataPath).use { input ->
NbtStreamUtils.read(input, true)
}
}
if (data == null)
return null
val spongeDataPath = this.spongeDataPath
if (Files.exists(dataPath)) {
try {
val spongeData = Files.newInputStream(spongeDataPath).use { input ->
NbtStreamUtils.read(input, true)
}
data.set(EXTENDED_SPONGE_DATA, spongeData)
} catch (t: Throwable) {
LanternGame.logger.error("Failed to read sponge user data for: $uniqueId", t)
}
}
fun readJsonData(query: DataQuery, path: Path) {
if (Files.exists(path)) {
Files.newBufferedReader(path).use { reader ->
val jsonData = JsonDataFormat.readContainer(JsonReader(reader))
data.set(query, jsonData)
}
}
}
readJsonData(ADVANCEMENTS, this.advancementsPath)
readJsonData(STATISTICS, this.statisticsPath)
return data
}
override fun save(data: DataView) = this.lock.write { this.save0(data) }
private fun save0(data: DataView) {
val advancementsData = data.getView(ADVANCEMENTS).orNull()
val statisticsData = data.getView(STATISTICS).orNull()
val spongeData = data.getView(EXTENDED_SPONGE_DATA).orNull()
data.remove(ADVANCEMENTS)
data.remove(STATISTICS)
data.remove(EXTENDED_SPONGE_DATA)
val dataPath = this.dataPath
val advancementsPath = this.advancementsPath
val statisticsPath = this.statisticsPath
val spongeDataPath = this.spongeDataPath
Files.createDirectories(dataPath.parent)
Files.createDirectories(advancementsPath.parent)
Files.createDirectories(statisticsPath.parent)
Files.createDirectories(spongeDataPath.parent)
SafeIO.write(dataPath) { tmpPath ->
Files.newOutputStream(tmpPath).use { output ->
NbtStreamUtils.write(data, output, true)
}
}
if (spongeData == null) {
Files.deleteIfExists(spongeDataPath)
} else {
SafeIO.write(spongeDataPath) { tmpPath ->
Files.newOutputStream(tmpPath).use { output ->
NbtStreamUtils.write(spongeData, output, true)
}
}
}
fun saveJsonData(jsonData: DataView?, path: Path) {
if (jsonData == null) {
Files.deleteIfExists(path)
} else {
SafeIO.write(spongeDataPath) { tmpPath ->
Files.newBufferedWriter(tmpPath).use { writer ->
JsonDataFormat.write(JsonWriter(writer), jsonData)
}
}
}
}
saveJsonData(advancementsData, advancementsPath)
saveJsonData(statisticsData, statisticsPath)
}
override fun delete(): Boolean = this.lock.write { this.delete0() }
private fun delete0(): Boolean {
var success = false
success = Files.deleteIfExists(this.dataPath) || success
success = Files.deleteIfExists(this.spongeDataPath) || success
success = Files.deleteIfExists(this.advancementsPath) || success
success = Files.deleteIfExists(this.statisticsPath) || success
return success
}
}
| mit | 31ecd4aa0f914f045d7943940342a972 | 35.994318 | 122 | 0.652434 | 4.543615 | false | false | false | false |
Nearsoft/nearbooks-android | app/src/main/java/com/nearsoft/nearbooks/view/widgets/SquareFrameLayout.kt | 2 | 2642 | /*
* Copyright (C) 2014 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.nearsoft.nearbooks.view.widgets
import android.annotation.TargetApi
import android.content.Context
import android.os.Build
import android.util.AttributeSet
import android.widget.FrameLayout
/**
* [FrameLayout] which forces itself to be laid out as square.
*/
class SquareFrameLayout : FrameLayout {
constructor(context: Context) : super(context) {
}
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
}
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
constructor(context: Context, attrs: AttributeSet,
defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes) {
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
val widthSize = MeasureSpec.getSize(widthMeasureSpec)
val heightSize = MeasureSpec.getSize(heightMeasureSpec)
if (widthSize == 0 && heightSize == 0) {
// If there are no constraints on size, let FrameLayout measure
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
// Now use the smallest of the measured dimensions for both dimensions
val minSize = Math.min(measuredWidth, measuredHeight)
setMeasuredDimension(minSize, minSize)
return
}
val size: Int
if (widthSize == 0 || heightSize == 0) {
// If one of the dimensions has no restriction on size, set both dimensions to be the
// on that does
size = Math.max(widthSize, heightSize)
} else {
// Both dimensions have restrictions on size, set both dimensions to be the
// smallest of the two
size = Math.min(widthSize, heightSize)
}
val newMeasureSpec = MeasureSpec.makeMeasureSpec(size, MeasureSpec.EXACTLY)
super.onMeasure(newMeasureSpec, newMeasureSpec)
}
}
| mit | 65af754c1f999ee31dbaf3ed69010086 | 35.191781 | 113 | 0.685087 | 4.743268 | false | false | false | false |
hellenxu/AndroidAdvanced | CrashCases/app/src/main/java/six/ca/crashcases/fragment/data/AppEventCenter.kt | 1 | 1471 | package six.ca.crashcases.fragment.data
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.channels.ConflatedBroadcastChannel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
/**
* @author hellenxu
* @date 2020-11-09
* Copyright 2020 Six. All rights reserved.
*/
@ExperimentalCoroutinesApi
class AppEventCenter private constructor(): AppEventCenterInterface {
private val _appEventFlow: MutableStateFlow<Event> = MutableStateFlow(Event.Standby)
private val appEventFlow: StateFlow<Event>
get() = _appEventFlow
@FlowPreview
@Synchronized
override fun subscribe(): Flow<Event> {
return appEventFlow
}
override fun reset() {
_appEventFlow.value = Event.Standby
}
override fun send(msg: Event): Boolean {
_appEventFlow.value = msg
return true
}
companion object {
@Volatile
private var instance: AppEventCenter? = null
fun getInstance(para: String = ""): AppEventCenter {
return instance ?: run {
synchronized(this) {
instance = AppEventCenter()
return@run instance!!
}
}
}
}
}
sealed class Event {
class SwitchTab(val tab: String): Event()
object Update: Event()
object Standby: Event()
} | apache-2.0 | 1456f5ac1294492a0631774d9980ae0f | 23.533333 | 88 | 0.662135 | 4.838816 | false | false | false | false |
RoverPlatform/rover-android | experiences/src/main/kotlin/io/rover/sdk/experiences/ui/blocks/image/ViewImage.kt | 1 | 2693 | package io.rover.sdk.experiences.ui.blocks.image
import android.view.View
import androidx.appcompat.widget.AppCompatImageView
import android.widget.ImageView
import io.rover.sdk.core.streams.androidLifecycleDispose
import io.rover.sdk.core.streams.subscribe
import io.rover.sdk.experiences.ui.concerns.ViewModelBinding
import io.rover.sdk.experiences.ui.concerns.MeasuredBindableView
/**
* Mixin that binds an image block view model to the relevant parts of an [ImageView].
*/
internal class ViewImage(
private val imageView: AppCompatImageView
) : ViewImageInterface {
private val shortAnimationDuration = imageView.resources.getInteger(
android.R.integer.config_shortAnimTime
)
init {
imageView.scaleType = ImageView.ScaleType.FIT_XY
}
override var viewModelBinding: MeasuredBindableView.Binding<ImageBlockViewModelInterface>? by ViewModelBinding { binding, subscriptionCallback ->
if (binding != null) {
val measuredSize = binding.measuredSize ?: throw RuntimeException("ViewImage may only be used with a view model binding including a measured size (ie. used within a Rover screen layout).")
with(imageView) {
alpha = 0f
val isAccessible = binding.viewModel.isClickable || !binding.viewModel.isDecorative
isFocusableInTouchMode = isAccessible
importantForAccessibility = if (isAccessible) {
contentDescription = binding.viewModel.accessibilityLabel
View.IMPORTANT_FOR_ACCESSIBILITY_YES
} else {
View.IMPORTANT_FOR_ACCESSIBILITY_NO
}
}
// we need to know the laid out dimensions of the view in order to ask the view
// model for an optimized version of the image suited to the view's size.
binding.viewModel.imageUpdates.androidLifecycleDispose(
imageView
).subscribe({ imageUpdate ->
imageView.setImageBitmap(imageUpdate.bitmap)
if (imageUpdate.fadeIn) {
imageView.animate()
// TODO: we should not have to peek the surrounding ImageBlockViewModel interface to discover opacity.
.alpha(binding.viewModel.opacity)
.setDuration(shortAnimationDuration.toLong())
.start()
} else {
imageView.alpha = binding.viewModel.opacity
}
}, { error -> throw(error) }, { subscriptionCallback(it) })
binding.viewModel.informDimensions(measuredSize)
}
}
}
| apache-2.0 | 43793872ada2b72b5b97f9c0af3878af | 41.078125 | 200 | 0.644634 | 5.322134 | false | false | false | false |
if710/if710.github.io | 2019-10-02/BroadcastReceiver/app/src/main/java/br/ufpe/cin/android/broadcastreceiver/BateriaActivity.kt | 1 | 1900 | package br.ufpe.cin.android.broadcastreceiver
import android.app.Activity
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.BatteryManager
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_bateria.*
class BateriaActivity : Activity() {
internal var onBattery: BroadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val pct = 100 * intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 1) / intent.getIntExtra(BatteryManager.EXTRA_SCALE, 1)
barra_carga.progress = pct
nivel_carga.text = pct.toString() + "%"
when (intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1)) {
BatteryManager.BATTERY_STATUS_CHARGING -> status_carga!!.text = "carregando"
BatteryManager.BATTERY_STATUS_FULL -> {
val plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1)
if (plugged == BatteryManager.BATTERY_PLUGGED_AC || plugged == BatteryManager.BATTERY_PLUGGED_USB) {
status_carga.text = "bateria cheia, plugada"
} else {
status_carga.text = "bateria cheia, mas descarregando"
}
}
else -> status_carga.text = "bateria descarregando"
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_bateria)
}
override fun onStart() {
super.onStart()
val f = IntentFilter(Intent.ACTION_BATTERY_CHANGED)
registerReceiver(onBattery, f)
}
override fun onStop() {
unregisterReceiver(onBattery)
super.onStop()
}
}
| mit | 6fa21fb45fe276f6f5a5f6daf43de018 | 32.928571 | 129 | 0.636316 | 4.398148 | false | false | false | false |
if710/if710.github.io | 2019-10-02/SystemServices/app/src/main/java/br/ufpe/cin/android/systemservices/sensor/SensorSingleValueActivity.kt | 1 | 3111 | package br.ufpe.cin.android.systemservices.sensor
import android.app.Activity
import android.content.Context
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import android.os.Bundle
import br.ufpe.cin.android.systemservices.R
import kotlinx.android.synthetic.main.activity_sensor_single_value.*
class SensorSingleValueActivity : Activity(), SensorEventListener {
internal var sensorManager: SensorManager? = null
internal var sensor: Sensor? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
sensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager
setContentView(R.layout.activity_sensor_single_value)
val i = intent
val sName = i.getStringExtra(SensorListActivity.SENSOR_NAME)
if (sName == null) {
finish()
}
val sType = i.getIntExtra(SensorListActivity.SENSOR_TYPE, Sensor.TYPE_ALL)
val listSensors = sensorManager?.getSensorList(sType)
if (listSensors != null) {
for (s in listSensors) {
if (s.name == sName) {
sensor = s
}
}
}
if (sensor == null) {
finish()
} else {
sensorName.text = sensor!!.name
}
}
override fun onStart() {
super.onStart()
//SensorManager.SENSOR_DELAY_UI
//SensorManager.SENSOR_DELAY_GAME
//SensorManager.SENSOR_DELAY_FASTEST
sensorManager?.registerListener(this, sensor, SensorManager.SENSOR_DELAY_NORMAL)
}
override fun onStop() {
//deixar de registrar é prejudicial, pois continua consumindo eventos do sensor
//ignora activity lifecycle, então é similar a um memory leak
//battery drain!
sensorManager?.unregisterListener(this)
super.onStop()
}
//recebe objeto SensorEvent representando leitura do Sensor
override fun onSensorChanged(event: SensorEvent) {
val values = arrayOfNulls<Float>(3)
values[0] = event.values[0]
updateValues(values)
//event.accuracy
//event.sensor
//event.timestamp
//Don't block the onSensorChanged() method
/*
Sensor data can change at a high rate, which means the system may call the
onSensorChanged(SensorEvent) method quite often. As a best practice, you
should do as little as possible within the onSensorChanged(SensorEvent) method
so you don't block it. If your application requires you to do any data filtering
or reduction of sensor data, you should perform that work outside of the
onSensorChanged(SensorEvent) method.
*/
}
//mudança na precisão das leituras do sensor
override fun onAccuracyChanged(sensor: Sensor, accuracy: Int) {
//nao estamos utilizando...
}
private fun updateValues(values: Array<Float?>) {
singleValue.text = values[0].toString()
}
}
| mit | 966b8d5ffeba2b6f1731fa29a589983c | 32.397849 | 88 | 0.660979 | 4.64275 | false | false | false | false |
jamieadkins95/Roach | domain/src/main/java/com/jamieadkins/gwent/domain/deck/model/GwentDeck.kt | 1 | 897 | package com.jamieadkins.gwent.domain.deck.model
import com.jamieadkins.gwent.domain.GwentFaction
import com.jamieadkins.gwent.domain.card.model.GwentCard
import com.jamieadkins.gwent.domain.card.model.GwentCardType
import java.util.*
data class GwentDeck(
val id: String,
val name: String = "",
val faction: GwentFaction,
val leader: GwentCard,
val createdAt: Date,
val cards: Map<String, GwentCard> = emptyMap(),
val cardCounts: Map<String, Int> = emptyMap(),
val maxProvisionCost: Int = 150) {
override fun toString(): String {
return "$name $faction ${leader.name}"
}
val totalCardCount: Int = cardCounts.values.sum()
val provisionCost: Int = cards.values.map { it.provisions * cardCounts.getValue(it.id) }.sum()
val unitCount: Int = cards.values.filter { it.type is GwentCardType.Unit }.map { cardCounts.getValue(it.id) }.sum()
} | apache-2.0 | 283fffd3b05f60d36c0704cf2d549849 | 34.92 | 119 | 0.70903 | 3.706612 | false | false | false | false |
colriot/anko | dsl/static/src/common/Ui.kt | 1 | 3238 | /*
* Copyright 2015 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.
*/
@file:JvmMultifileClass
@file:JvmName("UiKt")
package org.jetbrains.anko
import android.app.Activity
import android.app.Fragment
import android.content.Context
import android.view.View
import android.view.ViewGroup
import android.view.ViewManager
import org.jetbrains.anko.custom.ankoView
import org.jetbrains.anko.internals.AnkoInternals.NoBinding
fun <T : View> T.style(style: (View) -> Unit): T {
applyStyle(this, style)
return this
}
@Deprecated("Use ViewManager.ankoView() instead")
fun <T : View> __dslAddView(view: (ctx: Context) -> T, init: T.() -> Unit, manager: ViewManager): T {
return manager.ankoView({ ctx -> view(ctx) }) { init() }
}
@Deprecated("Use Context.ankoView() instead")
fun <T : View> __dslAddView(view: (ctx: Context) -> T, init: T.() -> Unit, ctx: Context): T {
return ctx.ankoView({ ctx -> view(ctx) }) { init() }
}
@Deprecated("Use Activity.ankoView() instead")
fun <T : View> __dslAddView(view: (ctx: Context) -> T, init: T.() -> Unit, act: Activity): T {
return act.ankoView({ ctx -> view(ctx) }) { init() }
}
@Deprecated("Use Context.ankoView() instead")
fun <T : View> __dslAddView(view: (ctx: Context) -> T, init: T.() -> Unit, fragment: Fragment): T {
return (fragment.activity as Context).ankoView({ ctx -> view(ctx) }) { init() }
}
private fun applyStyle(v: View, style: (View) -> Unit) {
style(v)
if (v is ViewGroup) {
val maxIndex = v.childCount - 1
for (i in 0 .. maxIndex) {
v.getChildAt(i)?.let { applyStyle(it, style) }
}
}
}
@NoBinding
fun Context.UI(setContentView: Boolean, init: UiHelper.() -> Unit): UiHelper {
val dsl = UiHelper(this, setContentView)
dsl.init()
return dsl
}
fun Context.UI(init: UiHelper.() -> Unit): UiHelper {
val dsl = UiHelper(this, false)
dsl.init()
return dsl
}
fun Activity.UI(init: UiHelper.() -> Unit): UiHelper = UI(true, init)
fun Fragment.UI(init: UiHelper.() -> Unit): UiHelper = activity.UI(false, init)
class UiHelper(val ctx: Context, private val setContentView: Boolean = true) : ViewManager {
private lateinit var view: View
fun toView() = view
override fun addView(view: View, params: ViewGroup.LayoutParams?) {
this.view = view
if (setContentView) {
when (ctx) {
is Activity -> ctx.setContentView(view)
else -> {}
}
}
}
override fun updateViewLayout(view: View, params: ViewGroup.LayoutParams) {
throw UnsupportedOperationException()
}
override fun removeView(view: View) {
throw UnsupportedOperationException()
}
} | apache-2.0 | d3c349b02fdca6d683b8d00f89328d33 | 30.144231 | 101 | 0.658122 | 3.687927 | false | false | false | false |
QuickBlox/quickblox-android-sdk | sample-videochat-kotlin/app/src/main/java/com/quickblox/sample/videochat/kotlin/services/CallService.kt | 1 | 24033 | package com.quickblox.sample.videochat.kotlin.services
import android.app.*
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.os.Binder
import android.os.Build
import android.os.IBinder
import android.preference.PreferenceManager
import android.text.TextUtils
import android.util.Log
import androidx.annotation.RequiresApi
import androidx.core.app.NotificationCompat
import com.quickblox.chat.QBChatService
import com.quickblox.sample.videochat.kotlin.R
import com.quickblox.sample.videochat.kotlin.activities.CallActivity
import com.quickblox.sample.videochat.kotlin.db.QbUsersDbManager
import com.quickblox.sample.videochat.kotlin.fragments.CAMERA_ENABLED
import com.quickblox.sample.videochat.kotlin.fragments.IS_CURRENT_CAMERA_FRONT
import com.quickblox.sample.videochat.kotlin.fragments.MIC_ENABLED
import com.quickblox.sample.videochat.kotlin.fragments.SPEAKER_ENABLED
import com.quickblox.sample.videochat.kotlin.util.NetworkConnectionChecker
import com.quickblox.sample.videochat.kotlin.utils.*
import com.quickblox.videochat.webrtc.*
import com.quickblox.videochat.webrtc.BaseSession.QBRTCSessionState
import com.quickblox.videochat.webrtc.callbacks.*
import com.quickblox.videochat.webrtc.exception.QBRTCSignalException
import com.quickblox.videochat.webrtc.view.QBRTCVideoTrack
import org.jivesoftware.smack.AbstractConnectionListener
import org.jivesoftware.smack.ConnectionListener
import org.webrtc.CameraVideoCapturer
import java.util.*
import kotlin.collections.HashMap
const val SERVICE_ID = 787
const val CHANNEL_ID = "Quickblox channel"
const val CHANNEL_NAME = "Quickblox background service"
const val MIN_OPPONENT_SIZE = 1
class CallService : Service() {
private var TAG = CallService::class.java.simpleName
private val callServiceBinder: CallServiceBinder = CallServiceBinder()
private var videoTrackMap: MutableMap<Int, QBRTCVideoTrack> = HashMap()
private lateinit var networkConnectionListener: NetworkConnectionListener
private lateinit var networkConnectionChecker: NetworkConnectionChecker
private lateinit var sessionEventsListener: SessionEventsListener
private lateinit var connectionListener: ConnectionListenerImpl
private lateinit var sessionStateListener: SessionStateListener
private lateinit var signalingListener: QBRTCSignalingListener
private lateinit var videoTrackListener: VideoTrackListener
private lateinit var appRTCAudioManager: AppRTCAudioManager
private var callTimerListener: CallTimerListener? = null
private var ringtonePlayer: RingtonePlayer? = null
private var currentSession: QBRTCSession? = null
private var expirationReconnectionTime: Long = 0
private var sharingScreenState: Boolean = false
private var isConnectedCall: Boolean = false
private lateinit var rtcClient: QBRTCClient
private val callTimerTask: CallTimerTask = CallTimerTask()
private var callTime: Long? = null
private val callTimer = Timer()
companion object {
fun start(context: Context) {
val intent = Intent(context, CallService::class.java)
context.startService(intent)
}
fun stop(context: Context) {
val intent = Intent(context, CallService::class.java)
context.stopService(intent)
}
}
override fun onCreate() {
currentSession = WebRtcSessionManager.getCurrentSession()
clearButtonsState()
initNetworkChecker()
initRTCClient()
initListeners()
initAudioManager()
ringtonePlayer = RingtonePlayer(this, R.raw.beep)
super.onCreate()
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
val notification = initNotification()
startForeground(SERVICE_ID, notification)
return super.onStartCommand(intent, flags, startId)
}
override fun onDestroy() {
super.onDestroy()
networkConnectionChecker.unregisterListener(networkConnectionListener)
removeConnectionListener(connectionListener)
releaseCurrentSession()
releaseAudioManager()
stopCallTimer()
clearButtonsState()
clearCallState()
stopForeground(true)
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.cancelAll()
}
override fun onBind(intent: Intent?): IBinder {
return callServiceBinder
}
private fun initNotification(): Notification {
var intentFlag = 0
val notifyIntent = Intent(this, CallActivity::class.java).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
intentFlag = PendingIntent.FLAG_IMMUTABLE
}
val notifyPendingIntent = PendingIntent.getActivity(this, 0, notifyIntent,
intentFlag)
val notificationTitle = getString(R.string.notification_title)
var notificationText = getString(R.string.notification_text, "")
val callTime = getCallTime()
if (!TextUtils.isEmpty(callTime)) {
notificationText = getString(R.string.notification_text, callTime)
}
val bigTextStyle = NotificationCompat.BigTextStyle()
bigTextStyle.setBigContentTitle(notificationTitle)
bigTextStyle.bigText(notificationText)
val channelId: String = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
createNotificationChannel(CHANNEL_ID, CHANNEL_NAME)
} else {
getString(R.string.app_name)
}
val builder = NotificationCompat.Builder(this, channelId)
builder.setStyle(bigTextStyle)
builder.setContentTitle(notificationTitle)
builder.setContentText(notificationText)
builder.setWhen(System.currentTimeMillis())
builder.setSmallIcon(R.drawable.ic_qb_logo)
val bitmapIcon = BitmapFactory.decodeResource(resources, R.mipmap.ic_launcher)
builder.setLargeIcon(bitmapIcon)
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
builder.priority = NotificationManager.IMPORTANCE_LOW
} else {
builder.priority = Notification.PRIORITY_LOW
}
builder.apply {
setContentIntent(notifyPendingIntent)
}
return builder.build()
}
@RequiresApi(Build.VERSION_CODES.O)
private fun createNotificationChannel(channelId: String, channelName: String): String {
val channel = NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_LOW)
channel.lightColor = getColor(R.color.green)
channel.lockscreenVisibility = Notification.VISIBILITY_PUBLIC
val service = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
service.createNotificationChannel(channel)
return channelId
}
private fun getCallTime(): String {
var time = ""
callTime?.let {
val format = String.format("%%0%dd", 2)
val elapsedTime = it / 1000
val seconds = String.format(format, elapsedTime % 60)
val minutes = String.format(format, elapsedTime % 3600 / 60)
val hours = String.format(format, elapsedTime / 3600)
time = "$minutes:$seconds"
if (!TextUtils.isEmpty(hours) && hours != "00") {
time = "$hours:$minutes:$seconds"
}
}
return time
}
fun playRingtone() {
ringtonePlayer?.play(true)
}
fun stopRingtone() {
ringtonePlayer?.stop()
}
private fun initNetworkChecker() {
networkConnectionChecker = NetworkConnectionChecker(application)
networkConnectionListener = NetworkConnectionListener()
networkConnectionChecker.registerListener(networkConnectionListener)
}
private fun initRTCClient() {
rtcClient = QBRTCClient.getInstance(this)
rtcClient.setCameraErrorHandler(CameraEventsListener())
applyRTCSettings()
rtcClient.prepareToProcessCalls()
}
private fun initListeners() {
sessionStateListener = SessionStateListener()
addSessionStateListener(sessionStateListener)
signalingListener = QBRTCSignalingListener()
addSignalingListener(signalingListener)
videoTrackListener = VideoTrackListener()
addVideoTrackListener(videoTrackListener)
connectionListener = ConnectionListenerImpl()
addConnectionListener(connectionListener)
sessionEventsListener = SessionEventsListener()
addSessionEventsListener(sessionEventsListener)
}
private fun initAudioManager() {
appRTCAudioManager = AppRTCAudioManager.create(this)
appRTCAudioManager.setOnWiredHeadsetStateListener { plugged, hasMicrophone ->
shortToast("Headset " + if (plugged) "plugged" else "unplugged")
}
appRTCAudioManager.setBluetoothAudioDeviceStateListener { connected ->
shortToast("Bluetooth " + if (connected) "connected" else "disconnected")
}
appRTCAudioManager.start { selectedAudioDevice, availableAudioDevices ->
shortToast("Audio device switched to $selectedAudioDevice")
}
if (currentSessionExist() && currentSession!!.conferenceType == QBRTCTypes.QBConferenceType.QB_CONFERENCE_TYPE_AUDIO) {
appRTCAudioManager.selectAudioDevice(AppRTCAudioManager.AudioDevice.EARPIECE)
}
}
fun releaseAudioManager() {
appRTCAudioManager.stop()
}
fun currentSessionExist(): Boolean {
return currentSession != null
}
private fun releaseCurrentSession() {
Log.d(TAG, "Release current session")
removeSessionStateListener(sessionStateListener)
removeSignalingListener(signalingListener)
removeSessionEventsListener(sessionEventsListener)
removeVideoTrackListener(videoTrackListener)
currentSession = null
}
fun addConnectionListener(connectionListener: ConnectionListener?) {
QBChatService.getInstance().addConnectionListener(connectionListener)
}
fun removeConnectionListener(connectionListener: ConnectionListener?) {
QBChatService.getInstance().removeConnectionListener(connectionListener)
}
fun addSessionStateListener(callback: QBRTCSessionStateCallback<*>?) {
currentSession?.addSessionCallbacksListener(callback)
}
fun removeSessionStateListener(callback: QBRTCSessionStateCallback<*>?) {
currentSession?.removeSessionCallbacksListener(callback)
}
fun addVideoTrackListener(callback: QBRTCClientVideoTracksCallbacks<QBRTCSession>?) {
currentSession?.addVideoTrackCallbacksListener(callback)
}
fun removeVideoTrackListener(callback: QBRTCClientVideoTracksCallbacks<QBRTCSession>?) {
currentSession?.removeVideoTrackCallbacksListener(callback)
}
private fun addSignalingListener(callback: QBRTCSignalingCallback?) {
currentSession?.addSignalingCallback(callback)
}
private fun removeSignalingListener(callback: QBRTCSignalingCallback?) {
currentSession?.removeSignalingCallback(callback)
}
fun addSessionEventsListener(callback: QBRTCSessionEventsCallback?) {
rtcClient.addSessionCallbacksListener(callback)
}
fun removeSessionEventsListener(callback: QBRTCSessionEventsCallback?) {
rtcClient.removeSessionsCallbacksListener(callback)
}
fun acceptCall(userInfo: Map<String, String>) {
currentSession?.acceptCall(userInfo)
}
fun startCall(userInfo: Map<String, String>) {
currentSession?.startCall(userInfo)
}
fun rejectCurrentSession(userInfo: Map<String, String>) {
currentSession?.rejectCall(userInfo)
}
fun hangUpCurrentSession(userInfo: Map<String, String>): Boolean {
stopRingtone()
var result = false
currentSession?.let {
it.hangUp(userInfo)
result = true
}
return result
}
fun setAudioEnabled(enabled: Boolean) {
currentSession?.mediaStreamManager?.localAudioTrack?.setEnabled(enabled)
}
fun startScreenSharing(data: Intent) {
sharingScreenState = true
currentSession?.mediaStreamManager?.videoCapturer = QBRTCScreenCapturer(data, null)
}
fun stopScreenSharing() {
sharingScreenState = false
try {
currentSession?.mediaStreamManager?.videoCapturer = QBRTCCameraVideoCapturer(this, null)
} catch (e: QBRTCCameraVideoCapturer.QBRTCCameraCapturerException) {
Log.i(TAG, "Error: device doesn't have camera")
}
}
fun getCallerId(): Int? {
return currentSession?.callerID
}
fun getOpponents(): List<Int>? {
return currentSession?.opponents
}
fun isVideoCall(): Boolean {
return QBRTCTypes.QBConferenceType.QB_CONFERENCE_TYPE_VIDEO == currentSession?.conferenceType
}
fun setVideoEnabled(videoEnabled: Boolean) {
currentSession?.mediaStreamManager?.localVideoTrack?.setEnabled(videoEnabled)
}
fun getCurrentSessionState(): BaseSession.QBRTCSessionState? {
return currentSession?.state
}
fun isMediaStreamManagerExist(): Boolean {
return currentSession?.mediaStreamManager != null
}
fun getPeerChannel(userId: Int): QBRTCTypes.QBRTCConnectionState? {
return currentSession?.getPeerConnection(userId)?.state
}
fun isCurrentSession(session: QBRTCSession?): Boolean {
var isCurrentSession = false
session?.let {
isCurrentSession = currentSession?.sessionID == it.sessionID
}
return isCurrentSession
}
fun switchCamera(cameraSwitchHandler: CameraVideoCapturer.CameraSwitchHandler) {
val videoCapturer = currentSession?.mediaStreamManager?.videoCapturer as QBRTCCameraVideoCapturer
videoCapturer.switchCamera(cameraSwitchHandler)
}
fun switchAudio() {
Log.v(TAG, "onSwitchAudio(), SelectedAudioDevice() = " + appRTCAudioManager.selectedAudioDevice)
if (appRTCAudioManager.selectedAudioDevice != AppRTCAudioManager.AudioDevice.SPEAKER_PHONE) {
appRTCAudioManager.selectAudioDevice(AppRTCAudioManager.AudioDevice.SPEAKER_PHONE)
} else {
if (appRTCAudioManager.audioDevices.contains(AppRTCAudioManager.AudioDevice.BLUETOOTH)) {
appRTCAudioManager.selectAudioDevice(AppRTCAudioManager.AudioDevice.BLUETOOTH)
} else if (appRTCAudioManager.audioDevices.contains(AppRTCAudioManager.AudioDevice.WIRED_HEADSET)) {
appRTCAudioManager.selectAudioDevice(AppRTCAudioManager.AudioDevice.WIRED_HEADSET)
} else {
appRTCAudioManager.selectAudioDevice(AppRTCAudioManager.AudioDevice.EARPIECE)
}
}
}
fun isSharingScreenState(): Boolean {
return sharingScreenState
}
fun isConnectedCall(): Boolean {
return isConnectedCall
}
fun getVideoTrackMap(): MutableMap<Int, QBRTCVideoTrack> {
return videoTrackMap
}
private fun addVideoTrack(userId: Int, videoTrack: QBRTCVideoTrack) {
videoTrackMap[userId] = videoTrack
}
fun getVideoTrack(userId: Int?): QBRTCVideoTrack? {
return videoTrackMap[userId]
}
private fun removeVideoTrack(userId: Int?) {
val videoTrack = getVideoTrack(userId)
val renderer = videoTrack?.renderer
videoTrack?.removeRenderer(renderer)
videoTrackMap.remove(userId)
}
fun setCallTimerCallback(callback: CallTimerListener) {
callTimerListener = callback
}
fun removeCallTimerCallback() {
callTimerListener = null
}
private fun startCallTimer() {
if (callTime == null) {
callTime = 1000
}
if (!callTimerTask.isRunning) {
callTimer.scheduleAtFixedRate(callTimerTask, 0, 1000)
}
}
private fun stopCallTimer() {
callTimerListener = null
callTimer.cancel()
callTimer.purge()
}
fun clearButtonsState() {
SharedPrefsHelper.delete(MIC_ENABLED)
SharedPrefsHelper.delete(SPEAKER_ENABLED)
SharedPrefsHelper.delete(CAMERA_ENABLED)
SharedPrefsHelper.delete(IS_CURRENT_CAMERA_FRONT)
}
fun clearCallState() {
SharedPrefsHelper.delete(EXTRA_IS_INCOMING_CALL)
}
private inner class CallTimerTask : TimerTask() {
var isRunning: Boolean = false
override fun run() {
isRunning = true
callTime = callTime?.plus(1000L)
val notification = initNotification()
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.notify(SERVICE_ID, notification)
callTimerListener?.let {
val callTime = getCallTime()
if (!TextUtils.isEmpty(callTime)) {
it.onCallTimeUpdate(callTime)
}
}
}
}
inner class CallServiceBinder : Binder() {
fun getService(): CallService = this@CallService
}
private inner class ConnectionListenerImpl : AbstractConnectionListener() {
override fun connectionClosedOnError(e: Exception?) {
val HANG_UP_TIME_10_SECONDS = 10 * 1000
expirationReconnectionTime = System.currentTimeMillis() + HANG_UP_TIME_10_SECONDS
}
override fun reconnectionSuccessful() {
}
override fun reconnectingIn(seconds: Int) {
Log.i(TAG, "reconnectingIn $seconds")
if (!isConnectedCall && expirationReconnectionTime < System.currentTimeMillis()) {
hangUpCurrentSession(HashMap())
}
}
}
private inner class SessionEventsListener : QBRTCClientSessionCallbacks {
override fun onUserNotAnswer(session: QBRTCSession?, userId: Int?) {
stopRingtone()
}
override fun onSessionStartClose(session: QBRTCSession?) {
// empty
}
override fun onReceiveHangUpFromUser(session: QBRTCSession?, userID: Int?, p2: MutableMap<String, String>?) {
stopRingtone()
if (session == WebRtcSessionManager.getCurrentSession()) {
val numberOpponents = session?.opponents?.size
if (numberOpponents == MIN_OPPONENT_SIZE || session?.state == QBRTCSessionState.QB_RTC_SESSION_PENDING) {
if (userID?.equals(session.callerID) == true){
currentSession?.hangUp(HashMap<String, String>())
}
} else {
userID?.let {
removeVideoTrack(it)
}
}
}
val participant = QbUsersDbManager.getUserById(userID)
val participantName = if (participant != null) participant.fullName else userID.toString()
shortToast("User " + participantName + " " + getString(R.string.text_status_hang_up) + " conversation")
}
override fun onCallAcceptByUser(session: QBRTCSession?, p1: Int?, p2: MutableMap<String, String>?) {
stopRingtone()
if (session != WebRtcSessionManager.getCurrentSession()) {
return
}
}
override fun onReceiveNewSession(session: QBRTCSession?) {
Log.d(TAG, "Session " + session?.sessionID + " are income")
WebRtcSessionManager.getCurrentSession()?.let {
Log.d(TAG, "Stop new session. Device now is busy")
session?.rejectCall(null)
}
}
override fun onUserNoActions(p0: QBRTCSession?, p1: Int?) {
longToast("Call was stopped by UserNoActions timer")
clearCallState()
clearButtonsState()
WebRtcSessionManager.setCurrentSession(null)
CallService.stop(this@CallService)
}
override fun onSessionClosed(session: QBRTCSession?) {
Log.d(TAG, "Session " + session?.sessionID + " start stop session")
if (session == currentSession) {
stopRingtone()
Log.d(TAG, "Stop session")
CallService.stop(this@CallService)
}
}
override fun onCallRejectByUser(session: QBRTCSession?, p1: Int?, p2: MutableMap<String, String>?) {
stopRingtone()
if (session != WebRtcSessionManager.getCurrentSession()) {
return
}
}
}
private inner class SessionStateListener : QBRTCSessionStateCallback<QBRTCSession> {
override fun onDisconnectedFromUser(session: QBRTCSession?, userId: Int?) {
Log.d(TAG, "Disconnected from user: $userId")
}
override fun onConnectedToUser(session: QBRTCSession?, userId: Int?) {
stopRingtone()
isConnectedCall = true
Log.d(TAG, "onConnectedToUser() is started")
startCallTimer()
}
override fun onConnectionClosedForUser(session: QBRTCSession?, userID: Int?) {
Log.d(TAG, "Connection closed for user: $userID")
shortToast("The user: " + userID + "has left the call")
removeVideoTrack(userID)
}
override fun onStateChanged(session: QBRTCSession?, sessionState: BaseSession.QBRTCSessionState?) {
}
}
private inner class QBRTCSignalingListener : QBRTCSignalingCallback {
override fun onSuccessSendingPacket(p0: QBSignalingSpec.QBSignalCMD?, p1: Int?) {
// empty
}
override fun onErrorSendingPacket(p0: QBSignalingSpec.QBSignalCMD?, p1: Int?, p2: QBRTCSignalException?) {
shortToast(R.string.dlg_signal_error)
}
}
private inner class NetworkConnectionListener : NetworkConnectionChecker.OnConnectivityChangedListener {
override fun connectivityChanged(availableNow: Boolean) {
shortToast("Internet connection " + if (availableNow) "available" else " unavailable")
}
}
private inner class CameraEventsListener : CameraVideoCapturer.CameraEventsHandler {
override fun onCameraError(s: String) {
shortToast("Camera error: $s")
}
override fun onCameraDisconnected() {
shortToast("Camera Disconnected: ")
}
override fun onCameraFreezed(s: String) {
shortToast("Camera freezed: $s")
hangUpCurrentSession(HashMap())
}
override fun onCameraOpening(s: String) {
shortToast("Camera opening: $s")
}
override fun onFirstFrameAvailable() {
shortToast("onFirstFrameAvailable: ")
}
override fun onCameraClosed() {
shortToast("Camera closed: ")
}
}
private inner class VideoTrackListener : QBRTCClientVideoTracksCallbacks<QBRTCSession> {
override fun onLocalVideoTrackReceive(session: QBRTCSession?, videoTrack: QBRTCVideoTrack?) {
videoTrack?.let {
val userId = QBChatService.getInstance().user.id
removeVideoTrack(userId)
addVideoTrack(userId, it)
}
Log.d(TAG, "onLocalVideoTrackReceive() run")
}
override fun onRemoteVideoTrackReceive(session: QBRTCSession?, videoTrack: QBRTCVideoTrack?, userId: Int?) {
if (videoTrack != null && userId != null) {
addVideoTrack(userId, videoTrack)
}
Log.d(TAG, "onRemoteVideoTrackReceive for opponent= $userId")
}
}
interface CallTimerListener {
fun onCallTimeUpdate(time: String)
}
} | bsd-3-clause | a9e346344d170c44db4a3f979e233beb | 35.032984 | 127 | 0.67295 | 5.150664 | false | false | false | false |
gpolitis/jitsi-videobridge | jvb/src/main/kotlin/org/jitsi/videobridge/cc/vp9/Vp9AdaptiveSourceProjectionContext.kt | 1 | 24307 | /*
* Copyright @ 2019-present 8x8, 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 org.jitsi.videobridge.cc.vp9
import org.jitsi.nlj.PacketInfo
import org.jitsi.nlj.RtpLayerDesc.Companion.indexString
import org.jitsi.nlj.codec.vpx.VpxUtils.Companion.applyExtendedPictureIdDelta
import org.jitsi.nlj.codec.vpx.VpxUtils.Companion.applyTl0PicIdxDelta
import org.jitsi.nlj.codec.vpx.VpxUtils.Companion.getExtendedPictureIdDelta
import org.jitsi.nlj.codec.vpx.VpxUtils.Companion.getTl0PicIdxDelta
import org.jitsi.nlj.format.PayloadType
import org.jitsi.nlj.rtp.codec.vp9.Vp9Packet
import org.jitsi.rtp.rtcp.RtcpSrPacket
import org.jitsi.rtp.util.RtpUtils.Companion.applySequenceNumberDelta
import org.jitsi.rtp.util.RtpUtils.Companion.applyTimestampDelta
import org.jitsi.rtp.util.RtpUtils.Companion.getSequenceNumberDelta
import org.jitsi.rtp.util.RtpUtils.Companion.getTimestampDiff
import org.jitsi.rtp.util.isNewerThan
import org.jitsi.utils.logging.DiagnosticContext
import org.jitsi.utils.logging.TimeSeriesLogger
import org.jitsi.utils.logging2.Logger
import org.jitsi.utils.logging2.createChildLogger
import org.jitsi.videobridge.cc.AdaptiveSourceProjectionContext
import org.jitsi.videobridge.cc.RewriteException
import org.jitsi.videobridge.cc.RtpState
import org.json.simple.JSONArray
import org.json.simple.JSONObject
/**
* This class represents a projection of a VP9 RTP stream
* and it is the main entry point for VP9 simulcast/svc RTP/RTCP rewriting. Read
* svc.md for implementation details. Instances of this class are thread-safe.
*/
class Vp9AdaptiveSourceProjectionContext(
private val diagnosticContext: DiagnosticContext,
private val payloadType: PayloadType,
rtpState: RtpState,
parentLogger: Logger
) : AdaptiveSourceProjectionContext {
private val logger: Logger = createChildLogger(parentLogger)
/**
* A map that stores the per-encoding VP9 picture maps.
*/
private val vp9PictureMaps = HashMap<Long, Vp9PictureMap>()
/**
* The [Vp9QualityFilter] instance that does quality filtering on the
* incoming pictures, to choose encodings and layers to forward.
*/
private val vp9QualityFilter = Vp9QualityFilter(logger)
private var lastVp9FrameProjection = Vp9FrameProjection(
diagnosticContext,
rtpState.ssrc, rtpState.maxSequenceNumber, rtpState.maxTimestamp
)
/**
* The picture ID index that started the latest stream resumption.
* We can't send frames with picIdIdx less than this, because we don't have
* space in the projected sequence number/picId/tl0PicIdx counts.
*/
private var lastPicIdIndexResumption = -1
@Synchronized
override fun accept(
packetInfo: PacketInfo,
incomingIndex: Int,
targetIndex: Int
): Boolean {
val packet = packetInfo.packet
if (packet !is Vp9Packet) {
logger.warn("Packet is not Vp9 packet")
return false
}
/* If insertPacketInMap returns null, this is a very old picture, more than Vp9PictureMap.PICTURE_MAP_SIZE old,
or something is wrong with the stream. */
val result = insertPacketInMap(packet) ?: return false
val frame = result.frame
if (result.isNewFrame) {
if (packet.isKeyframe && frameIsNewSsrc(frame)) {
/* If we're not currently projecting this SSRC, check if we've
* already decided to drop a subsequent base TL0 frame of this SSRC.
* If we have, we can't turn on the encoding starting from this
* packet, so treat this frame as though it weren't a keyframe.
*/
val f: Vp9Frame? = findNextBaseTl0(frame)
if (f != null && !f.isAccepted) {
frame.isKeyframe = false
}
}
val receivedMs = packetInfo.receivedTime
val acceptResult = vp9QualityFilter
.acceptFrame(frame, incomingIndex, targetIndex, receivedMs)
frame.isAccepted = acceptResult.accept && frame.index >= lastPicIdIndexResumption
if (frame.isAccepted) {
val projection: Vp9FrameProjection
try {
projection = createProjection(
frame = frame, initialPacket = packet, isResumption = acceptResult.isResumption,
isReset = result.isReset, mark = acceptResult.mark, receivedMs = receivedMs
)
} catch (e: Exception) {
logger.warn("Failed to create frame projection", e)
/* Make sure we don't have an accepted frame without a projection in the map. */
frame.isAccepted = false
return false
}
frame.projection = projection
if (projection.earliestProjectedSeqNum isNewerThan lastVp9FrameProjection.latestProjectedSeqNum) {
lastVp9FrameProjection = projection
}
}
}
val accept = frame.isAccepted && frame.projection?.accept(packet) == true
if (timeSeriesLogger.isTraceEnabled) {
val pt = diagnosticContext.makeTimeSeriesPoint("rtp_vp9")
.addField("ssrc", packet.ssrc)
.addField("timestamp", packet.timestamp)
.addField("seq", packet.sequenceNumber)
.addField("pictureId", packet.pictureId)
.addField("index", indexString(incomingIndex))
.addField("isInterPicturePredicted", packet.isInterPicturePredicted)
.addField("usesInterLayerDependency", packet.usesInterLayerDependency)
.addField("isUpperLevelReference", packet.isUpperLevelReference)
.addField("targetIndex", indexString(targetIndex))
.addField("new_frame", result.isNewFrame)
.addField("accept", accept)
vp9QualityFilter.addDiagnosticContext(pt)
timeSeriesLogger.trace(pt)
}
return accept
}
/** Look up a Vp9Frame for a packet. */
private fun lookupVp9Frame(vp9Packet: Vp9Packet): Vp9Frame? =
vp9PictureMaps[vp9Packet.ssrc]?.findPicture(vp9Packet)?.frame(vp9Packet)
/**
* Insert a packet in the appropriate Vp9FrameMap.
*/
private fun insertPacketInMap(vp9Packet: Vp9Packet) =
vp9PictureMaps.getOrPut(vp9Packet.ssrc) { Vp9PictureMap(logger) }.insertPacket(vp9Packet)
/**
* Calculate the projected sequence number gap between two frames (of the same encoding),
* allowing collapsing for unaccepted frames.
*/
private fun seqGap(frame1: Vp9Frame, frame2: Vp9Frame): Int {
var seqGap = getSequenceNumberDelta(
frame2.earliestKnownSequenceNumber,
frame1.latestKnownSequenceNumber
)
if (!frame1.isAccepted && !frame2.isAccepted && frame2.isImmediatelyAfter(frame1)) {
/* If neither frame is being projected, and they have consecutive
picture IDs, we don't need to leave any gap. */
seqGap = 0
} else {
/* If the earlier frame wasn't projected, and we haven't seen its
* final packet, we know it has to consume at least one more sequence number. */
if (!frame1.isAccepted && !frame1.seenEndOfFrame && seqGap > 1) {
seqGap--
}
/* Similarly, if the later frame wasn't projected and we haven't seen
* its first packet. */
if (!frame2.isAccepted && !frame2.seenStartOfFrame && seqGap > 1) {
seqGap--
}
/* If the frame wasn't accepted, it has to have consumed at least one sequence number,
* which we can collapse out. */
if (!frame1.isAccepted && seqGap > 0) {
seqGap--
}
}
return seqGap
}
private fun frameIsNewSsrc(frame: Vp9Frame): Boolean =
lastVp9FrameProjection.vp9Frame?.matchesSSRC(frame) != true
/**
* Find the previous frame before the given one.
*/
@Synchronized
private fun prevFrame(frame: Vp9Frame) =
vp9PictureMaps.get(frame.ssrc)?.prevFrame(frame)
/**
* Find the next frame after the given one.
*/
@Synchronized
private fun nextFrame(frame: Vp9Frame) =
vp9PictureMaps.get(frame.ssrc)?.nextFrame(frame)
/**
* Find the previous accepted frame before the given one.
*/
private fun findPrevAcceptedFrame(frame: Vp9Frame) =
vp9PictureMaps.get(frame.ssrc)?.findPrevAcceptedFrame(frame)
/**
* Find the next accepted frame after the given one.
*/
private fun findNextAcceptedFrame(frame: Vp9Frame) =
vp9PictureMaps.get(frame.ssrc)?.findNextAcceptedFrame(frame)
/**
* Find a subsequent base-layer TL0 frame after the given frame
* @param frame The frame to query
* @return A subsequent base-layer TL0 frame, or null
*/
private fun findNextBaseTl0(frame: Vp9Frame) =
vp9PictureMaps.get(frame.ssrc)?.findNextBaseTl0(frame)
/**
* Create a projection for this frame.
*/
private fun createProjection(
frame: Vp9Frame,
initialPacket: Vp9Packet,
mark: Boolean,
isResumption: Boolean,
isReset: Boolean,
receivedMs: Long
): Vp9FrameProjection {
if (frameIsNewSsrc(frame)) {
return createEncodingSwitchProjection(frame, initialPacket, mark, receivedMs)
} else if (isResumption) {
return createResumptionProjection(frame, initialPacket, mark, receivedMs)
} else if (isReset) {
return createResetProjection(frame, initialPacket, mark, receivedMs)
}
return createInEncodingProjection(frame, initialPacket, mark, receivedMs)
}
/**
* Create an projection for the first frame after an encoding switch.
*/
private fun createEncodingSwitchProjection(
frame: Vp9Frame,
initialPacket: Vp9Packet,
mark: Boolean,
receivedMs: Long
): Vp9FrameProjection {
assert(frame.isKeyframe)
lastPicIdIndexResumption = frame.index
var projectedSeqGap = if (!initialPacket.isStartOfFrame) {
val f = prevFrame(frame)
if (f != null) {
/* Leave enough of a gap to fill in the earlier packets of the keyframe */
seqGap(f, frame)
} else {
/* If this is the first packet we've seen on this encoding, and it's not the start of a frame,
* we have a problem - we don't know where this packet might fall in the frame.
* Guess a reasonably-sized guess for the number of packets that might have been dropped, and hope
* we don't end up reusing sequence numbers.
*/
16
}
} else {
1
}
if (lastVp9FrameProjection.vp9Frame?.seenEndOfFrame == false) {
/* Leave a gap to signal to the decoder that the previously routed
frame was incomplete. */
projectedSeqGap++
/* Make sure subsequent packets of the previous projection won't
overlap the new one. (This means the gap, above, will never be
filled in.)
*/
lastVp9FrameProjection.close()
}
val projectedSeq = applySequenceNumberDelta(lastVp9FrameProjection.latestProjectedSeqNum, projectedSeqGap)
// this is a simulcast switch. The typical incremental value =
// 90kHz / 30 = 90,000Hz / 30 = 3000 per frame or per 33ms
val tsDelta: Long
tsDelta = if (lastVp9FrameProjection.createdMs != 0L) {
(3000 * Math.max(1, (receivedMs - lastVp9FrameProjection.createdMs) / 33)).toLong()
} else {
3000
}
val projectedTs = applyTimestampDelta(lastVp9FrameProjection.timestamp, tsDelta)
val picId: Int
val tl0PicIdx: Int
if (lastVp9FrameProjection.vp9Frame != null) {
picId = applyExtendedPictureIdDelta(
lastVp9FrameProjection.pictureId,
1
)
tl0PicIdx = applyTl0PicIdxDelta(
lastVp9FrameProjection.tl0PICIDX,
1
)
} else {
picId = frame.pictureId
tl0PicIdx = frame.tl0PICIDX
}
return Vp9FrameProjection(
diagnosticContext = diagnosticContext,
vp9Frame = frame,
ssrc = lastVp9FrameProjection.ssrc,
timestamp = projectedTs,
sequenceNumberDelta = getSequenceNumberDelta(projectedSeq, initialPacket.sequenceNumber),
pictureId = picId,
tl0PICIDX = tl0PicIdx,
mark = mark,
createdMs = receivedMs
)
}
/**
* Create a projection for the first frame after a resumption, i.e. when a source is turned back on.
*/
private fun createResumptionProjection(
frame: Vp9Frame,
initialPacket: Vp9Packet,
mark: Boolean,
receivedMs: Long
): Vp9FrameProjection {
lastPicIdIndexResumption = frame.index
/* These must be non-null because we don't execute this function unless
frameIsNewSsrc has returned false.
*/
val lastFrame = prevFrame(frame)!!
val lastProjectedFrame = lastVp9FrameProjection.vp9Frame!!
/* Project timestamps linearly. */
val tsDelta = getTimestampDiff(
lastVp9FrameProjection.timestamp,
lastProjectedFrame.timestamp
)
val projectedTs = applyTimestampDelta(frame.timestamp, tsDelta)
/* Increment picId and tl0picidx by 1 from the last projected frame. */
val projectedPicId = applyExtendedPictureIdDelta(lastVp9FrameProjection.pictureId, 1)
val projectedTl0PicIdx = applyTl0PicIdxDelta(lastVp9FrameProjection.tl0PICIDX, 1)
/* Increment sequence numbers based on the last projected frame, but leave a gap
* for packet reordering in case this isn't the first packet of the keyframe.
*/
val seqGap = getSequenceNumberDelta(initialPacket.sequenceNumber, lastFrame.latestKnownSequenceNumber)
val newSeq = applySequenceNumberDelta(lastVp9FrameProjection.latestProjectedSeqNum, seqGap)
val seqDelta = getSequenceNumberDelta(newSeq, initialPacket.sequenceNumber)
return Vp9FrameProjection(
diagnosticContext,
frame, lastVp9FrameProjection.ssrc, projectedTs,
seqDelta,
projectedPicId, projectedTl0PicIdx, mark, receivedMs
)
}
/**
* Create a projection for the first frame after a frame reset, i.e. after a large gap in sequence numbers.
*/
private fun createResetProjection(
frame: Vp9Frame,
initialPacket: Vp9Packet,
mark: Boolean,
receivedMs: Long
): Vp9FrameProjection {
/* This must be non-null because we don't execute this function unless
frameIsNewSsrc has returned false.
*/
val lastFrame = lastVp9FrameProjection.vp9Frame!!
/* Apply the latest projected frame's projections out, linearly. */
val seqDelta = getSequenceNumberDelta(
lastVp9FrameProjection.latestProjectedSeqNum,
lastFrame.latestKnownSequenceNumber
)
val tsDelta = getTimestampDiff(
lastVp9FrameProjection.timestamp,
lastFrame.timestamp
)
val picIdDelta = getExtendedPictureIdDelta(
lastVp9FrameProjection.pictureId,
lastFrame.pictureId
)
val tl0PicIdxDelta = getTl0PicIdxDelta(
lastVp9FrameProjection.tl0PICIDX,
lastFrame.tl0PICIDX
)
val projectedTs = applyTimestampDelta(frame.timestamp, tsDelta)
val projectedPicId = applyExtendedPictureIdDelta(frame.pictureId, picIdDelta)
val projectedTl0PicIdx = applyTl0PicIdxDelta(frame.tl0PICIDX, tl0PicIdxDelta)
return Vp9FrameProjection(
diagnosticContext,
frame, lastVp9FrameProjection.ssrc, projectedTs,
seqDelta,
projectedPicId, projectedTl0PicIdx, mark, receivedMs
)
}
/**
* Create a frame projection for the normal case, i.e. as part of the same encoding as the
* previously-projected frame.
*/
private fun createInEncodingProjection(
frame: Vp9Frame,
initialPacket: Vp9Packet,
mark: Boolean,
receivedMs: Long
): Vp9FrameProjection {
val prevFrame = findPrevAcceptedFrame(frame)
if (prevFrame != null) {
return createInEncodingProjection(frame, prevFrame, initialPacket, mark, receivedMs)
}
/* prev frame has rolled off beginning of frame map, try next frame */
val nextFrame = findNextAcceptedFrame(frame)
if (nextFrame != null) {
return createInEncodingProjection(frame, nextFrame, initialPacket, mark, receivedMs)
}
/* Neither previous or next is found. Very big frame? Use previous projected.
(This must be valid because we don't execute this function unless
frameIsNewSsrc has returned false.)
*/
return createInEncodingProjection(
frame, lastVp9FrameProjection.vp9Frame!!,
initialPacket, mark, receivedMs
)
}
/**
* Create a frame projection for the normal case, i.e. as part of the same encoding as the
* previously-projected frame, based on a specific chosen previously-projected frame.
*/
private fun createInEncodingProjection(
frame: Vp9Frame,
refFrame: Vp9Frame,
initialPacket: Vp9Packet,
mark: Boolean,
receivedMs: Long
): Vp9FrameProjection {
val tsGap = getTimestampDiff(frame.timestamp, refFrame.timestamp)
val tl0Gap = getTl0PicIdxDelta(frame.tl0PICIDX, refFrame.tl0PICIDX)
val picGap = getExtendedPictureIdDelta(frame.pictureId, refFrame.pictureId)
val layerGap = frame.spatialLayer - refFrame.spatialLayer
var seqGap = 0
var f1 = refFrame
var f2: Vp9Frame?
val refSeq: Int
if (picGap > 0 || (picGap == 0 && layerGap > 0)) {
/* refFrame is earlier than frame in decode order. */
do {
f2 = nextFrame(f1)
checkNotNull(f2) {
"No next frame found after frame with picId ${f1.pictureId} layer ${f1.spatialLayer}, " +
"even though refFrame ${refFrame.pictureId}/${refFrame.spatialLayer} is before " +
"frame ${frame.pictureId}/${frame.spatialLayer}!"
}
seqGap += seqGap(f1, f2)
f1 = f2
} while (f2 !== frame)
/* refFrame is a projected frame, so it has a projection. */
refSeq = refFrame.projection!!.latestProjectedSeqNum
} else {
/* refFrame is later than frame in decode order. */
do {
f2 = prevFrame(f1)
checkNotNull(f2) {
"No previous frame found before frame with picId ${f1.pictureId} layer ${f1.spatialLayer}, " +
"even though refFrame ${refFrame.pictureId}/${refFrame.spatialLayer} is after " +
"frame ${frame.pictureId}/${frame.spatialLayer}!"
}
seqGap += -seqGap(f2, f1)
f1 = f2
} while (f2 !== frame)
refSeq = refFrame.projection!!.earliestProjectedSeqNum
}
val projectedSeq = applySequenceNumberDelta(refSeq, seqGap)
val projectedTs = applyTimestampDelta(refFrame.projection!!.timestamp, tsGap)
val projectedPicId = applyExtendedPictureIdDelta(refFrame.projection!!.pictureId, picGap)
val projectedTl0PicIdx = applyTl0PicIdxDelta(refFrame.projection!!.tl0PICIDX, tl0Gap)
return Vp9FrameProjection(
diagnosticContext = diagnosticContext,
vp9Frame = frame,
ssrc = lastVp9FrameProjection.ssrc,
timestamp = projectedTs,
sequenceNumberDelta = getSequenceNumberDelta(projectedSeq, initialPacket.sequenceNumber),
pictureId = projectedPicId,
tl0PICIDX = projectedTl0PicIdx,
mark = mark,
createdMs = receivedMs
)
}
override fun needsKeyframe(): Boolean {
if (vp9QualityFilter.needsKeyframe) {
return true
}
return lastVp9FrameProjection.vp9Frame == null
}
@Throws(RewriteException::class)
override fun rewriteRtp(packetInfo: PacketInfo) {
if (packetInfo.packet !is Vp9Packet) {
logger.info("Got a non-VP9 packet.")
throw RewriteException("Non-VP9 packet in VP9 source projection")
}
val vp9Packet = packetInfo.packetAs<Vp9Packet>()
if (vp9Packet.pictureId == -1) {
/* Should have been routed to generic projection context. */
logger.info("VP9 packet does not have picture ID, cannot track in frame map.")
throw RewriteException("VP9 packet without picture ID in VP9 source projection")
}
val vp9Frame: Vp9Frame = lookupVp9Frame(vp9Packet)
?: throw RewriteException("Frame not in tracker (aged off?)")
val vp9Projection = vp9Frame.projection
?: throw RewriteException("Frame does not have projection?")
/* Shouldn't happen for an accepted packet whose frame is still known? */
vp9Projection.rewriteRtp(vp9Packet)
}
override fun rewriteRtcp(rtcpSrPacket: RtcpSrPacket): Boolean {
val lastVp9FrameProjectionCopy: Vp9FrameProjection = lastVp9FrameProjection
if (rtcpSrPacket.senderSsrc != lastVp9FrameProjectionCopy.vp9Frame?.ssrc) {
return false
}
rtcpSrPacket.senderSsrc = lastVp9FrameProjectionCopy.ssrc
val srcTs = rtcpSrPacket.senderInfo.rtpTimestamp
val delta = getTimestampDiff(
lastVp9FrameProjectionCopy.timestamp,
lastVp9FrameProjectionCopy.vp9Frame.timestamp
)
val dstTs = applyTimestampDelta(srcTs, delta)
if (srcTs != dstTs) {
rtcpSrPacket.senderInfo.rtpTimestamp = dstTs
}
return true
}
override fun getRtpState() = RtpState(
lastVp9FrameProjection.ssrc,
lastVp9FrameProjection.latestProjectedSeqNum,
lastVp9FrameProjection.timestamp
)
override fun getPayloadType(): PayloadType {
return payloadType
}
@Synchronized
override fun getDebugState(): JSONObject {
val debugState = JSONObject()
debugState["class"] = Vp9AdaptiveSourceProjectionContext::class.java.simpleName
val mapSizes = JSONArray()
for ((key, value) in vp9PictureMaps.entries) {
val sizeInfo = JSONObject()
sizeInfo["ssrc"] = key
sizeInfo["size"] = value.size()
mapSizes.add(sizeInfo)
}
debugState["vp9FrameMaps"] = mapSizes
debugState["vp9QualityFilter"] = vp9QualityFilter.debugState
debugState["payloadType"] = payloadType.toString()
return debugState
}
companion object {
/**
* The time series logger for this class.
*/
private val timeSeriesLogger =
TimeSeriesLogger.getTimeSeriesLogger(Vp9AdaptiveSourceProjectionContext::class.java)
}
}
| apache-2.0 | d376e6697a57886105963722eadb98bc | 38.523577 | 119 | 0.636072 | 4.455912 | false | false | false | false |
CharlieZheng/NestedGridViewByListView | app/src/main/java/com/cdc/androidsamples/service/BookManagerService.kt | 1 | 3105 | package com.cdc.androidsamples.service
import android.app.Service
import android.content.Intent
import android.content.pm.PackageManager
import android.os.IBinder
import android.os.RemoteCallbackList
import android.util.Log
import com.cdc.aidl.Book
import com.cdc.aidl.IBookManager
import com.cdc.aidl.IOnNewBookArrivedListener
import java.util.concurrent.CopyOnWriteArrayList
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
/**
* @author zhenghanrong on 2017/11/11.
*/
class BookManagerService : Service() {
companion object {
private val TAG = BookManagerService::class.java.simpleName
}
private val serviceDestroyed = AtomicBoolean(false)
private val bookList = CopyOnWriteArrayList<Book>()
private val listenerList = RemoteCallbackList<IOnNewBookArrivedListener>()
private val binder = object : IBookManager.Stub() {
// fixme 大坑啊,得用[email protected]
override fun getBookList(): MutableList<Book> {
return [email protected]
}
override fun addBook(book: Book?) {
if (book != null) [email protected](book)
}
override fun registerListener(listener: IOnNewBookArrivedListener?) {
listenerList.register(listener)
val size = listenerList.beginBroadcast()
Log.v(TAG, "listenerList's size after register: " + size)
listenerList.finishBroadcast()
}
override fun unregisterListener(listener: IOnNewBookArrivedListener?) {
listenerList.unregister(listener)
Log.d(TAG, "unregister listener succeed.")
val size = listenerList.beginBroadcast()
Log.v(TAG, "listenerList's size after register: " + size)
listenerList.finishBroadcast()
}
}
private fun onNewBookArrived(book: Book) {
bookList.add(book)
val N = listenerList.beginBroadcast()
for (i in 0..(N-1)) {
val item = listenerList.getBroadcastItem(i)
Log.d(TAG, "onNewBookArrived, notify listener: " + item)
item.onNewBookArrived(book)
}
listenerList.finishBroadcast()
}
private inner class Worker : Runnable {
override fun run() {
while (!serviceDestroyed.get()) {
TimeUnit.SECONDS.sleep(5)
val bookId = bookList.size + 1
val newBook = Book(bookId, "new book#" + bookId)
onNewBookArrived(newBook)
}
}
}
override fun onCreate() {
super.onCreate()
bookList.add(Book(1, "Android"))
bookList.add(Book(2, "IOS"))
Thread(Worker()).start()
}
override fun onBind(intent: Intent?): IBinder? {
val check = checkCallingOrSelfPermission("com.cdc.permission.ACCESS_BOOK_SERVICE")
when (check) {
PackageManager.PERMISSION_DENIED -> {
return null
}
else -> {
return binder
}
}
}
} | apache-2.0 | 0495d9588f0a01c4215d25df2cbd7204 | 32.630435 | 90 | 0.633366 | 4.463203 | false | false | false | false |
ken-kentan/student-portal-plus | app/src/main/java/jp/kentan/studentportalplus/ui/lectureinfo/LectureInfoFragment.kt | 1 | 5572 | package jp.kentan.studentportalplus.ui.lectureinfo
import android.os.Bundle
import android.view.*
import android.widget.ArrayAdapter
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.widget.SearchView
import androidx.core.view.isVisible
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.DividerItemDecoration
import dagger.android.support.AndroidSupportInjection
import jp.kentan.studentportalplus.R
import jp.kentan.studentportalplus.data.component.LectureQuery
import jp.kentan.studentportalplus.databinding.DialogLectureFilterBinding
import jp.kentan.studentportalplus.databinding.FragmentListBinding
import jp.kentan.studentportalplus.ui.ViewModelFactory
import jp.kentan.studentportalplus.ui.lectureinfo.detail.LectureInfoDetailActivity
import jp.kentan.studentportalplus.ui.main.FragmentType
import jp.kentan.studentportalplus.ui.main.MainViewModel
import jp.kentan.studentportalplus.util.animateFadeInDelay
import javax.inject.Inject
class LectureInfoFragment : Fragment() {
companion object {
fun newInstance() = LectureInfoFragment()
}
@Inject
lateinit var viewModelFactory: ViewModelFactory
private lateinit var binding: FragmentListBinding
private lateinit var viewModel: LectureInfoViewModel
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_list, container, false)
return binding.root
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
AndroidSupportInjection.inject(this)
setHasOptionsMenu(true)
val provider = ViewModelProvider(requireActivity(), viewModelFactory)
viewModel = provider.get(LectureInfoViewModel::class.java)
val adapter = LectureInfoAdapter(layoutInflater, viewModel::onClick)
binding.recyclerView.apply {
setAdapter(adapter)
setHasFixedSize(true)
addItemDecoration(DividerItemDecoration(context, DividerItemDecoration.VERTICAL))
}
binding.note.text = getString(R.string.text_empty_data, getString(R.string.name_lecture_info))
viewModel.subscribe(adapter)
// Call MainViewModel::onAttachFragment
provider.get(MainViewModel::class.java)
.onAttachFragment(FragmentType.LECTURE_INFO)
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
inflater.inflate(R.menu.search_and_filter, menu)
val searchItem = menu.findItem(R.id.action_search)
val searchView = searchItem.actionView as SearchView
searchView.queryHint = getString(R.string.hint_query_subject_and_instructor)
searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(query: String?) = true
override fun onQueryTextChange(newText: String?): Boolean {
viewModel.onQueryTextChange(newText)
return true
}
})
val keyword = viewModel.query.keyword
if (!keyword.isNullOrBlank()) {
searchItem.expandActionView()
searchView.setQuery(keyword, false)
searchView.clearFocus()
}
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
if (item?.itemId == R.id.action_filter) {
showFilterDialog()
}
return super.onOptionsItemSelected(item)
}
private fun showFilterDialog() {
val context = requireContext()
val binding: DialogLectureFilterBinding =
DataBindingUtil.inflate(layoutInflater, R.layout.dialog_lecture_filter, binding.root as ViewGroup, false)
binding.apply {
orderSpinner.adapter = ArrayAdapter<LectureQuery.Order>(context, android.R.layout.simple_list_item_1, LectureQuery.Order.values())
query = [email protected]
}
AlertDialog.Builder(context)
.setView(binding.root)
.setTitle(R.string.title_filter_dialog)
.setPositiveButton(R.string.action_apply) { _, _ ->
viewModel.onFilterApplyClick(
binding.orderSpinner.selectedItem as LectureQuery.Order,
binding.unreadChip.isChecked,
binding.readChip.isChecked,
binding.attendChip.isChecked
)
}
.setNegativeButton(R.string.action_cancel, null)
.create()
.show()
}
private fun LectureInfoViewModel.subscribe(adapter: LectureInfoAdapter) {
val fragment = this@LectureInfoFragment
lectureInfoList.observe(fragment, Observer { list ->
adapter.submitList(list)
if (list.isEmpty()) {
binding.note.animateFadeInDelay(requireContext())
} else {
binding.note.apply {
alpha = 0f
isVisible = false
}
}
})
startDetailActivity.observe(fragment, Observer { id ->
startActivity(LectureInfoDetailActivity.createIntent(requireContext(), id))
})
}
}
| gpl-3.0 | b29afed074b89b29feaeeda6445abfd3 | 37.164384 | 142 | 0.680366 | 5.332057 | false | false | false | false |
android-pay/paymentsapi-quickstart | kotlin/app/src/main/java/com/google/android/gms/samples/wallet/viewmodel/CheckoutViewModel.kt | 1 | 5333 | package com.google.android.gms.samples.wallet.viewmodel
import android.app.Activity
import android.app.Application
import android.util.Log
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.google.android.gms.common.api.ApiException
import com.google.android.gms.pay.Pay
import com.google.android.gms.pay.PayApiAvailabilityStatus
import com.google.android.gms.pay.PayClient
import com.google.android.gms.samples.wallet.util.PaymentsUtil
import com.google.android.gms.tasks.Task
import com.google.android.gms.wallet.*
class CheckoutViewModel(application: Application) : AndroidViewModel(application) {
// A client for interacting with the Google Pay API.
private val paymentsClient: PaymentsClient = PaymentsUtil.createPaymentsClient(application)
// A client to interact with the Google Wallet API
private val walletClient: PayClient = Pay.getClient(application)
// LiveData with the result of whether the user can pay using Google Pay
private val _canUseGooglePay: MutableLiveData<Boolean> by lazy {
MutableLiveData<Boolean>().also {
fetchCanUseGooglePay()
}
}
// LiveData with the result of whether the user can save passes to Google Wallet
private val _canSavePasses: MutableLiveData<Boolean> by lazy {
MutableLiveData<Boolean>().also {
fetchCanAddPassesToGoogleWallet()
}
}
val canUseGooglePay: LiveData<Boolean> = _canUseGooglePay
val canSavePasses: LiveData<Boolean> = _canSavePasses
/**
* Determine the user's ability to pay with a payment method supported by your app and display
* a Google Pay payment button.
*
* @return a [LiveData] object that holds the future result of the call.
* @see [](https://developers.google.com/android/reference/com/google/android/gms/wallet/PaymentsClient.html.isReadyToPay)
) */
private fun fetchCanUseGooglePay() {
val isReadyToPayJson = PaymentsUtil.isReadyToPayRequest()
if (isReadyToPayJson == null) _canUseGooglePay.value = false
val request = IsReadyToPayRequest.fromJson(isReadyToPayJson.toString())
val task = paymentsClient.isReadyToPay(request)
task.addOnCompleteListener { completedTask ->
try {
_canUseGooglePay.value = completedTask.getResult(ApiException::class.java)
} catch (exception: ApiException) {
Log.w("isReadyToPay failed", exception)
_canUseGooglePay.value = false
}
}
}
/**
* Creates a [Task] that starts the payment process with the transaction details included.
*
* @param priceCents the price to show on the payment sheet.
* @return a [Task] with the payment information.
* @see [](https://developers.google.com/android/reference/com/google/android/gms/wallet/PaymentsClient#loadPaymentData(com.google.android.gms.wallet.PaymentDataRequest)
) */
fun getLoadPaymentDataTask(priceCents: Long): Task<PaymentData> {
val paymentDataRequestJson = PaymentsUtil.getPaymentDataRequest(priceCents)
val request = PaymentDataRequest.fromJson(paymentDataRequestJson.toString())
return paymentsClient.loadPaymentData(request)
}
/**
* Determine whether the API to save passes to Google Pay is available on the device.
*/
private fun fetchCanAddPassesToGoogleWallet() {
walletClient
.getPayApiAvailabilityStatus(PayClient.RequestType.SAVE_PASSES)
.addOnSuccessListener { status ->
_canSavePasses.value = status == PayApiAvailabilityStatus.AVAILABLE
// } else {
// We recommend to either:
// 1) Hide the save button
// 2) Fall back to a different Save Passes integration (e.g. JWT link)
// Note that a user might become eligible in the future.
}
.addOnFailureListener {
// Google Play Services is too old. API availability can't be verified.
_canUseGooglePay.value = false
}
}
/**
* Exposes the `savePassesJwt` method in the wallet client
*/
val savePassesJwt: (String, Activity, Int) -> Unit = walletClient::savePassesJwt
/**
* Exposes the `savePasses` method in the wallet client
*/
val savePasses: (String, Activity, Int) -> Unit = walletClient::savePasses
// Test generic object used to be created against the API
val genericObjectJwt = "eyJ0eXAiOiAiSldUIiwgImFsZyI6ICJSUzI1NiIsICJraWQiOiAiMTY4M2VjZDA1MmU5NTgyZWZhNGU5YTQxNjVmYzE5N2JjNmJlYTJhMCJ9.eyJpc3MiOiAid2FsbGV0LWxhYi10b29sc0BhcHBzcG90LmdzZXJ2aWNlYWNjb3VudC5jb20iLCAiYXVkIjogImdvb2dsZSIsICJ0eXAiOiAic2F2ZXRvd2FsbGV0IiwgImlhdCI6IDE2NTA1MzI2MjMsICJwYXlsb2FkIjogeyJnZW5lcmljT2JqZWN0cyI6IFt7ImlkIjogIjMzODgwMDAwMDAwMjIwOTUxNzcuZjUyZDRhZjYtMjQxMS00ZDU5LWFlNDktNzg2ZDY3N2FkOTJiIn1dfX0.fYKw6fpLfwwNMi5OGr4ybO3ybuCU7RYjQhw-QM_Z71mfOyv2wFUzf6dKgpspJKQmkiaBWBr1L9n8jq8ZMfj6iOA_9_njfUe9GepCwVLC0nZBDd2EqS3UrBYT7tEmk7W2-Cpy5FJFTt_eiqXBZgwa6vMw6e6mMp-GzSD5_ls39fjOPziboLyG-GDmph3f6UhBkjnUjYyY_FoYdlqkTkCWM7AFPcy-FbRyVDpIaHfVk4eYQi4Vzk0fwxaWWTfP3gSXXT6UJ9aFvaPYs0gnlV2WPVgGGKCMtYHFRGYX1t0WRpN2kbxfO5VuMKWJlz3TCnxp-9Axz-enuCgnq2cLvCk6Tw"
} | apache-2.0 | 9caa6d41268ade9dd374620c67b66a9d | 47.490909 | 768 | 0.730358 | 3.608254 | false | false | false | false |
pgutkowski/KGraphQL | src/jmh/kotlin/com/github/pgutkowski/kgraphql/RequestCachingBenchmark.kt | 1 | 1131 | package com.github.pgutkowski.kgraphql
import com.github.pgutkowski.kgraphql.schema.Schema
import org.openjdk.jmh.annotations.Benchmark
import org.openjdk.jmh.annotations.Fork
import org.openjdk.jmh.annotations.Measurement
import org.openjdk.jmh.annotations.OutputTimeUnit
import org.openjdk.jmh.annotations.Param
import org.openjdk.jmh.annotations.Scope
import org.openjdk.jmh.annotations.Setup
import org.openjdk.jmh.annotations.State
import org.openjdk.jmh.annotations.Warmup
import java.util.concurrent.TimeUnit
@State(Scope.Benchmark)
@Warmup(iterations = 10)
@Measurement(iterations = 5)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@Fork(value = 5)
open class RequestCachingBenchmark {
@Param("true", "false")
var caching = true
lateinit var schema : Schema
@Setup
fun setup(){
schema = BenchmarkSchema.create {
configure {
useCachingDocumentParser = caching
}
}
}
@Benchmark
fun benchmark() : String {
return schema.execute("{one{name, quantity, active}, two(name : \"FELLA\"){range{start, endInclusive}}, three{id}}")
}
} | mit | 3fce24620eed958ae31d195e0df463de | 26.609756 | 124 | 0.724138 | 4.068345 | false | false | false | false |
outlying/MpkTransit | creator/src/main/kotlin/com/antyzero/mpk/transit/creator/model/CsvContainer.kt | 1 | 1767 | package com.antyzero.mpk.transit.creator.model
/**
* Universal container for CSV like data
*/
open class CsvContainer<T>(
values: Collection<T> = emptyList(),
private val validator: CsvContainer<T>.(Any?) -> Unit = CsvContainer.checkForDuplicates()) where T : Map<String, Any?> {
val keys: MutableSet<String> = mutableSetOf()
val list: MutableList<T> = mutableListOf()
init {
values.forEach { add(it) }
}
fun add(element: T): Boolean {
validator.invoke(this, element)
element.keys
.takeIf { it.containsAll(this.keys) }
?.let {
this.keys.clear()
this.keys.addAll(element.keys)
}
return list.add(element)
}
override fun toString() = keys.joinToString(separator = ",") + "\n" + stopsToString()
private fun stopsToString(): String {
val stopsCsv = mutableListOf<String>()
for (stop in list) {
val values = mutableListOf<String>()
keys.forEachIndexed { index, key ->
values.add(index, if (stop.containsKey(key)) {
stop[key].toString()
} else {
""
})
}
stopsCsv.add(values.joinToString(separator = ","))
}
return stopsCsv.joinToString(separator = "\n")
}
companion object {
/**
* Validator method, universal
*/
fun <T : Map<String, Any?>> checkForDuplicates(): CsvContainer<T>.(Any?) -> Unit = { stop ->
list.forEach {
if (it == stop) {
throw IllegalStateException("Duplicate value $it")
}
}
}
}
} | gpl-3.0 | 474909c166b0ccecf52638a5ef50d8ee | 28.966102 | 128 | 0.515563 | 4.65 | false | false | false | false |
d9n/intellij-rust | src/main/kotlin/org/rust/ide/inspections/RsVariableMutableInspection.kt | 1 | 2384 | package org.rust.ide.inspections
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.psi.PsiElement
import com.intellij.psi.search.LocalSearchScope
import com.intellij.psi.search.searches.ReferencesSearch
import org.rust.ide.annotator.fixes.RemoveMutableFix
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.ext.descendantsOfType
import org.rust.lang.core.psi.ext.isMut
import org.rust.lang.core.psi.ext.parentOfType
import org.rust.lang.core.psi.ext.selfParameter
class RsVariableMutableInspection : RsLocalInspectionTool() {
override fun getDisplayName() = "No mutable required"
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) =
object : RsVisitor() {
override fun visitPatBinding(o: RsPatBinding) {
if (!o.isMut) return
val block = o.parentOfType<RsBlock>() ?: o.parentOfType<RsFunction>() ?: return
if (ReferencesSearch.search(o, LocalSearchScope(block))
.asSequence()
.any { checkOccurrenceNeedMutable(it.element.parent) }) return
if (block.descendantsOfType<RsMacroExpr>().any { checkExprPosition(o, it) }) return
holder.registerProblem(
o,
"Variable `${o.identifier.text}` does not need to be mutable",
*arrayOf(RemoveMutableFix(o))
)
}
}
fun checkExprPosition(o: RsPatBinding, expr: RsMacroExpr) = o.textOffset < expr.textOffset
fun checkOccurrenceNeedMutable(occurrence: PsiElement): Boolean {
val parent = occurrence.parent
when (parent) {
is RsUnaryExpr -> return parent.isMutable || parent.mul != null
is RsBinaryExpr -> return parent.left == occurrence
is RsMethodCallExpr -> {
val ref = parent.reference.resolve() as? RsFunction ?: return true
val self = ref.selfParameter ?: return true
return self.isMut
}
is RsTupleExpr,
is RsFieldExpr -> {
val expr = parent.parent as? RsUnaryExpr ?: return true
return expr.isMutable
}
is RsValueArgumentList -> return false
}
return true
}
private val RsUnaryExpr.isMutable: Boolean get() = mut != null
}
| mit | e5d946648ab1cd41b876cd97830fac1f | 41.571429 | 99 | 0.630872 | 4.855397 | false | false | false | false |
ibaton/3House | mobile/src/main/java/treehou/se/habit/ui/menu/NavigationDrawerFragment.kt | 1 | 11499 | package treehou.se.habit.ui.menu
import android.content.Context
import android.content.SharedPreferences
import android.content.res.Configuration
import android.os.Bundle
import android.support.annotation.IntDef
import android.support.v4.view.GravityCompat
import android.support.v4.widget.DrawerLayout
import android.support.v7.app.ActionBar
import android.support.v7.app.ActionBarDrawerToggle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.DefaultItemAnimator
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import java.util.ArrayList
import javax.inject.Inject
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.realm.Realm
import se.treehou.ng.ohcommunicator.connector.models.OHServer
import se.treehou.ng.ohcommunicator.connector.models.OHSitemap
import treehou.se.habit.HabitApplication
import treehou.se.habit.R
import treehou.se.habit.dagger.ApplicationComponent
import treehou.se.habit.dagger.ServerLoaderFactory
import treehou.se.habit.dagger.ServerLoaderFactory.ServerSitemapsResponse
import treehou.se.habit.ui.BaseFragment
import treehou.se.habit.util.Settings
class NavigationDrawerFragment : BaseFragment() {
private var mCallbacks: NavigationDrawerCallbacks = DummyNavigationDrawerCallbacks()
/**
* Helper component that ties the action bar to the navigation drawer.
*/
private var mDrawerToggle: ActionBarDrawerToggle? = null
private var mDrawerLayout: DrawerLayout? = null
private var mDrawerListView: RecyclerView? = null
private var mFragmentContainerView: View? = null
private var mCurrentSelectedPosition = 0
private var mUserLearnedDrawer: Boolean = false
private val items = ArrayList<DrawerItem>()
private lateinit var menuAdapter: DrawerAdapter
@Inject lateinit var sharedPreferences: SharedPreferences
@Inject lateinit var settings: Settings
@Inject lateinit var serverLoaderFactory: ServerLoaderFactory
protected val applicationComponent: ApplicationComponent
get() = (activity!!.application as HabitApplication).component()
val isDrawerOpen: Boolean
get() = mDrawerLayout != null && mDrawerLayout!!.isDrawerOpen(mFragmentContainerView!!)
private val actionBar: ActionBar?
get() = (activity as AppCompatActivity).supportActionBar
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
applicationComponent.inject(this)
// Read in the flag indicating whether or not the user has demonstrated awareness of the
// drawer. See PREF_USER_LEARNED_DRAWER for details.
mUserLearnedDrawer = sharedPreferences.getBoolean(PREF_USER_LEARNED_DRAWER, false)
if (savedInstanceState != null) {
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION)
}
items.add(DrawerItem(activity!!.getString(R.string.sitemaps), R.drawable.menu_sitemap, ITEM_SITEMAPS))
items.add(DrawerItem(activity!!.getString(R.string.controllers), R.drawable.menu_remote, ITEM_CONTROLLERS))
items.add(DrawerItem(activity!!.getString(R.string.servers), R.drawable.menu_servers, ITEM_SERVER))
items.add(DrawerItem(activity!!.getString(R.string.settings), R.drawable.menu_settings, ITEM_SETTINGS))
menuAdapter = DrawerAdapter()
val itemClickListener = object : DrawerAdapter.OnItemClickListener {
override fun onClickItem(item: DrawerItem) {
selectItem(item.value)
}
}
val sitemapClickListener = object : DrawerAdapter.OnSitemapClickListener {
override fun onClickItem(item: OHSitemap) {
selectSitemap(item)
}
}
menuAdapter.setItemClickListener(itemClickListener)
menuAdapter.setSitemapsClickListener(sitemapClickListener)
menuAdapter.add(items)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
// Indicate that this fragment would like to influence the set of actions in the action bar.
setHasOptionsMenu(true)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
mDrawerListView = inflater.inflate(
R.layout.fragment_navigation_drawer, container, false) as RecyclerView
mDrawerListView!!.itemAnimator = DefaultItemAnimator()
mDrawerListView!!.layoutManager = LinearLayoutManager(context)
mDrawerListView!!.adapter = menuAdapter
return mDrawerListView
}
private fun sitemapsObservable(): Observable<List<ServerSitemapsResponse>> {
return Realm.getDefaultInstance().asFlowable().toObservable()
.compose<List<OHServer>>(serverLoaderFactory.loadAllServersRx())
.compose(serverLoaderFactory.serversToSitemap(activity))
.compose(serverLoaderFactory.filterDisplaySitemapsList())
}
override fun onResume() {
super.onResume()
setupSitemapLoader()
}
private fun setupSitemapLoader() {
val settingsShowSitemapInMenuRx = settings.showSitemapsInMenuRx
settingsShowSitemapInMenuRx.asObservable()
.switchMap<List<ServerSitemapsResponse>> { showSitemaps ->
if (showSitemaps) {
sitemapsObservable()
} else {
Observable.just(listOf())
}
}
.compose(bindToLifecycle())
.observeOn(AndroidSchedulers.mainThread())
.subscribe ({ serverSitemapsResponses ->
val sitemaps = ArrayList<OHSitemap>()
for (response in serverSitemapsResponses) {
val newSitemaps = response.sitemaps
if(newSitemaps != null) {
sitemaps.addAll(newSitemaps)
}
}
menuAdapter.clearSitemaps()
menuAdapter.addSitemaps(sitemaps)
}, { logger.e(TAG, "Failed to setupSitemapLoader", it) })
}
/**
* Users of this fragment must call this method to set up the navigation drawer interactions.
*
* @param fragmentId The android:id of this fragment in its view's layout.
* @param drawerLayout The DrawerLayout containing this fragment's UI.
*/
fun setUp(fragmentId: Int, drawerLayout: DrawerLayout) {
mFragmentContainerView = activity!!.findViewById(fragmentId)
mDrawerLayout = drawerLayout
// set a custom shadow that overlays the treehou.se.habit.ui.main content when the drawer opens
mDrawerLayout!!.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START)
// set up the drawer's list view with items and click listener
val actionBar = actionBar
actionBar!!.setDisplayHomeAsUpEnabled(true)
actionBar.setHomeButtonEnabled(true)
// ActionBarDrawerToggle ties together the the proper interactions
// between the navigation drawer and the action bar app icon.
mDrawerToggle = object : ActionBarDrawerToggle(
activity,
mDrawerLayout,
R.string.navigation_drawer_open,
R.string.navigation_drawer_close
) {
override fun onDrawerClosed(drawerView: View) {
super.onDrawerClosed(drawerView)
if (!isAdded) {
return
}
activity!!.invalidateOptionsMenu()
}
override fun onDrawerOpened(drawerView: View) {
super.onDrawerOpened(drawerView)
if (!isAdded) {
return
}
if (!mUserLearnedDrawer) {
settings.userLearnedDrawer(true)
}
activity!!.invalidateOptionsMenu()
}
}
// Defer code dependent on restoration of previous instance state.
mDrawerLayout!!.post { mDrawerToggle!!.syncState() }
mDrawerLayout!!.setDrawerListener(mDrawerToggle)
}
private fun selectItem(value: Int) {
mDrawerLayout!!.closeDrawer(mFragmentContainerView!!)
mCallbacks.onNavigationDrawerItemSelected(value)
}
private fun selectSitemap(sitemap: OHSitemap) {
mDrawerLayout!!.closeDrawer(mFragmentContainerView!!)
mCallbacks.onSitemapItemSelected(sitemap)
}
override fun onAttach(context: Context?) {
super.onAttach(context)
mCallbacks = if (context is NavigationDrawerCallbacks) context else DummyNavigationDrawerCallbacks()
}
override fun onDetach() {
super.onDetach()
mCallbacks = DummyNavigationDrawerCallbacks()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition)
}
override fun onConfigurationChanged(newConfig: Configuration?) {
super.onConfigurationChanged(newConfig)
// Forward the new configuration the drawer toggle component.
mDrawerToggle!!.onConfigurationChanged(newConfig)
}
override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) {
if (mDrawerLayout != null && isDrawerOpen) {
showGlobalContextActionBar()
}
super.onCreateOptionsMenu(menu, inflater)
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
return mDrawerToggle!!.onOptionsItemSelected(item) || super.onOptionsItemSelected(item)
}
/**
* Per the navigation drawer design guidelines, updates the action bar to show the global app
* 'context', rather than just what's in the current screen.
*/
private fun showGlobalContextActionBar() {
val actionBar = actionBar
actionBar!!.setDisplayShowTitleEnabled(true)
}
/**
* Callbacks interface that all activities using this fragment must implement.
*/
interface NavigationDrawerCallbacks {
/**
* Called when an item in the navigation drawer is selected.
*/
fun onNavigationDrawerItemSelected(value: Int)
fun onSitemapItemSelected(sitemap: OHSitemap)
}
class DummyNavigationDrawerCallbacks: NavigationDrawerCallbacks{
override fun onSitemapItemSelected(sitemap: OHSitemap) {}
override fun onNavigationDrawerItemSelected(value: Int) {}
}
companion object {
val TAG = "NavigationDrawerFragment"
private val STATE_SELECTED_POSITION = "selected_navigation_drawer_position"
private val PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned"
@IntDef(ITEM_SITEMAPS, ITEM_CONTROLLERS, ITEM_SERVER, ITEM_SETTINGS)
@Retention(AnnotationRetention.SOURCE)
annotation class NavigationItems
const val ITEM_SITEMAPS = 1414
const val ITEM_CONTROLLERS = 1337
const val ITEM_SERVER = 5335
const val ITEM_SETTINGS = 4214
}
}
| epl-1.0 | 0d73196d31c215c4004cf0c7ccf3a1ac | 36.578431 | 115 | 0.680146 | 5.388472 | false | false | false | false |
JakeWharton/timber | timber-lint/src/test/java/timber/lint/WrongTimberUsageDetectorTest.kt | 1 | 49111 | package timber.lint
import com.android.tools.lint.checks.infrastructure.TestFiles.java
import com.android.tools.lint.checks.infrastructure.TestFiles.kotlin
import com.android.tools.lint.checks.infrastructure.TestFiles.manifest
import com.android.tools.lint.checks.infrastructure.TestLintTask.lint
import org.junit.Test
import timber.lint.WrongTimberUsageDetector.Companion.issues
class WrongTimberUsageDetectorTest {
private val TIMBER_STUB = kotlin("""
|package timber.log
|class Timber private constructor() {
| private companion object {
| @JvmStatic fun d(message: String?, vararg args: Any?) {}
| @JvmStatic fun d(t: Throwable?, message: String, vararg args: Any?) {}
| @JvmStatic fun tag(tag: String) = Tree()
| }
| open class Tree {
| open fun d(message: String?, vararg args: Any?) {}
| open fun d(t: Throwable?, message: String?, vararg args: Any?) {}
| }
|}""".trimMargin())
@Test fun usingAndroidLogWithTwoArguments() {
lint()
.files(
java("""
|package foo;
|import android.util.Log;
|public class Example {
| public void log() {
| Log.d("TAG", "msg");
| }
|}""".trimMargin()),
kotlin("""
|package foo
|import android.util.Log
|class Example {
| fun log() {
| Log.d("TAG", "msg")
| }
|}""".trimMargin())
)
.issues(*issues)
.run()
.expect("""
|src/foo/Example.java:5: Warning: Using 'Log' instead of 'Timber' [LogNotTimber]
| Log.d("TAG", "msg");
| ~~~~~~~~~~~~~~~~~~~
|src/foo/Example.kt:5: Warning: Using 'Log' instead of 'Timber' [LogNotTimber]
| Log.d("TAG", "msg")
| ~~~~~~~~~~~~~~~~~~~
|0 errors, 2 warnings""".trimMargin())
.expectFixDiffs("""
|Fix for src/foo/Example.java line 5: Replace with Timber.tag("TAG").d("msg"):
|@@ -5 +5
|- Log.d("TAG", "msg");
|+ Timber.tag("TAG").d("msg");
|Fix for src/foo/Example.java line 5: Replace with Timber.d("msg"):
|@@ -5 +5
|- Log.d("TAG", "msg");
|+ Timber.d("msg");
|Fix for src/foo/Example.kt line 5: Replace with Timber.tag("TAG").d("msg"):
|@@ -5 +5
|- Log.d("TAG", "msg")
|+ Timber.tag("TAG").d("msg")
|Fix for src/foo/Example.kt line 5: Replace with Timber.d("msg"):
|@@ -5 +5
|- Log.d("TAG", "msg")
|+ Timber.d("msg")
|""".trimMargin())
}
@Test fun usingAndroidLogWithThreeArguments() {
lint()
.files(
java("""
|package foo;
|import android.util.Log;
|public class Example {
| public void log() {
| Log.d("TAG", "msg", new Exception());
| }
|}""".trimMargin()),
kotlin("""
|package foo
|import android.util.Log
|class Example {
| fun log() {
| Log.d("TAG", "msg", Exception())
| }
|}""".trimMargin())
)
.issues(*issues)
.run()
.expect("""
|src/foo/Example.java:5: Warning: Using 'Log' instead of 'Timber' [LogNotTimber]
| Log.d("TAG", "msg", new Exception());
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|src/foo/Example.kt:5: Warning: Using 'Log' instead of 'Timber' [LogNotTimber]
| Log.d("TAG", "msg", Exception())
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|0 errors, 2 warnings""".trimMargin())
.expectFixDiffs("""
|Fix for src/foo/Example.java line 5: Replace with Timber.tag("TAG").d(new Exception(), "msg"):
|@@ -5 +5
|- Log.d("TAG", "msg", new Exception());
|+ Timber.tag("TAG").d(new Exception(), "msg");
|Fix for src/foo/Example.java line 5: Replace with Timber.d(new Exception(), "msg"):
|@@ -5 +5
|- Log.d("TAG", "msg", new Exception());
|+ Timber.d(new Exception(), "msg");
|Fix for src/foo/Example.kt line 5: Replace with Timber.tag("TAG").d(Exception(), "msg"):
|@@ -5 +5
|- Log.d("TAG", "msg", Exception())
|+ Timber.tag("TAG").d(Exception(), "msg")
|Fix for src/foo/Example.kt line 5: Replace with Timber.d(Exception(), "msg"):
|@@ -5 +5
|- Log.d("TAG", "msg", Exception())
|+ Timber.d(Exception(), "msg")
|""".trimMargin())
}
@Test fun usingFullyQualifiedAndroidLogWithTwoArguments() {
lint()
.files(
java("""
|package foo;
|public class Example {
| public void log() {
| android.util.Log.d("TAG", "msg");
| }
|}""".trimMargin()),
kotlin("""
|package foo
|class Example {
| fun log() {
| android.util.Log.d("TAG", "msg")
| }
|}""".trimMargin())
)
.issues(*issues)
.run()
.expect("""
|src/foo/Example.java:4: Warning: Using 'Log' instead of 'Timber' [LogNotTimber]
| android.util.Log.d("TAG", "msg");
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|src/foo/Example.kt:4: Warning: Using 'Log' instead of 'Timber' [LogNotTimber]
| android.util.Log.d("TAG", "msg")
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|0 errors, 2 warnings""".trimMargin())
.expectFixDiffs("""
|Fix for src/foo/Example.java line 4: Replace with Timber.tag("TAG").d("msg"):
|@@ -4 +4
|- android.util.Log.d("TAG", "msg");
|+ Timber.tag("TAG").d("msg");
|Fix for src/foo/Example.java line 4: Replace with Timber.d("msg"):
|@@ -4 +4
|- android.util.Log.d("TAG", "msg");
|+ Timber.d("msg");
|Fix for src/foo/Example.kt line 4: Replace with Timber.tag("TAG").d("msg"):
|@@ -4 +4
|- android.util.Log.d("TAG", "msg")
|+ Timber.tag("TAG").d("msg")
|Fix for src/foo/Example.kt line 4: Replace with Timber.d("msg"):
|@@ -4 +4
|- android.util.Log.d("TAG", "msg")
|+ Timber.d("msg")
|""".trimMargin())
}
@Test fun usingFullyQualifiedAndroidLogWithThreeArguments() {
lint()
.files(
java("""
|package foo;
|public class Example {
| public void log() {
| android.util.Log.d("TAG", "msg", new Exception());
| }
|}""".trimMargin()),
kotlin("""
|package foo
|class Example {
| fun log() {
| android.util.Log.d("TAG", "msg", Exception())
| }
|}""".trimMargin())
)
.issues(*issues)
.run()
.expect("""
|src/foo/Example.java:4: Warning: Using 'Log' instead of 'Timber' [LogNotTimber]
| android.util.Log.d("TAG", "msg", new Exception());
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|src/foo/Example.kt:4: Warning: Using 'Log' instead of 'Timber' [LogNotTimber]
| android.util.Log.d("TAG", "msg", Exception())
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|0 errors, 2 warnings""".trimMargin())
.expectFixDiffs("""
|Fix for src/foo/Example.java line 4: Replace with Timber.tag("TAG").d(new Exception(), "msg"):
|@@ -4 +4
|- android.util.Log.d("TAG", "msg", new Exception());
|+ Timber.tag("TAG").d(new Exception(), "msg");
|Fix for src/foo/Example.java line 4: Replace with Timber.d(new Exception(), "msg"):
|@@ -4 +4
|- android.util.Log.d("TAG", "msg", new Exception());
|+ Timber.d(new Exception(), "msg");
|Fix for src/foo/Example.kt line 4: Replace with Timber.tag("TAG").d(Exception(), "msg"):
|@@ -4 +4
|- android.util.Log.d("TAG", "msg", Exception())
|+ Timber.tag("TAG").d(Exception(), "msg")
|Fix for src/foo/Example.kt line 4: Replace with Timber.d(Exception(), "msg"):
|@@ -4 +4
|- android.util.Log.d("TAG", "msg", Exception())
|+ Timber.d(Exception(), "msg")
|""".trimMargin())
}
@Test fun innerStringFormat() {
lint()
.files(TIMBER_STUB,
java("""
|package foo;
|import timber.log.Timber;
|public class Example {
| public void log() {
| Timber.d(String.format("%s", "arg1"));
| }
|}""".trimMargin()),
kotlin("""
|package foo
|import timber.log.Timber
|class Example {
| fun log() {
| Timber.d(String.format("%s", "arg1"))
| }
|}""".trimMargin())
)
.issues(*issues)
.run()
.expect("""
|src/foo/Example.java:5: Warning: Using 'String#format' inside of 'Timber' [StringFormatInTimber]
| Timber.d(String.format("%s", "arg1"));
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~
|src/foo/Example.kt:5: Warning: Using 'String#format' inside of 'Timber' [StringFormatInTimber]
| Timber.d(String.format("%s", "arg1"))
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~
|0 errors, 2 warnings""".trimMargin())
.expectFixDiffs("""
|Fix for src/foo/Example.java line 5: Remove String.format(...):
|@@ -5 +5
|- Timber.d(String.format("%s", "arg1"));
|+ Timber.d("%s", "arg1");
|Fix for src/foo/Example.kt line 5: Remove String.format(...):
|@@ -5 +5
|- Timber.d(String.format("%s", "arg1"))
|+ Timber.d("%s", "arg1")
|""".trimMargin())
}
@Test fun innerStringFormatWithStaticImport() {
lint()
.files(TIMBER_STUB,
java("""
|package foo;
|import timber.log.Timber;
|import static java.lang.String.format;
|public class Example {
| public void log() {
| Timber.d(format("%s", "arg1"));
| }
|}""".trimMargin()),
kotlin("""
|package foo
|import timber.log.Timber
|import java.lang.String.format
|class Example {
| fun log() {
| Timber.d(format("%s", "arg1"))
| }
|}""".trimMargin())
)
// Remove when AGP 7.1.0-alpha07 is out
// https://groups.google.com/g/lint-dev/c/BigCO8sMhKU
.allowCompilationErrors()
.issues(*issues)
.run()
.expect("""
|src/foo/Example.java:6: Warning: Using 'String#format' inside of 'Timber' [StringFormatInTimber]
| Timber.d(format("%s", "arg1"));
| ~~~~~~~~~~~~~~~~~~~~
|src/foo/Example.kt:6: Warning: Using 'String#format' inside of 'Timber' [StringFormatInTimber]
| Timber.d(format("%s", "arg1"))
| ~~~~~~~~~~~~~~~~~~~~
|0 errors, 2 warnings""".trimMargin())
.expectFixDiffs("""
|Fix for src/foo/Example.java line 6: Remove String.format(...):
|@@ -6 +6
|- Timber.d(format("%s", "arg1"));
|+ Timber.d("%s", "arg1");
|Fix for src/foo/Example.kt line 6: Remove String.format(...):
|@@ -6 +6
|- Timber.d(format("%s", "arg1"))
|+ Timber.d("%s", "arg1")
|""".trimMargin())
}
@Test fun innerStringFormatInNestedMethods() {
lint()
.files(TIMBER_STUB,
java("""
|package foo;
|import timber.log.Timber;
|public class Example {
| public void log() {
| Timber.d(id(String.format("%s", "arg1")));
| }
| private String id(String s) { return s; }
|}""".trimMargin()),
kotlin("""
|package foo
|import timber.log.Timber
|class Example {
| fun log() {
| Timber.d(id(String.format("%s", "arg1")))
| }
| private fun id(s: String): String { return s }
|}""".trimMargin())
)
.issues(*issues)
.run()
.expect("""
|src/foo/Example.java:5: Warning: Using 'String#format' inside of 'Timber' [StringFormatInTimber]
| Timber.d(id(String.format("%s", "arg1")));
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~
|src/foo/Example.kt:5: Warning: Using 'String#format' inside of 'Timber' [StringFormatInTimber]
| Timber.d(id(String.format("%s", "arg1")))
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~
|0 errors, 2 warnings""".trimMargin())
}
@Test fun innerStringFormatInNestedAssignment() {
lint()
.files(TIMBER_STUB,
java("""
|package foo;
|import timber.log.Timber;
|public class Example {
| public void log() {
| String msg = null;
| Timber.d(msg = String.format("msg"));
| }
|}""".trimMargin())
// no kotlin equivalent, since nested assignments do not exist
)
.issues(*issues)
.run()
.expect("""
|src/foo/Example.java:6: Warning: Using 'String#format' inside of 'Timber' [StringFormatInTimber]
| Timber.d(msg = String.format("msg"));
| ~~~~~~~~~~~~~~~~~~~~
|0 errors, 1 warnings""".trimMargin())
}
@Test fun validStringFormatInCodeBlock() {
lint()
.files(TIMBER_STUB,
java("""
|package foo;
|public class Example {
| public void log() {
| for(;;) {
| String name = String.format("msg");
| }
| }
|}""".trimMargin()),
kotlin("""
|package foo
|class Example {
| fun log() {
| while(true) {
| val name = String.format("msg")
| }
| }
|}""".trimMargin())
)
.issues(*issues)
.run()
.expectClean()
}
@Test fun validStringFormatInConstructorCall() {
lint()
.files(TIMBER_STUB,
java("""
|package foo;
|public class Example {
| public void log() {
| new Exception(String.format("msg"));
| }
|}""".trimMargin()),
kotlin("""
|package foo
|class Example {
| fun log() {
| Exception(String.format("msg"))
| }
|}""".trimMargin())
)
.issues(*issues)
.run()
.expectClean()
}
@Test fun validStringFormatInStaticArray() {
lint()
.files(TIMBER_STUB,
java("""
|package foo;
|public class Example {
| static String[] X = { String.format("%s", 100) };
|}""".trimMargin()),
kotlin("""
|package foo
|class Example {
| companion object {
| val X = arrayOf(String.format("%s", 100))
| }
|}""".trimMargin())
)
.issues(*issues)
.run()
.expectClean()
}
@Test fun validStringFormatExtracted() {
lint()
.files(TIMBER_STUB,
java("""
|package foo;
|import timber.log.Timber;
|public class Example {
| public void log() {
| String message = String.format("%s", "foo");
| Timber.d(message);
| }
|}""".trimMargin()),
kotlin("""
|package foo
|import timber.log.Timber
|class Example {
| fun log() {
| val message = String.format("%s", "foo")
| Timber.d(message)
| }
|}""".trimMargin()),
)
.issues(*issues)
.run()
.expectClean()
}
@Test fun throwableNotAtBeginning() {
lint()
.files(TIMBER_STUB,
java("""
|package foo;
|import timber.log.Timber;
|public class Example {
| public void log() {
| Exception e = new Exception();
| Timber.d("%s", e);
| }
|}""".trimMargin()),
kotlin("""
|package foo
|import timber.log.Timber
|class Example {
| fun log() {
| val e = Exception()
| Timber.d("%s", e)
| }
|}""".trimMargin())
)
.issues(*issues)
.run()
.expect("""
|src/foo/Example.java:6: Warning: Throwable should be first argument [ThrowableNotAtBeginning]
| Timber.d("%s", e);
| ~~~~~~~~~~~~~~~~~
|src/foo/Example.kt:6: Warning: Throwable should be first argument [ThrowableNotAtBeginning]
| Timber.d("%s", e)
| ~~~~~~~~~~~~~~~~~
|0 errors, 2 warnings""".trimMargin())
.expectFixDiffs("""
|Fix for src/foo/Example.java line 6: Replace with e, "%s":
|@@ -6 +6
|- Timber.d("%s", e);
|+ Timber.d(e, "%s");
|Fix for src/foo/Example.kt line 6: Replace with e, "%s":
|@@ -6 +6
|- Timber.d("%s", e)
|+ Timber.d(e, "%s")
|""".trimMargin())
}
@Test fun stringConcatenationBothLiterals() {
lint()
.files(TIMBER_STUB,
java("""
|package foo;
|import timber.log.Timber;
|public class Example {
| public void log() {
| Timber.d("foo" + "bar");
| }
|}""".trimMargin()),
kotlin("""
|package foo
|import timber.log.Timber
|class Example {
| fun log() {
| Timber.d("foo" + "bar")
| }
|}""".trimMargin())
)
.issues(*issues)
.run()
.expectClean()
}
@Test fun stringConcatenationLeftLiteral() {
lint()
.files(TIMBER_STUB,
java("""
|package foo;
|import timber.log.Timber;
|public class Example {
| public void log() {
| String foo = "foo";
| Timber.d(foo + "bar");
| }
|}""".trimMargin()),
kotlin("""
|package foo
|import timber.log.Timber
|class Example {
| fun log() {
| val foo = "foo"
| Timber.d("${"$"}{foo}bar")
| }
|}""".trimMargin())
)
.issues(*issues)
.run()
.expect("""
|src/foo/Example.java:6: Warning: Replace String concatenation with Timber's string formatting [BinaryOperationInTimber]
| Timber.d(foo + "bar");
| ~~~~~~~~~~~
|0 errors, 1 warnings""".trimMargin())
.expectFixDiffs("""
|Fix for src/foo/Example.java line 5: Replace with "%sbar", foo:
|@@ -6 +6
|- Timber.d(foo + "bar");
|+ Timber.d("%sbar", foo);
|""".trimMargin())
}
@Test fun stringConcatenationRightLiteral() {
lint()
.files(TIMBER_STUB,
java("""
|package foo;
|import timber.log.Timber;
|public class Example {
| public void log() {
| String bar = "bar";
| Timber.d("foo" + bar);
| }
|}""".trimMargin()),
kotlin("""
|package foo
|import timber.log.Timber
|class Example {
| fun log() {
| val bar = "bar"
| Timber.d("foo${"$"}bar")
| }
|}""".trimMargin())
)
.issues(*issues)
.run()
.expect("""
|src/foo/Example.java:6: Warning: Replace String concatenation with Timber's string formatting [BinaryOperationInTimber]
| Timber.d("foo" + bar);
| ~~~~~~~~~~~
|0 errors, 1 warnings""".trimMargin())
.expectFixDiffs("""
|Fix for src/foo/Example.java line 5: Replace with "foo%s", bar:
|@@ -6 +6
|- Timber.d("foo" + bar);
|+ Timber.d("foo%s", bar);
|""".trimMargin())
}
@Test fun stringConcatenationBothVariables() {
lint()
.files(TIMBER_STUB,
java("""
|package foo;
|import timber.log.Timber;
|public class Example {
| public void log() {
| String foo = "foo";
| String bar = "bar";
| Timber.d(foo + bar);
| }
|}""".trimMargin()),
kotlin("""
|package foo
|import timber.log.Timber
|class Example {
| fun log() {
| val foo = "foo"
| val bar = "bar"
| Timber.d("${"$"}foo${"$"}bar")
| }
|}""".trimMargin())
)
.issues(*issues)
.run()
.expect("""
|src/foo/Example.java:7: Warning: Replace String concatenation with Timber's string formatting [BinaryOperationInTimber]
| Timber.d(foo + bar);
| ~~~~~~~~~
|0 errors, 1 warnings""".trimMargin())
.expectFixDiffs("""
|Fix for src/foo/Example.java line 6: Replace with "%s%s", foo, bar:
|@@ -7 +7
|- Timber.d(foo + bar);
|+ Timber.d("%s%s", foo, bar);
|""".trimMargin())
}
@Test fun stringConcatenationInsideTernary() {
lint()
.files(TIMBER_STUB,
java("""
|package foo;
|import timber.log.Timber;
|public class Example {
| public void log() {
| String s = "world!";
| Timber.d(true ? "Hello, " + s : "Bye");
| }
|}""".trimMargin()),
kotlin("""
|package foo
|import timber.log.Timber
|class Example {
| fun log() {
| val s = "world!"
| Timber.d(if(true) "Hello, ${"$"}s" else "Bye")
| }
|}""".trimMargin())
)
.issues(*issues)
.run()
.expect("""
|src/foo/Example.java:6: Warning: Replace String concatenation with Timber's string formatting [BinaryOperationInTimber]
| Timber.d(true ? "Hello, " + s : "Bye");
| ~~~~~~~~~~~~~
|0 errors, 1 warnings""".trimMargin())
}
@Test fun tooManyFormatArgs() {
lint()
.files(TIMBER_STUB,
java("""
|package foo;
|import timber.log.Timber;
|public class Example {
| public void log() {
| Timber.d("%s %s", "arg1");
| }
|}""".trimMargin()),
kotlin("""
|package foo
|import timber.log.Timber
|class Example {
| fun log() {
| Timber.d("%s %s", "arg1")
| }
|}""".trimMargin())
)
.issues(*issues)
.run()
.expect("""
|src/foo/Example.java:5: Error: Wrong argument count, format string %s %s requires 2 but format call supplies 1 [TimberArgCount]
| Timber.d("%s %s", "arg1");
| ~~~~~~~~~~~~~~~~~~~~~~~~~
|src/foo/Example.kt:5: Error: Wrong argument count, format string %s %s requires 2 but format call supplies 1 [TimberArgCount]
| Timber.d("%s %s", "arg1")
| ~~~~~~~~~~~~~~~~~~~~~~~~~
|2 errors, 0 warnings""".trimMargin())
}
@Test fun tooManyArgs() {
lint()
.files(TIMBER_STUB,
java("""
|package foo;
|import timber.log.Timber;
|public class Example {
| public void log() {
| Timber.d("%s", "arg1", "arg2");
| }
|}""".trimMargin()),
kotlin("""
|package foo
|import timber.log.Timber
|class Example {
| fun log() {
| Timber.d("%s", "arg1", "arg2")
| }
|}""".trimMargin())
)
.issues(*issues)
.run()
.expect("""
|src/foo/Example.java:5: Error: Wrong argument count, format string %s requires 1 but format call supplies 2 [TimberArgCount]
| Timber.d("%s", "arg1", "arg2");
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|src/foo/Example.kt:5: Error: Wrong argument count, format string %s requires 1 but format call supplies 2 [TimberArgCount]
| Timber.d("%s", "arg1", "arg2")
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|2 errors, 0 warnings""".trimMargin())
}
@Test fun wrongArgTypes() {
lint()
.files(TIMBER_STUB,
java("""
|package foo;
|import timber.log.Timber;
|public class Example {
| public void log() {
| Timber.d("%d", "arg1");
| }
|}""".trimMargin()),
kotlin("""
|package foo
|import timber.log.Timber
|class Example {
| fun log() {
| Timber.d("%d", "arg1")
| }
|}""".trimMargin())
)
.issues(*issues)
.run()
.expect("""
|src/foo/Example.java:5: Error: Wrong argument type for formatting argument '#1' in %d: conversion is 'd', received String (argument #2 in method call) [TimberArgTypes]
| Timber.d("%d", "arg1");
| ~~~~~~
|src/foo/Example.kt:5: Error: Wrong argument type for formatting argument '#1' in %d: conversion is 'd', received String (argument #2 in method call) [TimberArgTypes]
| Timber.d("%d", "arg1")
| ~~~~
|2 errors, 0 warnings""".trimMargin())
}
@Test fun tagTooLongLiteralOnly() {
lint()
.files(TIMBER_STUB,
java("""
|package foo;
|import timber.log.Timber;
|public class Example {
| public void log() {
| Timber.tag("abcdefghijklmnopqrstuvwx");
| }
|}""".trimMargin()),
kotlin("""
|package foo
|import timber.log.Timber
|class Example {
| fun log() {
| Timber.tag("abcdefghijklmnopqrstuvwx")
| }
|}""".trimMargin()),
manifest().minSdk(25)
)
.issues(*issues)
.run()
.expect("""
|src/foo/Example.java:5: Error: The logging tag can be at most 23 characters, was 24 (abcdefghijklmnopqrstuvwx) [TimberTagLength]
| Timber.tag("abcdefghijklmnopqrstuvwx");
| ~~~~~~~~~~~~~~~~~~~~~~~~~~
|1 errors, 0 warnings""".trimMargin())
}
@Test fun tagTooLongLiteralOnlyBeforeApi26() {
lint()
.files(TIMBER_STUB,
java("""
|package foo;
|import timber.log.Timber;
|public class Example {
| public void log() {
| Timber.tag("abcdefghijklmnopqrstuvwx");
| }
|}""".trimMargin()),
kotlin("""
|package foo
|import timber.log.Timber
|class Example {
| fun log() {
| Timber.tag("abcdefghijklmnopqrstuvwx")
| }
|}""".trimMargin()),
manifest().minSdk(26)
)
.issues(*issues)
.run()
.expectClean()
}
@Test fun tooManyFormatArgsInTag() {
lint()
.files(TIMBER_STUB,
java("""
|package foo;
|import timber.log.Timber;
|public class Example {
| public void log() {
| Timber.tag("tag").d("%s %s", "arg1");
| }
|}""".trimMargin()),
kotlin("""
|package foo
|import timber.log.Timber
|class Example {
| fun log() {
| Timber.tag("tag").d("%s %s", "arg1")
| }
|}""".trimMargin())
)
.issues(*issues)
.run()
.expect("""
|src/foo/Example.java:5: Error: Wrong argument count, format string %s %s requires 2 but format call supplies 1 [TimberArgCount]
| Timber.tag("tag").d("%s %s", "arg1");
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|src/foo/Example.kt:5: Error: Wrong argument count, format string %s %s requires 2 but format call supplies 1 [TimberArgCount]
| Timber.tag("tag").d("%s %s", "arg1")
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|2 errors, 0 warnings""".trimMargin())
}
@Test fun tooManyArgsInTag() {
lint()
.files(TIMBER_STUB,
java("""
|package foo;
|import timber.log.Timber;
|public class Example {
| public void log() {
| Timber.tag("tag").d("%s", "arg1", "arg2");
| }
|}""".trimMargin()),
kotlin("""
|package foo
|import timber.log.Timber
|class Example {
| fun log() {
| Timber.tag("tag").d("%s", "arg1", "arg2")
| }
|}""".trimMargin())
)
.issues(*issues)
.run()
.expect("""
|src/foo/Example.java:5: Error: Wrong argument count, format string %s requires 1 but format call supplies 2 [TimberArgCount]
| Timber.tag("tag").d("%s", "arg1", "arg2");
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|src/foo/Example.kt:5: Error: Wrong argument count, format string %s requires 1 but format call supplies 2 [TimberArgCount]
| Timber.tag("tag").d("%s", "arg1", "arg2")
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|2 errors, 0 warnings""".trimMargin())
}
@Test fun wrongArgTypesInTag() {
lint()
.files(TIMBER_STUB,
java("""
|package foo;
|import timber.log.Timber;
|public class Example {
| public void log() {
| Timber.tag("tag").d("%d", "arg1");
| }
|}""".trimMargin()),
kotlin("""
|package foo
|import timber.log.Timber
|class Example {
| fun log() {
| Timber.tag("tag").d("%d", "arg1")
| }
|}""".trimMargin())
)
.issues(*issues)
.run()
.expect("""
|src/foo/Example.java:5: Error: Wrong argument type for formatting argument '#1' in %d: conversion is 'd', received String (argument #2 in method call) [TimberArgTypes]
| Timber.tag("tag").d("%d", "arg1");
| ~~~~~~
|src/foo/Example.kt:5: Error: Wrong argument type for formatting argument '#1' in %d: conversion is 'd', received String (argument #2 in method call) [TimberArgTypes]
| Timber.tag("tag").d("%d", "arg1")
| ~~~~
|2 errors, 0 warnings""".trimMargin())
}
@Test fun exceptionLoggingUsingExceptionMessage() {
lint()
.files(TIMBER_STUB,
java("""
|package foo;
|import timber.log.Timber;
|public class Example {
| public void log() {
| Exception e = new Exception();
| Timber.d(e.getMessage());
| }
|}""".trimMargin()),
kotlin("""
|package foo
|import timber.log.Timber
|class Example {
| fun log() {
| val e = Exception()
| Timber.d(e.message)
| }
|}""".trimMargin())
)
.issues(*issues)
.run()
.expect("""
|src/foo/Example.java:6: Warning: Explicitly logging exception message is redundant [TimberExceptionLogging]
| Timber.d(e.getMessage());
| ~~~~~~~~~~~~~~~~~~~~~~~~
|src/foo/Example.kt:6: Warning: Explicitly logging exception message is redundant [TimberExceptionLogging]
| Timber.d(e.message)
| ~~~~~~~~~~~~~~~~~~~
|0 errors, 2 warnings""".trimMargin())
.expectFixDiffs("""
|Fix for src/foo/Example.java line 6: Replace message with throwable:
|@@ -6 +6
|- Timber.d(e.getMessage());
|+ Timber.d(e);
|Fix for src/foo/Example.kt line 6: Replace message with throwable:
|@@ -6 +6
|- Timber.d(e.message)
|+ Timber.d(e)
|""".trimMargin())
}
@Test fun exceptionLoggingUsingExceptionMessageArgument() {
lint()
.files(TIMBER_STUB,
java("""
|package foo;
|import timber.log.Timber;
|public class Example {
| public void log() {
| Exception e = new Exception();
| Timber.d(e, e.getMessage());
| }
|}""".trimMargin()),
kotlin("""
|package foo
|import timber.log.Timber
|class Example {
| fun log() {
| val e = Exception()
| Timber.d(e, e.message)
| }
|}""".trimMargin())
)
.issues(*issues)
.run()
.expect("""
|src/foo/Example.java:6: Warning: Explicitly logging exception message is redundant [TimberExceptionLogging]
| Timber.d(e, e.getMessage());
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~
|src/foo/Example.kt:6: Warning: Explicitly logging exception message is redundant [TimberExceptionLogging]
| Timber.d(e, e.message)
| ~~~~~~~~~~~~~~~~~~~~~~
|0 errors, 2 warnings""".trimMargin())
.expectFixDiffs("""
|Fix for src/foo/Example.java line 5: Remove redundant argument:
|@@ -6 +6
|- Timber.d(e, e.getMessage());
|+ Timber.d(e);
|Fix for src/foo/Example.kt line 5: Remove redundant argument:
|@@ -6 +6
|- Timber.d(e, e.message)
|+ Timber.d(e)
|""".trimMargin())
}
@Test fun exceptionLoggingUsingVariable() {
lint()
.files(TIMBER_STUB,
java("""
|package foo;
|import timber.log.Timber;
|public class Example {
| public void log() {
| String msg = "Hello";
| Exception e = new Exception();
| Timber.d(e, msg);
| }
|}""".trimMargin()),
kotlin("""
|package foo
|import timber.log.Timber
|class Example {
| fun log() {
| val msg = "Hello"
| val e = Exception()
| Timber.d(e, msg)
| }
|}""".trimMargin())
)
.issues(*issues)
.run()
.expectClean()
}
@Test fun exceptionLoggingUsingParameter() {
lint()
.files(TIMBER_STUB,
java("""
|package foo;
|import timber.log.Timber;
|public class Example {
| public void log(Exception e, String message) {
| Timber.d(e, message);
| }
|}""".trimMargin()),
kotlin("""
|package foo
|import timber.log.Timber
|class Example {
| fun log(e: Exception, message: String) {
| Timber.d(e, message)
| }
|}""".trimMargin())
)
.issues(*issues)
.run()
.expectClean()
}
@Test fun exceptionLoggingUsingMethod() {
lint()
.files(TIMBER_STUB,
java("""
|package foo;
|import timber.log.Timber;
|public class Example {
| public void log(Exception e) {
| Timber.d(e, method());
| }
| private String method() {
| return "foo";
| }
|}""".trimMargin()),
kotlin("""
|package foo
|import timber.log.Timber
|class Example {
| fun log(e: Exception) {
| Timber.d(e, method())
| }
| private fun method(): String {
| return "foo"
| }
|}""".trimMargin())
)
.issues(*issues)
.run()
.expectClean()
}
@Test fun exceptionLoggingUsingNonFinalField() {
lint()
.files(TIMBER_STUB,
java("""
|package foo;
|import timber.log.Timber;
|public class Example {
| private String message;
| public void log() {
| Exception e = new Exception();
| Timber.d(e, message);
| }
|}""".trimMargin()),
kotlin("""
|package foo
|import timber.log.Timber
|class Example {
| private var message = ""
| fun log() {
| val e = Exception()
| Timber.d(e, message)
| }
|}""".trimMargin())
)
.issues(*issues)
.run()
.expectClean()
}
@Test fun exceptionLoggingUsingFinalField() {
lint()
.files(TIMBER_STUB,
java("""
|package foo;
|import timber.log.Timber;
|public class Example {
| private final String message = "foo";
| public void log() {
| Exception e = new Exception();
| Timber.d(e, message);
| }
|}""".trimMargin()),
kotlin("""
|package foo
|import timber.log.Timber
|class Example {
| private val message = ""
| fun log() {
| val e = Exception()
| Timber.d(e, message)
| }
|}""".trimMargin())
)
.issues(*issues)
.run()
.expectClean()
}
@Test fun exceptionLoggingUsingEmptyStringMessage() {
lint()
.files(TIMBER_STUB,
java("""
|package foo;
|import timber.log.Timber;
|public class Example {
| public void log() {
| Exception e = new Exception();
| Timber.d(e, "");
| }
|}""".trimMargin()),
kotlin("""
|package foo
|import timber.log.Timber
|class Example {
| fun log() {
| val e = Exception()
| Timber.d(e, "")
| }
|}""".trimMargin())
)
.issues(*issues)
.run()
.expect("""
|src/foo/Example.java:6: Warning: Use single-argument log method instead of null/empty message [TimberExceptionLogging]
| Timber.d(e, "");
| ~~~~~~~~~~~~~~~
|src/foo/Example.kt:6: Warning: Use single-argument log method instead of null/empty message [TimberExceptionLogging]
| Timber.d(e, "")
| ~~~~~~~~~~~~~~~
|0 errors, 2 warnings""".trimMargin())
.expectFixDiffs("""
|Fix for src/foo/Example.java line 6: Remove redundant argument:
|@@ -6 +6
|- Timber.d(e, "");
|+ Timber.d(e);
|Fix for src/foo/Example.kt line 6: Remove redundant argument:
|@@ -6 +6
|- Timber.d(e, "")
|+ Timber.d(e)
|""".trimMargin())
}
@Test fun exceptionLoggingUsingNullMessage() {
lint()
.files(TIMBER_STUB,
java("""
|package foo;
|import timber.log.Timber;
|public class Example {
| public void log() {
| Exception e = new Exception();
| Timber.d(e, null);
| }
|}""".trimMargin()),
kotlin("""
|package foo
|import timber.log.Timber
|class Example {
| fun log() {
| val e = Exception()
| Timber.d(e, null)
| }
|}""".trimMargin())
)
.issues(*issues)
.run()
.expect("""
|src/foo/Example.java:6: Warning: Use single-argument log method instead of null/empty message [TimberExceptionLogging]
| Timber.d(e, null);
| ~~~~~~~~~~~~~~~~~
|src/foo/Example.kt:6: Warning: Use single-argument log method instead of null/empty message [TimberExceptionLogging]
| Timber.d(e, null)
| ~~~~~~~~~~~~~~~~~
|0 errors, 2 warnings""".trimMargin())
.expectFixDiffs("""
|Fix for src/foo/Example.java line 6: Remove redundant argument:
|@@ -6 +6
|- Timber.d(e, null);
|+ Timber.d(e);
|Fix for src/foo/Example.kt line 6: Remove redundant argument:
|@@ -6 +6
|- Timber.d(e, null)
|+ Timber.d(e)
|""".trimMargin())
}
@Test fun exceptionLoggingUsingValidMessage() {
lint()
.files(TIMBER_STUB,
java("""
|package foo;
|import timber.log.Timber;
|public class Example {
| public void log() {
| Exception e = new Exception();
| Timber.d(e, "Valid message");
| }
|}""".trimMargin()),
kotlin("""
|package foo
|import timber.log.Timber
|class Example {
| fun log() {
| val e = Exception()
| Timber.d(e, "Valid message")
| }
|}""".trimMargin())
)
.issues(*issues)
.run()
.expectClean()
}
@Test fun dateFormatNotDisplayingWarning() {
lint()
.files(TIMBER_STUB,
java("""
|package foo;
|import timber.log.Timber;
|public class Example {
| public void log() {
| Timber.d("%tc", new java.util.Date());
| }
|}""".trimMargin()),
kotlin("""
|package foo
|import timber.log.Timber
|class Example {
| fun log() {
| Timber.d("%tc", java.util.Date())
| }
|}""".trimMargin())
)
.issues(*issues)
.run()
.expectClean()
}
@Test fun systemTimeMillisValidMessage() {
lint()
.files(TIMBER_STUB,
java("""
|package foo;
|import timber.log.Timber;
|public class Example {
| public void log() {
| Timber.d("%tc", System.currentTimeMillis());
| }
|}""".trimMargin()),
kotlin("""
|package foo
|import timber.log.Timber
|class Example {
| fun log() {
| Timber.d("%tc", System.currentTimeMillis())
| }
|}""".trimMargin())
)
.issues(*issues)
.run()
.expectClean()
}
@Test fun wrappedBooleanType() {
lint()
.files(TIMBER_STUB,
java("""
|package foo;
|import timber.log.Timber;
|public class Example {
| public void log() {
| Timber.d("%b", Boolean.valueOf(true));
| }
|}""".trimMargin()),
// no kotlin equivalent, since primitive wrappers do not exist
)
.issues(*issues)
.run()
.expectClean()
}
@Test fun memberVariable() {
lint()
.files(TIMBER_STUB,
java("""
|package foo;
|import timber.log.Timber;
|public class Example {
| public static class Bar {
| public static String baz = "timber";
| }
| public void log() {
| Bar bar = new Bar();
| Timber.d(bar.baz);
| }
|}
""".trimMargin()),
kotlin("""
|package foo
|import timber.log.Timber
|class Example {
| class Bar {
| val baz = "timber"
| }
| fun log() {
| val bar = Bar()
| Timber.d(bar.baz)
| }
|}
""".trimMargin())
)
.issues(*issues)
.run()
.expectClean()
}
}
| apache-2.0 | b5aa1fa89d13f6fe0e36a71273dede7b | 34.743086 | 180 | 0.404695 | 4.615262 | false | false | false | false |
vjames19/kotlin-microservice-example | jooby-api/src/main/kotlin/io/github/vjames19/kotlinmicroserviceexample/blog/api/jooby/endpoint/UsersEndpoint.kt | 1 | 934 | package io.github.vjames19.kotlinmicroserviceexample.blog.api.jooby.endpoint
import io.github.vjames19.kotlinmicroserviceexample.blog.domain.User
import io.github.vjames19.kotlinmicroserviceexample.blog.service.UserService
import org.jooby.mvc.Body
import org.jooby.mvc.GET
import org.jooby.mvc.POST
import org.jooby.mvc.Path
import java.util.*
import java.util.concurrent.CompletableFuture
import javax.inject.Inject
/**
* Created by victor.reventos on 6/12/17.
*/
@Path("/users")
class UsersEndpoint @Inject constructor(val userService: UserService) {
@Path("/:id")
@GET
fun get(id: Long): CompletableFuture<Optional<User>> = userService.getUser(id)
@POST
fun create(@Body createUserRequest: CreateUserRequest): CompletableFuture<User> = userService.create(createUserRequest.toDomain())
}
data class CreateUserRequest(val username: String) {
fun toDomain(): User = User(id = 0, username = username)
} | mit | 51f22e0f42e56a5f8820a60d377d96c9 | 30.166667 | 134 | 0.77409 | 3.706349 | false | false | false | false |
ol-loginov/intellij-community | platform/script-debugger/protocol/protocol-model-generator/src/DomainGenerator.kt | 3 | 14412 | package org.jetbrains.protocolModelGenerator
import org.jetbrains.jsonProtocol.ItemDescriptor
import org.jetbrains.jsonProtocol.ProtocolMetaModel
import org.jetbrains.protocolReader.JSON_READER_PARAMETER_DEF
import org.jetbrains.protocolReader.TextOutput
import org.jetbrains.protocolReader.appendEnums
fun fixMethodName(name: String): String {
val i = name.indexOf("breakpoint")
return if (i > 0) name.substring(0, i) + 'B' + name.substring(i + 1) else name
}
trait TextOutConsumer {
fun append(out: TextOutput)
}
class DomainGenerator(val generator: Generator, val domain: ProtocolMetaModel.Domain) {
fun registerTypes() {
if (domain.types() != null) {
for (type in domain.types()!!) {
generator.typeMap.getTypeData(domain.domain(), type.id()).setType(type)
}
}
}
fun generateCommandsAndEvents() {
val requestsFileUpdater = generator.startJavaFile(generator.naming.params.getPackageNameVirtual(domain.domain()), "Requests.java")
val out = requestsFileUpdater.out
out.append("import org.jetbrains.annotations.NotNull;").newLine()
out.append("import org.jetbrains.jsonProtocol.Request;").newLine()
out.newLine().append("public final class ").append("Requests")
out.openBlock()
var isFirst = true
for (command in domain.commands()) {
val hasResponse = command.returns() != null
var onlyMandatoryParams = true
val params = command.parameters()
val hasParams = params != null && !params.isEmpty()
if (hasParams) {
for (parameter in params!!) {
if (parameter.optional()) {
onlyMandatoryParams = false
}
}
}
val returnType = if (hasResponse) generator.naming.commandResult.getShortName(command.name()) else "Void"
if (onlyMandatoryParams) {
if (isFirst) {
isFirst = false
}
else {
out.newLine().newLine()
}
out.append("@NotNull").newLine().append("public static Request<")
out.append(returnType)
out.append(">").space().append(fixMethodName(command.name())).append("(")
val classScope = OutputClassScope(this, generator.naming.params.getFullName(domain.domain(), command.name()))
val parameterTypes = if (hasParams) arrayOfNulls<BoxableType>(params!!.size()) else null
if (hasParams) {
classScope.writeMethodParameters<ProtocolMetaModel.Parameter>(out, params!!, parameterTypes!!)
}
out.append(')').openBlock()
val requestClassName = generator.naming.requestClassName.replace("Request", "SimpleRequest")
if (hasParams) {
out.append(requestClassName).append('<').append(returnType).append(">").append(" r =")
}
else {
out.append("return")
}
out.append(" new ").append(requestClassName).append("<").append(returnType).append(">(\"")
if (!domain.domain().isEmpty()) {
out.append(domain.domain()).append('.')
}
out.append(command.name()).append("\")").semi()
if (hasParams) {
classScope.writeWriteCalls<ProtocolMetaModel.Parameter>(out, params!!, parameterTypes!!, "r")
out.newLine().append("return r").semi()
}
out.closeBlock()
classScope.writeAdditionalMembers(out)
}
else {
generateRequest(command, returnType)
}
if (hasResponse) {
val fileUpdater = generator.startJavaFile(generator.naming.commandResult, domain, command.name())
generateJsonProtocolInterface(fileUpdater.out, generator.naming.commandResult.getShortName(command.name()), command.description(), command.returns(), null)
fileUpdater.update()
generator.jsonProtocolParserClassNames.add(generator.naming.commandResult.getFullName(domain.domain(), command.name()).getFullText())
generator.parserRootInterfaceItems.add(ParserRootInterfaceItem(domain.domain(), command.name(), generator.naming.commandResult))
}
}
out.closeBlock()
requestsFileUpdater.update()
if (domain.events() != null) {
for (event in domain.events()!!) {
generateEvenData(event)
generator.jsonProtocolParserClassNames.add(generator.naming.eventData.getFullName(domain.domain(), event.name()).getFullText())
generator.parserRootInterfaceItems.add(ParserRootInterfaceItem(domain.domain(), event.name(), generator.naming.eventData))
}
}
}
private fun generateRequest(command: ProtocolMetaModel.Command, returnType: String) {
val baseTypeBuilder = object : TextOutConsumer {
override fun append(out: TextOutput) {
out.space().append("extends ").append(generator.naming.requestClassName).append('<').append(returnType).append('>')
}
}
val memberBuilder = object : TextOutConsumer {
override fun append(out: TextOutput) {
out.append("@NotNull").newLine().append("@Override").newLine().append("public String getMethodName()").openBlock()
out.append("return \"")
if (!domain.domain().isEmpty()) {
out.append(domain.domain()).append('.')
}
out.append(command.name()).append('"').semi().closeBlock()
}
}
generateTopLevelOutputClass(generator.naming.params, command.name(), command.description(), baseTypeBuilder, memberBuilder, command.parameters())
}
fun generateCommandAdditionalParam(type: ProtocolMetaModel.StandaloneType) {
generateTopLevelOutputClass(generator.naming.additionalParam, type.id(), type.description(), null, null, type.properties())
}
private fun <P : ItemDescriptor.Named> generateTopLevelOutputClass(nameScheme: ClassNameScheme, baseName: String, description: String?, baseType: TextOutConsumer?, additionalMemberText: TextOutConsumer?, properties: List<P>?) {
val fileUpdater = generator.startJavaFile(nameScheme, domain, baseName)
if (nameScheme == generator.naming.params) {
fileUpdater.out.append("import org.jetbrains.annotations.NotNull;").newLine().newLine()
}
generateOutputClass(fileUpdater.out, nameScheme.getFullName(domain.domain(), baseName), description, baseType, additionalMemberText, properties)
fileUpdater.update()
}
private fun <P : ItemDescriptor.Named> generateOutputClass(out: TextOutput, classNamePath: NamePath, description: String?, baseType: TextOutConsumer?, additionalMemberText: TextOutConsumer?, properties: List<P>?) {
out.doc(description)
out.append("public final class ").append(classNamePath.lastComponent)
if (baseType == null) {
out.append(" extends ").append("org.jetbrains.jsonProtocol.OutMessage")
}
else {
baseType.append(out)
}
val classScope = OutputClassScope(this, classNamePath)
if (additionalMemberText != null) {
classScope.addMember(additionalMemberText)
}
out.openBlock()
classScope.generate<P>(out, properties)
classScope.writeAdditionalMembers(out)
out.closeBlock()
}
fun createStandaloneOutputTypeBinding(type: ProtocolMetaModel.StandaloneType, name: String): StandaloneTypeBinding {
return switchByType(type, MyCreateStandaloneTypeBindingVisitorBase(this, type, name))
}
fun createStandaloneInputTypeBinding(type: ProtocolMetaModel.StandaloneType): StandaloneTypeBinding {
return switchByType(type, object : CreateStandaloneTypeBindingVisitorBase(this, type) {
override fun visitObject(properties: List<ProtocolMetaModel.ObjectProperty>?): StandaloneTypeBinding {
return createStandaloneObjectInputTypeBinding(type, properties)
}
override fun visitEnum(enumConstants: List<String>): StandaloneTypeBinding {
val name = type.id()
return object : StandaloneTypeBinding {
override fun getJavaType() = StandaloneType(generator.naming.inputEnum.getFullName(domain.domain(), name), "writeEnum")
override fun generate() {
val fileUpdater = generator.startJavaFile(generator.naming.inputEnum, domain, name)
fileUpdater.out.doc(type.description())
appendEnums(enumConstants, generator.naming.inputEnum.getShortName(name), true, fileUpdater.out)
fileUpdater.update()
}
override fun getDirection() = TypeData.Direction.INPUT
}
}
override fun visitArray(items: ProtocolMetaModel.ArrayItemType): StandaloneTypeBinding {
val resolveAndGenerateScope = object : ResolveAndGenerateScope {
// This class is responsible for generating ad hoc type.
// If we ever are to do it, we should generate into string buffer and put strings
// inside TypeDef class.
override fun getDomainName() = domain.domain()
override fun getTypeDirection() = TypeData.Direction.INPUT
override fun generateNestedObject(description: String?, properties: List<ProtocolMetaModel.ObjectProperty>?) = throw UnsupportedOperationException()
}
val arrayType = ListType(generator.resolveType(items, resolveAndGenerateScope).type)
return createTypedefTypeBinding(type, object : Target {
override fun resolve(context: Target.ResolveContext): BoxableType {
return arrayType
}
}, generator.naming.inputTypedef, TypeData.Direction.INPUT)
}
})
}
fun createStandaloneObjectInputTypeBinding(type: ProtocolMetaModel.StandaloneType, properties: List<ProtocolMetaModel.ObjectProperty>?): StandaloneTypeBinding {
val name = type.id()
val fullTypeName = generator.naming.inputValue.getFullName(domain.domain(), name)
generator.jsonProtocolParserClassNames.add(fullTypeName.getFullText())
return object : StandaloneTypeBinding {
override fun getJavaType(): BoxableType {
return StandaloneType(fullTypeName, "writeMessage")
}
override fun generate() {
val className = generator.naming.inputValue.getFullName(domain.domain(), name)
val fileUpdater = generator.startJavaFile(generator.naming.inputValue, domain, name)
val out = fileUpdater.out
descriptionAndRequiredImport(type.description(), out)
out.append("public interface ").append(className.lastComponent).openBlock()
val classScope = InputClassScope(this@DomainGenerator, className)
if (properties != null) {
classScope.generateDeclarationBody(out, properties)
}
classScope.writeAdditionalMembers(out)
out.closeBlock()
fileUpdater.update()
}
override fun getDirection() = TypeData.Direction.INPUT
}
}
/**
* Typedef is an empty class that just holds description and
* refers to an actual type (such as String).
*/
fun createTypedefTypeBinding(type: ProtocolMetaModel.StandaloneType, target: Target, nameScheme: ClassNameScheme, direction: TypeData.Direction?): StandaloneTypeBinding {
val name = type.id()
val typedefJavaName = nameScheme.getFullName(domain.domain(), name)
val actualJavaType = target.resolve(object : Target.ResolveContext {
override fun generateNestedObject(shortName: String, description: String?, properties: List<ProtocolMetaModel.ObjectProperty>?): BoxableType {
val classNamePath = NamePath(shortName, typedefJavaName)
if (direction == null) {
throw RuntimeException("Unsupported")
}
when (direction) {
TypeData.Direction.INPUT -> throw RuntimeException("TODO")
TypeData.Direction.OUTPUT -> {
val out = TextOutput(StringBuilder())
generateOutputClass(out, classNamePath, description, null, null, properties)
}
else -> throw RuntimeException()
}
return StandaloneType(NamePath(shortName, typedefJavaName), "writeMessage")
}
})
return object : StandaloneTypeBinding {
override fun getJavaType() = actualJavaType
override fun generate() {
}
override fun getDirection() = direction
}
}
private fun generateEvenData(event: ProtocolMetaModel.Event) {
val className = generator.naming.eventData.getShortName(event.name())
val fileUpdater = generator.startJavaFile(generator.naming.eventData, domain, event.name())
val domainName = domain.domain()
val fullName = generator.naming.eventData.getFullName(domainName, event.name()).getFullText()
generateJsonProtocolInterface(fileUpdater.out, className, event.description(), event.parameters(), object : TextOutConsumer {
override fun append(out: TextOutput) {
out.append("org.jetbrains.wip.protocol.WipEventType<").append(fullName).append("> TYPE").newLine()
out.append("\t= new org.jetbrains.wip.protocol.WipEventType<").append(fullName).append(">")
out.append("(\"").append(domainName).append('.').append(event.name()).append("\", ").append(fullName).append(".class)").openBlock()
run {
out.append("@Override").newLine().append("public ").append(fullName).append(" read(")
out.append(generator.naming.inputPackage).append('.').append(READER_INTERFACE_NAME + " protocolReader, ").append(JSON_READER_PARAMETER_DEF).append(")").openBlock()
out.append("return protocolReader.").append(generator.naming.eventData.getParseMethodName(domainName, event.name())).append("(reader);").closeBlock()
}
out.closeBlock()
out.semi()
}
})
fileUpdater.update()
}
private fun generateJsonProtocolInterface(out: TextOutput, className: String, description: String?, parameters: List<ProtocolMetaModel.Parameter>?, additionalMembersText: TextOutConsumer?) {
descriptionAndRequiredImport(description, out)
out.append("public interface ").append(className).openBlock()
val classScope = InputClassScope(this, NamePath(className, NamePath(getPackageName(generator.naming.inputPackage, domain.domain()))))
if (additionalMembersText != null) {
classScope.addMember(additionalMembersText)
}
if (parameters != null) {
classScope.generateDeclarationBody(out, parameters)
}
classScope.writeAdditionalMembers(out)
out.closeBlock()
}
private fun descriptionAndRequiredImport(description: String?, out: TextOutput) {
out.append("import org.jetbrains.jsonProtocol.JsonType;").newLine().newLine()
if (description != null) {
out.doc(description)
}
out.append("@JsonType").newLine()
}
} | apache-2.0 | 19942165c6c976833037281832a22032 | 42.675758 | 229 | 0.694213 | 4.880461 | false | false | false | false |
olonho/carkot | translator/src/test/kotlin/tests/referential_equality_1/referential_equality_1.kt | 1 | 1704 | class referential_equality_1
fun referential_equality_1_EQEQ_true(): Int {
val instance = referential_equality_1()
var instance2 = referential_equality_1()
instance2 = instance
//problem with boolean in auto generated functions in clang
return if (instance == instance2) 1 else 0
}
fun referential_equality_1_EQEQ_false(): Int {
val instance = referential_equality_1()
val instance2 = referential_equality_1()
return if (instance == instance2) 1 else 0
}
fun referential_equality_1_EQEQEQ_true(): Int {
val instance = referential_equality_1()
var instance2 = referential_equality_1()
instance2 = instance
return if (instance === instance2) 1 else 0
}
fun referential_equality_1_EQEQEQ_false(): Int {
val instance = referential_equality_1()
val instance2 = referential_equality_1()
return if (instance === instance2) 1 else 0
}
fun referential_equality_1_EXCLEQEQ_false(): Int {
val instance = referential_equality_1()
var instance2 = referential_equality_1()
instance2 = instance
return if (instance != instance2) 1 else 0
}
fun referential_equality_1_EXCLEQEQ_true(): Int {
val instance = referential_equality_1()
val instance2 = referential_equality_1()
return if (instance != instance2) 1 else 0
}
fun referential_equality_1_EXCLEQEQEQ_false(): Int {
val instance = referential_equality_1()
var instance2 = referential_equality_1()
instance2 = instance
return if (instance !== instance2) 1 else 0
}
fun referential_equality_1_EXCLEQEQEQ_true(): Int {
val instance = referential_equality_1()
val instance2 = referential_equality_1()
return if (instance !== instance2) 1 else 0
} | mit | 161ccf78d99398f4db9fcb75591f1137 | 30.574074 | 63 | 0.700704 | 3.881549 | false | false | false | false |
langara/MyIntent | myutils/src/main/java/pl/mareklangiewicz/myutils/myhttp/OpenWeatherMap.kt | 1 | 12463 | package pl.mareklangiewicz.myutils.myhttp
import retrofit2.Call
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
import retrofit2.http.GET
import retrofit2.http.Query
object OpenWeatherMap {
const val URL = "http://api.openweathermap.org"
class Clouds {
/** Cloudiness, % */
var all: Int = 0
}
class Coord {
/** Latitude */
var lat: Float = 0f
/** Longitude */
var lon: Float = 0f
}
class City {
/** City id as in [http://bulk.openweathermap.org/sample/] */
var id: Long = 0
/** City name */
var name: String? = null
/** City location */
var coord: Coord? = null
/** Country code */
var country: String? = null
/** City population */
var population: Long = 0
}
class Wind {
/** Wind speed. Unit Default: meter/sec, Metric: meter/sec, Imperial: miles/hour. */
var speed: Float = 0f
/** Wind direction, degrees (meteorological) */
var deg: Float = 0f
}
class Sys {
var message: Float = 0f
var country: String? = null
var sunrise: Long = 0
var sunset: Long = 0
}
class Weather {
/** Weather condition id */
var id: Int = 0
/** Weather icon id */
var icon: String? = null
/** Weather condition within the group */
var description: String? = null
/** Group of weather parameters (Rain, Snow, Extreme, etc.) */
var main: String? = null
}
class Main {
/** Humidity, % */
var humidity: Int = 0
/** Atmospheric pressure on the sea level by default, hPa */
var pressure: Float = 0f
/**
* Maximum temperature at the moment of calculation. This is deviation from 'temp' that is possible
* for large cities and megalopolises geographically expanded (use these parameter optionally).
* Unit Default: Kelvin, Metric: Celsius, Imperial: Fahrenheit.
*/
var temp_max: Float = 0f
/** Atmospheric pressure on the sea level, hPa */
var sea_level: Float = 0f
/**
* Minimum temperature at the moment of calculation. This is deviation from 'temp' that is possible
* for large cities and megalopolises geographically expanded (use these parameter optionally).
* Unit Default: Kelvin, Metric: Celsius, Imperial: Fahrenheit.
*/
var temp_min: Float = 0f
/** Temperature. Unit Default: Kelvin, Metric: Celsius, Imperial: Fahrenheit. */
var temp: Float = 0f
/** Atmospheric pressure on the ground level, hPa */
var grnd_level: Float = 0f
}
class Temp {
/** Min daily temperature. Unit Default: Kelvin, Metric: Celsius, Imperial: Fahrenheit. */
var min: Float = 0f
/** Max daily temperature. Unit Default: Kelvin, Metric: Celsius, Imperial: Fahrenheit. */
var max: Float = 0f
/** Averaged daily temperature. Unit Default: Kelvin, Metric: Celsius, Imperial: Fahrenheit. */
var day: Float = 0f
/** Night temperature. Unit Default: Kelvin, Metric: Celsius, Imperial: Fahrenheit. */
var night: Float = 0f
/** Evening temperature. Unit Default: Kelvin, Metric: Celsius, Imperial: Fahrenheit. */
var eve: Float = 0f
/** Morning temperature. Unit Default: Kelvin, Metric: Celsius, Imperial: Fahrenheit. */
var morn: Float = 0f
}
class Forecast {
var id: Long = 0
/** Time of data forecasted, unix, UTC */
var dt: Long = 0
/** Cloudiness */
var clouds: Clouds? = null
/** Location */
var coord: Coord? = null
/** Wind conditions */
var wind: Wind? = null
/** Internal parameter */
var cod: Int = 0
var sys: Sys? = null
var name: String? = null
var base: String? = null
/** More info weather condition codes */
var weather: Array<Weather>? = null
/** Main conditions */
var main: Main? = null
}
class DailyForecast {
/** Time of data forecasted, unix, UTC */
var dt: Long = 0
/** Temperature */
var temp: Temp? = null
/** Atmospheric pressure on the sea level, hPa */
var pressure: Float = 0f
/** Humidity, % */
var humidity: Int = 0
/** More info weather condition codes */
var weather: Array<Weather>? = null
/** Wind speed. Unit Default: meter/sec, Metric: meter/sec, Imperial: miles/hour. */
var speed: Float = 0f
/** Wind direction, degrees (meteorological) */
var deg: Float = 0f
/** Cloudiness, % */
var clouds: Int = 0
/** Rain */
var rain: Float = 0f
/** Snow */
var snow: Float = 0f
}
class Forecasts {
/** City information */
var city: City? = null
/** Internal parameter */
var cod: String? = null
/** Internal parameter */
var message: String? = null
/** Number of forecasts returned in "list" */
var cnt: Long = 0
/** Array of forecasts */
var list: Array<Forecast>? = null
}
class DailyForecasts {
/** City information */
var city: City? = null
/** Internal parameter */
var cod: String? = null
/** Internal parameter */
var message: String? = null
/** Number of daily forecasts returned in "list" */
var cnt: Long = 0
/** Array of daily forecasts */
var list: Array<DailyForecast>? = null
}
/**
* Id list for cities are here [http://bulk.openweathermap.org/sample/]
*/
interface Service {
/**
* @param appid You have to get app id from [http://openweathermap.org/appid]
* @param lat Latitude
* @param lon Longitude
* @param units Default (null) means in Kelvin, "metric" means in Celsius, "imperial" means in Fahrenheit
*/
@GET("/data/2.5/weather") fun getWeatherByLocationCall(
@Query("appid") appid: String,
@Query("lat") lat: Float,
@Query("lon") lon: Float,
@Query("units") units: String? = null): Call<Forecast>
/**
* @param appid You have to get app id from [http://openweathermap.org/appid]
* @param city City name + optional country code after comma
* @param units Default (null) means in Kelvin, "metric" means in Celsius, "imperial" means in Fahrenheit
*/
@GET("/data/2.5/weather") fun getWeatherByCityCall(
@Query("appid") appid: String,
@Query("q") city: String,
@Query("units") units: String? = null): Call<Forecast>
/**
* @param appid You have to get app id from [http://openweathermap.org/appid]
* @param id City id (this is cheaper than city name) You can get the list from [http://bulk.openweathermap.org/sample/]
* @param units Default (null) means in Kelvin, "metric" means in Celsius, "imperial" means in Fahrenheit
*/
@GET("/data/2.5/weather") fun getWeatherByIdCall(
@Query("appid") appid: String,
@Query("id") id: Long,
@Query("units") units: String? = null): Call<Forecast>
/**
* Up to five days forecasts with data every 3 hours for given latitude and longitude
* @param appid You have to get app id from [http://openweathermap.org/appid]
* @param lat Latitude
* @param lon Longitude
* @param cnt Optional maximum number of forecasts in returned "list"
* @param units Default (null) means in Kelvin, "metric" means in Celsius, "imperial" means in Fahrenheit
*/
@GET("/data/2.5/forecast") fun getForecastByLocationCall(
@Query("appid") appid: String,
@Query("lat") lat: Float,
@Query("lon") lon: Float,
@Query("cnt") cnt: Long? = null,
@Query("units") units: String? = null): Call<Forecasts>
/**
* Up to five days forecasts with data every 3 hours for given city name
* @param appid You have to get app id from [http://openweathermap.org/appid]
* @param city City name + optional country code after comma
* @param cnt Optional maximum number of forecasts in returned "list"
* @param units Default (null) means in Kelvin, "metric" means in Celsius, "imperial" means in Fahrenheit
*/
@GET("/data/2.5/forecast") fun getForecastByCityCall(
@Query("appid") appid: String,
@Query("q") city: String,
@Query("cnt") cnt: Long? = null,
@Query("units") units: String? = null): Call<Forecasts>
/**
* Up to five days forecasts with data every 3 hours for given city id
* @param appid You have to get app id from [http://openweathermap.org/appid]
* @param id City id (this is cheaper than city name) You can get the list from [http://bulk.openweathermap.org/sample/]
* @param cnt Optional maximum number of forecasts in returned "list"
* @param units Default (null) means in Kelvin, "metric" means in Celsius, "imperial" means in Fahrenheit
*/
@GET("/data/2.5/forecast") fun getForecastByIdCall(
@Query("appid") appid: String,
@Query("id") id: Long,
@Query("cnt") cnt: Long? = null,
@Query("units") units: String? = null): Call<Forecasts>
/**
* Up to 16 days daily forecasts for given location
* @param appid You have to get app id from [http://openweathermap.org/appid]
* @param lat Latitude
* @param lon Longitude
* @param cnt Optional maximum number of daily forecasts in returned "list"
* @param units Default (null) means in Kelvin, "metric" means in Celsius, "imperial" means in Fahrenheit
*/
@GET("/data/2.5/forecast/daily") fun getDailyForecastByLocationCall(
@Query("appid") appid: String,
@Query("lat") lat: Float,
@Query("lon") lon: Float,
@Query("cnt") cnt: Long? = null,
@Query("units") units: String? = null): Call<DailyForecasts>
/**
* Up to 16 days daily forecasts for given city
* @param appid You have to get app id from [http://openweathermap.org/appid]
* @param city City name + optional country code after comma
* @param cnt Optional maximum number of daily forecasts in returned "list"
* @param units Default (null) means in Kelvin, "metric" means in Celsius, "imperial" means in Fahrenheit
*/
@GET("/data/2.5/forecast/daily") fun getDailyForecastByCityCall(
@Query("appid") appid: String,
@Query("q") city: String,
@Query("cnt") cnt: Long? = null,
@Query("units") units: String? = null): Call<DailyForecasts>
/**
* Up to 16 days daily forecasts for given city id
* @param appid You have to get app id from [http://openweathermap.org/appid]
* @param id City id (this is cheaper than city name) You can get the list from [http://bulk.openweathermap.org/sample/]
* @param cnt Optional maximum number of daily forecasts in returned "list"
* @param units Default (null) means in Kelvin, "metric" means in Celsius, "imperial" means in Fahrenheit
*/
@GET("/data/2.5/forecast/daily") fun getDailyForecastByIdCall(
@Query("appid") appid: String,
@Query("id") id: Long,
@Query("cnt") cnt: Long? = null,
@Query("units") units: String? = null): Call<DailyForecasts>
}
// private val interceptor = HttpLoggingInterceptor().apply { level = HttpLoggingInterceptor.Level.BODY }
// private val logclient = OkHttpClient.Builder().addInterceptor(interceptor).build()
private val retrofit = Retrofit.Builder()
.baseUrl(URL)
// .client(logclient)
.addConverterFactory(MoshiConverterFactory.create()).build()
val service = retrofit.create(Service::class.java)!!
} | apache-2.0 | 6df3ae0e19b46f0a983c788acb3a5e3f | 39.865574 | 128 | 0.574902 | 4.305009 | false | false | false | false |
255BITS/hypr | app/src/main/java/hypr/hypergan/com/hypr/GeneratorLoader/GeneratorLoader.kt | 1 | 5833 | package hypr.hypergan.com.hypr.GeneratorLoader
import android.content.res.AssetManager
import android.graphics.Bitmap
import hypr.hypergan.com.hypr.Generator.Generator
import org.tensorflow.lite.Interpreter
import org.tensorflow.Session
import java.nio.ByteBuffer
import java.nio.channels.FileChannel.MapMode.READ_ONLY
import android.content.res.AssetFileDescriptor
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import org.tensorflow.lite.gpu.GpuDelegate
import org.tensorflow.lite.nnapi.NnApiDelegate
import java.io.FileInputStream
import java.io.IOException
import java.nio.channels.FileChannel
open class GeneratorLoader {
lateinit var inference: Interpreter
var generator: Generator? = null
var channels: Int = 0
var width: Int = 0
var height: Int = 0
var z_dimsArray: LongArray = longArrayOf()
var z_dims: Long = 0
var raw: FloatArray = floatArrayOf()
var index: Int? = 0
var assets: AssetManager? = null
var bytes:ByteArray? = null
var buffer:ByteBuffer? = null
var options: Interpreter.Options? = null
var _getInputFromBitmap:FloatArray? = null
var inputs:Array<Any>? = null
var outputs:HashMap<Int, Any>? = null
init {
//this.delegate = GpuDelegate();
//this.options = Interpreter.Options().addDelegate(this.delegate)
}
fun setIndex(index: Int) {
this.index = index
}
fun loadGenerator(generator: Generator) {
this.generator = generator
this.width = generator.generator?.output?.width!!
this.height = generator.generator!!.output?.height!!
channels = generator.generator!!.output!!.channels!!
z_dimsArray = generator.generator!!.input!!.z_dims!!.map { item -> item.toLong() }.toLongArray()
z_dims = z_dimsArray.fold(1.toLong(), { mul, next -> mul * next })
raw = floatArrayOf()
System.gc()
raw = FloatArray(width * height * channels)
outputs = hashMapOf(0 to this.raw)
}
@Throws(IOException::class)
private fun loadModelFile(assetManager: AssetManager, modelPath: String): ByteBuffer {
val fileDescriptor = assetManager.openFd(modelPath)
val inputStream = FileInputStream(fileDescriptor.fileDescriptor)
val fileChannel = inputStream.getChannel()
val startOffset = fileDescriptor.startOffset
val declaredLength = fileDescriptor.declaredLength
return fileChannel.map(FileChannel.MapMode.READ_ONLY, startOffset, declaredLength)
}
fun load() {
val file = generator?.model_file
this.buffer = loadModelFile(this.assets!!, "generators/"+file)//this.assets?.open( "generators/"+file)
//TODO FIXME
//this.delegate = GpuDelegate();
//this.options = Interpreter.Options().addDelegate(this.delegate)
val nnApiDelegate = NnApiDelegate()
this.options = Interpreter.Options().addDelegate(nnApiDelegate)
this.inference = Interpreter( this.buffer!!, options )
this.buffer?.clear()
}
fun sample(z: FloatArray, mask: FloatArray, bitmap: Bitmap): IntArray {
print("Sampling ")
//var inputs:Array<Any> = getInputs(bitmap, z)
inputs = getInputs(bitmap, z)
if(!this::inference.isInitialized) {
this.load()
}
this.inference.runForMultipleInputsOutputs(inputs, outputs!!)
return manipulatePixelsInBitmap()
}
private fun getInputs(bitmap: Bitmap, z: FloatArray):Array<Any> {
if (generator!!.features.contains(Feature.ENCODING)) {
return arrayOf(arrayOf(getInputFromBitmap(bitmap)), arrayOf(z))
} else {
return arrayOf(z)
}
}
fun mask(bitmap: Bitmap): FloatArray {
//feedInput(bitmap)
val floatValues = FloatArray(width * height)
return floatValues
}
fun getInputFromBitmap(bitmap: Bitmap):FloatArray {
if(_getInputFromBitmap != null) {
return _getInputFromBitmap!!
}
val intValues = IntArray(width * height)
val floatValues = FloatArray(width * height * channels)
bitmap.getPixels(intValues, 0, bitmap.width, 0, 0, bitmap.width, bitmap.height)
for (i in 0..intValues.size - 1) {
val ival = intValues[i]
floatValues[i * 3] = ((ival shr 16 and 0xFF) / 255.0f - 0.5f) * 2
floatValues[i * 3 + 1] = ((ival shr 8 and 0xFF) / 255.0f - 0.5f) * 2
floatValues[i * 3 + 2] = ((ival and 0xFF) / 255.0f - 0.5f) * 2
}
_getInputFromBitmap = floatValues
return floatValues
}
fun random_z(min:Float=1.0f, range:Float=2.0f): FloatArray {
val z = FloatArray(z_dims.toInt())
val r = java.util.Random()
for (i in 0..z_dims.toInt() - 1)
z[i] = r.nextFloat() * range - min
return z
}
fun style_z(like:FloatArray):FloatArray {
val z = FloatArray(z_dims.toInt())
val r = java.util.Random()
for (i in 0..z_dims.toInt() - 1) {
//z[i] = 0.0f
if (i >= z_dims.toInt() / 2) {
z[i] = like[i]
} else {
z[i] = r.nextFloat() * 2.0f - 1.0f
}
}
return z
}
private fun manipulatePixelsInBitmap(): IntArray {
val pixelsInBitmap = IntArray(width * height)
for (i in 0..pixelsInBitmap.size - 1) {
val raw_one: Int = (((raw[i * 3] + 1) / 2.0 * 255).toInt()) shl 16
val raw_two: Int = (((raw[i * 3 + 1] + 1) / 2.0 * 255).toInt()) shl 8
val raw_three: Int = ((raw[i * 3 + 2] + 1) / 2.0 * 255).toInt()
pixelsInBitmap[i] = 0xFF000000.toInt() or raw_one or raw_two or raw_three
}
return pixelsInBitmap
}
} | mit | 391b9e7034dec028f50d0bb5b2489695 | 33.317647 | 110 | 0.621636 | 3.943881 | false | false | false | false |
StoneMain/Shortranks | ShortranksCommon/src/main/kotlin/eu/mikroskeem/shortranks/common/hookmanager/AbstractHookManager.kt | 1 | 2165 | /*
* This file is part of project Shortranks, licensed under the MIT License (MIT).
*
* Copyright (c) 2017-2019 Mark Vainomaa <[email protected]>
* Copyright (c) Contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package eu.mikroskeem.shortranks.common.hookmanager
import eu.mikroskeem.shortranks.api.HookManager
import eu.mikroskeem.shortranks.api.ScoreboardHook
import eu.mikroskeem.shortranks.common.consumeAll
import eu.mikroskeem.shortranks.common.toUnmodifiableList
/**
* @author Mark Vainomaa
*/
abstract class AbstractHookManager: HookManager {
protected val hooks = HashSet<ScoreboardHook>()
override fun registerHook(hook: ScoreboardHook) {
hooks.add(hook.apply(ScoreboardHook::hook))
}
override fun unregisterHook(hook: ScoreboardHook) {
hook.also { hooks.removeIf { it == hook } }.unhook()
}
override fun getHookByName(hookName: String): ScoreboardHook? = hooks.find { it.name == hookName }
override fun getRegisteredHooks(): List<ScoreboardHook> = hooks.toUnmodifiableList()
fun unregisterAllHooks() = hooks.consumeAll(ScoreboardHook::unhook)
} | mit | 1bb10785e0e6c190ea7ad64fe1ba60e3 | 42.32 | 102 | 0.758891 | 4.33 | false | false | false | false |
kjkrol/kotlin4fun-eshop-app | ordering-service/src/main/kotlin/kotlin4fun/eshop/ordering/order/item/OrderItemController.kt | 1 | 2062 | package kotlin4fun.eshop.ordering.order.item
import org.springframework.data.domain.Page
import org.springframework.data.domain.Pageable
import org.springframework.data.web.PagedResourcesAssembler
import org.springframework.hateoas.ExposesResourceFor
import org.springframework.hateoas.MediaTypes.HAL_JSON_VALUE
import org.springframework.hateoas.PagedResources
import org.springframework.hateoas.Resource
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
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.util.UUID
@RestController
@RequestMapping(path = arrayOf("/order-item/"), produces = arrayOf(HAL_JSON_VALUE))
@ExposesResourceFor(OrderItemDto::class)
internal class OrderItemController(val orderItemQuery: OrderItemQuery, val orderItemResourceAssembler: OrderItemResourceAssembler) {
@GetMapping(value = "{order-id}/product")
fun findOrderProducts(@PathVariable("order-id") orderId: UUID,
pageable: Pageable,
pagedResourcesAssembler: PagedResourcesAssembler<OrderItemDto>?): ResponseEntity<PagedResources<Resource<OrderItemDto>>?> {
val page: Page<OrderItemDto> = orderItemQuery.findOrderProducts(orderId, pageable)
return ResponseEntity(pagedResourcesAssembler?.toResource(page, orderItemResourceAssembler), HttpStatus.OK)
}
@GetMapping(value = "{order-id}/product/{product-id}")
fun findOrderItem(@PathVariable("order-id") orderId: UUID,
@PathVariable("product-id") productId: UUID): ResponseEntity<Resource<OrderItemDto>> {
val orderItem: OrderItemDto = orderItemQuery.findOrderItemById(orderId = orderId, productId = productId)
val resource: Resource<OrderItemDto> = orderItemResourceAssembler.toResource(orderItem)
return ResponseEntity(resource, HttpStatus.OK)
}
} | apache-2.0 | f2b5154067c5bb10c15360579dcfd326 | 53.289474 | 149 | 0.78516 | 4.572062 | false | false | false | false |
wendigo/chrome-reactive-kotlin | src/main/kotlin/pl/wendigo/chrome/targets/Target.kt | 1 | 1492 | package pl.wendigo.chrome.targets
import pl.wendigo.chrome.api.ProtocolDomains
import pl.wendigo.chrome.api.target.GetTargetInfoRequest
import pl.wendigo.chrome.api.target.TargetID
import pl.wendigo.chrome.api.target.TargetInfo
import pl.wendigo.chrome.protocol.ProtocolConnection
import pl.wendigo.chrome.sync
import java.io.Closeable
/**
* Represents browser [Target] that can be controlled via DevTools Protocol API
*/
class Target(
private val manager: Manager,
private val session: SessionTarget,
connection: ProtocolConnection
) : ProtocolDomains(connection), AutoCloseable, Closeable {
/**
* Retrieves [TargetInfo] for current target directly from debugger protocol.
*/
fun info(): TargetInfo {
return sync(Target.getTargetInfo(GetTargetInfoRequest(session.targetId))).targetInfo
}
/**
* Closes target releasing all resources on the debugger side.
*/
override fun close() {
return manager.close(this)
}
/**
* Returns target id.
*/
fun targetId(): TargetID = session.targetId
/**
* Returns target session information.
*/
fun session(): SessionTarget = session
/**
* Releases underlying connection.
*/
internal fun closeConnection() {
return connection.close()
}
override fun toString(): String {
return "Target(id='${session.targetId}', sessionId='${session.sessionId}, browserContextId='${session.browserContextID}')"
}
}
| apache-2.0 | e2bf233e5edc01f3f52086c2596b3707 | 27.150943 | 130 | 0.69571 | 4.590769 | false | false | false | false |
hannesa2/owncloud-android | owncloudData/src/androidTest/java/com/owncloud/android/data/roommigrations/MigrationToDB28Test.kt | 2 | 3720 | /**
* ownCloud Android client application
*
* @author Abel García de Prada
* Copyright (C) 2020 ownCloud GmbH.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
*
* 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 com.owncloud.android.data.roommigrations
import android.content.ContentValues
import android.database.sqlite.SQLiteDatabase
import androidx.sqlite.db.SupportSQLiteDatabase
import androidx.test.filters.SmallTest
import com.owncloud.android.data.ProviderMeta.ProviderTableMeta.CAPABILITIES_ACCOUNT_NAME
import com.owncloud.android.data.ProviderMeta.ProviderTableMeta.CAPABILITIES_CORE_POLLINTERVAL
import com.owncloud.android.data.ProviderMeta.ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_EXPIRE_DATE_DAYS
import com.owncloud.android.data.ProviderMeta.ProviderTableMeta.CAPABILITIES_TABLE_NAME
import com.owncloud.android.data.ProviderMeta.ProviderTableMeta.CAPABILITIES_VERSION_MAYOR
import com.owncloud.android.data.ProviderMeta.ProviderTableMeta.CAPABILITIES_VERSION_MICRO
import com.owncloud.android.data.ProviderMeta.ProviderTableMeta.CAPABILITIES_VERSION_MINOR
import com.owncloud.android.data.migrations.MIGRATION_27_28
import com.owncloud.android.testutil.OC_CAPABILITY
import org.junit.Assert.assertEquals
import org.junit.Test
/**
* Test the migration from database to version 28.
*/
@SmallTest
class MigrationToDB28Test : MigrationTest() {
@Test
fun migrate27To28() {
performMigrationTest(
previousVersion = DB_VERSION_27,
currentVersion = DB_VERSION_28,
insertData = { database -> insertDataToTest(database) },
validateMigration = { database -> validateMigrationTo28(database) },
listOfMigrations = arrayOf(MIGRATION_27_28)
)
}
@Test
fun startInVersion28_containsCorrectData() {
performMigrationTest(
previousVersion = DB_VERSION_28,
currentVersion = DB_VERSION_28,
insertData = { database -> insertDataToTest(database) },
validateMigration = { database -> validateMigrationTo28(database) },
listOfMigrations = arrayOf()
)
}
private fun insertDataToTest(database: SupportSQLiteDatabase) {
database.run {
insert(
CAPABILITIES_TABLE_NAME,
SQLiteDatabase.CONFLICT_NONE,
cvWithDefaultValues
)
close()
}
}
private fun validateMigrationTo28(database: SupportSQLiteDatabase) {
val count = getCount(database, CAPABILITIES_TABLE_NAME)
assertEquals(1, count)
database.close()
}
companion object {
val cvWithDefaultValues = ContentValues().apply {
put(CAPABILITIES_ACCOUNT_NAME, OC_CAPABILITY.accountName)
put(CAPABILITIES_VERSION_MAYOR, OC_CAPABILITY.versionMayor)
put(CAPABILITIES_VERSION_MINOR, OC_CAPABILITY.versionMinor)
put(CAPABILITIES_VERSION_MICRO, OC_CAPABILITY.versionMicro)
put(CAPABILITIES_CORE_POLLINTERVAL, OC_CAPABILITY.corePollInterval)
put(CAPABILITIES_SHARING_PUBLIC_EXPIRE_DATE_DAYS, OC_CAPABILITY.filesSharingPublicExpireDateDays)
}
}
}
| gpl-2.0 | 7525497b36102a59a1b36c6a7fa4543d | 38.56383 | 109 | 0.715784 | 4.475331 | false | true | false | false |
JoachimR/Bible2net | app/src/main/java/de/reiss/bible2net/theword/bible/list/BibleListItemViewHolder.kt | 1 | 1235 | package de.reiss.bible2net.theword.bible.list
import android.view.View
import android.widget.TextView
import de.reiss.bible2net.theword.R
import de.reiss.bible2net.theword.bible.BibleClickListener
import de.reiss.bible2net.theword.util.extensions.onClick
import de.reiss.bible2net.theword.util.view.ListItemViewHolder
import de.reiss.bible2net.theword.util.view.StableListItem
class BibleListItemViewHolder(
layout: View,
private val bibleClickListener: BibleClickListener
) :
ListItemViewHolder(layout) {
private val context = layout.context
private val language = layout.findViewById<TextView>(R.id.bible_item_language)
private val bibleName = layout.findViewById<TextView>(R.id.bible_item_bible_name)
private var item: BibleListItem? = null
init {
layout.onClick {
item?.let {
bibleClickListener.onBibleClicked(it.bible)
}
}
}
override fun bindViews(item: StableListItem, isLastItem: Boolean) {
if (item is BibleListItem) {
this.item = item
language.text = context.getString(R.string.bible_item_language, item.bible.languageCode)
bibleName.text = item.bible.bibleName
}
}
}
| gpl-3.0 | 550035adf0a84a1633ab1481726e6161 | 31.5 | 100 | 0.711741 | 3.983871 | false | false | false | false |
vimeo/vimeo-networking-java | models/src/main/java/com/vimeo/networking2/RentInteraction.kt | 1 | 2004 | @file:JvmName("RentInteractionUtils")
package com.vimeo.networking2
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
import com.vimeo.networking2.annotations.Internal
import com.vimeo.networking2.enums.StreamAccessType
import com.vimeo.networking2.enums.asEnum
import java.util.Date
/**
* The Rent interaction for an On Demand video.
*
* @param currency The currency code for the current user's region.
* @param displayPrice Formatted price to display to rent an On Demand video.
* @param drm Whether the video has DRM.
* @param expirationDate The time in ISO 8601 format when the rental period for the video expires.
* @param link The URL to rent the On Demand video on Vimeo.
* @param price The numeric value of the price for buying the On Demand video.
* @param purchaseTime The time in ISO 8601 format when the On Demand video was rented.
* @param streamAccess The user's streaming access to this On Demand video. See [RentInteraction.streamAccessType].
* @param uri The product URI to rent the On Demand video.
*/
@Internal
@JsonClass(generateAdapter = true)
data class RentInteraction(
@Internal
@Json(name = "currency")
val currency: String? = null,
@Internal
@Json(name = "display_price")
val displayPrice: Long? = null,
@Internal
@Json(name = "drm")
val drm: Boolean? = null,
@Internal
@Json(name = "expires_time")
val expirationDate: Date? = null,
@Internal
@Json(name = "link")
val link: String? = null,
@Internal
@Json(name = "price")
val price: Double? = null,
@Internal
@Json(name = "purchase_time")
val purchaseTime: Date? = null,
@Internal
@Json(name = "stream")
val streamAccess: String? = null,
@Internal
@Json(name = "uri")
val uri: String? = null
)
/**
* @see RentInteraction.streamAccess
* @see StreamAccessType
*/
val RentInteraction.streamAccessType: StreamAccessType
get() = streamAccess.asEnum(StreamAccessType.UNKNOWN)
| mit | b4b2e70843b0c071c7531f45398dca59 | 26.833333 | 115 | 0.707585 | 3.67033 | false | false | false | false |
AndroidX/androidx | paging/paging-common/src/main/kotlin/androidx/paging/CombinedLoadStates.kt | 3 | 4273 | /*
* Copyright 2020 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.paging
/**
* Collection of pagination [LoadState]s for both a [PagingSource], and [RemoteMediator].
*
* Note: The [LoadType] [REFRESH][LoadType.REFRESH] always has [LoadState.endOfPaginationReached]
* set to `false`.
*/
public class CombinedLoadStates(
/**
* Convenience for combined behavior of [REFRESH][LoadType.REFRESH] [LoadState], which
* generally defers to [mediator] if it exists, but if previously was [LoadState.Loading],
* awaits for both [source] and [mediator] to become [LoadState.NotLoading] to ensure the
* remote load was applied.
*
* For use cases that require reacting to [LoadState] of [source] and [mediator]
* specifically, e.g., showing cached data when network loads via [mediator] fail,
* [LoadStates] exposed via [source] and [mediator] should be used directly.
*/
public val refresh: LoadState,
/**
* Convenience for combined behavior of [PREPEND][LoadType.REFRESH] [LoadState], which
* generally defers to [mediator] if it exists, but if previously was [LoadState.Loading],
* awaits for both [source] and [mediator] to become [LoadState.NotLoading] to ensure the
* remote load was applied.
*
* For use cases that require reacting to [LoadState] of [source] and [mediator]
* specifically, e.g., showing cached data when network loads via [mediator] fail,
* [LoadStates] exposed via [source] and [mediator] should be used directly.
*/
public val prepend: LoadState,
/**
* Convenience for combined behavior of [APPEND][LoadType.REFRESH] [LoadState], which
* generally defers to [mediator] if it exists, but if previously was [LoadState.Loading],
* awaits for both [source] and [mediator] to become [LoadState.NotLoading] to ensure the
* remote load was applied.
*
* For use cases that require reacting to [LoadState] of [source] and [mediator]
* specifically, e.g., showing cached data when network loads via [mediator] fail,
* [LoadStates] exposed via [source] and [mediator] should be used directly.
*/
public val append: LoadState,
/**
* [LoadStates] corresponding to loads from a [PagingSource].
*/
public val source: LoadStates,
/**
* [LoadStates] corresponding to loads from a [RemoteMediator], or `null` if [RemoteMediator]
* not present.
*/
public val mediator: LoadStates? = null,
) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as CombinedLoadStates
if (refresh != other.refresh) return false
if (prepend != other.prepend) return false
if (append != other.append) return false
if (source != other.source) return false
if (mediator != other.mediator) return false
return true
}
override fun hashCode(): Int {
var result = refresh.hashCode()
result = 31 * result + prepend.hashCode()
result = 31 * result + append.hashCode()
result = 31 * result + source.hashCode()
result = 31 * result + (mediator?.hashCode() ?: 0)
return result
}
override fun toString(): String {
return "CombinedLoadStates(refresh=$refresh, prepend=$prepend, append=$append, " +
"source=$source, mediator=$mediator)"
}
internal fun forEach(op: (LoadType, Boolean, LoadState) -> Unit) {
source.forEach { type, state ->
op(type, false, state)
}
mediator?.forEach { type, state ->
op(type, true, state)
}
}
}
| apache-2.0 | d1861454cb94f9f2a254f72a6ee60346 | 38.564815 | 97 | 0.662064 | 4.346897 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/lang/core/types/ty/Ty.kt | 2 | 6614 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.types.ty
import org.rust.ide.presentation.render
import org.rust.lang.core.psi.RsStructItem
import org.rust.lang.core.psi.RsTypeAlias
import org.rust.lang.core.psi.ext.fields
import org.rust.lang.core.resolve.ImplLookup
import org.rust.lang.core.resolve.KnownItems
import org.rust.lang.core.resolve.knownItems
import org.rust.lang.core.types.*
import org.rust.lang.core.types.infer.TypeFoldable
import org.rust.lang.core.types.infer.TypeFolder
import org.rust.lang.core.types.infer.TypeVisitor
import org.rust.lang.core.types.infer.substitute
import org.rust.stdext.dequeOf
import java.util.*
/**
* Represents both a type, like `i32` or `S<Foo, Bar>`, as well
* as an unbound constructor `S`.
*
* The name `Ty` is short for `Type`, inspired by the Rust
* compiler.
*/
abstract class Ty(override val flags: TypeFlags = 0) : Kind, TypeFoldable<Ty> {
override fun foldWith(folder: TypeFolder): Ty = folder.foldTy(this)
override fun superFoldWith(folder: TypeFolder): Ty = this
override fun visitWith(visitor: TypeVisitor): Boolean = visitor.visitTy(this)
override fun superVisitWith(visitor: TypeVisitor): Boolean = false
open val aliasedBy: BoundElement<RsTypeAlias>? = null
open fun withAlias(aliasedBy: BoundElement<RsTypeAlias>) = this
/**
* Bindings between formal type parameters and actual type arguments.
*/
open val typeParameterValues: Substitution get() = emptySubstitution
/**
* User visible string representation of a type
*/
final override fun toString(): String = render(useAliasNames = false, skipUnchangedDefaultTypeArguments = false)
/**
* Use it instead of [equals] if you want to check that the types are the same from the Rust perspective.
*
* ```rust
* type A = i32;
* fn foo(a: A, b: i32) {
* // Types `A` and `B` are *equivalent*, but not equal
* }
* ```
*/
fun isEquivalentTo(other: Ty?): Boolean = other != null && isEquivalentToInner(other)
protected open fun isEquivalentToInner(other: Ty): Boolean = equals(other)
}
enum class Mutability {
MUTABLE,
IMMUTABLE;
val isMut: Boolean get() = this == MUTABLE
companion object {
fun valueOf(mutable: Boolean): Mutability =
if (mutable) MUTABLE else IMMUTABLE
val DEFAULT_MUTABILITY = MUTABLE
}
}
enum class BorrowKind {
/** `&expr` or `&mut expr` */
REF,
/** `&raw const expr` or `&raw mut expr` */
RAW
}
fun Ty.getTypeParameter(name: String): TyTypeParameter? {
return typeParameterValues.typeParameterByName(name)
}
val Ty.isSelf: Boolean
get() = this is TyTypeParameter && this.parameter is TyTypeParameter.Self
fun Ty.walk(): TypeIterator = TypeIterator(this)
/**
* Iterator that walks `root` and any types reachable from
* `root`, in depth-first order.
*/
class TypeIterator(root: Ty) : Iterator<Ty> {
private val stack: Deque<Ty> = dequeOf(root)
private var lastSubtreeSize: Int = 0
override fun hasNext(): Boolean = stack.isNotEmpty()
override fun next(): Ty {
val ty = stack.pop()
lastSubtreeSize = stack.size
pushSubTypes(stack, ty)
return ty
}
}
private fun pushSubTypes(stack: Deque<Ty>, parentTy: Ty) {
// Types on the stack are pushed in reverse order so as to
// maintain a pre-order traversal. It is like the
// natural order one would expect — the order of the
// types as they are written.
when (parentTy) {
is TyAdt ->
parentTy.typeArguments.asReversed().forEach(stack::push)
is TyAnon, is TyTraitObject, is TyProjection ->
parentTy.typeParameterValues.types.reversed().forEach(stack::push)
is TyArray ->
stack.push(parentTy.base)
is TyPointer ->
stack.push(parentTy.referenced)
is TyReference ->
stack.push(parentTy.referenced)
is TySlice ->
stack.push(parentTy.elementType)
is TyTuple ->
parentTy.types.asReversed().forEach(stack::push)
is TyFunction -> {
stack.push(parentTy.retType)
parentTy.paramTypes.asReversed().forEach(stack::push)
}
}
}
fun Ty.builtinDeref(items: KnownItems, explicit: Boolean = true): Pair<Ty, Mutability>? =
when {
this is TyAdt && item == items.Box -> Pair(typeArguments.firstOrNull() ?: TyUnknown, Mutability.IMMUTABLE)
this is TyReference -> Pair(referenced, mutability)
this is TyPointer && explicit -> Pair(referenced, mutability)
else -> null
}
tailrec fun Ty.stripReferences(): Ty =
when (this) {
is TyReference -> referenced.stripReferences()
else -> this
}
fun Ty.structTail(): Ty? {
val ancestors = mutableSetOf(this)
fun structTailInner(ty: Ty): Ty? {
return when (ty) {
is TyAdt -> {
val item = ty.item as? RsStructItem ?: return ty
val typeRef = item.fields.lastOrNull()?.typeReference
val fieldTy = typeRef?.rawType?.substitute(ty.typeParameterValues) ?: return null
if (!ancestors.add(fieldTy)) return null
structTailInner(fieldTy)
}
is TyTuple -> structTailInner(ty.types.last())
else -> ty
}
}
return structTailInner(this)
}
/**
* TODO:
* There are some problems with `Self` inference (e.g. https://github.com/intellij-rust/intellij-rust/issues/2530)
* so for now just assume `Self` is always copyable
*/
fun Ty.isMovesByDefault(lookup: ImplLookup): Boolean =
when (this) {
is TyUnknown, is TyReference, is TyPointer -> false
is TyTuple -> types.any { it.isMovesByDefault(lookup) }
is TyArray -> base.isMovesByDefault(lookup)
is TySlice -> elementType.isMovesByDefault(lookup)
is TyTypeParameter -> !(parameter == TyTypeParameter.Self || lookup.isCopy(this))
else -> !lookup.isCopy(this)
}
val Ty.isBox: Boolean
get() = this is TyAdt && item == item.knownItems.Box
val Ty.isIntegral: Boolean
get() = this is TyInteger || this is TyInfer.IntVar
val Ty.isFloat: Boolean
get() = this is TyFloat || this is TyInfer.FloatVar
val Ty.isScalar: Boolean
get() = isIntegral ||
isFloat ||
this is TyBool ||
this is TyChar ||
this is TyUnit ||
this is TyFunction || // really TyFnDef & TyFnPtr
this is TyPointer
| mit | 41ac654607d3e5caba1e57af0df05b49 | 30.042254 | 116 | 0.651391 | 4.026797 | false | false | false | false |
Ch3D/BatteryWatchDog | app/src/main/kotlin/com/ch3d/ifttt/batterywatchdog/BatteryLevelReceiver.kt | 1 | 1282 | package com.ch3d.ifttt.batterywatchdog
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.Intent.ACTION_BATTERY_CHANGED
import android.content.IntentFilter
import android.os.BatteryManager.EXTRA_LEVEL
import android.text.TextUtils
import com.ch3d.ifttt.batterywatchdog.PrefrencesProvider.Companion.getDefaultDeviceName
class BatteryLevelReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val key = context.getIftttKey()
if (TextUtils.isEmpty(key)) {
return
}
val deviceName = if (context.isCustomNameEnabled())
context.getCustomDeviceName() else getDefaultDeviceName()
val event = if (context.isCustomEventEnabled())
context.getCustomEventName() else ReportData.EVENT_BATTERY_LOW
ReportData(key!!, event!!, deviceName!!, getBatteryPercentage(context))
ReportAsyncTask().execute()
}
private fun getBatteryPercentage(context: Context): String {
val batteryStatus = context.registerReceiver(null, IntentFilter(ACTION_BATTERY_CHANGED))
val level = batteryStatus?.getIntExtra(EXTRA_LEVEL, -1) ?: 0
return Integer.toString(level)
}
}
| apache-2.0 | 24624f0a03e7380f9c1bb585a97fbd37 | 35.628571 | 96 | 0.733229 | 4.578571 | false | false | false | false |
inorichi/tachiyomi-extensions | src/ru/mintmanga/src/eu/kanade/tachiyomi/extension/ru/mintmanga/MintmangaActivity.kt | 1 | 1391 | package eu.kanade.tachiyomi.extension.ru.mintmanga
import android.app.Activity
import android.content.ActivityNotFoundException
import android.content.Intent
import android.os.Bundle
import android.util.Log
import kotlin.system.exitProcess
/**
* Springboard that accepts https://mintmanga.live/xxx intents and redirects them to
* the main tachiyomi process. The idea is to not install the intent filter unless
* you have this extension installed, but still let the main tachiyomi app control
* things.
*/
class MintmangaActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val pathSegments = intent?.data?.pathSegments
if (pathSegments != null && pathSegments.size > 0) {
val titleid = pathSegments[0]
val mainIntent = Intent().apply {
action = "eu.kanade.tachiyomi.SEARCH"
putExtra("query", "${Mintmanga.PREFIX_SLUG_SEARCH}$titleid")
putExtra("filter", packageName)
}
try {
startActivity(mainIntent)
} catch (e: ActivityNotFoundException) {
Log.e("MintmangaActivity", e.toString())
}
} else {
Log.e("MintmangaaActivity", "could not parse uri from intent $intent")
}
finish()
exitProcess(0)
}
}
| apache-2.0 | 0e7d1da997d1ff70c900ce4c678a7b46 | 33.775 | 84 | 0.646298 | 4.667785 | false | false | false | false |
stfalcon-studio/uaroads_android | app/src/main/java/com/stfalcon/new_uaroads_android/features/places/LocationChooserActivity.kt | 1 | 5145 | /*
* Copyright (c) 2017 stfalcon.com
*
* 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.stfalcon.new_uaroads_android.features.places
import android.content.Context
import android.location.Location
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.view.inputmethod.EditorInfo
import com.jakewharton.rxbinding2.widget.textChanges
import com.stfalcon.mvphelper.MvpActivity
import com.stfalcon.new_uaroads_android.R
import com.stfalcon.new_uaroads_android.common.network.models.LatLng
import com.stfalcon.new_uaroads_android.common.network.models.response.GeoPlacePrediction
import com.stfalcon.new_uaroads_android.ext.hideView
import com.stfalcon.new_uaroads_android.ext.showView
import com.stfalcon.new_uaroads_android.features.places.adapter.PlacesListAdapter
import kotlinx.android.synthetic.main.activity_location_chooser.*
import kotlinx.android.synthetic.main.item_place.*
import org.jetbrains.anko.intentFor
import org.jetbrains.anko.toast
import java.util.concurrent.TimeUnit
import javax.inject.Inject
class LocationChooserActivity : MvpActivity<LocationChooserContract.Presenter, LocationChooserContract.View>(),
LocationChooserContract.View {
override fun getLayoutResId() = R.layout.activity_location_chooser
companion object {
val RESULT_PLACE = 1
val RESULT_MY_LOCATION = 2
val KEY_PLACE_TITLE = "placeTitle"
val KEY_PLACE_LOCATION = "placeLocation"
private val KEY_LOCATION = "location"
fun getIntent(context: Context, location: Location?) = context.intentFor<LocationChooserActivity>(
KEY_LOCATION to location
)
}
@Inject lateinit var placeListAdapter: PlacesListAdapter
var location: Location? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
initToolbar()
initInputViews()
initRecyclerView()
}
private fun initInputViews() {
etSearch.textChanges()
.debounce(500, TimeUnit.MILLISECONDS)
.filter { !it.isEmpty() }
.subscribe {
presenter?.onQueryChanged(getString(R.string.query_ukraine, it.toString()))
}
etSearch.setOnEditorActionListener { v, actionId, _ ->
if (actionId == EditorInfo.IME_ACTION_SEARCH
&& v.text.isNotEmpty()) {
presenter?.onActionSearchClicked(getString(R.string.query_ukraine, v.text), v.text.toString())
return@setOnEditorActionListener true
}
return@setOnEditorActionListener false
}
viewMyLocation.setOnClickListener {
presenter?.onMyLocationSelected()
}
}
private fun initRecyclerView() {
placeListAdapter.onClickItem = { _, item ->
presenter?.onPlaceSelected(item)
}
recyclerView.adapter = placeListAdapter
recyclerView.layoutManager = LinearLayoutManager(this)
}
override fun parseIntent() {
super.parseIntent()
location = intent.getParcelableExtra(KEY_LOCATION)
}
private fun initToolbar() {
setSupportActionBar(toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
toolbar.setNavigationOnClickListener { presenter?.onClickNavigateButton() }
}
override fun navigateBack() {
finish()
}
override fun showResults(list: List<GeoPlacePrediction>) {
recyclerView.showView()
viewMyLocation.hideView()
placeListAdapter.clearItems()
placeListAdapter.addItems(list)
}
override fun showEmptyState(location: Location?) {
placeListAdapter.clearItems()
location?.let {
recyclerView.hideView()
viewMyLocation.showView()
tvPlaceTitle.text = getString(R.string.place_my_location)
tvPlaceSubtitle.text = getString(R.string.place_my_location_pos, it.longitude, it.longitude)
}
}
override fun showNoResutError(query: String) {
toast(getString(R.string.search_no_result_error, query))
}
override fun showError(error: String) {
toast(error)
}
override fun returnPlaceResult(placeTitle: String, placeLocation: LatLng) {
intent.putExtra(KEY_PLACE_TITLE, placeTitle)
intent.putExtra(KEY_PLACE_LOCATION, placeLocation)
setResult(RESULT_PLACE, intent)
finish()
}
override fun returnMyLocationResult() {
setResult(RESULT_MY_LOCATION, intent)
finish()
}
}
| apache-2.0 | 05ff6ad3f15fa7246456763524782591 | 34.239726 | 111 | 0.687658 | 4.585561 | false | false | false | false |
inorichi/tachiyomi-extensions | src/vi/hentaivn/src/eu/kanade/tachiyomi/extension/vi/hentaivn/HentaiVN.kt | 1 | 15420 | package eu.kanade.tachiyomi.extension.vi.hentaivn
import eu.kanade.tachiyomi.annotations.Nsfw
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.source.model.Filter
import eu.kanade.tachiyomi.source.model.FilterList
import eu.kanade.tachiyomi.source.model.MangasPage
import eu.kanade.tachiyomi.source.model.Page
import eu.kanade.tachiyomi.source.model.SChapter
import eu.kanade.tachiyomi.source.model.SManga
import eu.kanade.tachiyomi.source.online.ParsedHttpSource
import eu.kanade.tachiyomi.util.asJsoup
import okhttp3.CookieJar
import okhttp3.Headers
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.Locale
@Nsfw
class HentaiVN : ParsedHttpSource() {
override val baseUrl = "https://hentaivn.tv"
override val lang = "vi"
override val name = "HentaiVN"
override val supportsLatest = true
private val searchUrl = "$baseUrl/forum/search-plus.php"
private val searchClient = network.cloudflareClient
override val client: OkHttpClient = network.cloudflareClient.newBuilder()
.cookieJar(CookieJar.NO_COOKIES)
.addInterceptor { chain ->
val originalRequest = chain.request()
when {
originalRequest.url.toString().startsWith(searchUrl) -> {
searchClient.newCall(originalRequest).execute()
}
else -> chain.proceed(originalRequest)
}
}
.build()
override fun headersBuilder(): Headers.Builder = super.headersBuilder().add("Referer", baseUrl)
private val dateFormat = SimpleDateFormat("dd/MM/yyyy", Locale.ENGLISH)
override fun chapterFromElement(element: Element): SChapter {
if (element.select("a").isEmpty()) throw Exception(element.select("h2").html())
val chapter = SChapter.create()
element.select("a").first().let {
chapter.name = it.select("h2").text()
chapter.setUrlWithoutDomain(it.attr("href"))
}
chapter.date_upload = parseDate(element.select("td:nth-child(2)").text().trim())
return chapter
}
private fun parseDate(dateString: String): Long {
return try {
dateFormat.parse(dateString)?.time ?: 0L
} catch (e: ParseException) {
return 0L
}
}
override fun chapterListSelector() = ".page-info > table.listing > tbody > tr"
override fun imageUrlParse(document: Document) = ""
override fun latestUpdatesFromElement(element: Element): SManga {
val manga = SManga.create()
element.select(".box-description a").first().let {
manga.setUrlWithoutDomain(it.attr("href"))
manga.title = it.text().trim()
}
manga.thumbnail_url = element.select(".box-cover a img").attr("data-src")
return manga
}
override fun latestUpdatesNextPageSelector() = "ul.pagination > li:contains(Next)"
override fun latestUpdatesRequest(page: Int): Request {
return GET("$baseUrl/chap-moi.html?page=$page", headers)
}
override fun latestUpdatesSelector() = ".main > .block-left > .block-item > ul > li.item"
override fun mangaDetailsParse(document: Document): SManga {
val infoElement = document.select(".main > .page-left > .left-info > .page-info")
val manga = SManga.create()
manga.author = infoElement.select("p:contains(Tác giả:) a").text()
manga.description = infoElement.select(":root > p:contains(Nội dung:) + p").text()
manga.genre = infoElement.select("p:contains(Thể loại:) a").joinToString { it.text() }
manga.thumbnail_url = document.select(".main > .page-right > .right-info > .page-ava > img").attr("src")
manga.status = parseStatus(infoElement.select("p:contains(Tình Trạng:) a").firstOrNull()?.text())
return manga
}
private fun parseStatus(status: String?) = when {
status == null -> SManga.UNKNOWN
status.contains("Đang tiến hành") -> SManga.ONGOING
status.contains("Đã hoàn thành") -> SManga.COMPLETED
else -> SManga.UNKNOWN
}
override fun pageListParse(document: Document): List<Page> {
val pages = mutableListOf<Page>()
val pageUrl = document.select("link[rel=canonical]").attr("href")
document.select("#image > img").forEachIndexed { i, e ->
pages.add(Page(i, pageUrl, e.attr("abs:src")))
}
return pages
}
override fun popularMangaFromElement(element: Element) = latestUpdatesFromElement(element)
override fun popularMangaNextPageSelector() = latestUpdatesNextPageSelector()
override fun popularMangaRequest(page: Int): Request {
return GET("$baseUrl/tieu-diem.html?page=$page", headers)
}
override fun popularMangaSelector() = latestUpdatesSelector()
override fun searchMangaParse(response: Response): MangasPage {
val document = response.asJsoup()
if (document.select("p").toString().contains("Bạn chỉ có thể sử dụng chức năng này khi đã đăng ký thành viên"))
throw Exception("Đăng nhập qua WebView để kích hoạt tìm kiếm")
val mangas = document.select(searchMangaSelector()).map { element ->
searchMangaFromElement(element)
}
val hasNextPage = searchMangaNextPageSelector().let { selector ->
document.select(selector).first()
} != null
return MangasPage(mangas, hasNextPage)
}
override fun searchMangaFromElement(element: Element): SManga {
val manga = SManga.create()
element.select(".search-des > a").first().let {
manga.setUrlWithoutDomain(it.attr("href"))
manga.title = it.text().trim()
}
manga.thumbnail_url = element.select("div.search-img img").attr("abs:src")
return manga
}
override fun searchMangaNextPageSelector() = "ul.pagination > li:contains(Cuối)"
override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request {
val url = "$searchUrl?name=$query&page=$page&dou=&char=&group=0&search=".toHttpUrlOrNull()!!.newBuilder()
(if (filters.isEmpty()) getFilterList() else filters).forEach { filter ->
when (filter) {
is TextField -> url.addQueryParameter(filter.key, filter.state)
is GenreList ->
filter.state
.filter { it.state }
.map { it.id }
.forEach { url.addQueryParameter("tag[]", it) }
is GroupList -> {
val group = getGroupList()[filter.state]
url.addQueryParameter("group", group.id)
}
}
}
return GET(url.toString(), headers)
}
override fun searchMangaSelector() = ".search-ul .search-li"
private class TextField(name: String, val key: String) : Filter.Text(name)
private class Genre(name: String, val id: String) : Filter.CheckBox(name)
private class GenreList(genres: List<Genre>) : Filter.Group<Genre>("Thể loại", genres)
private class TransGroup(name: String, val id: String) : Filter.CheckBox(name) {
override fun toString(): String {
return name
}
}
private class GroupList(groups: Array<TransGroup>) : Filter.Select<TransGroup>("Nhóm dịch", groups)
override fun getFilterList() = FilterList(
TextField("Doujinshi", "dou"),
TextField("Nhân vật", "char"),
GenreList(getGenreList()),
GroupList(getGroupList())
)
// jQuery.makeArray($('#container > div > div > div.box-box.textbox > form > ul:nth-child(7) > li').map((i, e) => `Genre("${e.textContent}", "${e.children[0].value}")`)).join(',\n')
// https://hentaivn.net/forum/search-plus.php
private fun getGenreList() = listOf(
Genre("3D Hentai", "3"),
Genre("Action", "5"),
Genre("Adult", "116"),
Genre("Adventure", "203"),
Genre("Ahegao", "20"),
Genre("Anal", "21"),
Genre("Angel", "249"),
Genre("Ảnh động", "131"),
Genre("Animal", "127"),
Genre("Animal girl", "22"),
Genre("Artist", "115"),
Genre("BBW", "251"),
Genre("BDSM", "24"),
Genre("Bestiality", "25"),
Genre("Big Ass", "133"),
Genre("Big Boobs", "23"),
Genre("Big Penis", "32"),
Genre("Bloomers", "27"),
Genre("BlowJobs", "28"),
Genre("Body Swap", "29"),
Genre("Bodysuit", "30"),
Genre("Bondage", "254"),
Genre("Breast Sucking", "33"),
Genre("BreastJobs", "248"),
Genre("Brocon", "31"),
Genre("Brother", "242"),
Genre("Business Suit", "241"),
Genre("Catgirls", "39"),
Genre("Che ít", "101"),
Genre("Che nhiều", "129"),
Genre("Cheating", "34"),
Genre("Chikan", "35"),
Genre("Có che", "100"),
Genre("Comedy", "36"),
Genre("Comic", "120"),
Genre("Condom", "210"),
Genre("Cosplay", "38"),
Genre("Cousin", "2"),
Genre("Dark Skin", "40"),
Genre("Demon", "132"),
Genre("DemonGirl", "212"),
Genre("Devil", "104"),
Genre("DevilGirl", "105"),
Genre("Dirty", "253"),
Genre("Dirty Old Man", "41"),
Genre("Double Penetration", "42"),
Genre("Doujinshi", "44"),
Genre("Drama", "4"),
Genre("Drug", "43"),
Genre("Ecchi", "45"),
Genre("Elder Sister", "245"),
Genre("Elf", "125"),
Genre("Exhibitionism", "46"),
Genre("Fantasy", "123"),
Genre("Father", "243"),
Genre("Femdom", "47"),
Genre("Fingering", "48"),
Genre("Footjob", "108"),
Genre("Full Color", "37"),
Genre("Furry", "202"),
Genre("Futanari", "50"),
Genre("Game", "130"),
Genre("GangBang", "51"),
Genre("Garter Belts", "206"),
Genre("Gender Bender", "52"),
Genre("Ghost", "106"),
Genre("Glasses", "56"),
Genre("Group", "53"),
Genre("Guro", "55"),
Genre("Hairy", "247"),
Genre("Handjob", "57"),
Genre("Harem", "58"),
Genre("HentaiVN", "102"),
Genre("Historical", "80"),
Genre("Horror", "122"),
Genre("Housewife", "59"),
Genre("Humiliation", "60"),
Genre("Idol", "61"),
Genre("Imouto", "244"),
Genre("Incest", "62"),
Genre("Insect (Côn Trùng)", "26"),
Genre("Không che", "99"),
Genre("Kimono", "110"),
Genre("Loli", "63"),
Genre("Maids", "64"),
Genre("Manhwa", "114"),
Genre("Mature", "119"),
Genre("Miko", "124"),
Genre("Milf", "126"),
Genre("Mind Break", "121"),
Genre("Mind Control", "113"),
Genre("Monster", "66"),
Genre("Monstergirl", "67"),
Genre("Mother", "103"),
Genre("Nakadashi", "205"),
Genre("Netori", "1"),
Genre("Non-hen", "201"),
Genre("NTR", "68"),
Genre("Nurse", "69"),
Genre("Old Man", "211"),
Genre("Oneshot", "71"),
Genre("Oral", "70"),
Genre("Osananajimi", "209"),
Genre("Paizuri", "72"),
Genre("Pantyhose", "204"),
Genre("Pregnant", "73"),
Genre("Rape", "98"),
Genre("Romance", "117"),
Genre("Ryona", "207"),
Genre("Scat", "134"),
Genre("School Uniform", "74"),
Genre("SchoolGirl", "75"),
Genre("Series", "87"),
Genre("Sex Toys", "88"),
Genre("Shimapan", "246"),
Genre("Short Hentai", "118"),
Genre("Shota", "77"),
Genre("Shoujo", "76"),
Genre("Siscon", "79"),
Genre("Sister", "78"),
Genre("Slave", "82"),
Genre("Sleeping", "213"),
Genre("Small Boobs", "84"),
Genre("Sports", "83"),
Genre("Stockings", "81"),
Genre("Supernatural", "85"),
Genre("Sweating", "250"),
Genre("Swimsuit", "86"),
Genre("Teacher", "91"),
Genre("Tentacles", "89"),
Genre("Time Stop", "109"),
Genre("Tomboy", "90"),
Genre("Tracksuit", "252"),
Genre("Transformation", "256"),
Genre("Trap", "92"),
Genre("Tsundere", "111"),
Genre("Tự sướng", "65"),
Genre("Twins", "93"),
Genre("Vampire", "107"),
Genre("Vanilla", "208"),
Genre("Virgin", "95"),
Genre("X-ray", "94"),
Genre("Yandere", "112"),
Genre("Yaoi", "96"),
Genre("Yuri", "97"),
Genre("Zombie", "128")
)
// jQuery.makeArray($('#container > div > div > div.box-box.textbox > form > ul:nth-child(8) > li').map((i, e) => `TransGroup("${e.textContent}", "${e.children[0].value}")`)).join(',\n')
// https://hentaivn.net/forum/search-plus.php
private fun getGroupList() = arrayOf(
TransGroup("Tất cả", "0"),
TransGroup("Đang cập nhật", "1"),
TransGroup("Góc Hentai", "3"),
TransGroup("Hakihome", "4"),
TransGroup("LXERS", "5"),
TransGroup("Hentai-Homies", "6"),
TransGroup("BUZPLANET", "7"),
TransGroup("Trang Sally", "8"),
TransGroup("Loli Rules The World", "9"),
TransGroup("XXX Inc", "10"),
TransGroup("Kobato9x", "11"),
TransGroup("Blazing Soul", "12"),
TransGroup("TAYXUONG", "13"),
TransGroup("[S]ky [G]arden [G]roup", "14"),
TransGroup("Bloomer-kun", "15"),
TransGroup("DHT", "16"),
TransGroup("TruyenHen18", "17"),
TransGroup("iHentaiManga", "18"),
TransGroup("Quân cảng Kancolle X", "19"),
TransGroup("LHMANGA", "20"),
TransGroup("Ship of The Dream", "21"),
TransGroup("Fallen Angels", "22"),
TransGroup("TruyenHentai2H", "23"),
TransGroup("Lạc Thiên", "24"),
TransGroup("69HENTAIXXX", "25"),
TransGroup("DHL", "26"),
TransGroup("Hentai-AdutsManga", "27"),
TransGroup("Hatsu Kaze Desu Translator Team", "28"),
TransGroup("IHentai69", "29"),
TransGroup("Zest", "30"),
TransGroup("Demon Victory Team", "31"),
TransGroup("NTR Victory Team", "32"),
TransGroup("Rori Saikou", "33"),
TransGroup("Bullet Burn Team", "34"),
TransGroup("RE Team", "35"),
TransGroup("Rebelliones", "36"),
TransGroup("Shinto", "37"),
TransGroup("Sexual Paradise", "38"),
TransGroup("FA Dislike Team", "39"),
TransGroup("Triggered Team", "41"),
TransGroup("T.K Translation Team", "42"),
TransGroup("Mabu MG", "43"),
TransGroup("Team Zentsu", "44"),
TransGroup("Sweeter Than Salt", "46"),
TransGroup("Cà rà cà rà Cặt", "47"),
TransGroup("Paradise Of The Happiness", "48"),
TransGroup("Furry Break the 4th Wall", "49"),
TransGroup("The Ignite Team", "50"),
TransGroup("Cuồng Loli", "51"),
TransGroup("Depressed Lolicons Squad - DLS", "52"),
TransGroup("Heaven Of The Fuck", "53")
)
}
| apache-2.0 | 0039b980adccc1d3d6a61a719fce3f0f | 36.90099 | 190 | 0.566745 | 3.775148 | false | false | false | false |
qiuxiang/react-native-amap3d | lib/android/src/main/java/qiuxiang/amap3d/map_view/CircleManager.kt | 1 | 1373 | package qiuxiang.amap3d.map_view
import com.facebook.react.bridge.ReadableMap
import com.facebook.react.uimanager.SimpleViewManager
import com.facebook.react.uimanager.ThemedReactContext
import com.facebook.react.uimanager.annotations.ReactProp
import qiuxiang.amap3d.toLatLng
import qiuxiang.amap3d.toPx
@Suppress("unused")
internal class CircleManager : SimpleViewManager<Circle>() {
override fun getName(): String {
return "AMapCircle"
}
override fun createViewInstance(reactContext: ThemedReactContext): Circle {
return Circle(reactContext)
}
@ReactProp(name = "center")
fun setCenter(circle: Circle, center: ReadableMap) {
circle.center = center.toLatLng()
}
@ReactProp(name = "radius")
fun setRadius(circle: Circle, radius: Double) {
circle.radius = radius
}
@ReactProp(name = "fillColor", customType = "Color")
fun setFillColor(circle: Circle, fillColor: Int) {
circle.fillColor = fillColor
}
@ReactProp(name = "strokeColor", customType = "Color")
fun setStrokeColor(circle: Circle, strokeColor: Int) {
circle.strokeColor = strokeColor
}
@ReactProp(name = "strokeWidth")
fun setStrokeWidth(circle: Circle, strokeWidth: Float) {
circle.strokeWidth = strokeWidth.toPx().toFloat()
}
@ReactProp(name = "zIndex")
fun setIndex(circle: Circle, zIndex: Float) {
circle.zIndex = zIndex
}
}
| mit | 9c0db7be3d2042bc87e07b4c340f9011 | 27.020408 | 77 | 0.73343 | 3.900568 | false | false | false | false |
elect86/jAssimp | src/main/kotlin/assimp/ScenePreprocessor.kt | 2 | 6892 | package assimp
import kotlin.math.max
import kotlin.math.min
/**
* Created by elect on 18/11/2016.
*/
// ----------------------------------------------------------------------------------
/** ScenePreprocessor: Preprocess a scene before any post-processing steps are executed.
*
* The step computes data that needn't necessarily be provided by the importer, such as aiMesh::primitiveTypes.
*/
// ----------------------------------------------------------------------------------
object ScenePreprocessor {
/** Scene we're currently working on */
lateinit var scene: AiScene
/** Preprocess the current scene */
fun processScene(scene: AiScene) {
// scene cant be null
this.scene = scene
// Process all meshes
scene.meshes.forEach { it.process() }
// - nothing to do for nodes for the moment
// - nothing to do for textures for the moment
// - nothing to do for lights for the moment
// - nothing to do for cameras for the moment
// Process all animations
scene.animations.forEach { it.process() }
// Generate a default material if none was specified
if (scene.numMaterials == 0 && scene.numMeshes > 0) {
scene.materials.add(AiMaterial().apply {
color = AiMaterial.Color().apply { diffuse = AiColor3D(0.6f) }
// setup the default name to make this material identifiable
name = AI_DEFAULT_MATERIAL_NAME
})
logger.debug{"ScenePreprocessor: Adding default material '$AI_DEFAULT_MATERIAL_NAME'"}
scene.meshes.forEach { it.materialIndex = scene.numMaterials }
scene.numMaterials++
}
}
fun AiMesh.process() {
// TODO change -> for in textureCoords
textureCoords.forEach {
// If aiMesh::mNumUVComponents is *not* set assign the default value of 2
for (i in 0 until it.size)
if (it[i].isEmpty())
it[i] = FloatArray(2)
/* Ensure unsued components are zeroed. This will make 1D texture channels work as if they were 2D channels..
just in case an application doesn't handle this case */
// if (it[0].size == 2)
// for (uv in it)
// uv[2] = 0f
// else if (it[0].size == 1)
// for (uv in it) {
// uv[2] = 0f
// uv[1] = 0f
// }
// else if (it[0].size == 3) {
// // Really 3D coordinates? Check whether the third coordinate is != 0 for at least one element
// var coord3d = false
// for (uv in it)
// if (uv[2] != 0f)
// coord3d = true
// if (!coord3d) {
// logger.warn { "ScenePreprocessor: UVs are declared to be 3D but they're obviously not. Reverting to 2D." }
// for (i in 0 until it.size)
// it[i] = FloatArray(2)
// }
// }
}
// If the information which primitive types are there in the mesh is currently not available, compute it.
if (primitiveTypes == 0) faces.forEach {
primitiveTypes = when (it.size) {
3 -> primitiveTypes or AiPrimitiveType.TRIANGLE
2 -> primitiveTypes or AiPrimitiveType.LINE
1 -> primitiveTypes or AiPrimitiveType.POINT
else -> primitiveTypes or AiPrimitiveType.POLYGON
}
}
// If tangents and normals are given but no bitangents compute them
if (tangents.isNotEmpty() && normals.isNotEmpty() && bitangents.isEmpty()) {
bitangents = ArrayList(numVertices)
for (i in 0 until numVertices)
bitangents[i] = normals[i] cross tangents[i]
}
}
fun AiAnimation.process() {
var first = 10e10
var last = -10e10
channels.forEach { channel ->
// If the exact duration of the animation is not given compute it now.
if (duration == -1.0) {
channel!!.positionKeys.forEach {
// Position keys
first = min(first, it.time)
last = max(last, it.time)
}
channel.scalingKeys.forEach {
// Scaling keys
first = min(first, it.time)
last = max(last, it.time)
}
channel.rotationKeys.forEach {
// Rotation keys
first = min(first, it.time)
last = max(last, it.time)
}
}
/* Check whether the animation channel has no rotation or position tracks. In this case we generate a dummy
* track from the information we have in the transformation matrix of the corresponding node. */
if (channel!!.numRotationKeys == 0 || channel.numPositionKeys == 0 || channel.numScalingKeys == 0)
// Find the node that belongs to this animation
scene.rootNode.findNode(channel.nodeName)?.let {
// ValidateDS will complain later if 'node' is NULL
// Decompose the transformation matrix of the node
val scaling = AiVector3D()
val position = AiVector3D()
val rotation = AiQuaternion()
it.transformation.decompose(scaling, rotation, position)
if (channel.numRotationKeys == 0) { // No rotation keys? Generate a dummy track
channel.numRotationKeys = 1
channel.rotationKeys = arrayListOf(AiQuatKey(0.0, rotation))
logger.debug { "ScenePreprocessor: Dummy rotation track has been generated" }
}
if (channel.numScalingKeys == 0) { // No scaling keys? Generate a dummy track
channel.numScalingKeys = 1
channel.scalingKeys = arrayListOf(AiVectorKey(0.0, scaling))
logger.debug { "ScenePreprocessor: Dummy scaling track has been generated" }
}
if (channel.numPositionKeys == 0) { // No position keys? Generate a dummy track
channel.numPositionKeys = 1
channel.positionKeys = arrayListOf(AiVectorKey(0.0, position))
logger.debug { "ScenePreprocessor: Dummy position track has been generated" }
}
}
}
if (duration == -1.0) {
logger.debug { "ScenePreprocessor: Setting animation duration" }
duration = last - min(first, 0.0)
}
}
} | mit | cf4544c2ae6b97f8b444012945eb932a | 42.626582 | 128 | 0.519153 | 4.915835 | false | false | false | false |
Commit451/GitLabAndroid | app/src/main/java/com/commit451/gitlab/view/LabCoatNavigationView.kt | 2 | 10154 | package com.commit451.gitlab.view
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import coil.api.load
import coil.transform.CircleCropTransformation
import com.commit451.addendum.themeAttrColor
import com.commit451.alakazam.fadeOut
import com.commit451.gitlab.App
import com.commit451.gitlab.BuildConfig
import com.commit451.gitlab.R
import com.commit451.gitlab.activity.*
import com.commit451.gitlab.adapter.AccountAdapter
import com.commit451.gitlab.data.Prefs
import com.commit451.gitlab.event.CloseDrawerEvent
import com.commit451.gitlab.event.LoginEvent
import com.commit451.gitlab.event.ReloadDataEvent
import com.commit451.gitlab.extension.baseActivity
import com.commit451.gitlab.extension.mapResponseSuccess
import com.commit451.gitlab.extension.with
import com.commit451.gitlab.model.Account
import com.commit451.gitlab.model.api.User
import com.commit451.gitlab.navigation.Navigator
import com.commit451.gitlab.util.ImageUtil
import com.google.android.material.navigation.NavigationView
import com.google.android.material.navigation.NavigationView.OnNavigationItemSelectedListener
import org.greenrobot.eventbus.Subscribe
import timber.log.Timber
import java.util.*
/**
* Our very own navigation view
*/
class LabCoatNavigationView : NavigationView {
private lateinit var listAccounts: RecyclerView
private lateinit var iconArrow: View
private lateinit var textUsername: TextView
private lateinit var textEmail: TextView
private lateinit var imageProfile: ImageView
private lateinit var adapterAccounts: AccountAdapter
var user: User? = null
private val onNavigationItemSelectedListener = OnNavigationItemSelectedListener { menuItem ->
when (menuItem.itemId) {
R.id.nav_projects -> {
if (context !is ProjectsActivity) {
Navigator.navigateToProjects(context as Activity)
(context as Activity).finish()
(context as Activity).overridePendingTransition(R.anim.fade_in, R.anim.do_nothing)
}
App.bus().post(CloseDrawerEvent())
return@OnNavigationItemSelectedListener true
}
R.id.nav_groups -> {
if (context !is GroupsActivity) {
Navigator.navigateToGroups(context as Activity)
(context as Activity).finish()
(context as Activity).overridePendingTransition(R.anim.fade_in, R.anim.do_nothing)
}
App.bus().post(CloseDrawerEvent())
return@OnNavigationItemSelectedListener true
}
R.id.nav_activity -> {
if (context !is ActivityActivity) {
Navigator.navigateToActivity(context as Activity)
(context as Activity).finish()
(context as Activity).overridePendingTransition(R.anim.fade_in, R.anim.do_nothing)
}
App.bus().post(CloseDrawerEvent())
return@OnNavigationItemSelectedListener true
}
R.id.nav_todos -> {
if (context !is TodosActivity) {
Navigator.navigateToTodos(context as Activity)
(context as Activity).finish()
(context as Activity).overridePendingTransition(R.anim.fade_in, R.anim.do_nothing)
}
App.bus().post(CloseDrawerEvent())
return@OnNavigationItemSelectedListener true
}
R.id.nav_about -> {
App.bus().post(CloseDrawerEvent())
Navigator.navigateToAbout(context as Activity)
return@OnNavigationItemSelectedListener true
}
R.id.nav_settings -> {
App.bus().post(CloseDrawerEvent())
Navigator.navigateToSettings(context as Activity)
return@OnNavigationItemSelectedListener true
}
}
false
}
private val accountsAdapterListener = object : AccountAdapter.Listener {
override fun onAccountClicked(account: Account) {
switchToAccount(account)
}
override fun onAddAccountClicked() {
Navigator.navigateToLogin(context as Activity, true)
toggleAccounts()
App.bus().post(CloseDrawerEvent())
}
override fun onAccountLogoutClicked(account: Account) {
Prefs.removeAccount(account)
val accounts = Prefs.getAccounts()
if (accounts.isEmpty()) {
Navigator.navigateToLogin(context as Activity)
(context as Activity).finish()
} else {
if (account == App.get().getAccount()) {
switchToAccount(accounts[0])
}
}
}
}
constructor(context: Context) : super(context) {
init()
}
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
init()
}
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
init()
}
fun init() {
App.bus().register(this)
setNavigationItemSelectedListener(onNavigationItemSelectedListener)
inflateMenu(R.menu.navigation)
val header = inflateHeaderView(R.layout.header_nav_drawer)
// We have to do it like this due to inflation
imageProfile = header.findViewById(R.id.imageProfile)
iconArrow = header.findViewById(R.id.iconArrow)
textUsername = header.findViewById(R.id.textUsername)
textEmail = header.findViewById(R.id.textEmail)
val buttonDebug = header.findViewById<View>(R.id.buttonDebug)
val drawerHeader = header.findViewById<View>(R.id.drawerHeader)
imageProfile.setOnClickListener {
user?.let {
Navigator.navigateToUser(context as Activity, imageProfile, it)
}
}
buttonDebug.setOnClickListener {
context.startActivity(DebugActivity.newIntent(context))
}
drawerHeader.setOnClickListener {
toggleAccounts()
}
if (BuildConfig.DEBUG) {
buttonDebug.visibility = View.VISIBLE
}
listAccounts = RecyclerView(context)
listAccounts.layoutManager = LinearLayoutManager(context)
listAccounts.setBackgroundColor(context.themeAttrColor(android.R.attr.windowBackground))
addView(listAccounts)
val params = listAccounts.layoutParams as LayoutParams
params.setMargins(0, resources.getDimensionPixelSize(R.dimen.account_header_height), 0, 0)
listAccounts.visibility = View.GONE
adapterAccounts = AccountAdapter(context, accountsAdapterListener)
listAccounts.adapter = adapterAccounts
setSelectedNavigationItem()
setAccounts()
loadCurrentUser()
}
@SuppressLint("RestrictedApi")
override fun onDetachedFromWindow() {
App.bus().unregister(this)
super.onDetachedFromWindow()
}
private fun setSelectedNavigationItem() {
when (context) {
is ProjectsActivity -> {
setCheckedItem(R.id.nav_projects)
}
is GroupsActivity -> {
setCheckedItem(R.id.nav_groups)
}
is ActivityActivity -> {
setCheckedItem(R.id.nav_activity)
}
is TodosActivity -> {
setCheckedItem(R.id.nav_todos)
}
else -> {
throw IllegalStateException("You need to defined a menu item for this activity")
}
}
}
private fun setAccounts() {
val accounts = Prefs.getAccounts()
Timber.d("Got %s accounts", accounts.size)
adapterAccounts.setAccounts(accounts)
}
private fun loadCurrentUser() {
App.get().gitLab.getThisUser()
.mapResponseSuccess()
.with(baseActivity())
.subscribe({
bindUser(it)
}, {
Timber.e(it)
})
}
private fun bindUser(user: User) {
this.user = user
if (user.username != null) {
textUsername.text = user.username
}
if (user.email != null) {
textEmail.text = user.email
}
val url = ImageUtil.getAvatarUrl(user, resources.getDimensionPixelSize(R.dimen.larger_image_size))
imageProfile.load(url) {
transformations(CircleCropTransformation())
}
}
/**
* Toggle the visibility of accounts. Meaning hide it if it is showing, show it if it is hidden
*/
fun toggleAccounts() {
if (listAccounts.visibility == View.GONE) {
listAccounts.visibility = View.VISIBLE
listAccounts.alpha = 0.0f
listAccounts.animate().alpha(1.0f)
iconArrow.animate().rotation(180.0f)
} else {
listAccounts.fadeOut()
iconArrow.animate().rotation(0.0f)
}
}
fun switchToAccount(account: Account) {
Timber.d("Switching to account: %s", account)
account.lastUsed = Date()
App.get().setAccount(account)
Prefs.updateAccount(account)
toggleAccounts()
App.bus().post(ReloadDataEvent())
App.bus().post(CloseDrawerEvent())
// Trigger a reload in the adapter so that we will place the accounts
// in the correct order from most recently used
adapterAccounts.notifyDataSetChanged()
loadCurrentUser()
}
@Subscribe
fun onUserLoggedIn(event: LoginEvent) {
adapterAccounts.addAccount(event.account)
adapterAccounts.notifyDataSetChanged()
loadCurrentUser()
}
}
| apache-2.0 | 0f9ffac2cf9432121f94e0a267898675 | 35.52518 | 113 | 0.628521 | 4.941119 | false | false | false | false |
apollostack/apollo-android | apollo-runtime/src/main/java/com/apollographql/apollo3/internal/RealApolloQueryWatcher.kt | 1 | 8308 | package com.apollographql.apollo3.internal
import com.apollographql.apollo3.ApolloCall
import com.apollographql.apollo3.ApolloQueryWatcher
import com.apollographql.apollo3.api.ResponseAdapterCache
import com.apollographql.apollo3.api.Operation
import com.apollographql.apollo3.api.ApolloResponse
import com.apollographql.apollo3.api.internal.ApolloLogger
import com.apollographql.apollo3.api.internal.Optional
import com.apollographql.apollo3.cache.normalized.ApolloStore
import com.apollographql.apollo3.cache.normalized.ApolloStore.RecordChangeSubscriber
import com.apollographql.apollo3.cache.normalized.Record
import com.apollographql.apollo3.cache.normalized.internal.dependentKeys
import com.apollographql.apollo3.exception.ApolloCanceledException
import com.apollographql.apollo3.exception.ApolloException
import com.apollographql.apollo3.exception.ApolloHttpException
import com.apollographql.apollo3.exception.ApolloNetworkException
import com.apollographql.apollo3.exception.ApolloParseException
import com.apollographql.apollo3.fetcher.ResponseFetcher
import com.apollographql.apollo3.internal.CallState.IllegalStateMessage.Companion.forCurrentState
import java.util.concurrent.atomic.AtomicReference
class RealApolloQueryWatcher<D : Operation.Data>(
private var activeCall: RealApolloCall<D>,
val apolloStore: ApolloStore,
private val responseAdapterCache: ResponseAdapterCache,
val logger: ApolloLogger,
private val tracker: ApolloCallTracker,
private var refetchResponseFetcher: ResponseFetcher
) : ApolloQueryWatcher<D> {
var dependentKeys = emptySet<String>()
val recordChangeSubscriber: RecordChangeSubscriber = object : RecordChangeSubscriber {
override fun onCacheRecordsChanged(changedRecordKeys: Set<String>) {
if (dependentKeys.isEmpty() || !areDisjoint(dependentKeys, changedRecordKeys)) {
refetch()
}
}
}
private val state = AtomicReference(CallState.IDLE)
private val originalCallback = AtomicReference<ApolloCall.Callback<D>?>()
override fun enqueueAndWatch(callback: ApolloCall.Callback<D>): ApolloQueryWatcher<D> {
try {
activate(Optional.fromNullable(callback))
} catch (e: ApolloCanceledException) {
callback.onCanceledError(e)
return this
}
activeCall.enqueue(callbackProxy())
return this
}
@Synchronized
override fun refetchResponseFetcher(fetcher: ResponseFetcher): RealApolloQueryWatcher<D> {
check(!(state.get() !== CallState.IDLE)) { "Already Executed" }
refetchResponseFetcher = fetcher
return this
}
@Synchronized
override fun cancel() {
when (state.get()) {
CallState.ACTIVE -> try {
activeCall.cancel()
apolloStore.unsubscribe(recordChangeSubscriber)
} finally {
tracker.unregisterQueryWatcher(this)
originalCallback.set(null)
state.set(CallState.CANCELED)
}
CallState.IDLE -> state.set(CallState.CANCELED)
CallState.CANCELED, CallState.TERMINATED -> {
}
else -> throw IllegalStateException("Unknown state")
}
}
override val isCanceled: Boolean
get() = state.get() == CallState.CANCELED
override fun operation(): Operation<*> {
return activeCall.operation()
}
@Synchronized
override fun refetch() {
when (state.get()) {
CallState.ACTIVE -> {
apolloStore.unsubscribe(recordChangeSubscriber)
activeCall.cancel()
activeCall = activeCall.clone().responseFetcher(refetchResponseFetcher)
activeCall.enqueue(callbackProxy())
}
CallState.IDLE -> throw IllegalStateException("Cannot refetch a watcher which has not first called enqueueAndWatch.")
CallState.CANCELED -> throw IllegalStateException("Cannot refetch a canceled watcher,")
CallState.TERMINATED -> throw IllegalStateException("Cannot refetch a watcher which has experienced an error.")
else -> throw IllegalStateException("Unknown state")
}
}
override fun clone(): ApolloQueryWatcher<D> {
return RealApolloQueryWatcher(activeCall.clone(), apolloStore, responseAdapterCache, logger, tracker, refetchResponseFetcher)
}
private fun callbackProxy(): ApolloCall.Callback<D> {
return object : ApolloCall.Callback<D>() {
override fun onResponse(response: ApolloResponse<D>) {
val callback = responseCallback()
if (!callback.isPresent) {
logger.d("onResponse for watched operation: %s. No callback present.", operation().name())
return
}
apolloStore.subscribe(recordChangeSubscriber)
callback.get().onResponse(response)
}
override fun onCached(records: List<Record>) {
val callback = responseCallback()
if (!callback.isPresent) {
logger.d("onCached for watched operation: %s. No callback present.", operation().name())
return
}
dependentKeys = records.dependentKeys()
}
override fun onFailure(e: ApolloException) {
val callback = terminate()
if (!callback.isPresent) {
logger.d(e, "onFailure for operation: %s. No callback present.", operation().name())
return
}
if (e is ApolloHttpException) {
callback.get().onHttpError(e)
} else if (e is ApolloParseException) {
callback.get().onParseError(e)
} else if (e is ApolloNetworkException) {
callback.get().onNetworkError(e)
} else {
callback.get().onFailure(e)
}
}
override fun onStatusEvent(event: ApolloCall.StatusEvent) {
val callback = originalCallback.get()
if (callback == null) {
logger.d("onStatusEvent for operation: %s. No callback present.", operation().name())
return
}
callback.onStatusEvent(event)
}
}
}
@Synchronized
@Throws(ApolloCanceledException::class)
private fun activate(callback: Optional<ApolloCall.Callback<D>>) {
when (state.get()) {
CallState.IDLE -> {
originalCallback.set(callback.orNull())
tracker.registerQueryWatcher(this)
}
CallState.CANCELED -> throw ApolloCanceledException()
CallState.TERMINATED, CallState.ACTIVE -> throw IllegalStateException("Already Executed")
else -> throw IllegalStateException("Unknown state")
}
state.set(CallState.ACTIVE)
}
@Synchronized
fun responseCallback(): Optional<ApolloCall.Callback<D>> {
return when (state.get()) {
CallState.ACTIVE, CallState.CANCELED -> Optional.fromNullable(originalCallback.get())
CallState.IDLE, CallState.TERMINATED -> throw IllegalStateException(
forCurrentState(state.get()).expected(CallState.ACTIVE, CallState.CANCELED))
else -> throw IllegalStateException("Unknown state")
}
}
@Synchronized
fun terminate(): Optional<ApolloCall.Callback<D>> {
return when (state.get()) {
CallState.ACTIVE -> {
tracker.unregisterQueryWatcher(this)
state.set(CallState.TERMINATED)
Optional.fromNullable(originalCallback.getAndSet(null))
}
CallState.CANCELED -> Optional.fromNullable(originalCallback.getAndSet(null))
CallState.IDLE, CallState.TERMINATED -> throw IllegalStateException(
forCurrentState(state.get()).expected(CallState.ACTIVE, CallState.CANCELED))
else -> throw IllegalStateException("Unknown state")
}
}
companion object {
/**
* Checks if two [Set] are disjoint. Returns true if the sets don't have a single common element. Also returns
* true if either of the sets is null.
*
* @param setOne the first set
* @param setTwo the second set
* @param <E> the value type contained within the sets
* @return True if the sets don't have a single common element or if either of the sets is null.
</E> */
private fun <E> areDisjoint(setOne: Set<E>?, setTwo: Set<E>?): Boolean {
if (setOne == null || setTwo == null) {
return true
}
var smallerSet: Set<E> = setOne
var largerSet: Set<E> = setTwo
if (setOne.size > setTwo.size) {
smallerSet = setTwo
largerSet = setOne
}
for (el in smallerSet) {
if (largerSet.contains(el)) {
return false
}
}
return true
}
}
}
| mit | 631d5b5a9e62745b3fbfd665aa9ccbda | 36.59276 | 129 | 0.697761 | 4.564835 | false | false | false | false |
Heiner1/AndroidAPS | danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBolusGetCIRCFArray.kt | 1 | 5392 | package info.nightscout.androidaps.danars.comm
import dagger.android.HasAndroidInjector
import info.nightscout.shared.logging.LTag
import info.nightscout.androidaps.dana.DanaPump
import info.nightscout.androidaps.danars.encryption.BleEncryption
import javax.inject.Inject
class DanaRSPacketBolusGetCIRCFArray(
injector: HasAndroidInjector
) : DanaRSPacket(injector) {
@Inject lateinit var danaPump: DanaPump
init {
opCode = BleEncryption.DANAR_PACKET__OPCODE_BOLUS__GET_CIR_CF_ARRAY
aapsLogger.debug(LTag.PUMPCOMM, "New message")
}
override fun handleMessage(data: ByteArray) {
var dataIndex = DATA_START
var dataSize = 1
val language = byteArrayToInt(getBytes(data, dataIndex, dataSize))
dataIndex += dataSize
dataSize = 1
danaPump.units = byteArrayToInt(getBytes(data, dataIndex, dataSize))
dataIndex += dataSize
dataSize = 2
danaPump.morningCIR = byteArrayToInt(getBytes(data, dataIndex, dataSize))
dataIndex += dataSize
dataSize = 2
val cir02 = byteArrayToInt(getBytes(data, dataIndex, dataSize))
dataIndex += dataSize
dataSize = 2
danaPump.afternoonCIR = byteArrayToInt(getBytes(data, dataIndex, dataSize))
dataIndex += dataSize
dataSize = 2
val cir04 = byteArrayToInt(getBytes(data, dataIndex, dataSize))
dataIndex += dataSize
dataSize = 2
danaPump.eveningCIR = byteArrayToInt(getBytes(data, dataIndex, dataSize))
dataIndex += dataSize
dataSize = 2
val cir06 = byteArrayToInt(getBytes(data, dataIndex, dataSize))
dataIndex += dataSize
dataSize = 2
danaPump.nightCIR = byteArrayToInt(getBytes(data, dataIndex, dataSize))
val cf02: Double
val cf04: Double
val cf06: Double
if (danaPump.units == DanaPump.UNITS_MGDL) {
dataIndex += dataSize
dataSize = 2
danaPump.morningCF = byteArrayToInt(getBytes(data, dataIndex, dataSize)).toDouble()
dataIndex += dataSize
dataSize = 2
cf02 = byteArrayToInt(getBytes(data, dataIndex, dataSize)).toDouble()
dataIndex += dataSize
dataSize = 2
danaPump.afternoonCF = byteArrayToInt(getBytes(data, dataIndex, dataSize)).toDouble()
dataIndex += dataSize
dataSize = 2
cf04 = byteArrayToInt(getBytes(data, dataIndex, dataSize)).toDouble()
dataIndex += dataSize
dataSize = 2
danaPump.eveningCF = byteArrayToInt(getBytes(data, dataIndex, dataSize)).toDouble()
dataIndex += dataSize
dataSize = 2
cf06 = byteArrayToInt(getBytes(data, dataIndex, dataSize)).toDouble()
dataIndex += dataSize
dataSize = 2
danaPump.nightCF = byteArrayToInt(getBytes(data, dataIndex, dataSize)).toDouble()
} else {
dataIndex += dataSize
dataSize = 2
danaPump.morningCF = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0
dataIndex += dataSize
dataSize = 2
cf02 = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0
dataIndex += dataSize
dataSize = 2
danaPump.afternoonCF = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0
dataIndex += dataSize
dataSize = 2
cf04 = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0
dataIndex += dataSize
dataSize = 2
danaPump.eveningCF = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0
dataIndex += dataSize
dataSize = 2
cf06 = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0
dataIndex += dataSize
dataSize = 2
danaPump.nightCF = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0
}
if (danaPump.units < 0 || danaPump.units > 1) failed = true
aapsLogger.debug(LTag.PUMPCOMM, "Language: $language")
aapsLogger.debug(LTag.PUMPCOMM, "Pump units: " + if (danaPump.units == DanaPump.UNITS_MGDL) "MGDL" else "MMOL")
aapsLogger.debug(LTag.PUMPCOMM, "Current pump morning CIR: " + danaPump.morningCIR)
aapsLogger.debug(LTag.PUMPCOMM, "Current pump morning CF: " + danaPump.morningCF)
aapsLogger.debug(LTag.PUMPCOMM, "Current pump afternoon CIR: " + danaPump.afternoonCIR)
aapsLogger.debug(LTag.PUMPCOMM, "Current pump afternoon CF: " + danaPump.afternoonCF)
aapsLogger.debug(LTag.PUMPCOMM, "Current pump evening CIR: " + danaPump.eveningCIR)
aapsLogger.debug(LTag.PUMPCOMM, "Current pump evening CF: " + danaPump.eveningCF)
aapsLogger.debug(LTag.PUMPCOMM, "Current pump night CIR: " + danaPump.nightCIR)
aapsLogger.debug(LTag.PUMPCOMM, "Current pump night CF: " + danaPump.nightCF)
aapsLogger.debug(LTag.PUMPCOMM, "cir02: $cir02")
aapsLogger.debug(LTag.PUMPCOMM, "cir04: $cir04")
aapsLogger.debug(LTag.PUMPCOMM, "cir06: $cir06")
aapsLogger.debug(LTag.PUMPCOMM, "cf02: $cf02")
aapsLogger.debug(LTag.PUMPCOMM, "cf04: $cf04")
aapsLogger.debug(LTag.PUMPCOMM, "cf06: $cf06")
}
override val friendlyName: String = "BOLUS__GET_CIR_CF_ARRAY"
} | agpl-3.0 | 0322d3d069d5e032eba896d07601a1a5 | 45.491379 | 119 | 0.642433 | 4.636285 | false | false | false | false |
paslavsky/music-sync-manager | msm-server/src/main/kotlin/net/paslavsky/msm/setting/description/XmlPropertyGroup.kt | 1 | 2531 | package net.paslavsky.msm.setting.description
import javax.xml.bind.annotation.*
import java.util.ArrayList
import org.apache.commons.lang3.builder.ReflectionToStringBuilder
import org.apache.commons.lang3.builder.HashCodeBuilder
import org.apache.commons.lang3.builder.EqualsBuilder
import org.apache.commons.lang3.builder.ToStringBuilder
import org.apache.commons.lang3.builder.ToStringStyle
/**
* <p>Java class for Group complex type.
* <p/>
* <p>The following schema fragment specifies the expected content contained within this class.
* <p/>
* <pre>
* <complexType name="Group">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="group" type="{http://paslavsky.net/property-description/1.0}Group" maxOccurs="unbounded" minOccurs="0"/>
* <element name="property" type="{http://paslavsky.net/property-description/1.0}Property" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* <attribute name="name" use="required" type="{http://www.w3.org/2001/XMLSchema}string" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
* @author Andrey Paslavsky
* @version 1.0
*/
XmlAccessorType(XmlAccessType.FIELD)
XmlType(name = "Group", namespace = "http://paslavsky.net/property-description/1.0", propOrder = arrayOf("groups", "properties"))
public class XmlPropertyGroup {
XmlElement(name = "group", namespace = "http://paslavsky.net/property-description/1.0")
public val groups: MutableCollection<XmlPropertyGroup> = ArrayList()
XmlElement(name = "property", namespace = "http://paslavsky.net/property-description/1.0")
public val properties: MutableCollection<XmlProperty> = ArrayList()
XmlAttribute(name = "name", required = true)
public var name: String = ""
override fun toString(): String = ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE).
append("name", name)!!.
append("groups", "XmlPropertyGroup[${groups.size()}]")!!.
append("properties", "XmlProperty[${properties.size()}]")!!.
toString();
override fun hashCode(): Int = HashCodeBuilder().append(name)!!.toHashCode()
override fun equals(other: Any?): Boolean {
when {
other identityEquals null -> return false
other identityEquals this -> return true
other is XmlPropertyGroup -> return name == other.name
else -> return false
}
}
} | apache-2.0 | 2c2ed22ebf7462794967ccf07148a86b | 41.2 | 139 | 0.68471 | 3.852359 | false | false | false | false |
sjnyag/stamp | app/src/main/java/com/sjn/stamp/ui/item/holder/SimpleMediaViewHolder.kt | 1 | 751 | package com.sjn.stamp.ui.item.holder
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import com.sjn.stamp.R
import com.sjn.stamp.utils.ViewHelper
import eu.davidea.flexibleadapter.FlexibleAdapter
class SimpleMediaViewHolder(view: View, adapter: FlexibleAdapter<*>) : LongClickDisableViewHolder(view, adapter) {
var albumArtView: ImageView = view.findViewById(R.id.image)
var title: TextView = view.findViewById(R.id.title)
var subtitle: TextView = view.findViewById(R.id.subtitle)
private var _frontView: View = view.findViewById(R.id.front_view)
override fun getActivationElevation(): Float = ViewHelper.dpToPx(itemView.context, 4f)
override fun getFrontView(): View = _frontView
} | apache-2.0 | feca7c80efd9f9f34784ff344f034554 | 36.6 | 114 | 0.780293 | 3.891192 | false | false | false | false |
futurice/freesound-android | app/src/main/java/com/futurice/freesound/network/api/model/mapping/GeoLocationJsonAdapter.kt | 1 | 1182 | /*
* Copyright 2017 Futurice GmbH
*
* 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.futurice.freesound.network.api.model.mapping
import com.futurice.freesound.network.api.model.GeoLocation
import com.squareup.moshi.FromJson
import com.squareup.moshi.JsonDataException
class GeoLocationJsonAdapter {
@FromJson fun fromJson(json: String): GeoLocation =
json.trim()
.split(' ')
.mapNotNull { it.toDoubleOrNull() }
.takeIf { it.size == 2 }
?.let { GeoLocation(latitude = it[0], longitude = it[1]) }
?: throw JsonDataException("Unable to deserialize latitude/long values from: $json")
}
| apache-2.0 | d0914ee798b63f482a18d6109cf8773f | 37.129032 | 96 | 0.705584 | 4.161972 | false | false | false | false |
Turbo87/intellij-rust | src/main/kotlin/org/rust/cargo/project/module/RustExecutableModuleType.kt | 1 | 858 | package org.rust.cargo.project.module
import com.intellij.icons.AllIcons
import com.intellij.openapi.module.ModuleTypeManager
import org.rust.ide.icons.RustIcons
import javax.swing.Icon
class RustExecutableModuleType : RustModuleType(RustExecutableModuleType.MODULE_TYPE_ID) {
override fun createModuleBuilder(): RustModuleBuilder = RustModuleBuilder(INSTANCE)
override fun getName(): String = "Rust Executable Module"
override fun getDescription(): String = "Rust Executable Module"
override fun getBigIcon(): Icon = RustIcons.RUST
override fun getNodeIcon(isOpened: Boolean): Icon = AllIcons.Nodes.Module
companion object {
val MODULE_TYPE_ID = "RUST_EXECUTABLE_MODULE"
val INSTANCE by lazy {
ModuleTypeManager.getInstance().findByID(MODULE_TYPE_ID) as RustModuleType
}
}
}
| mit | 73816bc939e31dcfda45e5e8947ecb5c | 33.32 | 90 | 0.738928 | 4.445596 | false | false | false | false |
theScrabi/NewPipe | app/src/main/java/org/schabi/newpipe/database/feed/dao/FeedGroupDAO.kt | 4 | 2546 | package org.schabi.newpipe.database.feed.dao
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Transaction
import androidx.room.Update
import io.reactivex.rxjava3.core.Flowable
import io.reactivex.rxjava3.core.Maybe
import org.schabi.newpipe.database.feed.model.FeedGroupEntity
import org.schabi.newpipe.database.feed.model.FeedGroupSubscriptionEntity
@Dao
abstract class FeedGroupDAO {
@Query("SELECT * FROM feed_group ORDER BY sort_order ASC")
abstract fun getAll(): Flowable<List<FeedGroupEntity>>
@Query("SELECT * FROM feed_group WHERE uid = :groupId")
abstract fun getGroup(groupId: Long): Maybe<FeedGroupEntity>
@Transaction
open fun insert(feedGroupEntity: FeedGroupEntity): Long {
val nextSortOrder = nextSortOrder()
feedGroupEntity.sortOrder = nextSortOrder
return insertInternal(feedGroupEntity)
}
@Update(onConflict = OnConflictStrategy.IGNORE)
abstract fun update(feedGroupEntity: FeedGroupEntity): Int
@Query("DELETE FROM feed_group")
abstract fun deleteAll(): Int
@Query("DELETE FROM feed_group WHERE uid = :groupId")
abstract fun delete(groupId: Long): Int
@Query("SELECT subscription_id FROM feed_group_subscription_join WHERE group_id = :groupId")
abstract fun getSubscriptionIdsFor(groupId: Long): Flowable<List<Long>>
@Query("DELETE FROM feed_group_subscription_join WHERE group_id = :groupId")
abstract fun deleteSubscriptionsFromGroup(groupId: Long): Int
@Insert(onConflict = OnConflictStrategy.IGNORE)
abstract fun insertSubscriptionsToGroup(entities: List<FeedGroupSubscriptionEntity>): List<Long>
@Transaction
open fun updateSubscriptionsForGroup(groupId: Long, subscriptionIds: List<Long>) {
deleteSubscriptionsFromGroup(groupId)
insertSubscriptionsToGroup(subscriptionIds.map { FeedGroupSubscriptionEntity(groupId, it) })
}
@Transaction
open fun updateOrder(orderMap: Map<Long, Long>) {
orderMap.forEach { (groupId, sortOrder) -> updateOrder(groupId, sortOrder) }
}
@Query("UPDATE feed_group SET sort_order = :sortOrder WHERE uid = :groupId")
abstract fun updateOrder(groupId: Long, sortOrder: Long): Int
@Query("SELECT IFNULL(MAX(sort_order) + 1, 0) FROM feed_group")
protected abstract fun nextSortOrder(): Long
@Insert(onConflict = OnConflictStrategy.ABORT)
protected abstract fun insertInternal(feedGroupEntity: FeedGroupEntity): Long
}
| gpl-3.0 | cc6d18c99fb1c183908fa2d1e54d1d4a | 37 | 100 | 0.75216 | 4.514184 | false | false | false | false |
KotlinNLP/SimpleDNN | src/test/kotlin/core/arrays/ParamsArraySpec.kt | 1 | 5876 | /* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, you can obtain one at http://mozilla.org/MPL/2.0/.
* ------------------------------------------------------------------*/
package core.arrays
import com.kotlinnlp.simplednn.core.arrays.ParamsArray
import com.kotlinnlp.simplednn.core.functionalities.initializers.ConstantInitializer
import com.kotlinnlp.simplednn.core.functionalities.updatemethods.learningrate.LearningRateStructure
import com.kotlinnlp.simplednn.simplemath.ndarray.Shape
import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArray
import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArrayFactory
import com.kotlinnlp.simplednn.simplemath.ndarray.sparse.SparseNDArray
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
import kotlin.test.*
/**
*
*/
class ParamsArraySpec : Spek({
describe("a ParamsArray") {
context("initialization") {
context("with an NDArray") {
val paramsArray = ParamsArray(DenseNDArrayFactory.zeros(Shape(3, 7)))
val paramsArray2 = ParamsArray(DenseNDArrayFactory.zeros(Shape(3, 7)))
it("should contain values with the expected number of rows") {
assertEquals(3, paramsArray.values.rows)
}
it("should contain values with the expected number of columns") {
assertEquals(7, paramsArray.values.columns)
}
it("should contain a support structure initialized with null") {
assertNull(paramsArray.updaterSupportStructure)
}
it("should have a different uuid of the one of another instance") {
assertNotEquals(paramsArray.uuid, paramsArray2.uuid)
}
}
context("with a DoubleArray") {
val paramsArray = ParamsArray(doubleArrayOf(0.3, 0.4, 0.2, -0.2))
it("should contain the expected values") {
assertEquals(paramsArray.values, DenseNDArrayFactory.arrayOf(doubleArrayOf(0.3, 0.4, 0.2, -0.2)))
}
}
context("with a list of DoubleArray") {
val paramsArray = ParamsArray(listOf(
doubleArrayOf(0.3, 0.4, 0.2, -0.2),
doubleArrayOf(0.2, -0.1, 0.1, 0.6)
))
it("should contain the expected values") {
assertEquals(paramsArray.values, DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.3, 0.4, 0.2, -0.2),
doubleArrayOf(0.2, -0.1, 0.1, 0.6)
)))
}
}
context("with a matrix shape and initialized values") {
val paramsArray = ParamsArray(Shape(2, 4), initializer = ConstantInitializer(0.42))
it("should contain the expected values") {
assertEquals(paramsArray.values, DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.42, 0.42, 0.42, 0.42),
doubleArrayOf(0.42, 0.42, 0.42, 0.42)
)))
}
}
context("with a vector shape and initialized values") {
val paramsArray = ParamsArray(size = 4, initializer = ConstantInitializer(0.42))
it("should contain the expected values") {
assertEquals(paramsArray.values, DenseNDArrayFactory.arrayOf(
doubleArrayOf(0.42, 0.42, 0.42, 0.42)
))
}
}
}
context("support structure") {
val paramsArray = ParamsArray(DenseNDArrayFactory.zeros(Shape(3, 7))).apply {
getOrSetSupportStructure<LearningRateStructure>()
}
it("should have the expected support structure type") {
assertTrue { paramsArray.updaterSupportStructure is LearningRateStructure }
}
}
context("params errors") {
context("build a dense errors without values") {
val paramsArray = ParamsArray(DenseNDArrayFactory.zeros(Shape(3, 7)))
val paramsArray2 = ParamsArray(DenseNDArrayFactory.zeros(Shape(3, 7)))
val paramsErrors = paramsArray.buildDenseErrors()
it("should contain values with the expected shape") {
assertEquals(paramsArray.values.shape, paramsErrors.values.shape)
}
it("should contain the expected values") {
assertEquals(paramsErrors.values, DenseNDArrayFactory.zeros(Shape(3, 7)))
}
it("should contains the right reference to the paramsArray"){
assertSame(paramsErrors.refParams, paramsArray)
}
it("shouldn't contains the reference to the paramsArray2"){
assertNotSame(paramsErrors.refParams, paramsArray2)
}
it("should create its copy with the same reference to the paramsArray"){
assertSame(paramsErrors.copy().refParams, paramsArray)
}
}
context("build with default sparse errors") {
val paramsArray = ParamsArray(
values = DenseNDArrayFactory.zeros(Shape(3, 7)),
defaultErrorsType = ParamsArray.ErrorsType.Sparse)
val paramsErrors = paramsArray.buildDefaultErrors()
it("should create sparse errors"){
assertTrue { paramsErrors.values is SparseNDArray }
}
}
}
context("build with default dense errors") {
val paramsArray = ParamsArray(
values = DenseNDArrayFactory.zeros(Shape(3, 7)),
defaultErrorsType = ParamsArray.ErrorsType.Dense)
val paramsErrors = paramsArray.buildDefaultErrors()
it("should create dense errors"){
assertTrue { paramsErrors.values is DenseNDArray }
}
}
context("build with default errors") {
val paramsArray = ParamsArray(DenseNDArrayFactory.zeros(Shape(3, 7)))
val paramsErrors = paramsArray.buildDefaultErrors()
it("should create dense errors"){
assertTrue { paramsErrors.values is DenseNDArray }
}
}
}
})
| mpl-2.0 | 332937b3e6408db9d8ea577180278c9f | 31.826816 | 107 | 0.654697 | 4.645059 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/ReplaceRangeToWithUntilInspection.kt | 1 | 2966 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.inspections
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.intentions.getArguments
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.BindingContext
class ReplaceRangeToWithUntilInspection : AbstractRangeInspection() {
override fun visitRangeTo(expression: KtExpression, context: BindingContext, holder: ProblemsHolder) {
if (!isApplicable(expression)) return
holder.registerProblem(
expression,
KotlinBundle.message("inspection.replace.range.to.with.until.display.name"),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
ReplaceWithUntilQuickFix()
)
}
override fun visitUntil(expression: KtExpression, context: BindingContext, holder: ProblemsHolder) {
}
override fun visitDownTo(expression: KtExpression, context: BindingContext, holder: ProblemsHolder) {
}
class ReplaceWithUntilQuickFix : LocalQuickFix {
override fun getName() = KotlinBundle.message("replace.with.until.quick.fix.text")
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val element = descriptor.psiElement as KtExpression
applyFix(element)
}
}
companion object {
fun applyFixIfApplicable(expression: KtExpression) {
if (isApplicable(expression)) applyFix(expression)
}
private fun isApplicable(expression: KtExpression): Boolean {
return expression.getArguments()?.second?.deparenthesize()?.isMinusOne() == true
}
private fun applyFix(element: KtExpression) {
val args = element.getArguments() ?: return
element.replace(
KtPsiFactory(element).createExpressionByPattern(
"$0 until $1",
args.first ?: return,
(args.second?.deparenthesize() as? KtBinaryExpression)?.left ?: return
)
)
}
private fun KtExpression.isMinusOne(): Boolean {
if (this !is KtBinaryExpression) return false
if (operationToken != KtTokens.MINUS) return false
val constantValue = right?.constantValueOrNull()
val rightValue = (constantValue?.value as? Number)?.toInt() ?: return false
return rightValue == 1
}
}
}
private fun KtExpression.deparenthesize() = KtPsiUtil.safeDeparenthesize(this)
| apache-2.0 | e9d570e299f0f95ecc4d10099a3b4583 | 38.546667 | 120 | 0.688806 | 5.315412 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/RemoveWrongOptInAnnotationTargetFactory.kt | 1 | 2487 | // 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.quickfix
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.Errors.OPT_IN_MARKER_WITH_WRONG_TARGET
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction
import org.jetbrains.kotlin.psi.KtAnnotationEntry
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtValueArgument
import org.jetbrains.kotlin.resolve.checkers.OptInDescription
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
object RemoveWrongOptInAnnotationTargetFactory : KotlinIntentionActionsFactory() {
override fun doCreateActions(diagnostic: Diagnostic): List<IntentionAction> {
if (diagnostic.factory != OPT_IN_MARKER_WITH_WRONG_TARGET) return emptyList()
val annotationEntry = diagnostic.psiElement.safeAs<KtAnnotationEntry>() ?: return emptyList()
return listOf(RemoveAllForbiddenOptInTargetsFix(annotationEntry))
}
private class RemoveAllForbiddenOptInTargetsFix(annotationEntry: KtAnnotationEntry) :
KotlinQuickFixAction<KtAnnotationEntry>(annotationEntry) {
override fun getText(): String {
return KotlinBundle.message("fix.opt_in.remove.all.forbidden.targets")
}
override fun getFamilyName(): String = text
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val annotationEntry = element ?: return
val argumentList = annotationEntry.valueArgumentList ?: return
val forbiddenArguments: List<KtValueArgument> = argumentList.arguments.filter {
WRONG_TARGETS.any { name -> it.text?.contains(name) == true }
}
if (forbiddenArguments.size == argumentList.arguments.size) {
annotationEntry.delete()
} else {
forbiddenArguments.forEach {
argumentList.removeArgument(it)
}
}
}
companion object {
private val WRONG_TARGETS: List<String> = OptInDescription.WRONG_TARGETS_FOR_MARKER.map {it.toString() }
}
}
}
| apache-2.0 | b962ae81dea84818c6dd3c453204844a | 45.924528 | 158 | 0.723361 | 4.91502 | false | false | false | false |
ingokegel/intellij-community | platform/vcs-log/impl/src/com/intellij/vcs/log/visible/VcsLogFiltererImpl.kt | 1 | 25639 | // 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.vcs.log.visible
import com.intellij.diagnostic.opentelemetry.TraceManager
import com.intellij.diagnostic.telemetry.useWithScope
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.vcs.VcsException
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.containers.ContainerUtil
import com.intellij.vcs.log.*
import com.intellij.vcs.log.data.*
import com.intellij.vcs.log.data.index.IndexDataGetter
import com.intellij.vcs.log.data.index.VcsLogIndex
import com.intellij.vcs.log.graph.PermanentGraph
import com.intellij.vcs.log.graph.VisibleGraph
import com.intellij.vcs.log.graph.api.permanent.PermanentGraphInfo
import com.intellij.vcs.log.graph.impl.facade.LinearGraphController
import com.intellij.vcs.log.graph.impl.facade.PermanentGraphImpl
import com.intellij.vcs.log.graph.utils.DfsWalk
import com.intellij.vcs.log.history.FileHistory
import com.intellij.vcs.log.history.FileHistoryBuilder
import com.intellij.vcs.log.history.FileHistoryData
import com.intellij.vcs.log.history.removeTrivialMerges
import com.intellij.vcs.log.impl.HashImpl
import com.intellij.vcs.log.util.*
import com.intellij.vcs.log.util.VcsLogUtil.FULL_HASH_LENGTH
import com.intellij.vcs.log.util.VcsLogUtil.SHORT_HASH_LENGTH
import com.intellij.vcs.log.visible.filters.VcsLogFilterObject
import com.intellij.vcs.log.visible.filters.with
import com.intellij.vcs.log.visible.filters.without
import it.unimi.dsi.fastutil.ints.IntOpenHashSet
import it.unimi.dsi.fastutil.ints.IntSet
import java.util.function.BiConsumer
import java.util.stream.Collectors
class VcsLogFiltererImpl(private val logProviders: Map<VirtualFile, VcsLogProvider>,
private val storage: VcsLogStorage,
private val topCommitsDetailsCache: TopCommitsCache,
private val commitDetailsGetter: DataGetter<out VcsFullCommitDetails>,
private val index: VcsLogIndex) : VcsLogFilterer {
override fun filter(dataPack: DataPack,
oldVisiblePack: VisiblePack,
sortType: PermanentGraph.SortType,
allFilters: VcsLogFilterCollection,
commitCount: CommitCountStage): Pair<VisiblePack, CommitCountStage> {
val hashFilter = allFilters.get(VcsLogFilterCollection.HASH_FILTER)
val filters = allFilters.without(VcsLogFilterCollection.HASH_FILTER)
TraceManager.getTracer("vcs").spanBuilder("filter").useWithScope {
if (hashFilter != null && !hashFilter.hashes.isEmpty()) { // hashes should be shown, no matter if they match other filters or not
val hashFilterResult = applyHashFilter(dataPack, hashFilter, sortType, commitCount)
if (hashFilterResult != null) {
it.setAttribute("filters", hashFilterResult.first.filters.toString())
it.setAttribute("sortType", sortType.toString())
return hashFilterResult
}
}
val visibleRoots = VcsLogUtil.getAllVisibleRoots(dataPack.logProviders.keys, filters)
var matchingHeads = getMatchingHeads(dataPack.refsModel, visibleRoots, filters)
val rangeFilters = allFilters.get(VcsLogFilterCollection.RANGE_FILTER)
val commitCandidates: IntSet?
val forceFilterByVcs: Boolean
if (rangeFilters != null) {
/*
If we have both a range filter and a branch filter (e.g. `183\nmaster..feature`) they should be united: the graph should show both
commits contained in the range, and commits reachable from branches.
But the main filtering logic is opposite: matchingHeads + some other filter => makes the intersection of commits.
To overcome this logic for the range filter case, we are not using matchingHeads, but are collecting all commits reachable from
matchingHeads, and unite them with commits belonging to the range.
*/
val branchFilter = filters.get(VcsLogFilterCollection.BRANCH_FILTER)
val revisionFilter = filters.get(VcsLogFilterCollection.REVISION_FILTER)
val explicitMatchingHeads = getMatchingHeads(dataPack.refsModel, visibleRoots, branchFilter, revisionFilter)
val commitsReachableFromHeads = if (explicitMatchingHeads != null)
collectCommitsReachableFromHeads(dataPack, explicitMatchingHeads)
else IntOpenHashSet()
when (val commitsForRangeFilter = filterByRange(dataPack, rangeFilters)) {
is RangeFilterResult.Commits -> {
commitCandidates = IntCollectionUtil.union(listOf(commitsReachableFromHeads, commitsForRangeFilter.commits))
forceFilterByVcs = false
}
is RangeFilterResult.Error -> {
commitCandidates = null
forceFilterByVcs = true
}
is RangeFilterResult.InvalidRange -> {
commitCandidates = null
forceFilterByVcs = true
}
}
/*
At the same time, the root filter should intersect with the range filter (and the branch filter),
therefore we take matching heads from the root filter, but use reachable commits set for the branch filter.
*/
val matchingHeadsFromRoots = getMatchingHeads(dataPack.refsModel, visibleRoots)
matchingHeads = matchingHeadsFromRoots
}
else {
commitCandidates = null
forceFilterByVcs = false
}
try {
val filterResult = filterByDetails(dataPack, filters, commitCount, visibleRoots, matchingHeads, commitCandidates, forceFilterByVcs)
val visibleGraph = createVisibleGraph(dataPack, sortType, matchingHeads, filterResult.matchingCommits, filterResult.fileHistoryData)
val visiblePack = VisiblePack(dataPack, visibleGraph, filterResult.canRequestMore, filters)
it.setAttribute("filters", filters.toString())
it.setAttribute("sortType", sortType.toString())
return Pair(visiblePack, filterResult.commitCount)
}
catch (e: VcsException) {
return Pair(VisiblePack.ErrorVisiblePack(dataPack, filters, e), commitCount)
}
}
}
private fun collectCommitsReachableFromHeads(dataPack: DataPack, matchingHeads: Set<Int>): IntSet {
@Suppress("UNCHECKED_CAST") val permanentGraph = dataPack.permanentGraph as? PermanentGraphInfo<Int> ?: return IntOpenHashSet()
val startIds = matchingHeads.map { permanentGraph.permanentCommitsInfo.getNodeId(it) }
val result = IntOpenHashSet()
DfsWalk(startIds, permanentGraph.linearGraph).walk(true) { node: Int ->
result.add(permanentGraph.permanentCommitsInfo.getCommitId(node))
true
}
return result
}
private fun createVisibleGraph(dataPack: DataPack,
sortType: PermanentGraph.SortType,
matchingHeads: Set<Int>?,
matchingCommits: Set<Int>?,
fileHistoryData: FileHistoryData?): VisibleGraph<Int> {
if (matchingHeads.matchesNothing() || matchingCommits.matchesNothing()) {
return EmptyVisibleGraph.getInstance()
}
val permanentGraph = dataPack.permanentGraph
if (permanentGraph !is PermanentGraphImpl || fileHistoryData == null) {
return permanentGraph.createVisibleGraph(sortType, matchingHeads, matchingCommits)
}
if (fileHistoryData.startPaths.size == 1 && fileHistoryData.startPaths.single().isDirectory) {
val unmatchedRenames = matchingCommits?.let { fileHistoryData.getCommitsWithRenames().subtract(it) } ?: emptySet()
val preprocessor = FileHistoryBuilder(null, fileHistoryData.startPaths.single(), fileHistoryData,
FileHistory.EMPTY, unmatchedRenames,
removeTrivialMerges = FileHistoryBuilder.isRemoveTrivialMerges,
refine = FileHistoryBuilder.isRefine)
return permanentGraph.createVisibleGraph(sortType, matchingHeads, matchingCommits?.union(unmatchedRenames), preprocessor)
}
val preprocessor = BiConsumer<LinearGraphController, PermanentGraphInfo<Int>> { controller, permanentGraphInfo ->
if (FileHistoryBuilder.isRemoveTrivialMerges) {
removeTrivialMerges(controller, permanentGraphInfo, fileHistoryData) { trivialMerges ->
LOG.debug("Removed ${trivialMerges.size} trivial merges")
}
}
}
return permanentGraph.createVisibleGraph(sortType, matchingHeads, matchingCommits, preprocessor)
}
@Throws(VcsException::class)
private fun filterByDetails(dataPack: DataPack,
filters: VcsLogFilterCollection,
commitCount: CommitCountStage,
visibleRoots: Collection<VirtualFile>,
matchingHeads: Set<Int>?,
commitCandidates: IntSet?,
forceFilterByVcs: Boolean): FilterByDetailsResult {
val detailsFilters = filters.detailsFilters
if (!forceFilterByVcs && detailsFilters.isEmpty()) {
return FilterByDetailsResult(commitCandidates, false, commitCount)
}
val dataGetter = index.dataGetter
val (rootsForIndex, rootsForVcs) = if (dataGetter != null && dataGetter.canFilter(detailsFilters) && !forceFilterByVcs) {
visibleRoots.partition { index.isIndexed(it) }
}
else {
Pair(emptyList(), visibleRoots.toList())
}
val (filteredWithIndex, historyData) = if (rootsForIndex.isNotEmpty())
filterWithIndex(dataGetter!!, detailsFilters, commitCandidates)
else Pair(null, null)
if (rootsForVcs.isEmpty()) return FilterByDetailsResult(filteredWithIndex, false, commitCount, historyData)
val filterAllWithVcs = rootsForVcs.containsAll(visibleRoots)
val filtersForVcs = if (filterAllWithVcs) filters else filters.with(VcsLogFilterObject.fromRoots(rootsForVcs))
val headsForVcs = if (filterAllWithVcs) matchingHeads else getMatchingHeads(dataPack.refsModel, rootsForVcs, filtersForVcs)
val filteredWithVcs = filterWithVcs(dataPack.permanentGraph, filtersForVcs, headsForVcs, commitCount, commitCandidates)
val filteredCommits: Set<Int>? = union(filteredWithIndex, filteredWithVcs.matchingCommits)
return FilterByDetailsResult(filteredCommits, filteredWithVcs.canRequestMore, filteredWithVcs.commitCount, historyData)
}
private sealed class RangeFilterResult {
class Commits(val commits: IntSet) : RangeFilterResult()
object InvalidRange : RangeFilterResult()
object Error : RangeFilterResult()
}
private fun filterByRange(dataPack: DataPack, rangeFilter: VcsLogRangeFilter): RangeFilterResult {
val set = IntOpenHashSet()
for (range in rangeFilter.ranges) {
var rangeResolvedAnywhere = false
for ((root, _) in logProviders) {
val resolvedRange = resolveCommits(dataPack, root, range)
if (resolvedRange != null) {
val commits = getCommitsByRange(dataPack, root, resolvedRange)
if (commits == null) return RangeFilterResult.Error // error => will be handled by the VCS provider
else set.addAll(commits)
rangeResolvedAnywhere = true
}
}
// If a range is resolved in some roots, but not all of them => skip others and handle those which know about the range.
// Otherwise, if none of the roots know about the range => return null and let VcsLogProviders handle the range
if (!rangeResolvedAnywhere) {
LOG.warn("Range limits unresolved for: $range")
return RangeFilterResult.InvalidRange
}
}
return RangeFilterResult.Commits(set)
}
private fun resolveCommits(dataPack: DataPack, root: VirtualFile, range: VcsLogRangeFilter.RefRange): Pair<CommitId, CommitId>? {
val from = resolveCommit(dataPack, root, range.exclusiveRef)
val to = resolveCommit(dataPack, root, range.inclusiveRef)
if (from == null || to == null) {
LOG.debug("Range limits unresolved for: $range in $root")
return null
}
return from to to
}
private fun getCommitsByRange(dataPack: DataPack, root: VirtualFile, range: Pair<CommitId, CommitId>): IntSet? {
val fromIndex = storage.getCommitIndex(range.first.hash, root)
val toIndex = storage.getCommitIndex(range.second.hash, root)
return dataPack.subgraphDifference(toIndex, fromIndex)
}
private fun resolveCommit(dataPack: DataPack, root: VirtualFile, refName: String): CommitId? {
if (VcsLogUtil.isFullHash(refName)) {
val commitId = CommitId(HashImpl.build(refName), root)
return if (storage.containsCommit(commitId)) commitId else null
}
val ref = dataPack.refsModel.findBranch(refName, root)
return if (ref != null) {
CommitId(ref.commitHash, root)
}
else if (refName.length >= SHORT_HASH_LENGTH && VcsLogUtil.HASH_REGEX.matcher(refName).matches()) {
// don't search for too short hashes: high probability to treat a ref, existing not in all roots, as a hash
storage.findCommitId(CommitIdByStringCondition(refName))
}
else null
}
private fun filterWithIndex(dataGetter: IndexDataGetter,
detailsFilters: List<VcsLogDetailsFilter>,
commitCandidates: IntSet?): Pair<Set<Int>?, FileHistoryData?> {
val structureFilter = detailsFilters.filterIsInstance(VcsLogStructureFilter::class.java).singleOrNull()
?: return Pair(dataGetter.filter(detailsFilters, commitCandidates), null)
val historyData = dataGetter.createFileHistoryData(structureFilter.files).build()
val candidates = IntCollectionUtil.intersect(historyData.getCommits(), commitCandidates)
val filtersWithoutStructure = detailsFilters.filterNot { it is VcsLogStructureFilter }
if (filtersWithoutStructure.isEmpty()) {
return Pair(candidates, historyData)
}
return Pair(dataGetter.filter(filtersWithoutStructure, candidates), historyData)
}
@Throws(VcsException::class)
private fun filterWithVcs(graph: PermanentGraph<Int>,
filters: VcsLogFilterCollection,
matchingHeads: Set<Int>?,
commitCount: CommitCountStage,
commitCandidates: IntSet?): FilterByDetailsResult {
var commitCountToTry = commitCount
if (commitCountToTry == CommitCountStage.INITIAL) {
if (filters.get(VcsLogFilterCollection.RANGE_FILTER) == null) { // not filtering in memory by range for simplicity
val commitsFromMemory = filterDetailsInMemory(graph, filters.detailsFilters, matchingHeads, commitCandidates).toCommitIndexes()
if (commitsFromMemory.size >= commitCountToTry.count) {
return FilterByDetailsResult(commitsFromMemory, true, commitCountToTry)
}
}
commitCountToTry = commitCountToTry.next()
}
val commitsFromVcs = filteredDetailsInVcs(logProviders, filters, commitCountToTry.count).toCommitIndexes()
return FilterByDetailsResult(commitsFromVcs, commitsFromVcs.size >= commitCountToTry.count, commitCountToTry)
}
@Throws(VcsException::class)
private fun filteredDetailsInVcs(providers: Map<VirtualFile, VcsLogProvider>,
filterCollection: VcsLogFilterCollection,
maxCount: Int): Collection<CommitId> {
val commits = mutableListOf<CommitId>()
val visibleRoots = VcsLogUtil.getAllVisibleRoots(providers.keys, filterCollection)
for (root in visibleRoots) {
val provider = providers.getValue(root)
val userFilter = filterCollection.get(VcsLogFilterCollection.USER_FILTER)
if (userFilter != null && userFilter.getUsers(root).isEmpty()) {
// there is a structure or user filter, but it doesn't match this root
continue
}
val filesForRoot = VcsLogUtil.getFilteredFilesForRoot(root, filterCollection)
var actualFilterCollection = if (filesForRoot.isEmpty()) {
filterCollection.without(VcsLogFilterCollection.STRUCTURE_FILTER)
}
else {
filterCollection.with(VcsLogFilterObject.fromPaths(filesForRoot))
}
val rangeFilter = filterCollection.get(VcsLogFilterCollection.RANGE_FILTER)
if (rangeFilter != null) {
val resolvedRanges = mutableListOf<VcsLogRangeFilter.RefRange>()
for ((exclusiveRef, inclusiveRef) in rangeFilter.ranges) {
val exclusiveHash = provider.resolveReference(exclusiveRef, root)
val inclusiveHash = provider.resolveReference(inclusiveRef, root)
if (exclusiveHash != null && inclusiveHash != null) {
resolvedRanges.add(VcsLogRangeFilter.RefRange(exclusiveHash.asString(), inclusiveHash.asString()))
}
}
if (resolvedRanges.isEmpty()) {
continue
}
actualFilterCollection = filterCollection
.without(VcsLogFilterCollection.RANGE_FILTER)
.with(VcsLogFilterObject.fromRange(resolvedRanges))
}
val matchingCommits = provider.getCommitsMatchingFilter(root, actualFilterCollection, maxCount)
commits.addAll(matchingCommits.map { commit -> CommitId(commit.id, root) })
}
return commits
}
private fun applyHashFilter(dataPack: DataPack,
hashFilter: VcsLogHashFilter,
sortType: PermanentGraph.SortType,
commitCount: CommitCountStage): Pair<VisiblePack, CommitCountStage>? {
val hashes = hashFilter.hashes
val hashFilterResult = hashSetOf<Int>()
for (partOfHash in hashes) {
if (partOfHash.length == FULL_HASH_LENGTH) {
val hash = HashImpl.build(partOfHash)
for (root in dataPack.logProviders.keys) {
if (storage.containsCommit(CommitId(hash, root))) {
hashFilterResult.add(storage.getCommitIndex(hash, root))
}
}
}
else {
val commitId = storage.findCommitId(CommitIdByStringCondition(partOfHash))
if (commitId != null) hashFilterResult.add(storage.getCommitIndex(commitId.hash, commitId.root))
}
}
val filterMessages = Registry.`is`("vcs.log.filter.messages.by.hash")
if (!filterMessages || commitCount == CommitCountStage.INITIAL) {
if (hashFilterResult.isEmpty()) return null
val visibleGraph = dataPack.permanentGraph.createVisibleGraph(sortType, null, hashFilterResult)
val visiblePack = VisiblePack(dataPack, visibleGraph, filterMessages, VcsLogFilterObject.collection(hashFilter))
return Pair(visiblePack, if (filterMessages) commitCount.next() else CommitCountStage.ALL)
}
val textFilter = VcsLogFilterObject.fromPatternsList(ArrayList(hashes), false)
try {
val textFilterResult = filterByDetails(dataPack, VcsLogFilterObject.collection(textFilter),
commitCount, dataPack.logProviders.keys, null, null, false)
if (hashFilterResult.isEmpty() && textFilterResult.matchingCommits.matchesNothing()) return null
val filterResult = union(textFilterResult.matchingCommits, hashFilterResult)
val visibleGraph = dataPack.permanentGraph.createVisibleGraph(sortType, null, filterResult)
val visiblePack = VisiblePack(dataPack, visibleGraph, textFilterResult.canRequestMore,
VcsLogFilterObject.collection(hashFilter, textFilter))
return Pair(visiblePack, textFilterResult.commitCount)
}
catch (e: VcsException) {
return Pair(VisiblePack.ErrorVisiblePack(dataPack, VcsLogFilterObject.collection(hashFilter, textFilter), e), commitCount)
}
}
fun getMatchingHeads(refs: RefsModel,
roots: Collection<VirtualFile>,
filters: VcsLogFilterCollection): Set<Int>? {
val branchFilter = filters.get(VcsLogFilterCollection.BRANCH_FILTER)
val revisionFilter = filters.get(VcsLogFilterCollection.REVISION_FILTER)
if (branchFilter == null &&
revisionFilter == null &&
filters.get(VcsLogFilterCollection.ROOT_FILTER) == null &&
filters.get(VcsLogFilterCollection.STRUCTURE_FILTER) == null) {
return null
}
if (revisionFilter != null) {
if (branchFilter == null) {
return getMatchingHeads(roots, revisionFilter)
}
return getMatchingHeads(refs, roots, branchFilter).union(getMatchingHeads(roots, revisionFilter))
}
if (branchFilter == null) return getMatchingHeads(refs, roots)
return getMatchingHeads(refs, roots, branchFilter)
}
private fun getMatchingHeads(refs: RefsModel,
roots: Collection<VirtualFile>,
branchFilter: VcsLogBranchFilter?,
revisionFilter: VcsLogRevisionFilter?): Set<Int>? {
if (branchFilter == null && revisionFilter == null) return null
val branchMatchingHeads = if (branchFilter != null) getMatchingHeads(refs, roots, branchFilter) else emptySet()
val revisionMatchingHeads = if (revisionFilter != null) getMatchingHeads(roots, revisionFilter) else emptySet()
return branchMatchingHeads.union(revisionMatchingHeads)
}
private fun getMatchingHeads(refsModel: RefsModel, roots: Collection<VirtualFile>, filter: VcsLogBranchFilter): Set<Int> {
return mapRefsForRoots(refsModel, roots) { refs ->
refs.streamBranches().filter { filter.matches(it.name) }.collect(Collectors.toList())
}.toReferencedCommitIndexes()
}
private fun getMatchingHeads(roots: Collection<VirtualFile>, filter: VcsLogRevisionFilter): Set<Int> {
return filter.heads.filter { roots.contains(it.root) }.toCommitIndexes()
}
private fun getMatchingHeads(refsModel: RefsModel, roots: Collection<VirtualFile>): Set<Int> {
return mapRefsForRoots(refsModel, roots) { refs -> refs.commits }
}
private fun <T> mapRefsForRoots(refsModel: RefsModel, roots: Collection<VirtualFile>, mapping: (CompressedRefs) -> Iterable<T>) =
refsModel.allRefsByRoot.filterKeys { roots.contains(it) }.values.flatMapTo(mutableSetOf(), mapping)
private fun filterDetailsInMemory(permanentGraph: PermanentGraph<Int>,
detailsFilters: List<VcsLogDetailsFilter>,
matchingHeads: Set<Int>?,
commitCandidates: IntSet?): Collection<CommitId> {
val result = mutableListOf<CommitId>()
for (commit in permanentGraph.allCommits) {
if (commitCandidates == null || commitCandidates.contains(commit.id)) {
val data = getDetailsFromCache(commit.id)
?: // no more continuous details in the cache
break
if (matchesAllFilters(data, permanentGraph, detailsFilters, matchingHeads)) {
result.add(CommitId(data.id, data.root))
}
}
}
return result
}
private fun matchesAllFilters(commit: VcsCommitMetadata,
permanentGraph: PermanentGraph<Int>,
detailsFilters: List<VcsLogDetailsFilter>,
matchingHeads: Set<Int>?): Boolean {
val matchesAllDetails = detailsFilters.all { filter -> filter.matches(commit) }
return matchesAllDetails && matchesAnyHead(permanentGraph, commit, matchingHeads)
}
private fun matchesAnyHead(permanentGraph: PermanentGraph<Int>,
commit: VcsCommitMetadata,
matchingHeads: Set<Int>?): Boolean {
if (matchingHeads == null) {
return true
}
// TODO O(n^2)
val commitIndex = storage.getCommitIndex(commit.id, commit.root)
return ContainerUtil.intersects(permanentGraph.getContainingBranches(commitIndex), matchingHeads)
}
private fun getDetailsFromCache(commitIndex: Int): VcsCommitMetadata? {
return topCommitsDetailsCache.get(commitIndex) ?: commitDetailsGetter.getCommitDataIfAvailable(commitIndex)
}
private fun Collection<CommitId>.toCommitIndexes(): Set<Int> {
return this.mapTo(mutableSetOf()) { commitId ->
storage.getCommitIndex(commitId.hash, commitId.root)
}
}
private fun Collection<VcsRef>.toReferencedCommitIndexes(): Set<Int> {
return this.mapTo(mutableSetOf()) { ref ->
storage.getCommitIndex(ref.commitHash, ref.root)
}
}
}
private val LOG = Logger.getInstance(VcsLogFiltererImpl::class.java)
private data class FilterByDetailsResult(val matchingCommits: Set<Int>?,
val canRequestMore: Boolean,
val commitCount: CommitCountStage,
val fileHistoryData: FileHistoryData? = null)
fun areFiltersAffectedByIndexing(filters: VcsLogFilterCollection, roots: List<VirtualFile>): Boolean {
val detailsFilters = filters.detailsFilters
if (detailsFilters.isEmpty()) return false
val affectedRoots = VcsLogUtil.getAllVisibleRoots(roots, filters)
val needsIndex = affectedRoots.isNotEmpty()
if (needsIndex) {
LOG.debug("$filters are affected by indexing of $affectedRoots")
}
return needsIndex
}
internal fun <T> Collection<T>?.matchesNothing(): Boolean {
return this != null && this.isEmpty()
}
internal fun <T> union(c1: Set<T>?, c2: Set<T>?): Set<T>? {
if (c1 == null) return c2
if (c2 == null) return c1
return c1.union(c2)
}
| apache-2.0 | 63a7505d4c6a1c387cfdd58cc3021144 | 46.744879 | 140 | 0.694489 | 5.373926 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/jvm-debugger/core-fe10/src/org/jetbrains/kotlin/idea/debugger/KotlinClassRenderer.kt | 1 | 7597 | // 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.debugger
import com.intellij.debugger.JavaDebuggerBundle
import com.intellij.debugger.engine.DebuggerManagerThreadImpl
import com.intellij.debugger.engine.DebuggerUtils
import com.intellij.debugger.engine.JVMNameUtil
import com.intellij.debugger.engine.evaluation.EvaluationContext
import com.intellij.debugger.impl.DebuggerUtilsAsync
import com.intellij.debugger.settings.NodeRendererSettings
import com.intellij.debugger.ui.impl.watch.ValueDescriptorImpl
import com.intellij.debugger.ui.tree.DebuggerTreeNode
import com.intellij.debugger.ui.tree.NodeManager
import com.intellij.debugger.ui.tree.ValueDescriptor
import com.intellij.debugger.ui.tree.render.ChildrenBuilder
import com.intellij.debugger.ui.tree.render.ClassRenderer
import com.intellij.debugger.ui.tree.render.DescriptorLabelListener
import com.intellij.openapi.project.Project
import com.sun.jdi.*
import org.jetbrains.kotlin.idea.debugger.base.util.safeFields
import org.jetbrains.kotlin.idea.debugger.base.util.safeType
import org.jetbrains.kotlin.idea.debugger.core.isInKotlinSources
import org.jetbrains.kotlin.idea.debugger.core.isInKotlinSourcesAsync
import java.util.concurrent.CompletableFuture
import java.util.function.Function
class KotlinClassRenderer : ClassRenderer() {
init {
setIsApplicableChecker(Function { type: Type? ->
if (type is ReferenceType && type !is ArrayType && !type.canBeRenderedBetterByPlatformRenderers()) {
return@Function type.isInKotlinSourcesAsync()
}
CompletableFuture.completedFuture(false)
})
}
override fun buildChildren(value: Value?, builder: ChildrenBuilder, evaluationContext: EvaluationContext) {
DebuggerManagerThreadImpl.assertIsManagerThread()
if (value !is ObjectReference) {
builder.setChildren(emptyList())
return
}
val parentDescriptor = builder.parentDescriptor as ValueDescriptorImpl
val nodeManager = builder.nodeManager
val nodeDescriptorFactory = builder.descriptorManager
val refType = value.referenceType()
val gettersFuture = DebuggerUtilsAsync.allMethods(refType)
.thenApply { methods -> methods.getters().createNodes(value, parentDescriptor.project, evaluationContext, nodeManager) }
DebuggerUtilsAsync.allFields(refType).thenCombine(gettersFuture) { fields, getterNodes ->
if (fields.isEmpty() && getterNodes.isEmpty()) {
builder.setChildren(listOf(nodeManager.createMessageNode(KotlinDebuggerCoreBundle.message("message.class.has.no.properties"))))
return@thenCombine
}
createNodesToShow(fields, evaluationContext, parentDescriptor, nodeManager, nodeDescriptorFactory, value)
.thenAccept { nodesToShow ->
if (nodesToShow.isEmpty()) {
val classHasNoFieldsToDisplayMessage =
nodeManager.createMessageNode(
JavaDebuggerBundle.message("message.node.class.no.fields.to.display")
)
builder.setChildren(
listOf(classHasNoFieldsToDisplayMessage) +
getterNodes
)
return@thenAccept
}
builder.setChildren(mergeNodesLists(nodesToShow, getterNodes))
}
}
}
override fun calcLabel(
descriptor: ValueDescriptor,
evaluationContext: EvaluationContext?,
labelListener: DescriptorLabelListener
): String {
val renderer = NodeRendererSettings.getInstance().toStringRenderer
return renderer.calcLabel(descriptor, evaluationContext, labelListener)
}
override fun isApplicable(type: Type?) = throw IllegalStateException("Should not be called")
override fun shouldDisplay(context: EvaluationContext?, objInstance: ObjectReference, field: Field): Boolean {
val referenceType = objInstance.referenceType()
if (field.isStatic && referenceType.isKotlinObjectType()) {
if (field.isInstanceFieldOfType(referenceType)) {
return false
}
return true
}
return super.shouldDisplay(context, objInstance, field)
}
private fun mergeNodesLists(fieldNodes: List<DebuggerTreeNode>, getterNodes: List<DebuggerTreeNode>): List<DebuggerTreeNode> {
val namesToIndex = getterNodes.withIndex().associate { it.value.descriptor.name to it.index }
val result = ArrayList<DebuggerTreeNode>(fieldNodes.size + getterNodes.size)
val added = BooleanArray(getterNodes.size)
for (fieldNode in fieldNodes) {
result.add(fieldNode)
val name = fieldNode.descriptor.name.removeSuffix("\$delegate")
val index = namesToIndex[name] ?: continue
if (!added[index]) {
result.add(getterNodes[index])
added[index] = true
}
}
result.addAll(getterNodes.filterIndexed { i, _ -> !added[i] })
return result
}
private fun List<Method>.getters() =
filter { method ->
!method.isAbstract &&
GetterDescriptor.GETTER_PREFIXES.any { method.name().startsWith(it) } &&
method.argumentTypeNames().isEmpty() &&
method.name() != "getClass" &&
!method.name().endsWith("\$annotations") &&
method.declaringType().isInKotlinSources() &&
!method.isSimpleGetter() &&
!method.isLateinitVariableGetter()
}
.distinctBy { it.name() }
.toList()
private fun List<Method>.createNodes(
parentObject: ObjectReference,
project: Project,
evaluationContext: EvaluationContext,
nodeManager: NodeManager
) = map { nodeManager.createNode(GetterDescriptor(parentObject, it, project), evaluationContext) }
private fun ReferenceType.isKotlinObjectType() =
containsInstanceField() && hasPrivateConstructor()
private fun ReferenceType.containsInstanceField() =
safeFields().any { it.isInstanceFieldOfType(this) }
private fun ReferenceType.hasPrivateConstructor(): Boolean {
val constructor = methodsByName(JVMNameUtil.CONSTRUCTOR_NAME).singleOrNull() ?: return false
return constructor.isPrivate && constructor.argumentTypeNames().isEmpty()
}
/**
* IntelliJ Platform has good collections' debugger renderers.
*
* We want to use them even when the collection is implemented completely in Kotlin
* (e.g. lists, sets and maps empty singletons; subclasses of `Abstract(List|Set|Map)`;
* collections, built by `build(List|Set|Map) { ... }` methods).
*
* Also we want to use platform renderer for Map entries.
*/
private fun ReferenceType.canBeRenderedBetterByPlatformRenderers(): Boolean {
val typesWithGoodDefaultRenderers = listOf(
"java.util.Collection",
"java.util.Map",
"java.util.Map.Entry",
)
return typesWithGoodDefaultRenderers.any { superType -> DebuggerUtils.instanceOf(this, superType) }
}
private fun Field.isInstanceFieldOfType(type: Type) =
isStatic && isFinal && name() == "INSTANCE" && safeType() == type
}
| apache-2.0 | c1b5fa33e9428a94f968a262fbc61539 | 43.952663 | 158 | 0.67474 | 4.998026 | false | false | false | false |
csumissu/WeatherForecast | app/src/main/java/csumissu/weatherforecast/extensions/ContextExtensions.kt | 1 | 1103 | package csumissu.weatherforecast.extensions
import android.content.Context
import android.location.LocationManager
import android.net.ConnectivityManager
import android.support.annotation.LayoutRes
import android.support.v4.content.ContextCompat
import android.support.v4.content.PermissionChecker
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
/**
* @author yxsun
* @since 05/06/2017
*/
fun Context.color(res: Int): Int = ContextCompat.getColor(this, res)
val Context.locationManager: LocationManager
get() = getSystemService(Context.LOCATION_SERVICE) as LocationManager
val Context.connectivityManager: ConnectivityManager
get() = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
fun Context.inflate(@LayoutRes res: Int, parent: ViewGroup? = null, attach: Boolean = false): View {
return LayoutInflater.from(this).inflate(res, parent, attach)
}
fun Context.isPermissionGranted(permission: String): Boolean {
return PermissionChecker.checkSelfPermission(this, permission) == PermissionChecker.PERMISSION_GRANTED
} | mit | 64858bb48c4d72cc19d95854255f1a6c | 34.612903 | 106 | 0.81233 | 4.557851 | false | false | false | false |
yeoji/kotodo | src/main/kotlin/com/yeoji/kotodo/util/ResourcesUtil.kt | 1 | 1277 | package com.yeoji.kotodo.util
import java.io.File
import java.net.URL
/**
* This is a utility file that handles
* anything to do with the resources folder
*
* Created by jq on 20/04/2017.
*/
object ResourcesUtil {
/**
* Returns the file path from the resources folder
*/
fun getFilePathFromResources(path: String): String {
val classLoader: ClassLoader = ClassLoader.getSystemClassLoader()
val resourceUrl: URL? = classLoader.getResource(path)
if(resourceUrl != null) {
return resourceUrl.file
}
return ""
}
/**
* Create a file in the resources folder
* Returns the created file path
*/
fun createFile(path: String): String {
// use an existing path in the resources folder to get the resources path
val existingPath: String = getFilePathFromResources("config")
val resourcesPath: String = File(existingPath).parent
// create the new file in the resources path
val dirNames: String = path.substringBeforeLast(File.separator)
val filePath: String = resourcesPath + File.separator + path
File(resourcesPath + File.separator + dirNames).mkdirs()
File(filePath).createNewFile()
return filePath
}
} | mit | 472642fa96435b328d1c8049db6bdccc | 28.72093 | 81 | 0.658575 | 4.660584 | false | false | false | false |
GunoH/intellij-community | jvm/jvm-analysis-kotlin-tests/testSrc/com/intellij/codeInspection/tests/kotlin/test/junit/KotlinJUnitAssertEqualsOnArrayInspectionTest.kt | 7 | 1421 | package com.intellij.codeInspection.tests.kotlin.test.junit
import com.intellij.codeInspection.tests.ULanguage
import com.intellij.codeInspection.tests.test.junit.JUnitAssertEqualsOnArrayInspectionTestBase
class KotlinJUnitAssertEqualsOnArrayInspectionTest : JUnitAssertEqualsOnArrayInspectionTestBase() {
fun `test highlighting`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
import org.junit.jupiter.api.Assertions
class MyTest {
fun myTest() {
val a = arrayOf<Any>()
val e = arrayOf<String>("")
Assertions.<warning descr="'assertEquals()' called on array">assertEquals</warning>(a, e, "message")
}
}
""".trimIndent())
}
fun `test quickfix`() {
myFixture.testQuickFix(ULanguage.KOTLIN, """
import org.junit.jupiter.api.Assertions
class MyTest {
fun myTest() {
val a = arrayOf<Any>()
val e = arrayOf<String>("")
Assertions.assert<caret>Equals(a, e, "message")
}
}
""".trimIndent(), """
import org.junit.jupiter.api.Assertions
class MyTest {
fun myTest() {
val a = arrayOf<Any>()
val e = arrayOf<String>("")
Assertions.assertArrayEquals(a, e, "message")
}
}
""".trimIndent(), "Replace with 'assertArrayEquals()'")
}
} | apache-2.0 | fe0dbdf2dfd2ea5a9b73bcb6985faae1 | 31.318182 | 114 | 0.594652 | 4.800676 | false | true | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/AddJvmStaticIntention.kt | 1 | 4923 | // 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
import com.intellij.codeInsight.intention.LowPriorityAction
import com.intellij.ide.highlighter.JavaFileType
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiReferenceExpression
import com.intellij.psi.search.searches.ReferencesSearch
import org.jetbrains.kotlin.asJava.classes.KtLightClass
import org.jetbrains.kotlin.asJava.elements.KtLightElement
import org.jetbrains.kotlin.asJava.elements.KtLightField
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.base.util.restrictByFileType
import org.jetbrains.kotlin.idea.core.util.runSynchronouslyWithProgress
import org.jetbrains.kotlin.idea.base.util.codeUsageScope
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingRangeIntention
import org.jetbrains.kotlin.idea.util.addAnnotation
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.application.runWriteAction
import org.jetbrains.kotlin.idea.util.findAnnotation
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.load.java.JvmAbi
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.KtNamedDeclaration
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.psi.KtObjectDeclaration
import org.jetbrains.kotlin.psi.KtProperty
import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject
class AddJvmStaticIntention : SelfTargetingRangeIntention<KtNamedDeclaration>(
KtNamedDeclaration::class.java,
KotlinBundle.lazyMessage("add.jvmstatic.annotation")
), LowPriorityAction {
private val JvmStaticFqName = FqName("kotlin.jvm.JvmStatic")
private val JvmFieldFqName = FqName("kotlin.jvm.JvmField")
override fun startInWriteAction() = false
override fun applicabilityRange(element: KtNamedDeclaration): TextRange? {
if (element !is KtNamedFunction && element !is KtProperty) return null
if (element.hasModifier(KtTokens.ABSTRACT_KEYWORD)) return null
if (element.hasModifier(KtTokens.OPEN_KEYWORD)) return null
if (element.hasModifier(KtTokens.OVERRIDE_KEYWORD)) return null
val containingObject = element.containingClassOrObject as? KtObjectDeclaration ?: return null
if (containingObject.isObjectLiteral()) return null
if (element is KtProperty) {
if (element.hasModifier(KtTokens.CONST_KEYWORD)) return null
if (element.findAnnotation(JvmFieldFqName) != null) return null
}
if (element.findAnnotation(JvmStaticFqName) != null) return null
return element.nameIdentifier?.textRange
}
override fun applyTo(element: KtNamedDeclaration, editor: Editor?) {
val containingObject = element.containingClassOrObject as? KtObjectDeclaration ?: return
val isCompanionMember = containingObject.isCompanion()
val instanceFieldName = if (isCompanionMember) containingObject.name else JvmAbi.INSTANCE_FIELD
val instanceFieldContainingClass = if (isCompanionMember) (containingObject.containingClassOrObject ?: return) else containingObject
val project = element.project
val expressionsToReplaceWithQualifier =
project.runSynchronouslyWithProgress(KotlinBundle.message("looking.for.usages.in.java.files"), true) {
runReadAction {
val searchScope = element.codeUsageScope().restrictByFileType(JavaFileType.INSTANCE)
ReferencesSearch
.search(element, searchScope)
.mapNotNull {
val refExpr = it.element as? PsiReferenceExpression ?: return@mapNotNull null
if ((refExpr.resolve() as? KtLightElement<*, *>)?.kotlinOrigin != element) return@mapNotNull null
val qualifierExpr = refExpr.qualifierExpression as? PsiReferenceExpression ?: return@mapNotNull null
if (qualifierExpr.qualifierExpression == null) return@mapNotNull null
val instanceField = qualifierExpr.resolve() as? KtLightField ?: return@mapNotNull null
if (instanceField.name != instanceFieldName) return@mapNotNull null
if ((instanceField.containingClass as? KtLightClass)?.kotlinOrigin != instanceFieldContainingClass) return@mapNotNull null
qualifierExpr
}
}
} ?: return
runWriteAction {
element.addAnnotation(JvmStaticFqName)
expressionsToReplaceWithQualifier.forEach { it.replace(it.qualifierExpression!!) }
}
}
}
| apache-2.0 | 19a4ac180a68f302569368d816813d01 | 54.314607 | 158 | 0.732074 | 5.368593 | false | false | false | false |
GunoH/intellij-community | platform/configuration-store-impl/testSrc/DoNotStorePasswordTest.kt | 7 | 3637 | // 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.configurationStore
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.extensions.PluginDescriptor
import com.intellij.serviceContainer.ComponentManagerImpl
import com.intellij.testFramework.ProjectRule
import com.intellij.util.xmlb.XmlSerializerUtil
import org.jdom.Attribute
import org.jdom.Element
import org.junit.ClassRule
import org.junit.Test
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type
class DoNotStorePasswordTest {
companion object {
@JvmField
@ClassRule
val projectRule = ProjectRule()
}
@Test
fun printPasswordComponents() {
val processor: (componentClass: Class<*>, plugin: PluginDescriptor?) -> Unit = p@{ aClass, _ ->
val stateAnnotation = getStateSpec(aClass)
if (stateAnnotation == null || stateAnnotation.name.isEmpty()) {
return@p
}
for (i in aClass.genericInterfaces) {
if (checkType(i)) {
return@p
}
}
// public static class Project extends WebServersConfigManagerBaseImpl<WebServersConfigManagerBaseImpl.State> {
// so, we check not only PersistentStateComponent
checkType(aClass.genericSuperclass)
}
val app = ApplicationManager.getApplication() as ComponentManagerImpl
app.processAllImplementationClasses(processor)
// yes, we don't use default project here to be sure
(projectRule.project as ComponentManagerImpl).processAllImplementationClasses(processor)
for (container in listOf(app, projectRule.project as ComponentManagerImpl)) {
container.processAllImplementationClasses { aClass, _ ->
if (PersistentStateComponent::class.java.isAssignableFrom(aClass)) {
processor(aClass, null)
}
}
}
}
fun check(clazz: Class<*>) {
@Suppress("DEPRECATION")
if (clazz.isEnum || clazz === Attribute::class.java || clazz === Element::class.java ||
clazz === java.lang.String::class.java || clazz === java.lang.Integer::class.java || clazz === java.lang.Boolean::class.java ||
Map::class.java.isAssignableFrom(clazz) || com.intellij.openapi.util.JDOMExternalizable::class.java.isAssignableFrom(clazz)) {
return
}
for (accessor in XmlSerializerUtil.getAccessors(clazz)) {
val name = accessor.name
if (BaseXmlOutputter.doesNameSuggestSensitiveInformation(name)) {
if (clazz.typeName != "com.intellij.docker.registry.DockerRegistry") {
throw RuntimeException("${clazz.typeName}.${accessor.name}")
}
}
else if (!accessor.valueClass.isPrimitive) {
if (Collection::class.java.isAssignableFrom(accessor.valueClass)) {
val genericType = accessor.genericType
if (genericType is ParameterizedType) {
val type = genericType.actualTypeArguments[0]
if (type is Class<*>) {
check(type)
}
}
}
else if (accessor.valueClass != clazz) {
check(accessor.valueClass)
}
}
}
}
private fun checkType(type: Type): Boolean {
if (type !is ParameterizedType || !PersistentStateComponent::class.java.isAssignableFrom(type.rawType as Class<*>)) {
return false
}
type.actualTypeArguments[0].let {
if (it is ParameterizedType) {
check(it.rawType as Class<*>)
}
else {
check(it as Class<*>)
}
}
return true
}
} | apache-2.0 | 84079c6f9256888f5415397c0891acb9 | 33.980769 | 135 | 0.681606 | 4.76671 | false | false | false | false |
GunoH/intellij-community | plugins/markdown/core/src/org/intellij/plugins/markdown/model/psi/MarkdownPsiUsage.kt | 7 | 1694 | package org.intellij.plugins.markdown.model.psi
import com.intellij.find.usages.api.PsiUsage
import com.intellij.model.Pointer
import com.intellij.model.psi.PsiSymbolReference
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.SmartPointerManager
internal class MarkdownPsiUsage(
override val file: PsiFile,
override val range: TextRange,
override val declaration: Boolean
): PsiUsage {
override fun createPointer(): Pointer<out PsiUsage> {
return MarkdownPsiUsagePointer(file, range, declaration)
}
private class MarkdownPsiUsagePointer(
file: PsiFile,
range: TextRange,
private val declaration: Boolean
): Pointer<MarkdownPsiUsage> {
private val rangePointer = SmartPointerManager.getInstance(file.project).createSmartPsiFileRangePointer(file, range)
override fun dereference(): MarkdownPsiUsage? {
val file = rangePointer.element ?: return null
val range = rangePointer.range?.let(TextRange::create) ?: return null
return MarkdownPsiUsage(file, range, declaration)
}
}
companion object {
fun create(element: PsiElement, rangeInElement: TextRange, declaration: Boolean = false): MarkdownPsiUsage {
if (element is PsiFile) {
return MarkdownPsiUsage(element, rangeInElement, declaration)
}
return MarkdownPsiUsage(
element.containingFile,
rangeInElement.shiftRight(element.textRange.startOffset),
declaration
)
}
fun create(reference: PsiSymbolReference): MarkdownPsiUsage {
return create(reference.element, reference.rangeInElement, declaration = false)
}
}
}
| apache-2.0 | c12363ea7cd47ad149758ae0bf139542 | 32.88 | 120 | 0.749115 | 4.566038 | false | false | false | false |
bottiger/SoundWaves | app/src/main/kotlin/org/bottiger/podcast/fragments/subscription/SubscriptionsViewModel.kt | 1 | 3550 | package org.bottiger.podcast.fragments.subscription
import android.app.Application
import android.arch.lifecycle.AndroidViewModel
import android.arch.lifecycle.LiveData
import android.arch.lifecycle.LiveDataReactiveStreams
import android.arch.lifecycle.MutableLiveData
import android.support.v7.util.SortedList
import io.reactivex.BackpressureStrategy
import org.bottiger.podcast.SoundWaves
import org.bottiger.podcast.model.Library
import org.bottiger.podcast.model.events.SubscriptionChanged
import org.bottiger.podcast.provider.Subscription
/**
* Created by aplb on 22-06-2017.
*/
class SubscriptionsViewModel(application : Application, library: Library) : AndroidViewModel(application) {
val liveSubscription: LiveData<Subscription>
val liveSubscriptionChanged : LiveData<SubscriptionChanged>
init {
val type = Subscription::class.java
val publisher = library.mSubscriptionsChangePublisher.toFlowable(BackpressureStrategy.LATEST).ofType(type)
liveSubscription = LiveDataReactiveStreams.fromPublisher(publisher)
val changeType = SubscriptionChanged::class.java
val changedPublisher = SoundWaves.getRxBus2()
.toFlowable()
.ofType(changeType)
.filter{it.action == SubscriptionChanged.CHANGED}
liveSubscriptionChanged = LiveDataReactiveStreams.fromPublisher(changedPublisher)
}
}
/*
mRxSubscriptionChanged = SoundWaves.getRxBus()
.toObserverable()
.onBackpressureBuffer(10000)
.ofType(SubscriptionChanged.class)
.filter(new Func1<SubscriptionChanged, Boolean>() {
@Override
public Boolean call(SubscriptionChanged subscriptionChanged) {
return subscriptionChanged.getAction() == SubscriptionChanged.CHANGED;
}
})
.subscribe(new Action1<SubscriptionChanged>() {
@Override
public void call(SubscriptionChanged itemChangedEvent) {
Log.v(TAG, "Refreshing Subscription: " + itemChangedEvent.getId());
// Update the subscription fragment when a image is updated in an subscription
SortedList<Subscription> subscriptions = mLibrary.getSubscriptions();
Subscription subscription = mLibrary.getSubscription(itemChangedEvent.getId());
int index = subscriptions.indexOf(subscription); // doesn't work
for (int i = 0; i < subscriptions.size(); i++) {
Subscription currentSubscription = subscriptions.get(i);
if (subscription != null && subscription.equals(currentSubscription)) {
index = i;
break;
}
}
if (!mGridView.isComputingLayout()) {
mAdapter.notifyItemChanged(index);
}
}
}, new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
VendorCrashReporter.handleException(throwable);
Log.wtf(TAG, "Missing back pressure. Should not happen anymore :(");
}
});
*/ | gpl-3.0 | 5373fe4746af81aeb3bbfb75bbb20c0e | 43.949367 | 114 | 0.591831 | 5.887231 | false | false | false | false |
AsamK/TextSecure | qr/lib/src/main/java/org/signal/qr/ScannerView19.kt | 1 | 1498 | package org.signal.qr
import android.annotation.SuppressLint
import android.content.Context
import android.widget.FrameLayout
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import org.signal.qr.kitkat.QrCameraView
import org.signal.qr.kitkat.ScanListener
import org.signal.qr.kitkat.ScanningThread
/**
* API19 version of QR scanning. Uses deprecated camera APIs.
*/
@SuppressLint("ViewConstructor")
internal class ScannerView19 constructor(
context: Context,
private val scanListener: ScanListener
) : FrameLayout(context), ScannerView {
private var scanningThread: ScanningThread? = null
private val cameraView: QrCameraView
init {
cameraView = QrCameraView(context)
cameraView.layoutParams = LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)
addView(cameraView)
}
override fun start(lifecycleOwner: LifecycleOwner) {
lifecycleOwner.lifecycle.addObserver(object : DefaultLifecycleObserver {
override fun onResume(owner: LifecycleOwner) {
val scanningThread = ScanningThread()
scanningThread.setScanListener(scanListener)
cameraView.onResume()
cameraView.setPreviewCallback(scanningThread)
scanningThread.start()
[email protected] = scanningThread
}
override fun onPause(owner: LifecycleOwner) {
cameraView.onPause()
scanningThread?.stopScanning()
scanningThread = null
}
})
}
}
| gpl-3.0 | a000361b788a213241e9c97ad5edeac2 | 29.571429 | 96 | 0.757009 | 4.695925 | false | false | false | false |
ze-pequeno/dagger | java/dagger/hilt/android/plugin/main/src/main/kotlin/dagger/hilt/android/plugin/task/HiltTransformTestClassesTask.kt | 2 | 6505 | /*
* Copyright (C) 2020 The Dagger 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 dagger.hilt.android.plugin.task
import dagger.hilt.android.plugin.AndroidEntryPointClassTransformer
import dagger.hilt.android.plugin.HiltExtension
import dagger.hilt.android.plugin.util.capitalize
import dagger.hilt.android.plugin.util.getCompileKotlin
import dagger.hilt.android.plugin.util.isClassFile
import dagger.hilt.android.plugin.util.isJarFile
import java.io.File
import javax.inject.Inject
import org.gradle.api.Action
import org.gradle.api.DefaultTask
import org.gradle.api.Project
import org.gradle.api.file.ConfigurableFileCollection
import org.gradle.api.file.DirectoryProperty
import org.gradle.api.file.FileCollection
import org.gradle.api.provider.Property
import org.gradle.api.tasks.Classpath
import org.gradle.api.tasks.OutputDirectory
import org.gradle.api.tasks.TaskAction
import org.gradle.api.tasks.TaskProvider
import org.gradle.api.tasks.testing.Test
import org.gradle.workers.WorkAction
import org.gradle.workers.WorkParameters
import org.gradle.workers.WorkerExecutor
import org.jetbrains.kotlin.gradle.plugin.KotlinBasePluginWrapper
/**
* Task that transform classes used by host-side unit tests. See b/37076369
*/
abstract class HiltTransformTestClassesTask @Inject constructor(
private val workerExecutor: WorkerExecutor
) : DefaultTask() {
@get:Classpath
abstract val compiledClasses: ConfigurableFileCollection
@get:OutputDirectory
abstract val outputDir: DirectoryProperty
internal interface Parameters : WorkParameters {
val name: Property<String>
val compiledClasses: ConfigurableFileCollection
val outputDir: DirectoryProperty
}
abstract class WorkerAction : WorkAction<Parameters> {
override fun execute() {
val outputDir = parameters.outputDir.asFile.get()
outputDir.deleteRecursively()
outputDir.mkdirs()
val allInputs = parameters.compiledClasses.files.toList()
val classTransformer = AndroidEntryPointClassTransformer(
taskName = parameters.name.get(),
allInputs = allInputs,
sourceRootOutputDir = outputDir,
copyNonTransformed = false
)
// Parse the classpath in reverse so that we respect overwrites, if it ever happens.
allInputs.reversed().forEach {
if (it.isDirectory) {
it.walkTopDown().forEach { file ->
if (file.isClassFile()) {
classTransformer.transformFile(file)
}
}
} else if (it.isJarFile()) {
classTransformer.transformJarContents(it)
}
}
}
}
@TaskAction
fun transformClasses() {
workerExecutor.noIsolation().submit(WorkerAction::class.java) {
it.compiledClasses.from(compiledClasses)
it.outputDir.set(outputDir)
it.name.set(name)
}
}
internal class ConfigAction(
private val outputDir: File,
private val inputClasspath: FileCollection
) : Action<HiltTransformTestClassesTask> {
override fun execute(transformTask: HiltTransformTestClassesTask) {
transformTask.description = "Transforms AndroidEntryPoint annotated classes for JUnit tests."
transformTask.outputDir.set(outputDir)
transformTask.compiledClasses.from(inputClasspath)
}
}
companion object {
private const val TASK_PREFIX = "hiltTransformFor"
fun create(
project: Project,
@Suppress("DEPRECATION") unitTestVariant: com.android.build.gradle.api.UnitTestVariant,
extension: HiltExtension
) {
if (!extension.enableTransformForLocalTests) {
// Not enabled, nothing to do here.
return
}
// TODO(danysantiago): Only use project compiled sources as input, and not all dependency jars
// Using 'null' key to obtain the full compile classpath since we are not using the
// registerPreJavacGeneratedBytecode() API that would have otherwise given us a key to get
// a classpath up to the generated bytecode associated with the key.
val inputClasspath =
project.files(unitTestVariant.getCompileClasspath(null))
// Find the test sources Java compile task and add its output directory into our input
// classpath file collection. This also makes the transform task depend on the test compile
// task.
val testCompileTaskProvider = unitTestVariant.javaCompileProvider
inputClasspath.from(testCompileTaskProvider.map { it.destinationDirectory })
// Similarly, if the Kotlin plugin is configured, find the test sources Kotlin compile task
// and add its output directory to our input classpath file collection.
project.plugins.withType(KotlinBasePluginWrapper::class.java) {
val kotlinCompileTaskProvider = getCompileKotlin(unitTestVariant, project)
inputClasspath.from(kotlinCompileTaskProvider.map { it.destinationDirectory })
}
// Create and configure the transform task.
val outputDir =
project.buildDir.resolve("intermediates/hilt/${unitTestVariant.dirName}Output")
val hiltTransformProvider = project.tasks.register(
"$TASK_PREFIX${unitTestVariant.name.capitalize()}",
HiltTransformTestClassesTask::class.java,
ConfigAction(outputDir, inputClasspath)
)
// Map the transform task's output to a file collection.
val outputFileCollection =
project.files(hiltTransformProvider.map { it.outputDir })
// Configure test classpath by appending the transform output file collection to the start of
// the test classpath so they override the original ones. This also makes test task (the one
// that runs the tests) depend on the transform task.
@Suppress("UNCHECKED_CAST")
val testTaskProvider = project.tasks.named(
"test${unitTestVariant.name.capitalize()}"
) as TaskProvider<Test>
testTaskProvider.configure {
it.classpath = outputFileCollection + it.classpath
}
}
}
}
| apache-2.0 | 6c0240fef3f41a8bec46879636afa7f6 | 37.264706 | 100 | 0.733128 | 4.613475 | false | true | false | false |
TechzoneMC/SonarPet | api/src/main/kotlin/net/techcable/sonarpet/versioning/PluginVersioning.kt | 1 | 5033 | package net.techcable.sonarpet.versioning
import com.dsh105.echopet.compat.api.plugin.EchoPet
import com.dsh105.echopet.compat.api.util.Perm
import net.techcable.sonarpet.utils.scheduleTask
import org.bukkit.command.CommandSender
import java.io.IOException
import java.util.logging.Level
object PluginVersioning {
const val BRANCH = "master"
const val REPO = "TechzoneMC/SonarPet"
val currentVersion: PluginVersionInfo
get() {
val description = EchoPet.getPlugin().description
return PluginVersionInfo.parse(description.name, description.version)
}
var knownDifferenceWithLatest: VersionDifference? = null
private set
private val lock = Any()
@Throws(VersioningException::class, IOException::class)
fun compareToLatest(): VersionDifference {
require(currentVersion.isDevelopment) { "$currentVersion isn't a dev build" }
var difference = this.knownDifferenceWithLatest
if (difference != null) return difference
synchronized(lock) {
difference = this.knownDifferenceWithLatest
if (difference == null) {
difference = currentVersion.compareToRepo(repo = REPO, branch = BRANCH)
this.knownDifferenceWithLatest = difference
}
return difference!!
}
}
fun VersionDifference.sendTo(target: CommandSender) {
val message = StringBuilder("$currentVersion is $this the latest version")
if (currentVersion.isDirty) {
message.append(", but has uncommitted custom changes.")
}
target.sendMessage(message.toString())
if (behindBy > 0 || currentVersion.isDirty) {
target.sendMessage("Please update to the latest development build before reporting bugs with this one.")
}
}
val areNotificationsNeeded: Boolean
get() = PluginVersioning.currentVersion.isDevelopment
fun sendOutdatedVersionNotification(target: CommandSender) {
if (areNotificationsNeeded) {
PluginVersioning.sendVersionNotification(
target = target,
notification = {
if (!isIdentical || currentVersion.isDirty) {
PluginVersioning.apply {
sendTo(target)
}
}
}
)
}
}
@JvmOverloads
fun sendVersionNotification(target: CommandSender, notification: VersionDifference.() -> Unit, onWait: () -> Unit = {}) {
require(currentVersion.isDevelopment) { "$currentVersion isn't a dev build" }
val difference = knownDifferenceWithLatest
if (difference != null) {
difference.sendTo(target)
return
}
onWait()
EchoPet.getPlugin().scheduleTask(async = true) {
try {
compareToLatest().apply(notification)
} catch (e: Throwable) {
when (e) {
is UnknownVersionException -> {
target.sendMessage("Unknown version $currentVersion")
}
is VersioningException -> {
target.sendMessage("Error checking version: ${e.message}")
}
else -> {
target.sendMessage("Unexpected error checking version: ${e.javaClass.simpleName}")
EchoPet.getPlugin().logger.log(
Level.SEVERE,
"Unexpected error checking version",
e
)
}
}
}
}
}
fun runVersionCommand(target: CommandSender) {
if (Perm.DISPLAY_VERSION.hasPerm(target, true, true)) {
when (currentVersion.buildType) {
PluginVersionInfo.BuildType.RELEASE -> {
target.sendMessage("You are running release $currentVersion")
}
PluginVersionInfo.BuildType.DEV, PluginVersionInfo.BuildType.DIRTY -> {
val message = StringBuilder("You are running dev build $currentVersion")
if (currentVersion.isDirty) {
message.append(", which has uncommitted custom changes.")
}
target.sendMessage(message.toString())
check(currentVersion.isDevelopment)
sendVersionNotification(
target,
notification = { sendTo(target) },
onWait = { target.sendMessage("Checking version, please wait...") }
)
}
PluginVersionInfo.BuildType.UNKNOWN -> {
target.sendMessage("You are running unknown build $currentVersion")
}
}
}
}
} | gpl-3.0 | cba599ae2de2ba1f389d6465ad3393ca | 39.926829 | 125 | 0.553149 | 5.680587 | false | true | false | false |
CesarValiente/KUnidirectional | app/src/main/kotlin/com/cesarvaliente/kunidirectional/itemslist/recyclerview/ItemsDiffCallback.kt | 1 | 1407 | /**
* Copyright (C) 2017 Cesar Valiente & Corey Shaw
*
* https://github.com/CesarValiente
* https://github.com/coshaw
*
* 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.cesarvaliente.kunidirectional.itemslist.recyclerview
import android.support.v7.util.DiffUtil
import com.cesarvaliente.kunidirectional.store.Item
class ItemsDiffCallback(val oldItems: List<Item>, val newItems: List<Item>) : DiffUtil.Callback() {
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return oldItems[oldItemPosition].localId == newItems[newItemPosition].localId
}
override fun getOldListSize(): Int = oldItems.size
override fun getNewListSize(): Int = newItems.size
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return oldItems[oldItemPosition] == newItems[newItemPosition]
}
} | apache-2.0 | 0ceecb1bb155f31ae52a97f4114b7416 | 36.052632 | 99 | 0.748401 | 4.424528 | false | false | false | false |
github/codeql | java/ql/test/kotlin/library-tests/classes/generic_anonymous.kt | 1 | 623 | private class Generic<T>(val t: T) {
private val x = object {
val member = t
}
fun get() = x.member
}
fun stringIdentity(s: String) = Generic<String>(s).get()
fun intIdentity(i: Int) = Generic<Int>(i).get()
class Outer<T0> {
open interface C0<T0> {
fun fn0(): T0? = null
}
open interface C1<T1> {
fun fn1(): T1? = null
}
fun <U2> func1() {
fun <U3> func2() {
object: C0<U2>, C1<U3> {}
object: C0<U2>, C1<U2> {}
object: C0<U2>, C1<String> {}
object: C0<U2> {}
object: C0<String> {}
}
}
}
| mit | 94fd33e9ff6b08a7220f824ae22da56e | 17.878788 | 56 | 0.478331 | 2.819005 | false | false | false | false |
DemonWav/MinecraftDevIntelliJ | src/main/kotlin/com/demonwav/mcdev/translations/reference/usages.kt | 1 | 2251 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2020 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.translations.reference
import com.demonwav.mcdev.translations.TranslationConstants
import com.demonwav.mcdev.translations.TranslationFiles
import com.demonwav.mcdev.translations.lang.LangLexerAdapter
import com.demonwav.mcdev.translations.lang.gen.psi.LangTypes
import com.intellij.json.JsonElementTypes
import com.intellij.json.JsonLexer
import com.intellij.lang.cacheBuilder.DefaultWordsScanner
import com.intellij.lang.cacheBuilder.WordsScanner
import com.intellij.lang.findUsages.FindUsagesProvider
import com.intellij.psi.PsiElement
import com.intellij.psi.tree.TokenSet
sealed class TranslationFindUsagesProvider : FindUsagesProvider {
override fun canFindUsagesFor(element: PsiElement) =
TranslationFiles.toTranslation(element) != null && element.containingFile?.virtualFile.let {
TranslationFiles.getLocale(it) == TranslationConstants.DEFAULT_LOCALE
}
override fun getHelpId(psiElement: PsiElement): String? =
null
override fun getType(element: PsiElement) =
TranslationFiles.toTranslation(element)?.let { "translation" } ?: ""
override fun getDescriptiveName(element: PsiElement) =
TranslationFiles.toTranslation(element)?.key ?: ""
override fun getNodeText(element: PsiElement, useFullName: Boolean) =
TranslationFiles.toTranslation(element)?.let { "${it.key}=${it.text}" } ?: ""
}
class JsonFindUsagesProvider : TranslationFindUsagesProvider() {
override fun getWordsScanner(): WordsScanner? =
DefaultWordsScanner(
JsonLexer(),
TokenSet.create(JsonElementTypes.DOUBLE_QUOTED_STRING, JsonElementTypes.SINGLE_QUOTED_STRING),
TokenSet.create(JsonElementTypes.BLOCK_COMMENT, JsonElementTypes.LINE_COMMENT),
TokenSet.EMPTY
)
}
class LangFindUsagesProvider : TranslationFindUsagesProvider() {
override fun getWordsScanner(): WordsScanner? =
DefaultWordsScanner(
LangLexerAdapter(),
TokenSet.create(LangTypes.KEY),
TokenSet.create(LangTypes.COMMENT),
TokenSet.EMPTY
)
}
| mit | 397be63956d6d10a52788914a466f4dc | 35.306452 | 106 | 0.736117 | 4.789362 | false | false | false | false |
RuneSuite/client | updater-mapper/src/main/java/org/runestar/client/updater/mapper/std/classes/GraphicsObject.kt | 1 | 3317 | package org.runestar.client.updater.mapper.std.classes
import org.objectweb.asm.Opcodes.PUTFIELD
import org.objectweb.asm.Type.*
import org.runestar.client.updater.mapper.IdentityMapper
import org.runestar.client.updater.mapper.OrderMapper
import org.runestar.client.updater.mapper.DependsOn
import org.runestar.client.updater.mapper.MethodParameters
import org.runestar.client.updater.mapper.and
import org.runestar.client.updater.mapper.predicateOf
import org.runestar.client.updater.mapper.Class2
import org.runestar.client.updater.mapper.Field2
import org.runestar.client.updater.mapper.Instruction2
import org.runestar.client.updater.mapper.Method2
@DependsOn(Entity::class, SeqType::class)
class GraphicsObject : IdentityMapper.Class() {
override val predicate = predicateOf<Class2> { it.superType == type<Entity>() }
.and { it.instanceMethods.size == 2 }
.and { it.instanceFields.count { it.type == type<SeqType>() } == 1 }
@DependsOn(SeqType::class)
class seqType : IdentityMapper.InstanceField() {
override val predicate = predicateOf<Field2> { it.type == type<SeqType>() }
}
class frame : OrderMapper.InConstructor.Field(GraphicsObject::class, 0) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == INT_TYPE }
}
class frameCycle : OrderMapper.InConstructor.Field(GraphicsObject::class, 1) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == INT_TYPE }
}
class id : OrderMapper.InConstructor.Field(GraphicsObject::class, 2) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == INT_TYPE }
}
class plane : OrderMapper.InConstructor.Field(GraphicsObject::class, 3) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == INT_TYPE }
}
class x : OrderMapper.InConstructor.Field(GraphicsObject::class, 4) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == INT_TYPE }
}
class y : OrderMapper.InConstructor.Field(GraphicsObject::class, 5) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == INT_TYPE }
}
class height : OrderMapper.InConstructor.Field(GraphicsObject::class, 6) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == INT_TYPE }
}
class cycleStart : OrderMapper.InConstructor.Field(GraphicsObject::class, 7) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == INT_TYPE }
}
class isFinished : OrderMapper.InConstructor.Field(GraphicsObject::class, 0) {
override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == BOOLEAN_TYPE }
}
@MethodParameters("cycles")
class advance : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE }
}
@MethodParameters()
@DependsOn(Entity.getModel::class)
class getModel : InstanceMethod() {
override val predicate = predicateOf<Method2> { it.mark == method<Entity.getModel>().mark }
}
} | mit | b72f4c5c6e31c40be38ce042e25155e1 | 43.837838 | 116 | 0.712692 | 4.236271 | false | false | false | false |
google/intellij-community | platform/lang-impl/src/com/intellij/ui/ExperimentalUIImpl.kt | 2 | 4193 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:Suppress("ReplaceGetOrSet", "ReplacePutWithAssignment")
package com.intellij.ui
import com.fasterxml.jackson.jr.ob.JSON
import com.intellij.ide.ui.IconMapperBean
import com.intellij.ide.ui.LafManager
import com.intellij.ide.ui.RegistryBooleanOptionDescriptor
import com.intellij.ide.ui.UISettings
import com.intellij.ide.ui.laf.LafManagerImpl
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.util.registry.Registry
import com.intellij.util.ResourceUtil
import java.util.*
/**
* @author Konstantin Bulenkov
*/
class ExperimentalUIImpl : ExperimentalUI() {
override fun getIconMappings() = loadIconMappingsImpl()
override fun onExpUIEnabled() {
if (ApplicationManager.getApplication().isHeadlessEnvironment) return
setRegistryKeyIfNecessary("ide.experimental.ui", true)
setRegistryKeyIfNecessary("debugger.new.tool.window.layout", true)
UISettings.getInstance().openInPreviewTabIfPossible = true
val name = if (JBColor.isBright()) "Light" else "Dark"
val lafManager = LafManager.getInstance()
val laf = lafManager.installedLookAndFeels.firstOrNull { it.name == name }
if (laf != null) {
lafManager.currentLookAndFeel = laf
if (lafManager.autodetect) {
if (JBColor.isBright()) {
lafManager.setPreferredLightLaf(laf)
}
else {
lafManager.setPreferredDarkLaf(laf)
}
}
}
ApplicationManager.getApplication().invokeLater({ RegistryBooleanOptionDescriptor.suggestRestart(null) }, ModalityState.NON_MODAL)
}
override fun onExpUIDisabled() {
if (ApplicationManager.getApplication().isHeadlessEnvironment) return
setRegistryKeyIfNecessary("ide.experimental.ui", false)
setRegistryKeyIfNecessary("debugger.new.tool.window.layout", false)
val mgr = LafManager.getInstance() as LafManagerImpl
val currentLafName = mgr.currentLookAndFeel?.name
if (currentLafName == "Dark" || currentLafName == "Light") {
val laf = if (JBColor.isBright()) mgr.defaultLightLaf else mgr.defaultDarkLaf
mgr.setCurrentLookAndFeel(laf)
if (mgr.autodetect) {
if (JBColor.isBright()) {
mgr.setPreferredLightLaf(laf)
}
else {
mgr.setPreferredDarkLaf(laf)
}
}
}
ApplicationManager.getApplication().invokeLater({ RegistryBooleanOptionDescriptor.suggestRestart(null) }, ModalityState.NON_MODAL)
}
companion object {
fun loadIconMappingsImpl(): Map<ClassLoader, Map<String, String>> {
val extensions = IconMapperBean.EP_NAME.extensionList
if (extensions.isEmpty()) {
return emptyMap()
}
val result = HashMap<ClassLoader, MutableMap<String, String>>()
val json = JSON.builder().enable().enable(JSON.Feature.READ_ONLY).build()
for (iconMapper in extensions) {
val mappingFile = iconMapper.mappingFile
val classLoader = iconMapper.pluginClassLoader ?: continue
try {
val data = ResourceUtil.getResourceAsBytes(mappingFile, classLoader)!!
val map = result.computeIfAbsent(classLoader) { HashMap() }
readDataFromJson(json.mapFrom(data), "", map)
}
catch (ignore: Exception) {
logger<ExperimentalUIImpl>().warn("Can't find $mappingFile")
}
}
return result
}
private fun setRegistryKeyIfNecessary(key: String, value: Boolean) {
if (Registry.`is`(key) != value) {
Registry.get(key).setValue(value)
}
}
@Suppress("UNCHECKED_CAST")
private fun readDataFromJson(json: Map<String, Any>, prefix: String, result: MutableMap<String, String>) {
json.forEach { (key, value) ->
when (value) {
is String -> result[value] = prefix + key
is Map<*, *> -> readDataFromJson(value as Map<String, Any>, "$prefix$key/", result)
is List<*> -> value.forEach { result[it as String] = "$prefix$key" }
}
}
}
}
} | apache-2.0 | 857ce97365838283c1b2f415ab4d50d9 | 36.783784 | 134 | 0.69139 | 4.336091 | false | false | false | false |
apollographql/apollo-android | apollo-ast/src/main/kotlin/com/apollographql/apollo3/ast/internal/TypeExtensionsMergeScope.kt | 1 | 8577 | package com.apollographql.apollo3.ast.internal
import com.apollographql.apollo3.ast.GQLDefinition
import com.apollographql.apollo3.ast.GQLDirective
import com.apollographql.apollo3.ast.GQLEnumTypeDefinition
import com.apollographql.apollo3.ast.GQLEnumTypeExtension
import com.apollographql.apollo3.ast.GQLInputObjectTypeDefinition
import com.apollographql.apollo3.ast.GQLInputObjectTypeExtension
import com.apollographql.apollo3.ast.GQLInterfaceTypeDefinition
import com.apollographql.apollo3.ast.GQLInterfaceTypeExtension
import com.apollographql.apollo3.ast.GQLNamed
import com.apollographql.apollo3.ast.GQLNode
import com.apollographql.apollo3.ast.GQLObjectTypeDefinition
import com.apollographql.apollo3.ast.GQLObjectTypeExtension
import com.apollographql.apollo3.ast.GQLScalarTypeDefinition
import com.apollographql.apollo3.ast.GQLScalarTypeExtension
import com.apollographql.apollo3.ast.GQLSchemaDefinition
import com.apollographql.apollo3.ast.GQLSchemaExtension
import com.apollographql.apollo3.ast.GQLTypeSystemExtension
import com.apollographql.apollo3.ast.GQLUnionTypeDefinition
import com.apollographql.apollo3.ast.GQLUnionTypeExtension
import com.apollographql.apollo3.ast.Issue
import com.apollographql.apollo3.ast.SourceLocation
import com.apollographql.apollo3.ast.UnrecognizedAntlrRule
internal fun ValidationScope.mergeExtensions(definitions: List<GQLDefinition>): List<GQLDefinition> {
val (extensions, otherDefinitions) = definitions.partition { it is GQLTypeSystemExtension }
return extensions.fold(otherDefinitions) { acc, extension ->
when (extension) {
is GQLSchemaExtension -> mergeSchemaExtension(acc, schemaExtension = extension)
is GQLScalarTypeExtension -> merge<GQLScalarTypeDefinition, GQLScalarTypeExtension>(acc, extension) { merge(it, extension) }
is GQLInterfaceTypeExtension -> merge<GQLInterfaceTypeDefinition, GQLInterfaceTypeExtension>(acc, extension) { merge(it, extension) }
is GQLObjectTypeExtension -> merge<GQLObjectTypeDefinition, GQLObjectTypeExtension>(acc, extension) { merge(it, extension) }
is GQLInputObjectTypeExtension -> merge<GQLInputObjectTypeDefinition, GQLInputObjectTypeExtension>(acc, extension) { merge(it, extension) }
is GQLEnumTypeExtension -> merge<GQLEnumTypeDefinition, GQLEnumTypeExtension>(acc, extension) { merge(it, extension) }
is GQLUnionTypeExtension -> merge<GQLUnionTypeDefinition, GQLUnionTypeExtension>(acc, extension) { merge(it, extension) }
else -> throw UnrecognizedAntlrRule("Unrecognized type system extension", extension.sourceLocation)
}
}
}
private fun ValidationScope.merge(
unionTypeDefinition: GQLUnionTypeDefinition,
extension: GQLUnionTypeExtension,
): GQLUnionTypeDefinition = with(unionTypeDefinition) {
return copy(
directives = mergeDirectives(directives, extension.directives),
memberTypes = mergeUniquesOrThrow(memberTypes, extension.memberTypes)
)
}
private fun ValidationScope.merge(
enumTypeDefinition: GQLEnumTypeDefinition,
extension: GQLEnumTypeExtension,
): GQLEnumTypeDefinition = with(enumTypeDefinition) {
return copy(
directives = mergeDirectives(directives, extension.directives),
enumValues = mergeUniquesOrThrow(enumValues, extension.enumValues),
)
}
private fun ValidationScope.merge(
inputObjectTypeDefinition: GQLInputObjectTypeDefinition,
extension: GQLInputObjectTypeExtension,
): GQLInputObjectTypeDefinition = with(inputObjectTypeDefinition) {
return copy(
directives = mergeDirectives(directives, extension.directives),
inputFields = mergeUniquesOrThrow(inputFields, extension.inputFields)
)
}
private fun ValidationScope.merge(
objectTypeDefinition: GQLObjectTypeDefinition,
extension: GQLObjectTypeExtension,
): GQLObjectTypeDefinition = with(objectTypeDefinition) {
return copy(
directives = mergeDirectives(directives, extension.directives),
fields = mergeUniquesOrThrow(fields, extension.fields),
implementsInterfaces = mergeUniqueInterfacesOrThrow(implementsInterfaces, extension.implementsInterfaces, extension.sourceLocation)
)
}
private fun ValidationScope.merge(
interfaceTypeDefinition: GQLInterfaceTypeDefinition,
extension: GQLInterfaceTypeExtension,
): GQLInterfaceTypeDefinition = with(interfaceTypeDefinition) {
return copy(
fields = mergeUniquesOrThrow(fields, extension.fields),
implementsInterfaces = mergeUniqueInterfacesOrThrow(implementsInterfaces, extension.implementsInterfaces, extension.sourceLocation)
)
}
private fun ValidationScope.mergeSchemaExtension(
definitions: List<GQLDefinition>,
schemaExtension: GQLSchemaExtension,
): List<GQLDefinition> = with(definitions) {
var found = false
val newDefinitions = mutableListOf<GQLDefinition>()
forEach {
if (it is GQLSchemaDefinition) {
newDefinitions.add(merge(it, schemaExtension))
found = true
} else {
newDefinitions.add(it)
}
}
if (!found) {
issues.add(Issue.ValidationError("Cannot apply schema extension on non existing schema definition", schemaExtension.sourceLocation))
}
return newDefinitions
}
private fun ValidationScope.merge(
scalarTypeDefinition: GQLScalarTypeDefinition,
scalarTypeExtension: GQLScalarTypeExtension,
): GQLScalarTypeDefinition = with(scalarTypeDefinition) {
return copy(
directives = mergeDirectives(directives, scalarTypeExtension.directives)
)
}
private inline fun <reified T, E> ValidationScope.merge(
definitions: List<GQLDefinition>,
extension: E,
merge: (T) -> T,
): List<GQLDefinition> where T : GQLDefinition, T : GQLNamed, E : GQLNamed, E : GQLNode = with(definitions) {
var found = false
val newDefinitions = mutableListOf<GQLDefinition>()
forEach {
if (it is T && it.name == extension.name) {
if (found) {
issues.add(Issue.ValidationError("Multiple '${extension.name}' types found while merging extensions. This is a bug, check validation code", extension.sourceLocation))
}
newDefinitions.add(merge(it))
found = true
} else {
newDefinitions.add(it)
}
}
if (!found) {
issues.add(Issue.ValidationError("Cannot find type `${extension.name}` to apply extension", extension.sourceLocation))
}
return newDefinitions
}
private fun ValidationScope.merge(
schemaDefinition: GQLSchemaDefinition,
extension: GQLSchemaExtension,
): GQLSchemaDefinition = with(schemaDefinition) {
return copy(
directives = mergeDirectives(directives, extension.directives),
rootOperationTypeDefinitions = mergeUniquesOrThrow(rootOperationTypeDefinitions, extension.operationTypesDefinition) { it.operationType }
)
}
private fun ValidationScope.mergeDirectives(
list: List<GQLDirective>,
other: List<GQLDirective>,
): List<GQLDirective> {
val result = mutableListOf<GQLDirective>()
result.addAll(list)
for (directive in other) {
if (result.any { it.name == directive.name } ) {
val definition = directiveDefinitions[directive.name] ?: error("Cannot find directive definition '${directive.name}")
if (!definition.repeatable) {
issues.add(Issue.ValidationError("Cannot add non-repeatable directive `${directive.name}`", directive.sourceLocation))
continue
}
}
result.add(directive)
}
return result
}
private inline fun <reified T> IssuesScope.mergeUniquesOrThrow(
list: List<T>,
others: List<T>,
): List<T> where T : GQLNamed, T : GQLNode = with(list) {
return (this + others).apply {
groupBy { it.name }.entries.firstOrNull { it.value.size > 1 }?.let {
issues.add(Issue.ValidationError("Cannot merge already existing node `${it.key}`", it.value.first().sourceLocation))
}
}
}
private fun IssuesScope.mergeUniqueInterfacesOrThrow(
list: List<String>,
others: List<String>,
sourceLocation: SourceLocation,
): List<String> = with(list) {
return (this + others).apply {
groupBy { it }.entries.firstOrNull { it.value.size > 1 }?.let {
issues.add(Issue.ValidationError("Cannot merge interface ${it.value.first()} as it's already defined", sourceLocation))
}
}
}
private inline fun <reified T : GQLNode> IssuesScope.mergeUniquesOrThrow(
list: List<T>,
others: List<T>,
name: (T) -> String,
): List<T> = with(list) {
return (this + others).apply {
groupBy { name(it) }.entries.firstOrNull { it.value.size > 1 }?.let {
issues.add(Issue.ValidationError("Cannot merge already existing node `${it.key}`", it.value.first().sourceLocation))
}
}
}
| mit | b7d99a46bd6d5924b912e09ab07919df | 39.079439 | 174 | 0.762738 | 4.364885 | false | false | false | false |
JetBrains/intellij-community | platform/lang-impl/src/com/intellij/navigation/JBProtocolNavigateCommand.kt | 1 | 1824 | // 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.navigation
import com.intellij.ide.IdeBundle
import com.intellij.openapi.application.JBProtocolCommand
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.LogicalPosition
import com.intellij.openapi.project.DumbService
open class JBProtocolNavigateCommand : JBProtocolCommand(NAVIGATE_COMMAND) {
/**
* The handler parses the following "navigate" command parameters:
*
* \\?project=(?<project>[\\w]+)
* (&fqn[\\d]*=(?<fqn>[\\w.\\-#]+))*
* (&path[\\d]*=(?<path>[\\w-_/\\\\.]+)
* (:(?<lineNumber>[\\d]+))?
* (:(?<columnNumber>[\\d]+))?)*
* (&selection[\\d]*=
* (?<line1>[\\d]+):(?<column1>[\\d]+)
* -(?<line2>[\\d]+):(?<column2>[\\d]+))*
*/
override suspend fun execute(target: String?, parameters: Map<String, String>, fragment: String?): String? {
if (target != REFERENCE_TARGET) {
return IdeBundle.message("jb.protocol.navigate.target", target)
}
val openProjectResult = openProject(parameters)
val project = when(openProjectResult) {
is ProtocolOpenProjectResult.Success -> openProjectResult.project
is ProtocolOpenProjectResult.Error -> return openProjectResult.message
}
DumbService.getInstance(project).runWhenSmart {
NavigatorWithinProject(project, parameters, ::locationToOffset).navigate(listOf(
NavigatorWithinProject.NavigationKeyPrefix.FQN,
NavigatorWithinProject.NavigationKeyPrefix.PATH
))
}
return null
}
private fun locationToOffset(locationInFile: LocationInFile, editor: Editor): Int {
return editor.logicalPositionToOffset(LogicalPosition(locationInFile.line, locationInFile.column))
}
}
| apache-2.0 | edb8ff0fba49bc81e4fa54f6a6e11323 | 37.808511 | 120 | 0.6875 | 4.136054 | false | false | false | false |
allotria/intellij-community | platform/external-system-impl/testSrc/com/intellij/openapi/externalSystem/configurationStore/ExternalSystemStorageTest.kt | 1 | 34867 | // 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 com.intellij.openapi.externalSystem.configurationStore
import com.intellij.configurationStore.StoreReloadManager
import com.intellij.facet.FacetManager
import com.intellij.facet.FacetType
import com.intellij.facet.mock.MockFacetType
import com.intellij.facet.mock.MockSubFacetType
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.*
import com.intellij.openapi.application.ex.PathManagerEx
import com.intellij.openapi.application.impl.coroutineDispatchingContext
import com.intellij.openapi.externalSystem.ExternalSystemModulePropertyManager
import com.intellij.openapi.externalSystem.model.ProjectSystemId
import com.intellij.openapi.externalSystem.model.project.ModuleData
import com.intellij.openapi.externalSystem.model.project.ProjectData
import com.intellij.openapi.externalSystem.service.project.IdeModifiableModelsProviderImpl
import com.intellij.openapi.externalSystem.service.project.manage.ExternalProjectsDataStorage
import com.intellij.openapi.externalSystem.service.project.manage.ExternalProjectsManagerImpl
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.module.ModuleTypeId
import com.intellij.openapi.project.ExternalStorageConfigurationManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.doNotEnableExternalStorageByDefaultInTests
import com.intellij.openapi.project.getProjectCacheFileName
import com.intellij.openapi.roots.ExternalProjectSystemRegistry
import com.intellij.openapi.roots.LanguageLevelProjectExtension
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.roots.ModuleRootModificationUtil
import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.packaging.artifacts.ArtifactManager
import com.intellij.packaging.elements.ArtifactRootElement
import com.intellij.packaging.elements.PackagingElementFactory
import com.intellij.packaging.impl.artifacts.PlainArtifactType
import com.intellij.packaging.impl.elements.ArchivePackagingElement
import com.intellij.pom.java.LanguageLevel
import com.intellij.project.stateStore
import com.intellij.testFramework.*
import com.intellij.testFramework.rules.ProjectModelRule
import com.intellij.util.io.*
import com.intellij.util.ui.UIUtil
import com.intellij.workspaceModel.ide.impl.jps.serialization.JpsProjectModelSynchronizer
import com.intellij.workspaceModel.storage.bridgeEntities.ModuleEntity
import com.intellij.workspaceModel.storage.bridgeEntities.externalSystemOptions
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import org.apache.log4j.Logger
import org.assertj.core.api.Assertions.assertThat
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Assume.assumeTrue
import org.junit.Before
import org.junit.ClassRule
import org.junit.Rule
import org.junit.Test
import java.io.File
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
class ExternalSystemStorageTest {
companion object {
@JvmField
@ClassRule
val appRule = ApplicationRule()
}
@JvmField
@Rule
val disposableRule = DisposableRule()
@JvmField
@Rule
val tempDirManager = TemporaryDirectory()
@Test
fun `save single mavenized module`() = saveProjectInExternalStorageAndCheckResult("singleModule") { project, projectDir ->
val module = ModuleManager.getInstance(project).newModule(projectDir.resolve("test.iml").systemIndependentPath, ModuleTypeId.JAVA_MODULE)
ModuleRootModificationUtil.addContentRoot(module, projectDir.systemIndependentPath)
ExternalSystemModulePropertyManager.getInstance(module).setMavenized(true)
}
@Test
fun `load single mavenized module`() = loadProjectAndCheckResults("singleModule") { project ->
val module = ModuleManager.getInstance(project).modules.single()
assertThat(module.name).isEqualTo("test")
assertThat(module.moduleTypeName).isEqualTo(ModuleTypeId.JAVA_MODULE)
assertThat(module.moduleFilePath).isEqualTo("${project.basePath}/test.iml")
assertThat(ExternalSystemModulePropertyManager.getInstance(module).isMavenized()).isTrue()
assertThat(ExternalStorageConfigurationManager.getInstance(project).isEnabled).isTrue()
}
@Test
fun `save single module from external system`() = saveProjectInExternalStorageAndCheckResult("singleModuleFromExternalSystem") { project, projectDir ->
val module = ModuleManager.getInstance(project).newModule(projectDir.resolve("test.iml").systemIndependentPath,
ModuleTypeId.JAVA_MODULE)
ModuleRootModificationUtil.addContentRoot(module, projectDir.systemIndependentPath)
setExternalSystemOptions(module, projectDir)
}
@Test
fun `applying external system options twice`() {
createProjectAndUseInLoadComponentStateMode(tempDirManager, directoryBased = true, useDefaultProjectSettings = false) { project ->
runBlocking {
withContext(AppUIExecutor.onWriteThread().coroutineDispatchingContext()) {
runWriteAction {
val projectDir = project.stateStore.directoryStorePath!!.parent
val module = ModuleManager.getInstance(project).newModule(projectDir.resolve("test.iml").systemIndependentPath,
ModuleTypeId.JAVA_MODULE)
ModuleRootModificationUtil.addContentRoot(module, projectDir.systemIndependentPath)
val propertyManager = ExternalSystemModulePropertyManager.getInstance(module)
val systemId = ProjectSystemId("GRADLE")
val moduleData = ModuleData("test", systemId, "", "", "", projectDir.systemIndependentPath).also {
it.group = "group"
it.version = "42.0"
}
val projectData = ProjectData(systemId, "", "", projectDir.systemIndependentPath)
val modelsProvider = IdeModifiableModelsProviderImpl(project)
propertyManager.setExternalOptions(systemId, moduleData, projectData)
propertyManager.setExternalOptions(systemId, moduleData, projectData)
val externalOptionsFromBuilder = modelsProvider.actualStorageBuilder
.entities(ModuleEntity::class.java).singleOrNull()?.externalSystemOptions
assertEquals("GRADLE", externalOptionsFromBuilder?.externalSystem)
}
}
}
}
}
@Test
fun `load single module from external system`() = loadProjectAndCheckResults("singleModuleFromExternalSystem") { project ->
val module = ModuleManager.getInstance(project).modules.single()
assertThat(module.name).isEqualTo("test")
assertThat(module.moduleTypeName).isEqualTo(ModuleTypeId.JAVA_MODULE)
assertThat(module.moduleFilePath).isEqualTo("${project.basePath}/test.iml")
assertThat(ExternalSystemModulePropertyManager.getInstance(module).isMavenized()).isFalse()
assertThat(ExternalStorageConfigurationManager.getInstance(project).isEnabled).isTrue()
checkExternalSystemOptions(module, project.basePath!!)
}
@Test
fun `save single module from external system in internal storage`() = saveProjectInInternalStorageAndCheckResult("singleModuleFromExternalSystemInInternalStorage") { project, projectDir ->
val module = ModuleManager.getInstance(project).newModule(projectDir.resolve("test.iml").systemIndependentPath,
ModuleTypeId.JAVA_MODULE)
ModuleRootModificationUtil.addContentRoot(module, projectDir.systemIndependentPath)
setExternalSystemOptions(module, projectDir)
}
@Test
fun `load single module from external system in internal storage`() = loadProjectAndCheckResults("singleModuleFromExternalSystemInInternalStorage") { project ->
val module = ModuleManager.getInstance(project).modules.single()
assertThat(module.name).isEqualTo("test")
assertThat(module.moduleTypeName).isEqualTo(ModuleTypeId.JAVA_MODULE)
assertThat(module.moduleFilePath).isEqualTo("${project.basePath}/test.iml")
assertThat(ExternalSystemModulePropertyManager.getInstance(module).isMavenized()).isFalse()
assertThat(ExternalStorageConfigurationManager.getInstance(project).isEnabled).isFalse()
checkExternalSystemOptions(module, project.basePath!!)
}
private fun setExternalSystemOptions(module: Module, projectDir: Path) {
val propertyManager = ExternalSystemModulePropertyManager.getInstance(module)
val systemId = ProjectSystemId("GRADLE")
val moduleData = ModuleData("test", systemId, "", "", "", projectDir.systemIndependentPath).also {
it.group = "group"
it.version = "42.0"
}
val projectData = ProjectData(systemId, "", "", projectDir.systemIndependentPath)
propertyManager.setExternalOptions(systemId, moduleData, projectData)
}
private fun checkExternalSystemOptions(module: Module, projectDirPath: String) {
val propertyManager = ExternalSystemModulePropertyManager.getInstance(module)
assertThat(propertyManager.getExternalSystemId()).isEqualTo("GRADLE")
assertThat(propertyManager.getExternalModuleGroup()).isEqualTo("group")
assertThat(propertyManager.getExternalModuleVersion()).isEqualTo("42.0")
assertThat(propertyManager.getLinkedProjectId()).isEqualTo("test")
assertThat(propertyManager.getLinkedProjectPath()).isEqualTo(projectDirPath)
assertThat(propertyManager.getRootProjectPath()).isEqualTo(projectDirPath)
}
@Test
fun `save imported module in internal storage`() = saveProjectInInternalStorageAndCheckResult("singleModuleInInternalStorage") { project, projectDir ->
val module = ModuleManager.getInstance(project).newModule(projectDir.resolve("test.iml").systemIndependentPath,
ModuleTypeId.JAVA_MODULE)
ModuleRootModificationUtil.addContentRoot(module, projectDir.systemIndependentPath)
ExternalSystemModulePropertyManager.getInstance(module).setMavenized(true)
}
@Test
fun `load imported module from internal storage`() = loadProjectAndCheckResults("singleModuleInInternalStorage") { project ->
val module = ModuleManager.getInstance(project).modules.single()
assertThat(module.name).isEqualTo("test")
assertThat(module.moduleTypeName).isEqualTo(ModuleTypeId.JAVA_MODULE)
assertThat(module.moduleFilePath).isEqualTo("${project.basePath}/test.iml")
assertThat(ExternalSystemModulePropertyManager.getInstance(module).isMavenized()).isTrue()
assertThat(ExternalStorageConfigurationManager.getInstance(project).isEnabled).isFalse()
}
@Test
fun `save mixed modules`() = saveProjectInExternalStorageAndCheckResult("mixedModules") { project, projectDir ->
val regular = ModuleManager.getInstance(project).newModule(projectDir.resolve("regular.iml").systemIndependentPath, ModuleTypeId.JAVA_MODULE)
ModuleRootModificationUtil.addContentRoot(regular, projectDir.resolve("regular").systemIndependentPath)
val imported = ModuleManager.getInstance(project).newModule(projectDir.resolve("imported.iml").systemIndependentPath, ModuleTypeId.JAVA_MODULE)
ModuleRootModificationUtil.addContentRoot(imported, projectDir.resolve("imported").systemIndependentPath)
ExternalSystemModulePropertyManager.getInstance(imported).setMavenized(true)
ExternalSystemModulePropertyManager.getInstance(imported).setLinkedProjectPath("${project.basePath}/imported")
}
@Test
fun `load mixed modules`() = loadProjectAndCheckResults("mixedModules") { project ->
val modules = ModuleManager.getInstance(project).modules.sortedBy { it.name }
assertThat(modules).hasSize(2)
val (imported, regular) = modules
assertThat(imported.name).isEqualTo("imported")
assertThat(regular.name).isEqualTo("regular")
assertThat(imported.moduleTypeName).isEqualTo(ModuleTypeId.JAVA_MODULE)
assertThat(regular.moduleTypeName).isEqualTo(ModuleTypeId.JAVA_MODULE)
assertThat(imported.moduleFilePath).isEqualTo("${project.basePath}/imported.iml")
assertThat(regular.moduleFilePath).isEqualTo("${project.basePath}/regular.iml")
assertThat(ModuleRootManager.getInstance(imported).contentRootUrls.single()).isEqualTo(VfsUtil.pathToUrl("${project.basePath}/imported"))
assertThat(ModuleRootManager.getInstance(regular).contentRootUrls.single()).isEqualTo(VfsUtil.pathToUrl("${project.basePath}/regular"))
val externalModuleProperty = ExternalSystemModulePropertyManager.getInstance(imported)
assertThat(externalModuleProperty.isMavenized()).isTrue()
assertThat(externalModuleProperty.getLinkedProjectPath()).isEqualTo("${project.basePath}/imported")
assertThat(ExternalSystemModulePropertyManager.getInstance(regular).isMavenized()).isFalse()
}
@Test
fun `save regular facet in imported module`() = saveProjectInExternalStorageAndCheckResult("regularFacetInImportedModule") { project, projectDir ->
val imported = ModuleManager.getInstance(project).newModule(projectDir.resolve("imported.iml").systemIndependentPath, ModuleTypeId.JAVA_MODULE)
FacetManager.getInstance(imported).addFacet(MockFacetType.getInstance(), "regular", null)
ExternalSystemModulePropertyManager.getInstance(imported).setMavenized(true)
}
@Test
fun `load regular facet in imported module`() = loadProjectAndCheckResults("regularFacetInImportedModule") { project ->
val module = ModuleManager.getInstance(project).modules.single()
assertThat(module.name).isEqualTo("imported")
assertThat(ExternalSystemModulePropertyManager.getInstance(module).isMavenized()).isTrue()
val facet = FacetManager.getInstance(module).allFacets.single()
assertThat(facet.name).isEqualTo("regular")
assertThat(facet.type).isEqualTo(MockFacetType.getInstance())
assertThat(facet.externalSource).isNull()
}
@Test
fun `do not load modules from external system dir if external storage is disabled`() =
loadProjectAndCheckResults("externalStorageIsDisabled") { project ->
assertThat(ModuleManager.getInstance(project).modules).isEmpty()
}
@Test
fun `load modules from internal storage if external is disabled but file exist`() =
loadProjectAndCheckResults("singleModuleInInternalAndExternalStorages") { project ->
val modules = ModuleManager.getInstance(project).modules
assertThat(modules).hasSize(1)
val testModule= modules[0]
assertThat(testModule.name).isEqualTo("test")
assertThat(testModule.moduleTypeName).isEqualTo(ModuleTypeId.JAVA_MODULE)
assertThat(testModule.moduleFilePath).isEqualTo("${project.basePath}/test.iml")
assertThat(ModuleRootManager.getInstance(testModule).contentRootUrls.single()).isEqualTo(VfsUtil.pathToUrl("${project.basePath}/test"))
val externalModuleProperty = ExternalSystemModulePropertyManager.getInstance(testModule)
assertThat(externalModuleProperty.isMavenized()).isTrue()
}
@Test
fun `save imported facet in imported module`() = saveProjectInExternalStorageAndCheckResult("importedFacetInImportedModule") { project, projectDir ->
val imported = ModuleManager.getInstance(project).newModule(projectDir.resolve("imported.iml").systemIndependentPath, ModuleTypeId.JAVA_MODULE)
addFacet(imported, ExternalProjectSystemRegistry.MAVEN_EXTERNAL_SOURCE_ID, "imported")
ExternalSystemModulePropertyManager.getInstance(imported).setMavenized(true)
}
private fun addFacet(module: Module, externalSystemId: String?, facetName: String) {
val facetManager = FacetManager.getInstance(module)
val model = facetManager.createModifiableModel()
val source = externalSystemId?.let { ExternalProjectSystemRegistry.getInstance().getSourceById(it) }
model.addFacet(facetManager.createFacet(MockFacetType.getInstance(), facetName, null), source)
runWriteActionAndWait { model.commit() }
}
@Test
fun `edit imported facet in internal storage with regular facet`() {
assumeTrue(ProjectModelRule.isWorkspaceModelEnabled)
loadModifySaveAndCheck("singleModuleFromExternalSystemInInternalStorage", "mixedFacetsInInternalStorage") { project ->
val module = ModuleManager.getInstance(project).modules.single()
addFacet(module, null, "regular")
runBlocking { project.stateStore.save() }
addFacet(module, "GRADLE", "imported")
}
}
@Test
fun `edit regular facet in internal storage with imported facet`() {
assumeTrue(ProjectModelRule.isWorkspaceModelEnabled)
loadModifySaveAndCheck("singleModuleFromExternalSystemInInternalStorage", "mixedFacetsInInternalStorage") { project ->
val module = ModuleManager.getInstance(project).modules.single()
addFacet(module, "GRADLE", "imported")
runBlocking { project.stateStore.save() }
addFacet(module, null, "regular")
}
}
@Test
fun `edit imported facet in external storage with regular facet`() {
loadModifySaveAndCheck("singleModuleFromExternalSystem", "mixedFacetsInExternalStorage") { project ->
val module = ModuleManager.getInstance(project).modules.single()
addFacet(module, null, "regular")
runBlocking { project.stateStore.save() }
addFacet(module, "GRADLE", "imported")
}
}
@Test
fun `edit regular facet in external storage with imported facet`() {
loadModifySaveAndCheck("singleModuleFromExternalSystem", "mixedFacetsInExternalStorage") { project ->
val module = ModuleManager.getInstance(project).modules.single()
addFacet(module, "GRADLE", "imported")
runBlocking { project.stateStore.save() }
addFacet(module, null, "regular")
}
}
@Test
fun `load imported facet in imported module`() = loadProjectAndCheckResults("importedFacetInImportedModule") { project ->
val module = ModuleManager.getInstance(project).modules.single()
assertThat(ExternalSystemModulePropertyManager.getInstance(module).isMavenized()).isTrue()
val facet = FacetManager.getInstance(module).allFacets.single()
assertThat(facet.name).isEqualTo("imported")
assertThat(facet.externalSource!!.id).isEqualTo(ExternalProjectSystemRegistry.MAVEN_EXTERNAL_SOURCE_ID)
}
@Test
fun `save libraries`() = saveProjectInExternalStorageAndCheckResult("libraries") { project, _ ->
val libraryTable = LibraryTablesRegistrar.getInstance().getLibraryTable(project)
val model = libraryTable.modifiableModel
model.createLibrary("regular", null)
model.createLibrary("imported", null, externalSource)
model.commit()
}
@Test
fun `save libraries in internal storage`() = saveProjectInInternalStorageAndCheckResult("librariesInInternalStorage") { project, _ ->
val libraryTable = LibraryTablesRegistrar.getInstance().getLibraryTable(project)
val model = libraryTable.modifiableModel
model.createLibrary("regular", null)
model.createLibrary("imported", null, externalSource)
model.commit()
}
@Test
fun `load unloaded modules`() {
assumeTrue(ProjectModelRule.isWorkspaceModelEnabled)
loadProjectAndCheckResults("unloadedModules") { project ->
val unloadedModuleName = "imported"
val moduleManager = ModuleManager.getInstance(project)
val moduleDescription = moduleManager.getUnloadedModuleDescription(unloadedModuleName)
assertThat(moduleDescription).isNotNull
val contentRoots = moduleDescription!!.contentRoots
assertThat(contentRoots.size).isEqualTo(1)
assertThat(contentRoots[0].fileName).isEqualTo(unloadedModuleName)
}
}
@Test
fun `load libraries`() = loadProjectAndCheckResults("libraries") { project ->
val libraryTable = LibraryTablesRegistrar.getInstance().getLibraryTable(project)
runInEdtAndWait {
UIUtil.dispatchAllInvocationEvents()
}
val libraries = libraryTable.libraries.sortedBy { it.name }
assertThat(libraries).hasSize(2)
val (imported, regular) = libraries
assertThat(imported.name).isEqualTo("imported")
assertThat(regular.name).isEqualTo("regular")
assertThat(imported.externalSource!!.id).isEqualTo("test")
assertThat(regular.externalSource).isNull()
}
@Test
fun `save artifacts`() = saveProjectInExternalStorageAndCheckResult("artifacts") { project, projectDir ->
val model = ArtifactManager.getInstance(project).createModifiableModel()
val regular = model.addArtifact("regular", PlainArtifactType.getInstance())
regular.outputPath = projectDir.resolve("out/artifacts/regular").systemIndependentPath
val root = PackagingElementFactory.getInstance().createArchive("a.jar")
val imported = model.addArtifact("imported", PlainArtifactType.getInstance(), root, externalSource)
imported.outputPath = projectDir.resolve("out/artifacts/imported").systemIndependentPath
model.commit()
}
@Test
fun `load artifacts`() = loadProjectAndCheckResults("artifacts") { project ->
val artifacts = ArtifactManager.getInstance(project).sortedArtifacts
assertThat(artifacts).hasSize(2)
val (imported, regular) = artifacts
assertThat(imported.name).isEqualTo("imported")
assertThat(regular.name).isEqualTo("regular")
assertThat(imported.externalSource!!.id).isEqualTo("test")
assertThat(regular.externalSource).isNull()
assertThat(imported.outputPath).isEqualTo("${project.basePath}/out/artifacts/imported")
assertThat(regular.outputPath).isEqualTo("${project.basePath}/out/artifacts/regular")
assertThat((imported.rootElement as ArchivePackagingElement).name).isEqualTo("a.jar")
assertThat(regular.rootElement).isInstanceOf(ArtifactRootElement::class.java)
}
@Test
fun `mark module as mavenized`() {
assumeTrue(ProjectModelRule.isWorkspaceModelEnabled)
//after module is mavenized, we still store iml file with empty root tag inside; it would be better to delete the file in such cases,
// but it isn't simple to implement so let's leave it as is for now; and the old project model behaves in the same way.
loadModifySaveAndCheck("singleRegularModule", "singleModuleAfterMavenization") { project ->
val module = ModuleManager.getInstance(project).modules.single()
ExternalSystemModulePropertyManager.getInstance(module).setMavenized(true)
}
}
@Test
fun `remove regular module with enabled external storage`() {
loadModifySaveAndCheck("twoRegularModules", "twoRegularModulesAfterRemoval") { project ->
val moduleManager = ModuleManager.getInstance(project)
val module = moduleManager.findModuleByName("test2")
assertThat(module).isNotNull
runWriteActionAndWait {
moduleManager.disposeModule(module!!)
}
}
}
@Test
fun `change storeExternally property and save libraries to internal storage`() {
assumeTrue(ProjectModelRule.isWorkspaceModelEnabled)
loadModifySaveAndCheck("librariesInExternalStorage", "librariesAfterStoreExternallyPropertyChanged") { project ->
ExternalProjectsManagerImpl.getInstance(project).setStoreExternally(false)
}
}
@Test
fun `change storeExternally property several times`() {
assumeTrue(ProjectModelRule.isWorkspaceModelEnabled)
loadModifySaveAndCheck("librariesInExternalStorage", "librariesAfterStoreExternallyPropertyChanged") { project ->
ExternalProjectsManagerImpl.getInstance(project).setStoreExternally(false)
runBlocking { project.stateStore.save() }
ExternalProjectsManagerImpl.getInstance(project).setStoreExternally(true)
runBlocking { project.stateStore.save() }
ExternalProjectsManagerImpl.getInstance(project).setStoreExternally(false)
}
}
@Test
fun `remove library stored externally`() {
assumeTrue(ProjectModelRule.isWorkspaceModelEnabled)
loadModifySaveAndCheck("librariesInExternalStorage", "singleLibraryInExternalStorage") { project ->
val libraryTable = LibraryTablesRegistrar.getInstance().getLibraryTable(project)
runWriteActionAndWait {
libraryTable.removeLibrary(libraryTable.getLibraryByName("spring")!!)
libraryTable.removeLibrary(libraryTable.getLibraryByName("kotlin")!!)
}
}
}
@Test
fun `clean up iml file if we start store project model at external storage`() {
assumeTrue(ProjectModelRule.isWorkspaceModelEnabled)
loadModifySaveAndCheck("singleModule", "singleModuleAfterStoreExternallyPropertyChanged") { project ->
ExternalProjectsManagerImpl.getInstance(project).setStoreExternally(false)
runBlocking { project.stateStore.save() }
ExternalProjectsManagerImpl.getInstance(project).setStoreExternally(true)
}
}
@Test
fun `test facet and libraries saved in internal store after IDE reload`() {
assumeTrue(ProjectModelRule.isWorkspaceModelEnabled)
loadModifySaveAndCheck("singleModuleFacetAndLibFromExternalSystemInInternalStorage", "singleModuleFacetAndLibFromExternalSystem") { project ->
ExternalProjectsManagerImpl.getInstance(project).setStoreExternally(true)
}
}
@Test
fun `clean up facet tag in iml file if we start store project model at external storage`() {
assumeTrue(ProjectModelRule.isWorkspaceModelEnabled)
loadModifySaveAndCheck("importedFacetInImportedModule", "importedFacetAfterStoreExternallyPropertyChanged") { project ->
ExternalProjectsManagerImpl.getInstance(project).setStoreExternally(false)
runBlocking { project.stateStore.save() }
ExternalProjectsManagerImpl.getInstance(project).setStoreExternally(true)
}
}
@Test
fun `clean up external_build_system at saving data at idea folder`() {
assumeTrue(ProjectModelRule.isWorkspaceModelEnabled)
loadModifySaveAndCheck("singleModuleWithLibrariesInInternalStorage", "singleModuleWithLibrariesInInternalStorage") { project ->
ExternalProjectsManagerImpl.getInstance(project).setStoreExternally(true)
runBlocking { project.stateStore.save() }
ExternalProjectsManagerImpl.getInstance(project).setStoreExternally(false)
}
}
@Test
fun `check project model saved correctly at internal storage`() {
assumeTrue(ProjectModelRule.isWorkspaceModelEnabled)
loadModifySaveAndCheck("twoModulesWithLibsAndFacetsInExternalStorage", "twoModulesWithLibrariesAndFacets") { project ->
ExternalProjectsManagerImpl.getInstance(project).setStoreExternally(false)
}
}
@Test
fun `check project model saved correctly at internal storage after misc manual modification`() {
assumeTrue(ProjectModelRule.isWorkspaceModelEnabled)
loadModifySaveAndCheck("twoModulesWithLibsAndFacetsInExternalStorage", "twoModulesWithLibrariesAndFacets") { project ->
val miscFile = File(project.projectFilePath!!)
miscFile.writeText("""
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_8" />
</project>
""".trimIndent())
WriteAction.runAndWait<RuntimeException> {
VfsUtil.markDirtyAndRefresh(false, false, false, miscFile)
StoreReloadManager.getInstance().flushChangedProjectFileAlarm()
}
}
}
@Test
fun `check project model saved correctly at external storage after misc manual modification`() {
assumeTrue(ProjectModelRule.isWorkspaceModelEnabled)
loadModifySaveAndCheck("twoModulesWithLibrariesAndFacets", "twoModulesInExtAndLibsAndFacetsInInternalStorage") { project ->
val miscFile = File(project.projectFilePath!!)
miscFile.writeText("""
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_8" />
</project>
""".trimIndent())
WriteAction.runAndWait<RuntimeException> {
VfsUtil.markDirtyAndRefresh(false, false, false, miscFile)
StoreReloadManager.getInstance().flushChangedProjectFileAlarm()
}
}
}
@Test
fun `external-system-id attributes are not removed from libraries, artifacts and facets on save`() {
assumeTrue(ProjectModelRule.isWorkspaceModelEnabled)
loadModifySaveAndCheck("elementsWithExternalSystemIdAttributes", "elementsWithExternalSystemIdAttributes") { project ->
JpsProjectModelSynchronizer.getInstance(project)!!.markAllEntitiesAsDirty()
}
}
@Test
fun `incorrect modules setup`() {
suppressLogs {
loadProjectAndCheckResults("incorrectModulesSetupDifferentIml") { project ->
val modules = ModuleManager.getInstance(project).modules
assertEquals(1, modules.size)
}
}
}
@Test
fun `incorrect modules setup same iml`() {
loadProjectAndCheckResults("incorrectModulesSetupSameIml") { project ->
val modules = ModuleManager.getInstance(project).modules
assertEquals(1, modules.size)
}
}
@Test
fun `incorrect modules setup with facet`() {
suppressLogs {
loadProjectAndCheckResults("incorrectModulesSetupWithFacet") { project ->
val modules = ModuleManager.getInstance(project).modules
assertEquals(1, modules.size)
val facets = FacetManager.getInstance(modules.single()).allFacets
assertEquals(1, facets.size)
}
}
}
@Before
fun registerFacetType() {
WriteAction.runAndWait<RuntimeException> {
FacetType.EP_NAME.getPoint().registerExtension(MockFacetType(), disposableRule.disposable)
FacetType.EP_NAME.getPoint().registerExtension(MockSubFacetType(), disposableRule.disposable)
}
}
private val externalSource get() = ExternalProjectSystemRegistry.getInstance().getSourceById("test")
private fun saveProjectInInternalStorageAndCheckResult(testDataDirName: String, setupProject: (Project, Path) -> Unit) {
doNotEnableExternalStorageByDefaultInTests {
saveProjectAndCheckResult(testDataDirName, false, setupProject)
}
}
private fun saveProjectInExternalStorageAndCheckResult(testDataDirName: String, setupProject: (Project, Path) -> Unit) {
saveProjectAndCheckResult(testDataDirName, true, setupProject)
}
private fun saveProjectAndCheckResult(testDataDirName: String,
storeExternally: Boolean,
setupProject: (Project, Path) -> Unit) {
runBlocking {
createProjectAndUseInLoadComponentStateMode(tempDirManager, directoryBased = true, useDefaultProjectSettings = false) { project ->
ExternalProjectsManagerImpl.getInstance(project).setStoreExternally(storeExternally)
val projectDir = project.stateStore.directoryStorePath!!.parent
val cacheDir = ExternalProjectsDataStorage.getProjectConfigurationDir(project)
cacheDir.delete()
runBlocking {
withContext(AppUIExecutor.onWriteThread().coroutineDispatchingContext()) {
runWriteAction {
//we need to set language level explicitly because otherwise if some tests modifies language level in the default project, we'll
// get different content in misc.xml
LanguageLevelProjectExtension.getInstance(project)!!.languageLevel = LanguageLevel.JDK_1_8
setupProject(project, projectDir)
}
}
}
saveAndCompare(project, testDataDirName)
}
}
}
private fun saveAndCompare(project: Project, dataDirNameToCompareWith: String) {
val cacheDir = ExternalProjectsDataStorage.getProjectConfigurationDir(project)
Disposer.register(disposableRule.disposable, Disposable { cacheDir.delete() })
runBlocking {
project.stateStore.save()
}
val expectedDir = tempDirManager.newPath("expectedStorage")
FileUtil.copyDir(testDataRoot.resolve("common").toFile(), expectedDir.toFile())
FileUtil.copyDir(testDataRoot.resolve(dataDirNameToCompareWith).toFile(), expectedDir.toFile())
val projectDir = project.stateStore.directoryStorePath!!.parent
projectDir.toFile().assertMatches(directoryContentOf(expectedDir.resolve("project")))
val expectedCacheDir = expectedDir.resolve("cache")
if (Files.exists(expectedCacheDir)) {
cacheDir.toFile().assertMatches(directoryContentOf(expectedCacheDir), FileTextMatcher.ignoreBlankLines())
}
else {
assertTrue("$cacheDir doesn't exist", !Files.exists(cacheDir) || isFolderWithoutFiles(cacheDir.toFile()))
}
}
private fun loadModifySaveAndCheck(dataDirNameToLoad: String, dataDirNameToCompareWith: String, modifyProject: (Project) -> Unit) {
loadProjectAndCheckResults(dataDirNameToLoad) { project ->
modifyProject(project)
saveAndCompare(project, dataDirNameToCompareWith)
}
}
private val testDataRoot
get() = Paths.get(PathManagerEx.getCommunityHomePath()).resolve("platform/external-system-impl/testData/jpsSerialization")
private fun loadProjectAndCheckResults(testDataDirName: String, checkProject: (Project) -> Unit) {
@Suppress("RedundantSuspendModifier")
suspend fun copyProjectFiles(dir: VirtualFile): Path {
val projectDir = VfsUtil.virtualToIoFile(dir)
FileUtil.copyDir(testDataRoot.resolve("common/project").toFile(), projectDir)
val testProjectFilesDir = testDataRoot.resolve(testDataDirName).resolve("project").toFile()
if (testProjectFilesDir.exists()) {
FileUtil.copyDir(testProjectFilesDir, projectDir)
}
val testCacheFilesDir = testDataRoot.resolve(testDataDirName).resolve("cache").toFile()
if (testCacheFilesDir.exists()) {
val cachePath = appSystemDir.resolve("external_build_system").resolve(getProjectCacheFileName(dir.toNioPath()))
FileUtil.copyDir(testCacheFilesDir, cachePath.toFile())
}
VfsUtil.markDirtyAndRefresh(false, true, true, dir)
return projectDir.toPath()
}
doNotEnableExternalStorageByDefaultInTests {
runBlocking {
createOrLoadProject(tempDirManager, ::copyProjectFiles, loadComponentState = true, useDefaultProjectSettings = false) {
checkProject(it)
}
}
}
}
private fun isFolderWithoutFiles(root: File): Boolean = root.walk().none { it.isFile }
private inline fun suppressLogs(action: () -> Unit) {
val oldInstance = LoggedErrorProcessor.getInstance()
try {
LoggedErrorProcessor.setNewInstance(object : LoggedErrorProcessor() {
override fun processError(message: String?, t: Throwable?, details: Array<out String>?, logger: Logger) {
}
})
action()
}
finally {
LoggedErrorProcessor.setNewInstance(oldInstance)
}
}
} | apache-2.0 | 3e69184b298fb2d1655bbd5fbf8ec3c2 | 47.630404 | 190 | 0.760404 | 5.293305 | false | true | false | false |
aporter/coursera-android | ExamplesKotlin/FragmentDynamicLayout/app/src/main/java/course/examples/fragments/dynamiclayout/QuoteViewerActivity.kt | 1 | 6186 | package course.examples.fragments.dynamiclayout
import android.os.Bundle
import android.support.v4.app.FragmentActivity
import android.support.v4.app.FragmentManager
import android.util.Log
import android.widget.FrameLayout
import android.widget.LinearLayout
//Several Activity lifecycle methods are instrumented to emit LogCat output
//so you can follow this class' lifecycle
class QuoteViewerActivity : FragmentActivity(), ListSelectionListener {
companion object {
private const val MATCH_PARENT = LinearLayout.LayoutParams.MATCH_PARENT
private const val TAG = "QuoteViewerActivity"
lateinit var mTitleArray: Array<String>
lateinit var mQuoteArray: Array<String>
}
private var mQuoteFragment: QuotesFragment? = null
private var mTitleFragment: TitlesFragment? = null
private lateinit var mFragmentManager: FragmentManager
private lateinit var mTitleFrameLayout: FrameLayout
private lateinit var mQuotesFrameLayout: FrameLayout
override fun onCreate(savedInstanceState: Bundle?) {
Log.i(TAG, "${javaClass.simpleName}: entered onCreate()")
super.onCreate(savedInstanceState)
// Get the string arrays with the titles and quotes
mTitleArray = resources.getStringArray(R.array.Titles)
mQuoteArray = resources.getStringArray(R.array.Quotes)
setContentView(R.layout.main)
// Get references to the TitleFragment and to the QuotesFragment containers
mTitleFrameLayout = findViewById(R.id.title_fragment_container)
mQuotesFrameLayout = findViewById(R.id.quote_fragment_container)
// Get a reference to the FragmentManager
mFragmentManager = supportFragmentManager
mQuoteFragment =
mFragmentManager.findFragmentById(R.id.quote_fragment_container) as QuotesFragment?
mTitleFragment =
mFragmentManager.findFragmentById(R.id.title_fragment_container) as TitlesFragment?
if (null == mFragmentManager.findFragmentById(R.id.title_fragment_container)) {
mTitleFragment = TitlesFragment()
mTitleFragment?.let {mTitleFragment ->
// Start a new FragmentTransaction
val fragmentTransaction = mFragmentManager
.beginTransaction()
// Add the TitleFragment to the layout
fragmentTransaction.add(
R.id.title_fragment_container,
mTitleFragment
)
// Commit the FragmentTransaction
fragmentTransaction.commit()
}
}
// Set layout parameters
setLayout()
// Add a OnBackStackChangedListener to reset the layout when the back stack changes
mFragmentManager
.addOnBackStackChangedListener { layoutAfterBackStackedChanged() }
}
private fun layoutAfterBackStackedChanged() {
// If backed up to single pane display uncheck any checked titles
if (null == mFragmentManager.findFragmentById(R.id.quote_fragment_container)) {
mTitleFragment?.unCheckSelection()
}
// Set layout parameters
setLayout()
}
private fun setLayout() {
// Determine whether the QuoteFragment has been created
if (null == mFragmentManager.findFragmentById(R.id.quote_fragment_container)) {
// Make the TitleFragment occupy the entire layout
mTitleFrameLayout.layoutParams = LinearLayout.LayoutParams(
MATCH_PARENT, MATCH_PARENT
)
mQuotesFrameLayout.layoutParams = LinearLayout.LayoutParams(
0,
MATCH_PARENT
)
} else {
// Make the TitleLayout take 1/3 of the layout's width
mTitleFrameLayout.layoutParams = LinearLayout.LayoutParams(
0,
MATCH_PARENT, 1f
)
// Make the QuoteLayout take 2/3's of the layout's width
mQuotesFrameLayout.layoutParams = LinearLayout.LayoutParams(
0,
MATCH_PARENT, 2f
)
}
}
// Called when the user selects an item in the TitlesFragment
override fun onListSelection(index: Int) {
// If the QuoteFragment has not been created, create and add it now
if (null == mFragmentManager.findFragmentById(R.id.quote_fragment_container)) {
mQuoteFragment = QuotesFragment()
mQuoteFragment?.let {mQuoteFragment ->
// Start a new FragmentTransaction
val fragmentTransaction = mFragmentManager
.beginTransaction()
// Add the QuoteFragment to the layout
fragmentTransaction.add(
R.id.quote_fragment_container,
mQuoteFragment
)
// Add this FragmentTransaction to the backstack
fragmentTransaction.addToBackStack(null)
// Commit the FragmentTransaction
fragmentTransaction.commit()
// Force Android to execute the committed FragmentTransaction
mFragmentManager.executePendingTransactions()
}
}
// Tell the QuoteFragment to show the quote string at position index
mQuoteFragment?.showQuoteAtIndex(index)
}
override fun onDestroy() {
Log.i(TAG, "${javaClass.simpleName}: entered onDestroy()")
super.onDestroy()
}
override fun onPause() {
Log.i(TAG, "${javaClass.simpleName}: entered onPause()")
super.onPause()
}
override fun onRestart() {
Log.i(TAG, "${javaClass.simpleName}: entered onRestart()")
super.onRestart()
}
override fun onResume() {
Log.i(TAG, "${javaClass.simpleName}: entered onResume()")
super.onResume()
}
override fun onStart() {
Log.i(TAG, "${javaClass.simpleName}: entered onStart()")
super.onStart()
}
override fun onStop() {
Log.i(TAG, "${javaClass.simpleName}: entered onStop()")
super.onStop()
}
} | mit | 040808dad5633dd9cad05edc8bd4a597 | 31.563158 | 95 | 0.633042 | 5.45022 | false | false | false | false |
CORDEA/MackerelClient | app/src/main/java/jp/cordea/mackerelclient/activity/ServiceMetricsActivity.kt | 1 | 5281 | package jp.cordea.mackerelclient.activity
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.isVisible
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import dagger.Lazy
import dagger.android.AndroidInjection
import dagger.android.AndroidInjector
import dagger.android.DispatchingAndroidInjector
import dagger.android.support.HasSupportFragmentInjector
import io.reactivex.disposables.SerialDisposable
import jp.cordea.mackerelclient.ListItemDecoration
import jp.cordea.mackerelclient.MetricsType
import jp.cordea.mackerelclient.R
import jp.cordea.mackerelclient.adapter.MetricsAdapter
import jp.cordea.mackerelclient.databinding.ActivityServiceMetricsBinding
import jp.cordea.mackerelclient.databinding.ContentServiceMetricsBinding
import jp.cordea.mackerelclient.fragment.MetricsDeleteConfirmDialogFragment
import jp.cordea.mackerelclient.viewmodel.ServiceMetricsViewModel
import javax.inject.Inject
class ServiceMetricsActivity : AppCompatActivity(),
HasSupportFragmentInjector,
MetricsDeleteConfirmDialogFragment.OnDeleteMetricsListener {
@Inject
lateinit var dispatchingAndroidInjector: DispatchingAndroidInjector<Fragment>
@Inject
lateinit var viewModelProvider: Lazy<ServiceMetricsViewModel>
private val disposable = SerialDisposable()
private val viewModel get() = viewModelProvider.get()
private var enableRefresh = false
private lateinit var serviceName: String
private lateinit var adapter: MetricsAdapter
private lateinit var contentBinding: ContentServiceMetricsBinding
override fun onCreate(savedInstanceState: Bundle?) {
AndroidInjection.inject(this)
super.onCreate(savedInstanceState)
val binding = DataBindingUtil.setContentView<ActivityServiceMetricsBinding>(
this,
R.layout.activity_service_metrics
)
contentBinding = binding.content
supportActionBar?.setDisplayHomeAsUpEnabled(true)
serviceName = intent.getStringExtra(SERVICE_NAME_KEY)
adapter = MetricsAdapter(this, MetricsType.SERVICE, serviceName)
contentBinding.recyclerView.adapter = adapter
contentBinding.recyclerView.addItemDecoration(ListItemDecoration(this))
contentBinding.recyclerView.layoutManager = LinearLayoutManager(this)
contentBinding.swipeRefresh.setOnRefreshListener {
if (enableRefresh) {
refresh(true)
}
contentBinding.swipeRefresh.isRefreshing = false
}
if (savedInstanceState == null) {
viewModel.start(serviceName)
}
refresh(false)
}
override fun onDestroy() {
super.onDestroy()
disposable.dispose()
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.metric, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == MetricsEditActivity.REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
refresh(true)
}
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> finish()
R.id.action_add -> {
val intent = MetricsEditActivity
.createIntent(this, MetricsType.SERVICE, serviceName)
startActivityForResult(intent, MetricsEditActivity.REQUEST_CODE)
}
}
return super.onOptionsItemSelected(item)
}
override fun onDelete(id: Int) {
viewModel.removeBy(id)
refresh(false)
}
override fun supportFragmentInjector(): AndroidInjector<Fragment> = dispatchingAndroidInjector
private fun refresh(forceRefresh: Boolean) {
enableRefresh = false
adapter.clear()
if (viewModel.isExistsMetricsDefinition) {
contentBinding.noticeContainer.isVisible = false
contentBinding.progress.isVisible = true
contentBinding.swipeRefresh.isVisible = true
} else {
contentBinding.noticeContainer.isVisible = true
contentBinding.progress.isVisible = false
contentBinding.swipeRefresh.isVisible = false
return
}
viewModel
.fetchMetrics(forceRefresh)
.subscribe({
adapter.add(it)
}, {}, {
contentBinding.progress.isVisible = false
enableRefresh = true
})
.run(disposable::set)
}
companion object {
private const val SERVICE_NAME_KEY = "ServiceNameKey"
fun createIntent(context: Context, name: String): Intent =
Intent(context, ServiceMetricsActivity::class.java).apply {
putExtra(ServiceMetricsActivity.SERVICE_NAME_KEY, name)
}
}
}
| apache-2.0 | 298143e1452c717174926cbf80d2b04b | 34.206667 | 98 | 0.701572 | 5.405322 | false | false | false | false |
moko256/twicalico | app/src/main/java/com/github/moko256/twitlatte/database/CachedUsersSQLiteOpenHelper.kt | 1 | 7759 | /*
* Copyright 2015-2019 The twitlatte 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 com.github.moko256.twitlatte.database
import android.content.ContentValues
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import com.github.moko256.latte.client.base.entity.AccessToken
import com.github.moko256.latte.client.base.entity.Emoji
import com.github.moko256.latte.client.base.entity.User
import com.github.moko256.latte.html.entity.Link
import com.github.moko256.twitlatte.database.utils.*
import com.github.moko256.twitlatte.text.splitWithComma
import java.io.File
import java.util.*
/**
* Created by moko256 on 2017/03/17.
*
* @author moko256
*/
class CachedUsersSQLiteOpenHelper(context: Context, accessToken: AccessToken?) : SQLiteOpenHelper(context, if (accessToken != null) File(context.cacheDir, accessToken.getKeyString() + "/" + "CachedUsers.db").absolutePath else null, null, 3) {
private companion object {
private const val TABLE_NAME = "CachedUsers"
private val TABLE_COLUMNS = arrayOf(
"id",
"name",
"screenName",
"location",
"description",
"profileImageURLHttps",
"url",
"isProtected",
"followersCount",
"friendsCount",
"createdAt",
"favoritesCount",
"profileBannerImageUrl",
"statusesCount",
"isVerified",
"urls_urls",
"urls_starts",
"urls_ends",
"Emoji_shortcodes",
"Emoji_urls"
)
}
override fun onCreate(db: SQLiteDatabase) {
db.createTableWithUniqueIntKey(TABLE_NAME, TABLE_COLUMNS, 0 /*TABLE_COLUMNS.indexOf("id")*/)
}
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
if (oldVersion < 3) {
db.execSQL("drop table CachedStatuses")
onCreate(db)
}
}
fun getCachedUser(id: Long): User? {
return read {
selectSingleOrNull(
TABLE_NAME,
TABLE_COLUMNS,
"id=$id"
) {
User(
id = getLong(0),
name = getString(1),
screenName = getString(2),
location = getString(3),
description = getString(4),
profileImageURLHttps = getString(5),
url = getString(6),
isProtected = getBoolean(7),
followersCount = getInt(8),
favoritesCount = getInt(9),
friendsCount = getInt(10),
createdAt = Date(getLong(11)),
profileBannerImageUrl = getString(12),
statusesCount = getInt(13),
isVerified = getBoolean(14),
descriptionLinks = restoreLinks(
getString(15).splitWithComma(),
getString(16).splitWithComma(),
getString(17).splitWithComma()
),
emojis = restoreEmojis(
getString(18).splitWithComma(),
getString(19).splitWithComma()
)
)
}
}
}
fun addCachedUser(user: User) {
transaction {
addCachedUserAtTransaction(this, user)
}
}
fun addCachedUsers(users: Collection<User>) {
transaction {
for (user in users) {
addCachedUserAtTransaction(this, user)
}
}
}
private fun addCachedUserAtTransaction(database: SQLiteDatabase, user: User) {
val contentValues = ContentValues(TABLE_COLUMNS.size)
contentValues.put(TABLE_COLUMNS[0], user.id)
contentValues.put(TABLE_COLUMNS[1], user.name)
contentValues.put(TABLE_COLUMNS[2], user.screenName)
contentValues.put(TABLE_COLUMNS[3], user.location)
contentValues.put(TABLE_COLUMNS[4], user.description)
contentValues.put(TABLE_COLUMNS[5], user.profileImageURLHttps)
contentValues.put(TABLE_COLUMNS[6], user.url)
contentValues.put(TABLE_COLUMNS[7], user.isProtected)
contentValues.put(TABLE_COLUMNS[8], user.followersCount)
contentValues.put(TABLE_COLUMNS[9], user.favoritesCount)
contentValues.put(TABLE_COLUMNS[10], user.friendsCount)
contentValues.put(TABLE_COLUMNS[11], user.createdAt.time)
contentValues.put(TABLE_COLUMNS[12], user.profileBannerImageUrl)
contentValues.put(TABLE_COLUMNS[13], user.statusesCount)
contentValues.put(TABLE_COLUMNS[14], user.isVerified)
val descriptionLinks = user.descriptionLinks
if (descriptionLinks != null) {
val size = descriptionLinks.size
val urls = arrayOfNulls<String>(size)
val starts = arrayOfNulls<String>(size)
val ends = arrayOfNulls<String>(size)
descriptionLinks.forEachIndexed { i, entity ->
urls[i] = entity.url
starts[i] = entity.start.toString()
ends[i] = entity.end.toString()
}
contentValues.put(TABLE_COLUMNS[15], urls.joinToString(","))
contentValues.put(TABLE_COLUMNS[16], starts.joinToString(","))
contentValues.put(TABLE_COLUMNS[17], ends.joinToString(","))
}
val emojis = user.emojis
if (emojis != null) {
val listSize = emojis.size
val shortCodes = arrayOfNulls<String>(listSize)
val urls = arrayOfNulls<String>(listSize)
emojis.forEachIndexed { i, emoji ->
shortCodes[i] = emoji.shortCode
urls[i] = emoji.url
}
contentValues.put(TABLE_COLUMNS[18], shortCodes.joinToString(","))
contentValues.put(TABLE_COLUMNS[19], urls.joinToString(","))
}
database.replace(TABLE_NAME, null, contentValues)
}
fun deleteCachedUser(id: Long) {
write {
delete(TABLE_NAME, "id=$id", null)
}
}
private fun restoreLinks(
urls: List<String>?,
starts: List<String>?,
ends: List<String>?
): Array<Link>? = if (urls != null
&& starts != null
&& starts.size == urls.size
&& ends != null
&& ends.size == urls.size) {
Array(urls.size) {
Link(
url = urls[it],
start = starts[it].toInt(),
end = ends[it].toInt()
)
}
} else {
null
}
private fun restoreEmojis(shortCodes: List<String>?,
urls: List<String>?): Array<Emoji>? =
if (shortCodes != null && urls != null) {
Array(shortCodes.size) {
Emoji(shortCodes[it], urls[it])
}
} else {
null
}
} | apache-2.0 | 9d2bdad3e93eb211ac52b6a7d23e988a | 34.760369 | 242 | 0.559479 | 4.713852 | false | false | false | false |
leafclick/intellij-community | plugins/groovy/src/org/jetbrains/plugins/groovy/ext/logback/util.kt | 1 | 3148 | // Copyright 2000-2018 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.plugins.groovy.ext.logback
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiRecursiveElementWalkingVisitor
import com.intellij.psi.util.CachedValueProvider.Result
import com.intellij.psi.util.CachedValuesManager
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrLiteral
import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GroovyScriptClass
import org.jetbrains.plugins.groovy.lang.psi.patterns.GroovyPatterns.groovyLiteralExpression
import org.jetbrains.plugins.groovy.lang.psi.patterns.psiMethod
import org.jetbrains.plugins.groovy.lang.resolve.imports.*
internal const val configName = "logback.groovy"
internal const val configDelegateFqn = "ch.qos.logback.classic.gaffer.ConfigurationDelegate"
internal const val componentDelegateFqn = "ch.qos.logback.classic.gaffer.ComponentDelegate"
internal val appenderMethodPattern = psiMethod(configDelegateFqn, "appender")
internal val appenderDeclarationPattern = groovyLiteralExpression().methodCallParameter(0, appenderMethodPattern)
internal fun PsiClass?.isLogbackConfig() = this is GroovyScriptClass && this.containingFile.isLogbackConfig()
internal fun PsiFile?.isLogbackConfig() = this?.originalFile?.virtualFile?.name == configName
internal fun PsiElement.isBefore(other: PsiElement) = textRange.startOffset < other.textRange.startOffset
internal val PsiFile.appenderDeclarations: Map<String, GrLiteral> get() = CachedValuesManager.getCachedValue(this) {
Result.create(computeAppenderDeclarations(), this)
}
private fun PsiFile.computeAppenderDeclarations(): Map<String, GrLiteral> {
val result = mutableMapOf<String, GrLiteral>()
val visitor = object : PsiRecursiveElementWalkingVisitor() {
override fun visitElement(currentElement: PsiElement) {
super.visitElement(currentElement)
if (appenderDeclarationPattern.accepts(currentElement)) {
val literal = currentElement as GrLiteral
val literalValue = literal.value as? String ?: return
if (!result.containsKey(literalValue)) result.put(literalValue, literal)
}
}
}
accept(visitor)
return result
}
/**
* see ch.qos.logback.classic.gaffer.GafferConfigurator#importCustomizer()
*/
internal fun buildImports(): List<GroovyImport> {
val packageImports = arrayOf(
"ch.qos.logback.core",
"ch.qos.logback.core.encoder",
"ch.qos.logback.core.read",
"ch.qos.logback.core.rolling",
"ch.qos.logback.core.status",
"ch.qos.logback.classic.net"
)
val levelFqn = "ch.qos.logback.classic.Level"
val levels = arrayOf("OFF", "ERROR", "WARN", "INFO", "DEBUG", "TRACE", "ALL")
return mutableListOf<GroovyImport>().apply {
packageImports.mapTo(this, ::StarImport)
this += RegularImport("ch.qos.logback.classic.encoder.PatternLayoutEncoder")
this += StaticStarImport(levelFqn)
levels.mapTo(this) {
StaticImport(levelFqn, it, it.toLowerCase())
}
}
}
| apache-2.0 | 2644c820491f548b0bf0b27bf307ee48 | 43.338028 | 140 | 0.776366 | 4.153034 | false | true | false | false |
zdary/intellij-community | platform/platform-impl/src/com/intellij/ide/plugins/marketplace/MarketplaceRequests.kt | 1 | 18112 | // Copyright 2000-2021 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.ide.plugins.marketplace
import com.fasterxml.jackson.core.type.TypeReference
import com.fasterxml.jackson.databind.ObjectMapper
import com.intellij.ide.IdeBundle
import com.intellij.ide.plugins.PluginInfoProvider
import com.intellij.ide.plugins.PluginNode
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.application.impl.ApplicationInfoImpl
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.util.BuildNumber
import com.intellij.util.Url
import com.intellij.util.Urls
import com.intellij.util.concurrency.annotations.RequiresBackgroundThread
import com.intellij.util.io.HttpRequests
import com.intellij.util.io.URLUtil
import com.intellij.util.io.exists
import com.intellij.util.io.write
import com.intellij.util.ui.IoErrorText
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.Nls
import org.xml.sax.InputSource
import org.xml.sax.SAXException
import java.io.IOException
import java.io.Reader
import java.net.HttpURLConnection
import java.net.URLConnection
import java.nio.file.Files
import java.nio.file.NoSuchFileException
import java.nio.file.Path
import java.nio.file.Paths
import java.util.concurrent.Callable
import java.util.concurrent.Future
import javax.xml.parsers.ParserConfigurationException
import javax.xml.parsers.SAXParserFactory
private val LOG = logger<MarketplaceRequests>()
private const val FULL_PLUGINS_XML_IDS_FILENAME = "pluginsXMLIds.json"
@ApiStatus.Internal
class MarketplaceRequests : PluginInfoProvider {
companion object {
@JvmStatic
val Instance
get() = PluginInfoProvider.getInstance() as MarketplaceRequests
@JvmStatic
fun parsePluginList(reader: Reader): List<PluginNode> {
try {
val parser = SAXParserFactory.newInstance().newSAXParser()
val handler = RepositoryContentHandler()
parser.parse(InputSource(reader), handler)
return handler.pluginsList
}
catch (e: Exception) {
when (e) {
is ParserConfigurationException, is SAXException, is RuntimeException -> throw IOException(e)
else -> throw e
}
}
}
}
private val applicationInfo
get() = ApplicationInfoImpl.getShadowInstanceImpl()
private val PLUGIN_MANAGER_URL = applicationInfo.pluginManagerUrl.trimEnd('/')
private val IDE_BUILD_FOR_REQUEST = URLUtil.encodeURIComponent(applicationInfo.pluginsCompatibleBuild)
private val MARKETPLACE_ORGANIZATIONS_URL = Urls.newFromEncoded("${PLUGIN_MANAGER_URL}/api/search/aggregation/organizations")
.addParameters(mapOf("build" to IDE_BUILD_FOR_REQUEST))
private val JETBRAINS_PLUGINS_URL = Urls.newFromEncoded(
"${PLUGIN_MANAGER_URL}/api/search/plugins?organization=JetBrains&max=1000"
).addParameters(mapOf("build" to IDE_BUILD_FOR_REQUEST))
private val COMPATIBLE_UPDATE_URL = "${PLUGIN_MANAGER_URL}/api/search/compatibleUpdates"
private val objectMapper by lazy { ObjectMapper() }
private fun getUpdatesMetadataFilesDirectory(): Path = Paths.get(PathManager.getPluginsPath(), "meta")
internal fun getBrokenPluginsFile(): Path = Paths.get(PathManager.getPluginsPath(), "brokenPlugins.json")
private fun getUpdateMetadataFile(update: IdeCompatibleUpdate): Path {
return getUpdatesMetadataFilesDirectory().resolve(update.externalUpdateId + ".json")
}
private fun getUpdateMetadataUrl(update: IdeCompatibleUpdate): String {
return "${PLUGIN_MANAGER_URL}/files/${update.externalPluginId}/${update.externalUpdateId}/meta.json"
}
private fun createSearchUrl(query: String, count: Int): Url {
return Urls.newFromEncoded("$PLUGIN_MANAGER_URL/api/search/plugins?$query&build=$IDE_BUILD_FOR_REQUEST&max=$count")
}
private fun createFeatureUrl(param: Map<String, String>): Url {
return Urls.newFromEncoded("${PLUGIN_MANAGER_URL}/feature/getImplementations").addParameters(param)
}
fun getFeatures(param: Map<String, String>): List<FeatureImpl> {
if (param.isEmpty()) {
return emptyList()
}
try {
return HttpRequests
.request(createFeatureUrl(param))
.throwStatusCodeException(false)
.productNameAsUserAgent()
.connect {
objectMapper.readValue(
it.inputStream,
object : TypeReference<List<FeatureImpl>>() {}
)
}
}
catch (e: Exception) {
logWarnOrPrintIfDebug("Can not get features from Marketplace", e)
return emptyList()
}
}
internal fun getFeatures(
featureType: String,
implementationName: String,
): List<FeatureImpl> {
val param = mapOf(
"featureType" to featureType,
"implementationName" to implementationName,
"build" to applicationInfo.pluginsCompatibleBuild,
)
return getFeatures(param)
}
@RequiresBackgroundThread
@JvmOverloads
@Throws(IOException::class)
fun getMarketplacePlugins(indicator: ProgressIndicator? = null): Set<PluginId> {
return readOrUpdateFile(
Paths.get(PathManager.getPluginsPath(), FULL_PLUGINS_XML_IDS_FILENAME),
"${PLUGIN_MANAGER_URL}/files/$FULL_PLUGINS_XML_IDS_FILENAME",
indicator,
IdeBundle.message("progress.downloading.available.plugins"),
::parseXmlIds,
)
}
override fun loadPlugins(indicator: ProgressIndicator?): Future<Set<PluginId>> {
return ApplicationManager.getApplication().executeOnPooledThread(Callable {
try {
getMarketplacePlugins(indicator)
}
catch (e: IOException) {
logWarnOrPrintIfDebug("Cannot get plugins from Marketplace", e)
emptySet()
}
})
}
override fun loadCachedPlugins(): Set<PluginId>? {
val pluginXmlIdsFile = Paths.get(PathManager.getPluginsPath(), FULL_PLUGINS_XML_IDS_FILENAME)
try {
if (Files.size(pluginXmlIdsFile) > 0) {
return Files.newBufferedReader(pluginXmlIdsFile).use(::parseXmlIds)
}
}
catch (ignore: IOException) {
}
return null
}
@Throws(IOException::class)
fun searchPlugins(query: String, count: Int): List<PluginNode> {
val marketplaceSearchPluginData = HttpRequests.request(createSearchUrl(query, count))
.throwStatusCodeException(false)
.connect {
objectMapper.readValue(
it.inputStream,
object : TypeReference<List<MarketplaceSearchPluginData>>() {}
)
}
// Marketplace Search Service can produce objects without "externalUpdateId". It means that an update is not in the search index yet.
return marketplaceSearchPluginData.filter { it.externalUpdateId != null }.map { it.toPluginNode() }
}
fun getAllPluginsVendors(): List<String> {
try {
return HttpRequests
.request(MARKETPLACE_ORGANIZATIONS_URL)
.productNameAsUserAgent()
.throwStatusCodeException(false)
.connect {
objectMapper.readValue(it.inputStream, AggregationSearchResponse::class.java).aggregations.keys.toList()
}
}
catch (e: Exception) {
logWarnOrPrintIfDebug("Can not get organizations from Marketplace", e)
return emptyList()
}
}
fun getBrokenPlugins(currentBuild: BuildNumber): Map<PluginId, Set<String>> {
val brokenPlugins = try {
readOrUpdateFile(
getBrokenPluginsFile(),
"${PLUGIN_MANAGER_URL}/files/brokenPlugins.json",
null,
""
) { objectMapper.readValue(it, object : TypeReference<List<MarketplaceBrokenPlugin>>() {}) }
}
catch (e: Exception) {
logWarnOrPrintIfDebug("Can not get broken plugins file from Marketplace", e)
return emptyMap()
}
val brokenPluginsMap = HashMap<PluginId, MutableSet<String>>()
brokenPlugins.forEach { record ->
try {
val parsedOriginalUntil = record.originalUntil?.trim()
val parsedOriginalSince = record.originalSince?.trim()
if (!parsedOriginalUntil.isNullOrEmpty() && !parsedOriginalSince.isNullOrEmpty()) {
val originalUntil = BuildNumber.fromString(parsedOriginalUntil, record.id, null) ?: currentBuild
val originalSince = BuildNumber.fromString(parsedOriginalSince, record.id, null) ?: currentBuild
val until = BuildNumber.fromString(record.until) ?: currentBuild
val since = BuildNumber.fromString(record.since) ?: currentBuild
if (currentBuild in originalSince..originalUntil && currentBuild !in since..until) {
brokenPluginsMap.computeIfAbsent(PluginId.getId(record.id)) { HashSet() }.add(record.version)
}
}
}
catch (e: Exception) {
LOG.error("cannot parse ${record}", e)
}
}
return brokenPluginsMap
}
fun getAllPluginsTags(): List<String> {
try {
return HttpRequests
.request(Urls.newFromEncoded(
"${PLUGIN_MANAGER_URL}/api/search/aggregation/tags"
).addParameters(mapOf("build" to IDE_BUILD_FOR_REQUEST)))
.productNameAsUserAgent()
.throwStatusCodeException(false)
.connect {
objectMapper.readValue(it.inputStream, AggregationSearchResponse::class.java).aggregations.keys.toList()
}
}
catch (e: Exception) {
logWarnOrPrintIfDebug("Can not get tags from Marketplace", e)
return emptyList()
}
}
@Throws(IOException::class)
fun loadPluginDescriptor(xmlId: String, ideCompatibleUpdate: IdeCompatibleUpdate, indicator: ProgressIndicator? = null): PluginNode {
return readOrUpdateFile(
getUpdateMetadataFile(ideCompatibleUpdate),
getUpdateMetadataUrl(ideCompatibleUpdate),
indicator,
IdeBundle.message("progress.downloading.plugins.meta", xmlId),
::parseJsonPluginMeta
).toPluginNode()
}
@JvmOverloads
fun loadLastCompatiblePluginDescriptors(
pluginIds: Set<PluginId>,
buildNumber: BuildNumber? = null,
): List<PluginNode> {
return getLastCompatiblePluginUpdate(pluginIds, buildNumber)
.map { loadPluginDescriptor(it.pluginId, it, null) }
}
fun loadPluginDetails(pluginNode: PluginNode): PluginNode {
val externalPluginId = pluginNode.externalPluginId
val externalUpdateId = pluginNode.externalUpdateId
if (externalPluginId == null || externalUpdateId == null) return pluginNode
val ideCompatibleUpdate = IdeCompatibleUpdate(externalUpdateId = externalUpdateId, externalPluginId = externalPluginId)
return loadPluginDescriptor(pluginNode.pluginId.idString, ideCompatibleUpdate).apply {
// these three fields are not present in `IntellijUpdateMetadata`, but present in `MarketplaceSearchPluginData`
rating = pluginNode.rating
downloads = pluginNode.downloads
date = pluginNode.date
}
}
@Throws(IOException::class)
fun <T> readOrUpdateFile(file: Path?,
url: String,
indicator: ProgressIndicator?,
@Nls indicatorMessage: String,
parser: (Reader) -> T): T {
val eTag = if (file == null) null else loadETagForFile(file)
return HttpRequests
.request(url)
.tuner { connection ->
if (eTag != null) {
connection.setRequestProperty("If-None-Match", eTag)
}
}
.productNameAsUserAgent()
.connect { request ->
try {
indicator?.checkCanceled()
val connection = request.connection
if (file != null && isNotModified(connection, file)) {
return@connect Files.newBufferedReader(file).use(parser)
}
if (indicator != null) {
indicator.checkCanceled()
indicator.text2 = indicatorMessage
}
if (file == null) {
return@connect request.reader.use(parser)
}
synchronized(this) {
request.saveToFile(file, indicator)
connection.getHeaderField("ETag")?.let { saveETagForFile(file, it) }
}
return@connect Files.newBufferedReader(file).use(parser)
}
catch (e: HttpRequests.HttpStatusException) {
LOG.warnWithDebug("Cannot load data from ${url} (statusCode=${e.statusCode})", e)
throw e
}
catch (e: Exception) {
LOG.warnWithDebug("Error reading Marketplace file: ${e} (file=${file} URL=${url})", e)
if (file != null && LOG.isDebugEnabled) {
LOG.debug("File content:\n${runCatching { Files.readString(file) }.getOrElse { IoErrorText.message(e) }}")
}
throw e
}
}
}
@JvmOverloads
fun getLastCompatiblePluginUpdate(
ids: Set<PluginId>,
buildNumber: BuildNumber? = null,
): List<IdeCompatibleUpdate> {
try {
if (ids.isEmpty()) {
return emptyList()
}
val data = objectMapper.writeValueAsString(CompatibleUpdateRequest(ids, buildNumber))
return HttpRequests
.post(Urls.newFromEncoded(COMPATIBLE_UPDATE_URL).toExternalForm(), HttpRequests.JSON_CONTENT_TYPE)
.productNameAsUserAgent()
.throwStatusCodeException(false)
.connect {
it.write(data)
objectMapper.readValue(it.inputStream, object : TypeReference<List<IdeCompatibleUpdate>>() {})
}
}
catch (e: Exception) {
logWarnOrPrintIfDebug("Can not get compatible updates from Marketplace", e)
return emptyList()
}
}
@Deprecated("Please use `PluginId`", replaceWith = ReplaceWith("getLastCompatiblePluginUpdate(PluginId.get(id), buildNumber, indicator)"))
@RequiresBackgroundThread
@JvmOverloads
fun getLastCompatiblePluginUpdate(
id: String,
buildNumber: BuildNumber? = null,
indicator: ProgressIndicator? = null,
): PluginNode? = getLastCompatiblePluginUpdate(PluginId.getId(id), buildNumber, indicator)
@RequiresBackgroundThread
@JvmOverloads
fun getLastCompatiblePluginUpdate(
pluginId: PluginId,
buildNumber: BuildNumber? = null,
indicator: ProgressIndicator? = null,
): PluginNode? {
return getLastCompatiblePluginUpdate(setOf(pluginId), buildNumber).firstOrNull()
?.let { loadPluginDescriptor(pluginId.idString, it, indicator) }
}
fun getCompatibleUpdateByModule(module: String): PluginId? {
try {
val data = objectMapper.writeValueAsString(CompatibleUpdateForModuleRequest(module))
return HttpRequests.post(
Urls.newFromEncoded(COMPATIBLE_UPDATE_URL).toExternalForm(),
HttpRequests.JSON_CONTENT_TYPE,
).productNameAsUserAgent()
.throwStatusCodeException(false)
.connect {
it.write(data)
objectMapper.readValue(it.inputStream, object : TypeReference<List<IdeCompatibleUpdate>>() {})
}.firstOrNull()
?.pluginId
?.let { PluginId.getId(it) }
}
catch (e: Exception) {
logWarnOrPrintIfDebug("Can not get compatible update by module from Marketplace", e)
return null
}
}
var jetBrainsPluginsIds: Set<String>? = null
private set
fun loadJetBrainsPluginsIds() {
if (jetBrainsPluginsIds != null) {
return
}
jetBrainsPluginsIds = try {
HttpRequests
.request(JETBRAINS_PLUGINS_URL)
.productNameAsUserAgent()
.throwStatusCodeException(false)
.connect {
objectMapper.readValue(it.inputStream, object : TypeReference<List<MarketplaceSearchPluginData>>() {})
.asSequence()
.map(MarketplaceSearchPluginData::id)
.toCollection(HashSet())
}
}
catch (e: Exception) {
logWarnOrPrintIfDebug("Can not get JetBrains plugins' IDs from Marketplace", e)
null
}
}
private fun parseXmlIds(reader: Reader): Set<PluginId> {
return objectMapper.readValue(reader, object : TypeReference<Set<String>>() {}).map { PluginId.getId(it) }.toCollection(HashSet())
}
private fun parseJsonPluginMeta(reader: Reader) = objectMapper.readValue(reader, IntellijUpdateMetadata::class.java)
}
private fun loadETagForFile(file: Path): String {
val eTagFile = getETagFile(file)
try {
val lines = Files.readAllLines(eTagFile)
if (lines.size == 1) {
return lines[0]
}
LOG.warn("Can't load ETag from '" + eTagFile + "'. Unexpected number of lines: " + lines.size)
Files.deleteIfExists(eTagFile)
}
catch (ignore: NoSuchFileException) {
}
catch (e: IOException) {
LOG.warn("Can't load ETag from '$eTagFile'", e)
}
return ""
}
@Suppress("SpellCheckingInspection")
private fun getETagFile(file: Path): Path = file.parent.resolve("${file.fileName}.etag")
private fun saveETagForFile(file: Path, eTag: String) {
val eTagFile = getETagFile(file)
try {
eTagFile.write(eTag)
}
catch (e: IOException) {
LOG.warn("Can't save ETag to '$eTagFile'", e)
}
}
private fun isNotModified(urlConnection: URLConnection, file: Path?): Boolean {
return file != null && file.exists() && Files.size(file) > 0 &&
urlConnection is HttpURLConnection && urlConnection.responseCode == HttpURLConnection.HTTP_NOT_MODIFIED
}
private data class CompatibleUpdateRequest(
val build: String,
val pluginXMLIds: List<String>,
) {
@JvmOverloads
constructor(
pluginIds: Set<PluginId>,
buildNumber: BuildNumber? = null,
) : this(
ApplicationInfoImpl.orFromPluginsCompatibleBuild(buildNumber),
pluginIds.map { it.idString },
)
}
private data class CompatibleUpdateForModuleRequest(
val module: String,
val build: String,
) {
@JvmOverloads
constructor(
module: String,
buildNumber: BuildNumber? = null,
) : this(
module,
ApplicationInfoImpl.orFromPluginsCompatibleBuild(buildNumber),
)
}
private fun logWarnOrPrintIfDebug(message: String, throwable: Throwable) {
if (LOG.isDebugEnabled) {
LOG.debug(message, throwable)
}
else {
LOG.warn("${message}: ${throwable.message}")
}
}
| apache-2.0 | 2f1914667e9fbbf7c4376341afec72dd | 33.697318 | 140 | 0.691862 | 4.511083 | false | false | false | false |
zdary/intellij-community | platform/platform-api/src/com/intellij/ide/SaveAndSyncHandler.kt | 10 | 2610 | // 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 com.intellij.ide
import com.intellij.openapi.application.AccessToken
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.components.ComponentManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.ModificationTracker
import com.intellij.openapi.util.SimpleModificationTracker
import org.jetbrains.annotations.ApiStatus
abstract class SaveAndSyncHandler {
companion object {
@JvmStatic
fun getInstance(): SaveAndSyncHandler {
return ApplicationManager.getApplication().getService(SaveAndSyncHandler::class.java)
}
}
protected val externalChangesModificationTracker = SimpleModificationTracker()
/**
* If project is specified - only project settings will be saved.
* If project is not specified - app and all project settings will be saved.
*/
data class SaveTask @JvmOverloads constructor(val project: Project? = null, val forceSavingAllSettings: Boolean = false) {
companion object {
// for Java clients
@JvmStatic
fun projectIncludingAllSettings(project: Project) = SaveTask(project = project, forceSavingAllSettings = true)
}
}
@ApiStatus.Internal
abstract fun scheduleSave(task: SaveTask, forceExecuteImmediately: Boolean)
fun scheduleSave(task: SaveTask) {
scheduleSave(task, forceExecuteImmediately = false)
}
@JvmOverloads
fun scheduleProjectSave(project: Project, forceSavingAllSettings: Boolean = false) {
scheduleSave(SaveTask(project, forceSavingAllSettings = forceSavingAllSettings))
}
abstract fun scheduleRefresh()
abstract fun refreshOpenFiles()
open fun disableAutoSave(): AccessToken = AccessToken.EMPTY_ACCESS_TOKEN
abstract fun blockSaveOnFrameDeactivation()
abstract fun unblockSaveOnFrameDeactivation()
abstract fun blockSyncOnFrameActivation()
abstract fun unblockSyncOnFrameActivation()
@ApiStatus.Experimental
open fun maybeRefresh(modalityState: ModalityState) {
}
@ApiStatus.Internal
abstract fun saveSettingsUnderModalProgress(componentManager: ComponentManager): Boolean
/**
* @return a modification tracker incrementing when external commands are likely run.
* Currently it happens on IDE frame deactivation and/or [scheduleRefresh] invocation.
*/
@ApiStatus.Experimental
fun getExternalChangesTracker(): ModificationTracker = externalChangesModificationTracker
}
| apache-2.0 | 5f70e95afbf5233e8e9aff48bef79e42 | 34.27027 | 140 | 0.785824 | 5.326531 | false | false | false | false |
AndroidX/androidx | navigation/navigation-compose-lint/src/main/java/androidx/navigation/compose/lint/UnrememberedGetBackStackEntryDetector.kt | 3 | 3677 | /*
* Copyright 2021 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.
*/
@file:Suppress("UnstableApiUsage")
package androidx.navigation.compose.lint
import androidx.compose.lint.Name
import androidx.compose.lint.Package
import androidx.compose.lint.isInPackageName
import androidx.compose.lint.isNotRememberedWithKeys
import com.android.tools.lint.detector.api.Category
import com.android.tools.lint.detector.api.Detector
import com.android.tools.lint.detector.api.Implementation
import com.android.tools.lint.detector.api.Issue
import com.android.tools.lint.detector.api.JavaContext
import com.android.tools.lint.detector.api.Scope
import com.android.tools.lint.detector.api.Severity
import com.android.tools.lint.detector.api.SourceCodeScanner
import com.intellij.psi.PsiMethod
import java.util.EnumSet
import org.jetbrains.uast.UCallExpression
/**
* [Detector] that checks `getBackStackEntry` calls to make sure that if they are called inside a
* Composable body, they are `remember`ed with a `NavBackStackEntry` as a key.
*/
class UnrememberedGetBackStackEntryDetector : Detector(), SourceCodeScanner {
override fun getApplicableMethodNames(): List<String> = listOf(
GetBackStackEntry.shortName
)
override fun visitMethodCall(context: JavaContext, node: UCallExpression, method: PsiMethod) {
if (!method.isInPackageName(PackageName)) return
if (node.isNotRememberedWithKeys(NavBackStackEntry)) {
context.report(
UnrememberedGetBackStackEntry,
node,
context.getNameLocation(node),
"Calling getBackStackEntry during composition without using `remember` " +
"with a NavBackStackEntry key"
)
}
}
companion object {
val UnrememberedGetBackStackEntry = Issue.create(
"UnrememberedGetBackStackEntry",
"Calling getBackStackEntry during composition without using `remember`" +
"with a NavBackStackEntry key",
"Backstack entries retrieved during composition need to be `remember`ed, otherwise " +
"they will be retrieved from the navController again, and be changed. You also " +
"need to pass in a key of a NavBackStackEntry to the remember call or they will " +
"not be updated properly. If this is in a `NavGraphBuilder.composable` scope, " +
"you should pass in the lambda's given entry as the key. Either hoist the state " +
"to an object that is not created during composition, or wrap the state in a " +
"call to `remember` with a `NavBackStackEntry` as a key.",
Category.CORRECTNESS, 3, Severity.ERROR,
Implementation(
UnrememberedGetBackStackEntryDetector::class.java,
EnumSet.of(Scope.JAVA_FILE, Scope.TEST_SOURCES)
)
)
}
}
private val PackageName = Package("androidx.navigation")
private val GetBackStackEntry = Name(PackageName, "getBackStackEntry")
private val NavBackStackEntry = Name(PackageName, "NavBackStackEntry")
| apache-2.0 | 7f7b2ecaff1ca724a01887284892773e | 43.301205 | 99 | 0.709546 | 4.642677 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/completion/src/org/jetbrains/kotlin/idea/completion/LookupElementsCollector.kt | 2 | 7831 | // 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.completion
import com.intellij.codeInsight.completion.*
import com.intellij.codeInsight.completion.impl.RealPrefixMatchingWeigher
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.codeInsight.lookup.LookupElementDecorator
import com.intellij.openapi.util.TextRange
import com.intellij.patterns.ElementPattern
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.descriptors.MemberDescriptor
import org.jetbrains.kotlin.idea.completion.handlers.WithExpressionPrefixInsertHandler
import org.jetbrains.kotlin.idea.completion.handlers.WithTailInsertHandler
import org.jetbrains.kotlin.idea.core.completion.DeclarationLookupObject
import org.jetbrains.kotlin.idea.intentions.InsertExplicitTypeArgumentsIntention
import org.jetbrains.kotlin.psi.KtCallExpression
import org.jetbrains.kotlin.psi.KtDotQualifiedExpression
import org.jetbrains.kotlin.psi.psiUtil.collectDescendantsOfType
import org.jetbrains.kotlin.resolve.ImportedFromObjectCallableDescriptor
import kotlin.math.max
class LookupElementsCollector(
private val onFlush: () -> Unit,
private val prefixMatcher: PrefixMatcher,
private val completionParameters: CompletionParameters,
resultSet: CompletionResultSet,
sorter: CompletionSorter,
private val filter: ((LookupElement) -> Boolean)?,
private val allowExpectDeclarations: Boolean
) {
var bestMatchingDegree = Int.MIN_VALUE
private set
private val elements = ArrayList<LookupElement>()
private val resultSet = resultSet.withPrefixMatcher(prefixMatcher).withRelevanceSorter(sorter)
private val postProcessors = ArrayList<(LookupElement) -> LookupElement>()
private val processedCallables = HashSet<CallableDescriptor>()
var isResultEmpty: Boolean = true
private set
fun flushToResultSet() {
if (elements.isNotEmpty()) {
onFlush()
resultSet.addAllElements(elements)
elements.clear()
isResultEmpty = false
}
}
fun addLookupElementPostProcessor(processor: (LookupElement) -> LookupElement) {
postProcessors.add(processor)
}
fun addDescriptorElements(
descriptors: Iterable<DeclarationDescriptor>,
lookupElementFactory: AbstractLookupElementFactory,
notImported: Boolean = false,
withReceiverCast: Boolean = false,
prohibitDuplicates: Boolean = false
) {
for (descriptor in descriptors) {
addDescriptorElements(descriptor, lookupElementFactory, notImported, withReceiverCast, prohibitDuplicates)
}
}
fun addDescriptorElements(
descriptor: DeclarationDescriptor,
lookupElementFactory: AbstractLookupElementFactory,
notImported: Boolean = false,
withReceiverCast: Boolean = false,
prohibitDuplicates: Boolean = false
) {
if (prohibitDuplicates && descriptor is CallableDescriptor && unwrapIfImportedFromObject(descriptor) in processedCallables) return
var lookupElements = lookupElementFactory.createStandardLookupElementsForDescriptor(descriptor, useReceiverTypes = true)
if (withReceiverCast) {
lookupElements = lookupElements.map { it.withReceiverCast() }
}
addElements(lookupElements, notImported)
if (prohibitDuplicates && descriptor is CallableDescriptor) processedCallables.add(unwrapIfImportedFromObject(descriptor))
}
fun addElement(element: LookupElement, notImported: Boolean = false) {
if (!prefixMatcher.prefixMatches(element)) {
return
}
if (!allowExpectDeclarations) {
val descriptor = (element.`object` as? DeclarationLookupObject)?.descriptor
if ((descriptor as? MemberDescriptor)?.isExpect == true) return
}
if (notImported) {
element.putUserData(NOT_IMPORTED_KEY, Unit)
if (isResultEmpty && elements.isEmpty()) { /* without these checks we may get duplicated items */
addElement(element.suppressAutoInsertion())
} else {
addElement(element)
}
return
}
val decorated = JustTypingLookupElementDecorator(element, completionParameters)
var result: LookupElement = decorated
for (postProcessor in postProcessors) {
result = postProcessor(result)
}
val declarationLookupObject = result.`object` as? DeclarationLookupObject
if (declarationLookupObject != null) {
result = DeclarationLookupObjectLookupElementDecorator(result, declarationLookupObject)
}
if (filter?.invoke(result) ?: true) {
elements.add(result)
}
val matchingDegree = RealPrefixMatchingWeigher.getBestMatchingDegree(result, prefixMatcher)
bestMatchingDegree = max(bestMatchingDegree, matchingDegree)
}
fun addElements(elements: Iterable<LookupElement>, notImported: Boolean = false) {
elements.forEach { addElement(it, notImported) }
}
fun restartCompletionOnPrefixChange(prefixCondition: ElementPattern<String>) {
resultSet.restartCompletionOnPrefixChange(prefixCondition)
}
}
private class JustTypingLookupElementDecorator(element: LookupElement, private val completionParameters: CompletionParameters) :
LookupElementDecorator<LookupElement>(element) {
// used to avoid insertion of spaces before/after ',', '=' on just typing
private fun isJustTyping(context: InsertionContext, element: LookupElement): Boolean {
if (!completionParameters.isAutoPopup) return false
val insertedText = context.document.getText(TextRange(context.startOffset, context.tailOffset))
return insertedText == element.getUserDataDeep(KotlinCompletionCharFilter.JUST_TYPING_PREFIX)
}
override fun getDecoratorInsertHandler(): InsertHandler<LookupElementDecorator<LookupElement>> = InsertHandler { context, decorator ->
delegate.handleInsert(context)
if (context.shouldAddCompletionChar() && !isJustTyping(context, this)) {
when (context.completionChar) {
',' -> WithTailInsertHandler.COMMA.postHandleInsert(context, delegate)
'=' -> WithTailInsertHandler.EQ.postHandleInsert(context, delegate)
'!' -> {
WithExpressionPrefixInsertHandler("!").postHandleInsert(context)
context.setAddCompletionChar(false)
}
}
}
val (typeArgs, exprOffset) = argList ?: return@InsertHandler
val beforeCaret = context.file.findElementAt(exprOffset) ?: return@InsertHandler
val callExpr = when (val beforeCaretExpr = beforeCaret.prevSibling) {
is KtCallExpression -> beforeCaretExpr
is KtDotQualifiedExpression -> beforeCaretExpr.collectDescendantsOfType<KtCallExpression>().lastOrNull()
else -> null
} ?: return@InsertHandler
InsertExplicitTypeArgumentsIntention.applyTo(callExpr, typeArgs, true)
}
}
private class DeclarationLookupObjectLookupElementDecorator(
element: LookupElement,
private val declarationLookupObject: DeclarationLookupObject
) : LookupElementDecorator<LookupElement>(element) {
override fun getPsiElement() = declarationLookupObject.psiElement
}
private fun unwrapIfImportedFromObject(descriptor: CallableDescriptor): CallableDescriptor =
if (descriptor is ImportedFromObjectCallableDescriptor<*>) descriptor.callableFromObject else descriptor
| apache-2.0 | a8c00cb75341ebec77c78d53b39e7632 | 40.877005 | 158 | 0.725195 | 5.62168 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/jvm-debugger/sequence/src/org/jetbrains/kotlin/idea/debugger/sequence/trace/dsl/KotlinListVariable.kt | 6 | 1201 | // 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.debugger.sequence.trace.dsl
import com.intellij.debugger.streams.trace.dsl.Expression
import com.intellij.debugger.streams.trace.dsl.ListVariable
import com.intellij.debugger.streams.trace.dsl.VariableDeclaration
import com.intellij.debugger.streams.trace.dsl.impl.VariableImpl
import com.intellij.debugger.streams.trace.impl.handler.type.ListType
class KotlinListVariable(override val type: ListType, name: String) : VariableImpl(type, name), ListVariable {
override operator fun get(index: Expression): Expression = call("get", index)
override operator fun set(index: Expression, newValue: Expression): Expression = call("set", index, newValue)
override fun add(element: Expression): Expression = call("add", element)
override fun contains(element: Expression): Expression = call("contains", element)
override fun size(): Expression = property("size")
override fun defaultDeclaration(): VariableDeclaration =
KotlinVariableDeclaration(this, false, type.defaultValue)
} | apache-2.0 | 1d5f517c7614bbb48625583433c2275d | 53.636364 | 158 | 0.782681 | 4.33574 | false | false | false | false |
jotomo/AndroidAPS | danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_General_Get_User_Time_Change_Flag.kt | 1 | 973 | package info.nightscout.androidaps.danars.comm
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.danars.encryption.BleEncryption
class DanaRS_Packet_General_Get_User_Time_Change_Flag(
injector: HasAndroidInjector
) : DanaRS_Packet(injector) {
init {
opCode = BleEncryption.DANAR_PACKET__OPCODE_REVIEW__GET_USER_TIME_CHANGE_FLAG
aapsLogger.debug(LTag.PUMPCOMM, "New message")
}
override fun handleMessage(data: ByteArray) {
if (data.size < 3) {
failed = true
return
} else failed = false
val dataIndex = DATA_START
val dataSize = 1
val userTimeChangeFlag = byteArrayToInt(getBytes(data, dataIndex, dataSize))
aapsLogger.debug(LTag.PUMPCOMM, "UserTimeChangeFlag: $userTimeChangeFlag")
}
override fun getFriendlyName(): String {
return "REVIEW__GET_USER_TIME_CHANGE_FLAG"
}
} | agpl-3.0 | b1c5557707daf9f3c1ba03d542773875 | 31.466667 | 85 | 0.695786 | 4.363229 | false | false | false | false |
vuyaniShabangu/now.next | Research/Tower-develop/Tower-develop/Android/src/org/droidplanner/android/fragments/widget/diagnostics/EkfFlagsViewer.kt | 10 | 3797 | package org.droidplanner.android.fragments.widget.diagnostics
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.support.annotation.StringRes
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.o3dr.services.android.lib.drone.property.EkfStatus
import org.droidplanner.android.R
import org.droidplanner.android.fragments.widget.diagnostics.BaseWidgetDiagnostic
import java.util.*
import kotlin.properties.Delegates
/**
* Created by Fredia Huya-Kouadio on 9/15/15.
*/
public class EkfFlagsViewer : BaseWidgetDiagnostic() {
companion object {
@StringRes public val LABEL_ID: Int = R.string.title_ekf_flags_viewer
}
private val ekfFlagsViews: HashMap<EkfStatus.EkfFlags, TextView?> = HashMap()
private val okFlagDrawable: Drawable? by lazy(LazyThreadSafetyMode.NONE) {
resources?.getDrawable(R.drawable.ic_check_box_green_500_24dp)
}
private val badFlagDrawable: Drawable? by lazy(LazyThreadSafetyMode.NONE) {
resources?.getDrawable(R.drawable.ic_cancel_red_500_24dp)
}
private val unknownFlagDrawable: Drawable? by lazy(LazyThreadSafetyMode.NONE) {
resources?.getDrawable(R.drawable.ic_help_orange_500_24dp)
}
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater?.inflate(R.layout.fragment_ekf_flags_viewer, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?){
super.onViewCreated(view, savedInstanceState)
setupEkfFlags(view)
}
override fun disableEkfView() {
disableEkfFlags()
}
override fun updateEkfView(ekfStatus: EkfStatus) {
updateEkfFlags(ekfStatus)
}
private fun disableEkfFlags(){
for(flagView in ekfFlagsViews.values)
flagView?.setCompoundDrawablesWithIntrinsicBounds(null, null, unknownFlagDrawable, null)
}
private fun updateEkfFlags(ekfStatus: EkfStatus){
for((flag, flagView) in ekfFlagsViews){
val isFlagSet = if(flag === EkfStatus.EkfFlags.EKF_CONST_POS_MODE) !ekfStatus.isEkfFlagSet(flag) else ekfStatus.isEkfFlagSet(flag)
val flagDrawable = if(isFlagSet) okFlagDrawable else badFlagDrawable
flagView?.setCompoundDrawablesWithIntrinsicBounds(null, null, flagDrawable, null)
}
}
private fun setupEkfFlags(view: View){
ekfFlagsViews.put(EkfStatus.EkfFlags.EKF_ATTITUDE, view.findViewById(R.id.ekf_attitude_flag) as TextView?)
ekfFlagsViews.put(EkfStatus.EkfFlags.EKF_CONST_POS_MODE, view.findViewById(R.id.ekf_const_pos_flag) as TextView?)
ekfFlagsViews.put(EkfStatus.EkfFlags.EKF_VELOCITY_VERT, view.findViewById(R.id.ekf_velocity_vert_flag) as TextView?)
ekfFlagsViews.put(EkfStatus.EkfFlags.EKF_VELOCITY_HORIZ, view.findViewById(R.id.ekf_velocity_horiz_flag) as TextView?)
ekfFlagsViews.put(EkfStatus.EkfFlags.EKF_POS_HORIZ_REL, view.findViewById(R.id.ekf_position_horiz_rel_flag) as TextView?)
ekfFlagsViews.put(EkfStatus.EkfFlags.EKF_POS_HORIZ_ABS, view.findViewById(R.id.ekf_position_horiz_abs_flag) as TextView?)
ekfFlagsViews.put(EkfStatus.EkfFlags.EKF_PRED_POS_HORIZ_ABS, view.findViewById(R.id.ekf_position_horiz_pred_abs_flag) as TextView?)
ekfFlagsViews.put(EkfStatus.EkfFlags.EKF_PRED_POS_HORIZ_REL, view.findViewById(R.id.ekf_position_horiz_pred_rel_flag) as TextView?)
ekfFlagsViews.put(EkfStatus.EkfFlags.EKF_POS_VERT_AGL, view.findViewById(R.id.ekf_position_vert_agl_flag) as TextView?)
ekfFlagsViews.put(EkfStatus.EkfFlags.EKF_POS_VERT_ABS, view.findViewById(R.id.ekf_position_vert_abs_flag) as TextView?)
}
} | mit | 9df480456b1219f36caa190ed35c76b9 | 45.888889 | 142 | 0.745325 | 3.636973 | false | false | false | false |
ingokegel/intellij-community | platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/BooleanEntityImpl.kt | 1 | 5822 | // 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.entities.test.api
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.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
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.containers.toMutableWorkspaceList
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class BooleanEntityImpl : BooleanEntity, WorkspaceEntityBase() {
companion object {
val connections = listOf<ConnectionId>(
)
}
override var data: Boolean = false
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: BooleanEntityData?) : ModifiableWorkspaceEntityBase<BooleanEntity>(), BooleanEntity.Builder {
constructor() : this(BooleanEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity BooleanEntity 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")
}
}
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 BooleanEntity
this.entitySource = dataSource.entitySource
this.data = dataSource.data
if (parents != null) {
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override var data: Boolean
get() = getEntityData().data
set(value) {
checkModificationAllowed()
getEntityData().data = value
changedProperty.add("data")
}
override fun getEntityData(): BooleanEntityData = result ?: super.getEntityData() as BooleanEntityData
override fun getEntityClass(): Class<BooleanEntity> = BooleanEntity::class.java
}
}
class BooleanEntityData : WorkspaceEntityData<BooleanEntity>() {
var data: Boolean = false
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<BooleanEntity> {
val modifiable = BooleanEntityImpl.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): BooleanEntity {
val entity = BooleanEntityImpl()
entity.data = data
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
return entity
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return BooleanEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return BooleanEntity(data, entitySource) {
}
}
override fun getRequiredParents(): List<Class<out WorkspaceEntity>> {
val res = mutableListOf<Class<out WorkspaceEntity>>()
return res
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as BooleanEntityData
if (this.entitySource != other.entitySource) return false
if (this.data != other.data) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as BooleanEntityData
if (this.data != other.data) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + data.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
result = 31 * result + data.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
collector.sameForAllEntities = true
}
}
| apache-2.0 | 78965e9fdb9d25819a159d490f2ab78c | 30.13369 | 121 | 0.729303 | 5.235612 | false | false | false | false |
idea4bsd/idea4bsd | platform/platform-impl/src/com/intellij/ui/layout/Row.kt | 3 | 2599 | /*
* 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 com.intellij.ui.layout
import com.intellij.BundleBase
import com.intellij.ui.components.Label
import com.intellij.ui.components.Link
import com.intellij.ui.components.Panel
import com.intellij.util.ui.UIUtil
import com.intellij.util.ui.UIUtil.ComponentStyle
import com.intellij.util.ui.UIUtil.FontColor
import java.awt.Component
import java.awt.event.ActionEvent
import javax.swing.JButton
import javax.swing.JComponent
import javax.swing.JLabel
abstract class Row() {
fun label(text: String, gapLeft: Int = 0, style: ComponentStyle? = null, fontColor: FontColor? = null, bold: Boolean = false) {
Label(text, style, fontColor, bold)(gapLeft = gapLeft)
}
fun link(text: String, style: ComponentStyle? = null, action: () -> Unit) {
val result = Link(text, action = action)
style?.let { UIUtil.applyStyle(it, result) }
result()
}
fun button(text: String, actionListener: (event: ActionEvent) -> Unit) {
val button = JButton(BundleBase.replaceMnemonicAmpersand(text))
button.addActionListener(actionListener)
button()
}
fun hint(text: String) {
label(text, style = ComponentStyle.SMALL, fontColor = FontColor.BRIGHTER, gapLeft = 3 * HORIZONTAL_GAP)
}
fun panel(title: String, wrappedComponent: Component, vararg constraints: CCFlags) {
val panel = Panel(title)
panel.add(wrappedComponent)
panel(*constraints)
}
abstract operator fun JComponent.invoke(vararg constraints: CCFlags, gapLeft: Int = 0)
inline fun right(init: Row.() -> Unit) {
alignRight()
init()
}
protected abstract fun alignRight()
@Deprecated(message = "Nested row is prohibited", level = DeprecationLevel.ERROR)
fun row(label: String, init: Row.() -> Unit) {
}
@Deprecated(message = "Nested row is prohibited", level = DeprecationLevel.ERROR)
fun row(label: JLabel? = null, init: Row.() -> Unit) {
}
@Deprecated(message = "Nested noteRow is prohibited", level = DeprecationLevel.ERROR)
fun noteRow(text: String) {
}
} | apache-2.0 | 4a570fe7010286cc3f1780276c745ef5 | 32.333333 | 129 | 0.724509 | 3.908271 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/caches/project/KotlinStdlibCache.kt | 1 | 6017 | /*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.caches.project
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.OrderRootType
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.search.DelegatingGlobalSearchScope
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.util.indexing.FileBasedIndex
import org.jetbrains.kotlin.caches.project.cacheInvalidatingOnRootModifications
import org.jetbrains.kotlin.idea.configuration.IdeBuiltInsLoadingState
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.idea.vfilefinder.KotlinStdlibIndex
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
import java.util.*
import java.util.concurrent.ConcurrentHashMap
// TODO(kirpichenkov): works only for JVM (see KT-44552)
interface KotlinStdlibCache {
fun isStdlib(libraryInfo: LibraryInfo): Boolean
fun isStdlibDependency(libraryInfo: LibraryInfo): Boolean
fun findStdlibInModuleDependencies(module: IdeaModuleInfo): LibraryInfo?
companion object {
fun getInstance(project: Project): KotlinStdlibCache =
if (IdeBuiltInsLoadingState.isFromClassLoader) {
Disabled
} else {
ServiceManager.getService(project, KotlinStdlibCache::class.java)
?: error("Failed to load service ${KotlinStdlibCache::class.java.name}")
}
val Disabled = object : KotlinStdlibCache {
override fun isStdlib(libraryInfo: LibraryInfo) = false
override fun isStdlibDependency(libraryInfo: LibraryInfo) = false
override fun findStdlibInModuleDependencies(module: IdeaModuleInfo): LibraryInfo? = null
}
}
}
class KotlinStdlibCacheImpl(val project: Project) : KotlinStdlibCache {
//@JvmInline
private inline class StdlibDependency(val libraryInfo: LibraryInfo?)
private val isStdlibCache: MutableMap<LibraryInfo, Boolean>
get() = project.cacheInvalidatingOnRootModifications {
ConcurrentHashMap<LibraryInfo, Boolean>()
}
private val isStdlibDependencyCache: MutableMap<LibraryInfo, Boolean>
get() = project.cacheInvalidatingOnRootModifications {
ConcurrentHashMap<LibraryInfo, Boolean>()
}
private val moduleStdlibDependencyCache: MutableMap<IdeaModuleInfo, StdlibDependency>
get() = project.cacheInvalidatingOnRootModifications {
ConcurrentHashMap<IdeaModuleInfo, StdlibDependency>()
}
private class LibraryScope(
project: Project,
private val directories: Set<VirtualFile>
) : DelegatingGlobalSearchScope(GlobalSearchScope.allScope(project)) {
private val fileSystems = directories.mapTo(hashSetOf(), VirtualFile::getFileSystem)
override fun contains(file: VirtualFile): Boolean =
file.fileSystem in fileSystems && generateSequence(file, VirtualFile::getParent).any { it in directories }
override fun toString() = "All files under: $directories"
}
private fun libraryScopeContainsIndexedFilesForNames(libraryInfo: LibraryInfo, names: Collection<FqName>) = runReadAction {
names.any { name ->
FileBasedIndex.getInstance().getContainingFiles(
KotlinStdlibIndex.KEY,
name,
LibraryScope(project, libraryInfo.library.rootProvider.getFiles(OrderRootType.CLASSES).toSet())
).isNotEmpty()
}
}
private fun libraryScopeContainsIndexedFilesForName(libraryInfo: LibraryInfo, name: FqName) =
libraryScopeContainsIndexedFilesForNames(libraryInfo, listOf(name))
override fun isStdlib(libraryInfo: LibraryInfo): Boolean {
return isStdlibCache.getOrPut(libraryInfo) {
libraryScopeContainsIndexedFilesForName(libraryInfo, KotlinStdlibIndex.KOTLIN_STDLIB_NAME)
}
}
override fun isStdlibDependency(libraryInfo: LibraryInfo): Boolean {
return isStdlibDependencyCache.getOrPut(libraryInfo) {
libraryScopeContainsIndexedFilesForNames(libraryInfo, KotlinStdlibIndex.STANDARD_LIBRARY_DEPENDENCY_NAMES)
}
}
override fun findStdlibInModuleDependencies(module: IdeaModuleInfo): LibraryInfo? {
val stdlibDependency = moduleStdlibDependencyCache.getOrPut(module) {
fun IdeaModuleInfo.asStdLibInfo() = this.safeAs<LibraryInfo>()?.takeIf { isStdlib(it) }
val stdLib: LibraryInfo? = module.asStdLibInfo() ?: run {
val checkedLibraryInfo = mutableSetOf<IdeaModuleInfo>()
val stack = ArrayDeque<IdeaModuleInfo>()
stack.add(module)
// bfs
while (stack.isNotEmpty()) {
val poll = stack.poll()
if (!checkedLibraryInfo.add(poll)) continue
val dependencies = poll.dependencies().filter { !checkedLibraryInfo.contains(it) }
dependencies
.filterIsInstance<LibraryInfo>()
.firstOrNull { isStdlib(it) }
?.let { return@run it }
stack += dependencies
}
null
}
StdlibDependency(stdLib)
}
return stdlibDependency.libraryInfo
}
}
fun LibraryInfo.isCoreKotlinLibrary(project: Project): Boolean =
isKotlinStdlib(project) || isKotlinStdlibDependency(project)
fun LibraryInfo.isKotlinStdlib(project: Project): Boolean =
KotlinStdlibCache.getInstance(project).isStdlib(this)
fun LibraryInfo.isKotlinStdlibDependency(project: Project): Boolean =
KotlinStdlibCache.getInstance(project).isStdlibDependency(this)
| apache-2.0 | fcca5a82da2fdb70e4316818d802a2d3 | 41.373239 | 127 | 0.701512 | 5.484959 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/core/src/org/jetbrains/kotlin/idea/statistics/KotlinLibraryUsageImportProcessor.kt | 5 | 1400 | // 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.statistics
import com.intellij.internal.statistic.libraryUsage.LibraryUsageImportProcessor
import com.intellij.openapi.fileTypes.FileType
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import org.jetbrains.kotlin.idea.KotlinFileType
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtImportDirective
import org.jetbrains.kotlin.psi.psiUtil.getQualifiedElementSelector
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
class KotlinLibraryUsageImportProcessor : LibraryUsageImportProcessor<KtImportDirective> {
override fun isApplicable(fileType: FileType): Boolean = fileType == KotlinFileType.INSTANCE
override fun imports(file: PsiFile): List<KtImportDirective> = file.safeAs<KtFile>()?.importDirectives.orEmpty()
override fun isSingleElementImport(import: KtImportDirective): Boolean = !import.isAllUnder
override fun importQualifier(import: KtImportDirective): String? = import.importedFqName?.asString()
override fun resolve(import: KtImportDirective): PsiElement? = import.importedReference
?.getQualifiedElementSelector()
?.mainReference
?.resolve()
}
| apache-2.0 | 8896cdf3cab32919951b491650aecffd | 57.333333 | 158 | 0.813571 | 4.912281 | false | false | false | false |
kichikuou/system3-sdl2 | android/app/src/main/java/io/github/kichikuou/system3/GameActivity.kt | 1 | 9260 | /* Copyright (C) 2019 <[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 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
package io.github.kichikuou.system3
import android.app.AlertDialog
import android.content.Context
import android.content.SharedPreferences
import android.media.MediaPlayer
import android.os.Bundle
import android.text.InputType
import android.util.Log
import android.view.ContextMenu
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.EditText
import org.libsdl.app.SDLActivity
import java.io.File
import java.io.IOException
// Intent for this activity must have the following extras:
// - EXTRA_GAME_ROOT (string): A path to the game installation.
// - EXTRA_SAVE_DIR (string): A directory where save files will be stored.
class GameActivity : SDLActivity() {
companion object {
const val EXTRA_GAME_ROOT = "GAME_ROOT"
const val EXTRA_SAVE_DIR = "SAVE_DIR"
const val PREF_USE_FM = "use_fm_sound"
}
private lateinit var gameRoot: File
private lateinit var cdda: CddaPlayer
private lateinit var prefs: SharedPreferences
private val midi = MidiPlayer()
private var useFM = true
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
gameRoot = File(intent.getStringExtra(EXTRA_GAME_ROOT)!!)
cdda = CddaPlayer(File(gameRoot, Launcher.PLAYLIST_FILE))
prefs = getSharedPreferences("system3", Context.MODE_PRIVATE)
useFM = prefs.getBoolean(PREF_USE_FM, useFM)
registerForContextMenu(mLayout)
}
override fun onStop() {
super.onStop()
cdda.onActivityStop()
midi.onActivityStop()
}
override fun onResume() {
super.onResume()
cdda.onActivityResume()
midi.onActivityResume()
}
override fun getLibraries(): Array<String> {
return arrayOf("SDL2", "system3")
}
override fun getArguments(): Array<String> {
val args = arrayListOf(
"-gamedir", intent.getStringExtra(EXTRA_GAME_ROOT)!!,
"-savedir", intent.getStringExtra(EXTRA_SAVE_DIR)!! + "/@")
if (useFM)
args.add("-fm")
return args.toTypedArray()
}
override fun setTitle(title: CharSequence?) {
super.setTitle(title)
val str = title?.toString()?.substringAfter(':', "")
if (str.isNullOrEmpty())
return
File(gameRoot, Launcher.TITLE_FILE).writeText(str)
Launcher.updateGameList()
}
private fun textInputDialog(oldVal: String, maxLen: Int, result: Array<String?>) {
val input = EditText(this)
input.inputType = InputType.TYPE_CLASS_TEXT
input.setText(oldVal)
AlertDialog.Builder(this)
.setMessage(getString(R.string.input_dialog_message, maxLen))
.setView(input)
.setPositiveButton(R.string.ok) {_, _ ->
val s = input.text.toString()
result[0] = if (s.length <= maxLen) s else s.substring(0, maxLen)
}
.setNegativeButton(R.string.cancel) {_, _ -> }
.setOnDismissListener {
synchronized(result) {
@Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN") (result as Object).notify()
}
}
.show()
}
private var menuShown = false
private fun openMenu() {
if (menuShown)
return
openContextMenu(mLayout)
menuShown = true
}
override fun onCreateContextMenu(menu: ContextMenu, v: View?, menuInfo: ContextMenu.ContextMenuInfo?) {
super.onCreateContextMenu(menu, v, menuInfo)
menuInflater.inflate(R.menu.game_menu, menu)
menu.findItem(if (useFM) R.id.fm_sound else R.id.midi_sound).isChecked = true
}
override fun onContextItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.quit_game -> {
finish()
true
}
R.id.fm_sound -> {
selectSynthesizer(true)
useFM = true
prefs.edit().putBoolean(PREF_USE_FM, useFM).apply()
true
}
R.id.midi_sound -> {
selectSynthesizer(false)
useFM = false
prefs.edit().putBoolean(PREF_USE_FM, useFM).apply()
true
}
else -> super.onOptionsItemSelected(item)
}
}
override fun onContextMenuClosed(menu: Menu) {
super.onContextMenuClosed(menu)
menuShown = false
}
// C functions we call
private external fun selectSynthesizer(use_fm: Boolean)
// The functions below are called in the SDL thread by JNI.
@Suppress("unused") fun cddaStart(track: Int, loop: Boolean) = cdda.start(track, loop)
@Suppress("unused") fun cddaStop() = cdda.stop()
@Suppress("unused") fun cddaCurrentPosition() = cdda.currentPosition()
@Suppress("unused") fun midiStart(path: String, loop: Boolean) = midi.start(path, loop)
@Suppress("unused") fun midiStop() = midi.stop()
@Suppress("unused") fun midiCurrentPosition() = midi.currentPosition()
@Suppress("unused") fun inputString(oldVal: String, maxLen: Int): String? {
val result = arrayOfNulls<String?>(1)
runOnUiThread { textInputDialog(oldVal, maxLen, result) }
// Block the calling thread.
synchronized(result) {
try {
@Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN") (result as Object).wait()
} catch (ex: InterruptedException) {
ex.printStackTrace()
}
}
return result[0]
}
@Suppress("unused") fun popupMenu() {
runOnUiThread { openMenu() }
}
}
private class CddaPlayer(private val playlistPath: File) {
private val playlist =
try {
playlistPath.readLines()
} catch (e: IOException) {
Log.e("loadPlaylist", "Cannot load $playlistPath", e)
emptyList()
}
private var currentTrack = 0
private val player = MediaPlayer()
private var playerPaused = false
fun start(track: Int, loop: Boolean) {
val f = playlist.elementAtOrNull(track - 1)
if (f.isNullOrEmpty()) {
Log.w("cddaStart", "No playlist entry for track $track")
return
}
Log.v("cddaStart", "$f Loop:$loop")
try {
player.apply {
reset()
setDataSource(File(playlistPath.parent, f).path)
isLooping = loop
prepare()
start()
}
currentTrack = track
} catch (e: IOException) {
Log.e("cddaStart", "Cannot play $f", e)
player.reset()
}
}
fun stop() {
if (currentTrack > 0 && player.isPlaying) {
player.stop()
currentTrack = 0
}
}
fun currentPosition(): Int {
if (currentTrack == 0)
return 0
val frames = player.currentPosition * 75 / 1000
return currentTrack or (frames shl 8)
}
fun onActivityStop() {
if (currentTrack > 0 && player.isPlaying) {
player.pause()
playerPaused = true
}
}
fun onActivityResume() {
if (playerPaused) {
player.start()
playerPaused = false
}
}
}
private class MidiPlayer {
private val player = MediaPlayer()
private var playing = false
private var playerPaused = false
fun start(path: String, loop: Boolean) {
try {
player.apply {
reset()
setDataSource(path)
isLooping = loop
prepare()
start()
}
playing = true
} catch (e: IOException) {
Log.e("midiStart", "Cannot play midi", e)
player.reset()
}
}
fun stop() {
if (playing && player.isPlaying) {
player.stop()
playing = false
}
}
fun currentPosition(): Int {
return if (playing) player.currentPosition else 0
}
fun onActivityStop() {
if (playing && player.isPlaying) {
player.pause()
playerPaused = true
}
}
fun onActivityResume() {
if (playerPaused) {
player.start()
playerPaused = false
}
}
}
| gpl-2.0 | 832352a54b5ee058bff46c4ec8cc90b0 | 30.496599 | 107 | 0.584233 | 4.392789 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.