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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
k9mail/k-9 | app/core/src/main/java/com/fsck/k9/network/ConnectivityManagerApi23.kt | 2 | 2561 | package com.fsck.k9.network
import android.net.ConnectivityManager.NetworkCallback
import android.net.Network
import android.net.NetworkCapabilities
import android.net.NetworkRequest
import android.os.Build
import androidx.annotation.RequiresApi
import timber.log.Timber
import android.net.ConnectivityManager as SystemConnectivityManager
@RequiresApi(Build.VERSION_CODES.M)
internal class ConnectivityManagerApi23(
private val systemConnectivityManager: SystemConnectivityManager
) : ConnectivityManagerBase() {
private var isRunning = false
private var lastActiveNetwork: Network? = null
private var wasConnected: Boolean? = null
private val networkCallback = object : NetworkCallback() {
override fun onAvailable(network: Network) {
Timber.v("Network available: $network")
notifyIfActiveNetworkOrConnectivityHasChanged()
}
override fun onLost(network: Network) {
Timber.v("Network lost: $network")
notifyIfActiveNetworkOrConnectivityHasChanged()
}
private fun notifyIfActiveNetworkOrConnectivityHasChanged() {
val activeNetwork = systemConnectivityManager.activeNetwork
val isConnected = isNetworkAvailable()
synchronized(this@ConnectivityManagerApi23) {
if (activeNetwork != lastActiveNetwork || isConnected != wasConnected) {
lastActiveNetwork = activeNetwork
wasConnected = isConnected
if (isConnected) {
notifyOnConnectivityChanged()
} else {
notifyOnConnectivityLost()
}
}
}
}
}
@Synchronized
override fun start() {
if (!isRunning) {
isRunning = true
val networkRequest = NetworkRequest.Builder().build()
systemConnectivityManager.registerNetworkCallback(networkRequest, networkCallback)
}
}
@Synchronized
override fun stop() {
if (isRunning) {
isRunning = false
systemConnectivityManager.unregisterNetworkCallback(networkCallback)
}
}
override fun isNetworkAvailable(): Boolean {
val activeNetwork = systemConnectivityManager.activeNetwork ?: return false
val networkCapabilities = systemConnectivityManager.getNetworkCapabilities(activeNetwork)
return networkCapabilities?.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) == true
}
}
| apache-2.0 | 3042da5b16da84d71582c29e8637fc2c | 34.082192 | 102 | 0.668489 | 5.91455 | false | false | false | false |
Maccimo/intellij-community | platform/workspaceModel/storage/gen/com/intellij/workspaceModel/storage/bridgeEntities/api/FacetsOrderEntityImpl.kt | 2 | 8751 | package com.intellij.workspaceModel.storage.bridgeEntities.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.EntityLink
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.extractOneToOneParent
import com.intellij.workspaceModel.storage.impl.updateOneToOneParentOfChild
import com.intellij.workspaceModel.storage.referrersx
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class FacetsOrderEntityImpl: FacetsOrderEntity, WorkspaceEntityBase() {
companion object {
internal val MODULEENTITY_CONNECTION_ID: ConnectionId = ConnectionId.create(ModuleEntity::class.java, FacetsOrderEntity::class.java, ConnectionId.ConnectionType.ONE_TO_ONE, false)
val connections = listOf<ConnectionId>(
MODULEENTITY_CONNECTION_ID,
)
}
@JvmField var _orderOfFacets: List<String>? = null
override val orderOfFacets: List<String>
get() = _orderOfFacets!!
override val moduleEntity: ModuleEntity
get() = snapshot.extractOneToOneParent(MODULEENTITY_CONNECTION_ID, this)!!
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: FacetsOrderEntityData?): ModifiableWorkspaceEntityBase<FacetsOrderEntity>(), FacetsOrderEntity.Builder {
constructor(): this(FacetsOrderEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity FacetsOrderEntity 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().isOrderOfFacetsInitialized()) {
error("Field FacetsOrderEntity#orderOfFacets should be initialized")
}
if (!getEntityData().isEntitySourceInitialized()) {
error("Field FacetsOrderEntity#entitySource should be initialized")
}
if (_diff != null) {
if (_diff.extractOneToOneParent<WorkspaceEntityBase>(MODULEENTITY_CONNECTION_ID, this) == null) {
error("Field FacetsOrderEntity#moduleEntity should be initialized")
}
}
else {
if (this.entityLinks[EntityLink(false, MODULEENTITY_CONNECTION_ID)] == null) {
error("Field FacetsOrderEntity#moduleEntity should be initialized")
}
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
override var orderOfFacets: List<String>
get() = getEntityData().orderOfFacets
set(value) {
checkModificationAllowed()
getEntityData().orderOfFacets = value
changedProperty.add("orderOfFacets")
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override var moduleEntity: ModuleEntity
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToOneParent(MODULEENTITY_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false, MODULEENTITY_CONNECTION_ID)]!! as ModuleEntity
} else {
this.entityLinks[EntityLink(false, MODULEENTITY_CONNECTION_ID)]!! as ModuleEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) {
if (value is ModifiableWorkspaceEntityBase<*>) {
value.entityLinks[EntityLink(true, MODULEENTITY_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) {
_diff.updateOneToOneParentOfChild(MODULEENTITY_CONNECTION_ID, this, value)
}
else {
if (value is ModifiableWorkspaceEntityBase<*>) {
value.entityLinks[EntityLink(true, MODULEENTITY_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(false, MODULEENTITY_CONNECTION_ID)] = value
}
changedProperty.add("moduleEntity")
}
override fun getEntityData(): FacetsOrderEntityData = result ?: super.getEntityData() as FacetsOrderEntityData
override fun getEntityClass(): Class<FacetsOrderEntity> = FacetsOrderEntity::class.java
}
}
class FacetsOrderEntityData : WorkspaceEntityData<FacetsOrderEntity>() {
lateinit var orderOfFacets: List<String>
fun isOrderOfFacetsInitialized(): Boolean = ::orderOfFacets.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<FacetsOrderEntity> {
val modifiable = FacetsOrderEntityImpl.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): FacetsOrderEntity {
val entity = FacetsOrderEntityImpl()
entity._orderOfFacets = orderOfFacets
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
return entity
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return FacetsOrderEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as FacetsOrderEntityData
if (this.orderOfFacets != other.orderOfFacets) return false
if (this.entitySource != other.entitySource) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as FacetsOrderEntityData
if (this.orderOfFacets != other.orderOfFacets) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + orderOfFacets.hashCode()
return result
}
} | apache-2.0 | 73b63656416b58b009dac314090dd958 | 39.897196 | 187 | 0.631928 | 5.742126 | false | false | false | false |
NCBSinfo/NCBSinfo | app/src/main/java/com/rohitsuratekar/NCBSinfo/fragments/AddTripsFragment.kt | 1 | 4968 | package com.rohitsuratekar.NCBSinfo.fragments
import android.app.TimePickerDialog
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.rohitsuratekar.NCBSinfo.R
import com.rohitsuratekar.NCBSinfo.adapters.EditTransportTripAdapter
import com.rohitsuratekar.NCBSinfo.common.*
import com.rohitsuratekar.NCBSinfo.models.EditFragment
import kotlinx.android.synthetic.main.fragment_add_trips.*
import java.util.*
class AddTripsFragment : EditFragment() {
private lateinit var adapter: EditTransportTripAdapter
private var itemList = mutableListOf<String>()
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_add_trips, container, false)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
adapter = EditTransportTripAdapter(itemList)
adapter.setUndoOn(false)
adapter.registerAdapterDataObserver(object : RecyclerView.AdapterDataObserver() {
override fun onChanged() {
super.onChanged()
sharedModel.updateTrips(itemList)
}
override fun onItemRangeRemoved(positionStart: Int, itemCount: Int) {
super.onItemRangeRemoved(positionStart, itemCount)
itemList.sort()
adapter.notifyDataSetChanged()
sharedModel.updateTrips(itemList)
sharedModel.updateTripSelection(false)
checkEmptyList()
}
})
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
callback?.hideProgress()
sharedModel.updateReadState(Constants.EDIT_TRIPS)
callback?.setFragmentTitle(R.string.et_add_trips)
et_trip_add_fab.setOnClickListener { selectTime() }
et_trip_next.setOnClickListener { callback?.navigate(Constants.EDIT_START_TRIP) }
et_trip_previous.setOnClickListener { callback?.navigateWithPopback() }
setUpRecycler()
et_trip_add_skip.setOnClickListener {
sharedModel.updateConfirmState(Constants.EDIT_TRIPS, true)
sharedModel.updateConfirmState(Constants.EDIT_START_TRIP, true)
sharedModel.skipTrips(true)
}
}
private fun setUpRecycler() {
checkOldData()
et_trip_recycler.layoutManager = LinearLayoutManager(context)
et_trip_recycler.adapter = adapter
et_trip_recycler.setHasFixedSize(true)
et_trip_recycler.addItemDecoration(SwipeItemDecorator())
val mItemTouchHelper = ItemTouchHelper(TouchHelper.get(context!!, et_trip_recycler))
mItemTouchHelper.attachToRecyclerView(et_trip_recycler)
checkEmptyList()
}
private fun checkEmptyList() {
if (itemList.isEmpty()) {
et_trip_holder.hideMe()
et_trip_add_skip.showMe()
et_trip_add_note.text = getString(R.string.et_trips_sub_note_with_skip)
} else {
et_trip_holder.showMe()
et_trip_add_skip.hideMe()
et_trip_add_note.text = getString(R.string.et_trips_sub_note)
}
}
private fun getFormattedDate(hour: Int, minute: Int): String {
var returnString = hour.toString()
if (returnString.length == 1) {
returnString = "0$returnString"
}
returnString = if (minute.toString().length == 1) {
"$returnString:0$minute"
} else {
"$returnString:$minute"
}
return returnString
}
private fun selectTime() {
val cal = Calendar.getInstance()
TimePickerDialog(context!!, TimePickerDialog.OnTimeSetListener { _, hourOfDay, minute ->
val t = getFormattedDate(hourOfDay, minute)
if (t in itemList) {
context?.toast(getString(R.string.et_same_trip_warning, convertTimeFormat(t)))
} else {
itemList.add(t)
itemList.sort()
adapter.notifyDataSetChanged()
checkEmptyList()
sharedModel.updateTripSelection(false)
}
}, cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), false).show()
}
private fun checkOldData() {
sharedModel.tripList.value?.let {
itemList.clear()
itemList.addAll(it)
adapter.notifyDataSetChanged()
checkEmptyList()
}
}
}
| mit | 739c706845d0b4d69672c85dc5b49810 | 35.353383 | 96 | 0.634259 | 4.865818 | false | false | false | false |
leantechstacks/jcart-backoffice-service | src/main/kotlin/com/leantechstacks/jcart/bo/web/model/ProductModel.kt | 1 | 935 | package com.leantechstacks.jcart.bo.web.model
import com.leantechstacks.jcart.bo.entities.Category
import com.leantechstacks.jcart.bo.entities.Product
import com.leantechstacks.jcart.bo.entities.Vendor
import java.math.BigDecimal
data class ProductModel (
var id: Long = 0,
var name: String = "",
var description: String? = null,
var price: BigDecimal = BigDecimal.ZERO,
var vendor: Vendor = Vendor(),
var categoryId: Long = 0
) {
constructor(productEntity: Product) : this(productEntity.id,
productEntity.name,
productEntity.description,
productEntity.price,
productEntity.vendor,
productEntity.category.id)
fun toEntity(): Product {
return Product(id,
name,
description.orEmpty(),
price,
vendor,
Category(categoryId))
}
}
| apache-2.0 | 775188492e2b2183ef13f7eadee3052b | 29.16129 | 64 | 0.611765 | 4.651741 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/test/java/org/wordpress/android/ui/reader/usecases/ReaderGetPostUseCaseTest.kt | 1 | 5151 | package org.wordpress.android.ui.reader.usecases
import kotlinx.coroutines.InternalCoroutinesApi
import org.assertj.core.api.Assertions.assertThat
import org.junit.Before
import org.junit.Test
import org.mockito.Mock
import org.mockito.kotlin.mock
import org.mockito.kotlin.spy
import org.mockito.kotlin.whenever
import org.wordpress.android.BaseUnitTest
import org.wordpress.android.TEST_DISPATCHER
import org.wordpress.android.datasets.wrappers.ReaderPostTableWrapper
import org.wordpress.android.models.ReaderPost
import org.wordpress.android.models.ReaderPostDiscoverData
import org.wordpress.android.models.ReaderPostDiscoverData.DiscoverType
import org.wordpress.android.test
@InternalCoroutinesApi
class ReaderGetPostUseCaseTest : BaseUnitTest() {
@Mock private lateinit var readerPostTableWrapper: ReaderPostTableWrapper
private val readerPostId = 1L
private val readerBlogId = 2L
private val discoverPostId = 3L
private val discoverBlogId = 4L
private val readerPost = ReaderPost().apply {
postId = readerPostId
blogId = readerBlogId
}
private val readerDiscoverSourcePost = ReaderPost().apply {
postId = discoverPostId
blogId = discoverBlogId
}
private lateinit var useCase: ReaderGetPostUseCase
@Before
fun setUp() {
useCase = ReaderGetPostUseCase(TEST_DISPATCHER, readerPostTableWrapper)
}
@Test
fun `given feed, when reader post is retrieved, feed post is returned`() = test {
whenever(
readerPostTableWrapper.getFeedPost(
blogId = readerBlogId,
postId = readerPostId,
excludeTextColumn = false
)
)
.thenReturn(readerPost)
val result = useCase.get(blogId = readerBlogId, postId = readerPostId, isFeed = true)
assertThat(result).isEqualTo(Pair<ReaderPost?, Boolean>(readerPost, true))
}
@Test
fun `given blog, when reader post is retrieved, blog post is returned`() = test {
whenever(
readerPostTableWrapper.getBlogPost(
blogId = readerBlogId,
postId = readerPostId,
excludeTextColumn = false
)
)
.thenReturn(readerPost)
val result = useCase.get(blogId = readerBlogId, postId = readerPostId, isFeed = false)
assertThat(result).isEqualTo(Pair<ReaderPost?, Boolean>(readerPost, false))
}
@Test
fun `given editor pick discover post is found, when reader post is retrieved, discover source post returned`() =
test {
val readerPost = createPost(discoverType = DiscoverType.EDITOR_PICK)
whenever(
readerPostTableWrapper.getBlogPost(
blogId = readerBlogId,
postId = readerPostId,
excludeTextColumn = false
)
).thenReturn(readerPost)
whenever(
readerPostTableWrapper.getBlogPost(
blogId = readerDiscoverSourcePost.blogId,
postId = readerDiscoverSourcePost.postId,
excludeTextColumn = false
)
).thenReturn(readerDiscoverSourcePost)
val result = useCase.get(blogId = readerBlogId, postId = readerPostId, isFeed = false)
assertThat(result).isEqualTo(Pair<ReaderPost?, Boolean>(readerDiscoverSourcePost, false))
}
@Test
fun `given non editor pick reader post is found, when reader post is retrieved, reader post is returned`() =
test {
val readerPost = createPost(discoverType = DiscoverType.SITE_PICK)
whenever(
readerPostTableWrapper.getBlogPost(
blogId = readerBlogId,
postId = readerPostId,
excludeTextColumn = false
)
).thenReturn(readerPost)
val result = useCase.get(blogId = readerBlogId, postId = readerPostId, isFeed = false)
assertThat(result).isEqualTo(Pair<ReaderPost?, Boolean>(readerPost, false))
}
private fun createPost(discoverType: DiscoverType = DiscoverType.OTHER): ReaderPost {
val post = spy(readerPost)
// The ReaderPost contains business logic and accesses static classes. Using spy() allows us to use it in tests.
whenever(post.isDiscoverPost).thenReturn(true)
val mockedDiscoverData: ReaderPostDiscoverData = mock()
whenever(post.discoverData).thenReturn(mockedDiscoverData)
whenever(mockedDiscoverData.discoverType).thenReturn(discoverType)
whenever(mockedDiscoverData.postId).thenReturn(readerDiscoverSourcePost.postId)
whenever(mockedDiscoverData.blogId).thenReturn(readerDiscoverSourcePost.blogId)
return post
}
}
| gpl-2.0 | 266cefab0e2df696e968a627b670bef4 | 39.242188 | 120 | 0.62648 | 5.468153 | false | true | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/stats/refresh/utils/WrappingLinearLayoutManager.kt | 1 | 2136 | package org.wordpress.android.ui.stats.refresh.utils
import android.content.Context
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
/**
* This class should be used only when the RecyclerView's height is set to wrap_content.
* In a normal recycler view when were decreasing the number of items, it first changes the RV height and then
* animates the removal of items. This doesn't look good because the items first disappear only to slide back into
* the view once their animation is finished. This layout manager reverts the order of animations and first animates
* the removal of items and then decreases the height of the wrapped recycler view.
* Solution is based on: https://stackoverflow.com/questions/40242011/custom-recyclerviews-layoutmanager-automeasuring-after-animation-finished-on-i
*/
class WrappingLinearLayoutManager(
context: Context?,
orientation: Int,
reverseLayout: Boolean
) : LinearLayoutManager(
context,
orientation,
reverseLayout
) {
private var enableAutoMeasure: Boolean = true
fun init() {
enableAutoMeasure = true
}
fun onItemRangeRemoved() {
enableAutoMeasure = false
}
override fun onMeasure(
recycler: RecyclerView.Recycler,
state: RecyclerView.State,
widthSpec: Int,
heightSpec: Int
) {
super.onMeasure(recycler, state, widthSpec, heightSpec)
if (!enableAutoMeasure) {
super.requestLayout()
requestSimpleAnimationsInNextLayout()
setMeasuredDimension(width, height)
}
}
override fun onItemsRemoved(recyclerView: RecyclerView, positionStart: Int, itemCount: Int) {
super.onItemsRemoved(recyclerView, positionStart, itemCount)
postOnAnimation {
recyclerView.itemAnimator?.isRunning {
enableAutoMeasure = true
requestLayout()
}
}
}
override fun isAutoMeasureEnabled(): Boolean = enableAutoMeasure
override fun supportsPredictiveItemAnimations(): Boolean = false
}
| gpl-2.0 | 925572670568a99980e6435ec4db3da3 | 34.016393 | 148 | 0.704588 | 5.085714 | false | false | false | false |
Turbo87/intellij-rust | src/test/kotlin/org/rust/lang/core/lexer/RustLexingTestCase.kt | 1 | 2156 | package org.rust.lang.core.lexer
import com.intellij.lexer.Lexer
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.application.ex.PathManagerEx
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.CharsetToolkit
import com.intellij.testFramework.LexerTestCase
import com.intellij.testFramework.UsefulTestCase
import org.jetbrains.annotations.NonNls
import org.rust.lang.RustTestCase
import org.rust.lang.pathToGoldTestFile
import org.rust.lang.pathToSourceTestFile
import java.io.File
import java.io.IOException
import java.nio.file.Paths
public class RustLexingTestCase : LexerTestCase(), RustTestCase {
override fun getDirPath(): String {
throw UnsupportedOperationException()
}
override fun getTestDataPath(): String = "org/rust/lang/core/lexer/fixtures"
override fun createLexer(): Lexer? = RustLexer()
// NOTE(matkad): this is basically a copy-paste of doFileTest.
// The only difference is that encoding is set to utf-8
fun doTest() {
val filePath = pathToSourceTestFile(getTestName(true))
var text = ""
try {
val fileText = FileUtil.loadFile(filePath.toFile(), CharsetToolkit.UTF8);
text = StringUtil.convertLineSeparators(if (shouldTrim()) fileText.trim() else fileText);
} catch (e: IOException) {
fail("can't load file " + filePath + ": " + e.message);
}
doTest(text);
}
protected override fun doTest(@NonNls text: String, expected: String?, lexer: Lexer) {
val result = printTokens(text, 0, lexer)
if (expected != null) {
UsefulTestCase.assertSameLines(expected, result)
} else {
UsefulTestCase.assertSameLinesWithFile(pathToGoldTestFile(getTestName(true)).toFile().canonicalPath, result)
}
}
fun testComments() = doTest()
fun testShebang() = doTest()
fun testFloat() = doTest()
fun testIdentifiers() = doTest()
fun testCharLiterals() = doTest()
fun testStringLiterals() = doTest()
fun testByteLiterals() = doTest()
}
| mit | b18a40a76ea716a9ab4e2a162b272391 | 35.542373 | 120 | 0.705473 | 4.427105 | false | true | false | false |
hsson/card-balance-app | app/src/main/java/se/creotec/chscardbalance2/receiver/BootReceiver.kt | 1 | 859 | // Copyright (c) 2017 Alexander Håkansson
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
package se.creotec.chscardbalance2.receiver
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.util.Log
import se.creotec.chscardbalance2.Constants
import se.creotec.chscardbalance2.service.BalanceWork
class BootReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent?) {
Log.i(LOG_TAG, "System boot detected")
if (intent == null || intent.action == null) {
return
} else if (intent.action == Constants.ACTION_BOOT_COMPLETED) {
BalanceWork.scheduleRepeating()
}
}
companion object {
private val LOG_TAG = BootReceiver::class.java.name
}
}
| mit | af87809248ea718819bfb904121dc506 | 29.642857 | 70 | 0.70979 | 4.29 | false | false | false | false |
ingokegel/intellij-community | plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/panels/management/packages/columns/renderers/PackageVersionTableCellRenderer.kt | 1 | 4165 | /*******************************************************************************
* Copyright 2000-2022 JetBrains s.r.o. and contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.columns.renderers
import com.intellij.icons.AllIcons
import com.intellij.ui.components.JBComboBoxLabel
import com.intellij.ui.components.JBLabel
import com.jetbrains.packagesearch.intellij.plugin.looksLikeGradleVariable
import com.jetbrains.packagesearch.intellij.plugin.ui.PackageSearchUI
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageModel
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageOperations
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.UiPackageModel
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.columns.colors
import net.miginfocom.swing.MigLayout
import org.jetbrains.annotations.Nls
import javax.swing.JPanel
import javax.swing.JTable
import javax.swing.table.TableCellRenderer
internal class PackageVersionTableCellRenderer : TableCellRenderer {
private var onlyStable = false
fun updateData(onlyStable: Boolean) {
this.onlyStable = onlyStable
}
override fun getTableCellRendererComponent(
table: JTable,
value: Any,
isSelected: Boolean,
hasFocus: Boolean,
row: Int,
column: Int
) = JPanel(MigLayout("al left center, insets 0 8 0 0")).apply {
table.colors.applyTo(this, isSelected)
val bgColor = if (!isSelected && value is UiPackageModel.SearchResult) {
PackageSearchUI.ListRowHighlightBackground
} else {
background
}
background = bgColor
val viewModel = checkNotNull(value as? UiPackageModel<*>)
val labelText = when (viewModel) {
is UiPackageModel.Installed -> versionMessage(viewModel.packageModel, viewModel.packageOperations)
is UiPackageModel.SearchResult -> viewModel.selectedVersion.displayName
}
val hasVersionsToChooseFrom = viewModel.sortedVersions.isNotEmpty()
val labelComponent = if (hasVersionsToChooseFrom) {
JBComboBoxLabel().apply {
icon = AllIcons.General.LinkDropTriangle
text = labelText
}
} else {
JBLabel().apply { text = labelText }
}
add(
labelComponent.apply {
table.colors.applyTo(this, isSelected)
background = bgColor
}
)
}
@Nls
private fun versionMessage(packageModel: PackageModel.Installed, packageOperations: PackageOperations): String {
val installedVersions = packageModel.usageInfo.asSequence()
.map { it.declaredVersion }
.distinct()
.sorted()
.joinToString { if (looksLikeGradleVariable(it)) "[${it.displayName}]" else it.displayName }
require(installedVersions.isNotBlank()) { "An installed package cannot produce an empty installed versions list" }
@Suppress("HardCodedStringLiteral") // Composed of @Nls components
return buildString {
append(installedVersions)
if (packageOperations.canUpgradePackage) {
val upgradeVersion = packageOperations.targetVersion ?: return@buildString
append(" → ")
append(upgradeVersion.displayName)
}
}
}
}
| apache-2.0 | 3e4c4533226f1b8a323f55ae94bdd5b8 | 38.647619 | 122 | 0.668748 | 5.216792 | false | false | false | false |
simoneapp/S3-16-simone | app/src/main/java/app/simone/multiplayer/controller/FirebaseListAdapterFactory.kt | 2 | 2422 | package app.simone.multiplayer.controller
import android.view.View
import android.widget.TextView
import app.simone.R
import app.simone.multiplayer.model.FacebookUser
import app.simone.multiplayer.model.MatchUserInfo
import app.simone.multiplayer.view.FriendsCellFiller
import app.simone.multiplayer.view.nearby.WaitingRoomActivity
import com.firebase.ui.database.FirebaseListAdapter
import com.google.firebase.database.*
/**
* Helper class producing adapters containing Facebook friends. Using `FirebaseListAdapter`, there's no
* need to handle updates to the adapter, since they're already handled by this custom adapter.
* @author Nicola Giancecchi
*/
class FirebaseListAdapterFactory {
companion object {
val db = FirebaseDatabase.getInstance()
/**
* Produces a Waiting Room Adapter, starting from the `ref` reference.
* @param ref reference node to be observed
* @param activity activity to be updated
* @return a FirebaseListAdapter<> object
*/
fun getWaitingRoomAdapter(ref: DatabaseReference, activity: WaitingRoomActivity) : FirebaseListAdapter<MatchUserInfo> {
return object : FirebaseListAdapter<MatchUserInfo>(activity, MatchUserInfo::class.java,
R.layout.cell_friends, ref.child(NearbyGameController.USERS_REF)) {
override fun populateView(v: View?, model: MatchUserInfo?, position: Int) {
val itemRef = getRef(position)
val key = itemRef.key
val userRef = db.getReference(NearbyGameController.USERS_REF).child(key)
val name = v?.findViewById(R.id.text_name) as TextView
userRef.addListenerForSingleValueEvent(object: ValueEventListener {
override fun onCancelled(p0: DatabaseError?) { }
override fun onDataChange(p0: DataSnapshot?) {
FriendsCellFiller.setName(v, p0?.child(FacebookUser.kNAME)?.value.toString())
FriendsCellFiller.setImage(v, p0?.child(FacebookUser.kPICTURE)?.value.toString(), activity)
if(model != null) {
FriendsCellFiller.setSelected(v, model.taken, activity)
}
}
})
}
}
}
}
} | mit | c2379f0d0a93f818e5f4a286d326c6cc | 40.775862 | 127 | 0.634187 | 4.912779 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertSealedClassToEnumIntention.kt | 1 | 7774 | // 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.intentions
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.TextRange
import com.intellij.psi.ElementDescriptionUtil
import com.intellij.psi.PsiElement
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.refactoring.util.CommonRefactoringUtil
import com.intellij.refactoring.util.RefactoringDescriptionLocation
import org.jetbrains.annotations.Nls
import org.jetbrains.kotlin.asJava.unwrapped
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.base.util.reformatted
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingRangeIntention
import org.jetbrains.kotlin.idea.core.util.runSynchronouslyWithProgress
import org.jetbrains.kotlin.idea.search.declarationsSearch.HierarchySearchRequest
import org.jetbrains.kotlin.idea.search.declarationsSearch.searchInheritors
import org.jetbrains.kotlin.idea.util.liftToExpected
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.psi.KtObjectDeclaration
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.KtSuperTypeCallEntry
import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.kotlin.resolve.descriptorUtil.getSuperClassNotAny
class ConvertSealedClassToEnumIntention : SelfTargetingRangeIntention<KtClass>(
KtClass::class.java,
KotlinBundle.lazyMessage("convert.to.enum.class")
) {
override fun applicabilityRange(element: KtClass): TextRange? {
val nameIdentifier = element.nameIdentifier ?: return null
val sealedKeyword = element.modifierList?.getModifier(KtTokens.SEALED_KEYWORD) ?: return null
val classDescriptor = element.resolveToDescriptorIfAny() ?: return null
if (classDescriptor.getSuperClassNotAny() != null) return null
return TextRange(sealedKeyword.startOffset, nameIdentifier.endOffset)
}
override fun applyTo(element: KtClass, editor: Editor?) {
val project = element.project
val klass = element.liftToExpected() as? KtClass ?: element
val searchAction = {
HierarchySearchRequest(klass, klass.useScope, false).searchInheritors().mapNotNull { it.unwrapped }
}
val subclasses: List<PsiElement> = if (element.isPhysical)
project.runSynchronouslyWithProgress(KotlinBundle.message("searching.inheritors"), true, searchAction) ?: return
else
searchAction().map { subClass ->
// search finds physical elements
try {
PsiTreeUtil.findSameElementInCopy(subClass, klass.containingFile)
} catch (_: IllegalStateException) {
return
}
}
val subclassesByContainer: Map<KtClass?, List<PsiElement>> = subclasses.sortedBy { it.textOffset }.groupBy {
if (it !is KtObjectDeclaration) return@groupBy null
if (it.superTypeListEntries.size != 1) return@groupBy null
val containingClass = it.containingClassOrObject as? KtClass ?: return@groupBy null
if (containingClass != klass && containingClass.liftToExpected() != klass) return@groupBy null
containingClass
}
val inconvertibleSubclasses: List<PsiElement> = subclassesByContainer[null] ?: emptyList()
if (inconvertibleSubclasses.isNotEmpty()) {
return showError(
KotlinBundle.message("all.inheritors.must.be.nested.objects.of.the.class.itself.and.may.not.inherit.from.other.classes.or.interfaces"),
inconvertibleSubclasses,
project,
editor
)
}
@Suppress("UNCHECKED_CAST")
val nonSealedClasses = (subclassesByContainer.keys as Set<KtClass>).filter { !it.isSealed() }
if (nonSealedClasses.isNotEmpty()) {
return showError(
KotlinBundle.message("all.expected.and.actual.classes.must.be.sealed.classes"),
nonSealedClasses,
project,
editor
)
}
if (subclassesByContainer.isNotEmpty()) {
subclassesByContainer.forEach { (currentClass, currentSubclasses) ->
processClass(currentClass!!, currentSubclasses, project)
}
} else {
processClass(klass, emptyList(), project)
}
}
private fun showError(@Nls message: String, elements: List<PsiElement>, project: Project, editor: Editor?) {
if (elements.firstOrNull()?.isPhysical == false) return
val elementDescriptions = elements.map {
ElementDescriptionUtil.getElementDescription(it, RefactoringDescriptionLocation.WITHOUT_PARENT)
}
@NlsSafe
val errorText = buildString {
append(message)
append(KotlinBundle.message("following.problems.are.found"))
elementDescriptions.sorted().joinTo(this)
}
return CommonRefactoringUtil.showErrorHint(project, editor, errorText, text, null)
}
private fun processClass(klass: KtClass, subclasses: List<PsiElement>, project: Project) {
val needSemicolon = klass.declarations.size > subclasses.size
val movedDeclarations = run {
val subclassesSet = subclasses.toSet()
klass.declarations.filter { it in subclassesSet }
}
val psiFactory = KtPsiFactory(klass)
val comma = psiFactory.createComma()
val semicolon = psiFactory.createSemicolon()
val constructorCallNeeded = klass.hasExplicitPrimaryConstructor() || klass.secondaryConstructors.isNotEmpty()
val entriesToAdd = movedDeclarations.mapIndexed { i, subclass ->
subclass as KtObjectDeclaration
val entryText = buildString {
append(subclass.name)
if (constructorCallNeeded) {
append((subclass.superTypeListEntries.firstOrNull() as? KtSuperTypeCallEntry)?.valueArgumentList?.text ?: "()")
}
}
val entry = psiFactory.createEnumEntry(entryText)
subclass.body?.let { body -> entry.add(body) }
if (i < movedDeclarations.lastIndex) {
entry.add(comma)
} else if (needSemicolon) {
entry.add(semicolon)
}
entry
}
movedDeclarations.forEach { it.delete() }
klass.removeModifier(KtTokens.SEALED_KEYWORD)
if (klass.isInterface()) {
klass.getClassOrInterfaceKeyword()?.replace(psiFactory.createClassKeyword())
}
klass.addModifier(KtTokens.ENUM_KEYWORD)
if (entriesToAdd.isNotEmpty()) {
val firstEntry = entriesToAdd
.reversed()
.asSequence()
.map { klass.addDeclarationBefore(it, null) }
.last()
// TODO: Add formatter rule
firstEntry.parent.addBefore(psiFactory.createNewLine(), firstEntry)
} else if (needSemicolon) {
klass.declarations.firstOrNull()?.let { anchor ->
val delimiter = anchor.parent.addBefore(semicolon, anchor).reformatted()
delimiter.reformatted()
}
}
}
} | apache-2.0 | d9642d440819a5e2aa63e997c8df47f5 | 41.955801 | 158 | 0.674813 | 5.175766 | false | false | false | false |
ingokegel/intellij-community | plugins/kotlin/jvm-debugger/core-fe10/src/org/jetbrains/kotlin/idea/debugger/stepping/smartStepInto/SmartStepTargetVisitor.kt | 1 | 15531 | // 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.debugger.stepping.smartStepInto
import com.intellij.debugger.actions.MethodSmartStepTarget
import com.intellij.debugger.actions.SmartStepTarget
import com.intellij.psi.PsiMethod
import com.intellij.util.Range
import com.intellij.util.containers.OrderedSet
import org.jetbrains.kotlin.builtins.functions.FunctionInvokeDescriptor
import org.jetbrains.kotlin.builtins.isBuiltinFunctionalType
import org.jetbrains.kotlin.builtins.isFunctionType
import org.jetbrains.kotlin.codegen.intrinsics.IntrinsicMethods
import org.jetbrains.kotlin.config.JvmTarget
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.idea.base.facet.platform.platform
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall
import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde
import org.jetbrains.kotlin.idea.debugger.core.breakpoints.isInlineOnly
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.load.java.JvmAbi
import org.jetbrains.kotlin.load.java.isFromJava
import org.jetbrains.kotlin.platform.jvm.JdkPlatform
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.calls.util.getParentCall
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.isInlineClassType
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter
import org.jetbrains.kotlin.resolve.scopes.getDescriptorsFiltered
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.SimpleType
import org.jetbrains.kotlin.types.checker.isSingleClassifierType
import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull
// TODO support class initializers, local functions, delegated properties with specified type, setter for properties
class SmartStepTargetVisitor(
private val element: KtElement,
private val lines: Range<Int>,
private val consumer: OrderedSet<SmartStepTarget>
) : KtTreeVisitorVoid() {
private fun append(target: SmartStepTarget) {
consumer += target
}
private val intrinsicMethods = run {
val jvmTarget = element.platform.firstIsInstanceOrNull<JdkPlatform>()?.targetVersion ?: JvmTarget.DEFAULT
IntrinsicMethods(jvmTarget)
}
override fun visitLambdaExpression(lambdaExpression: KtLambdaExpression) {
recordFunction(lambdaExpression.functionLiteral)
}
override fun visitNamedFunction(function: KtNamedFunction) {
if (!recordFunction(function)) {
super.visitNamedFunction(function)
}
}
override fun visitCallableReferenceExpression(expression: KtCallableReferenceExpression) {
recordCallableReference(expression)
super.visitCallableReferenceExpression(expression)
}
private fun recordCallableReference(expression: KtCallableReferenceExpression) {
val bindingContext = expression.analyze(BodyResolveMode.PARTIAL)
val resolvedCall = expression.callableReference.getResolvedCall(bindingContext) ?: return
when (val descriptor = resolvedCall.resultingDescriptor) {
is FunctionDescriptor -> recordFunctionReference(expression, descriptor)
is PropertyDescriptor -> recordGetter(expression, descriptor, bindingContext)
}
}
private fun recordFunctionReference(expression: KtCallableReferenceExpression, descriptor: FunctionDescriptor) {
val declaration = DescriptorToSourceUtilsIde.getAnyDeclaration(element.project, descriptor)
if (descriptor.isFromJava && declaration is PsiMethod) {
append(MethodSmartStepTarget(declaration, null, expression, true, lines))
} else if (declaration is KtNamedFunction) {
val label = KotlinMethodSmartStepTarget.calcLabel(descriptor)
append(
KotlinMethodReferenceSmartStepTarget(
lines,
expression,
label,
declaration,
CallableMemberInfo(descriptor)
)
)
}
}
private fun recordGetter(expression: KtExpression, descriptor: PropertyDescriptor, bindingContext: BindingContext) {
val getterDescriptor = descriptor.getter
if (getterDescriptor == null || getterDescriptor.isDefault) return
val ktDeclaration = DescriptorToSourceUtilsIde.getAnyDeclaration(element.project, getterDescriptor) as? KtDeclaration ?: return
val delegatedResolvedCall = bindingContext[BindingContext.DELEGATED_PROPERTY_RESOLVED_CALL, getterDescriptor]
if (delegatedResolvedCall != null) {
val delegatedPropertyGetterDescriptor = delegatedResolvedCall.resultingDescriptor
val delegateDeclaration = DescriptorToSourceUtilsIde.getAnyDeclaration(
element.project, delegatedPropertyGetterDescriptor
) as? KtDeclarationWithBody ?: return
val label = "${descriptor.name}." + KotlinMethodSmartStepTarget.calcLabel(delegatedPropertyGetterDescriptor)
appendPropertyFilter(delegatedPropertyGetterDescriptor, delegateDeclaration, label, expression, lines)
} else {
if (ktDeclaration is KtPropertyAccessor && ktDeclaration.hasBody()) {
val label = KotlinMethodSmartStepTarget.calcLabel(getterDescriptor)
appendPropertyFilter(getterDescriptor, ktDeclaration, label, expression, lines)
}
}
}
private fun appendPropertyFilter(
descriptor: CallableMemberDescriptor,
declaration: KtDeclarationWithBody,
label: String,
expression: KtExpression,
lines: Range<Int>
) {
val methodInfo = CallableMemberInfo(descriptor)
when (expression) {
is KtCallableReferenceExpression ->
append(
KotlinMethodReferenceSmartStepTarget(
lines,
expression,
label,
declaration,
methodInfo
)
)
else -> {
val ordinal = countExistingMethodCalls(declaration)
append(
KotlinMethodSmartStepTarget(
lines,
expression,
label,
declaration,
ordinal,
methodInfo
)
)
}
}
}
private fun recordFunction(function: KtFunction): Boolean {
val (parameter, resultingDescriptor) = function.getParameterAndResolvedCallDescriptor() ?: return false
val target = createSmartStepTarget(function, parameter, resultingDescriptor)
if (target != null) {
append(target)
return true
}
return false
}
private fun createSmartStepTarget(
function: KtFunction,
parameter: ValueParameterDescriptor,
resultingDescriptor: CallableMemberDescriptor
): KotlinLambdaSmartStepTarget? {
val declaration = DescriptorToSourceUtilsIde.getAnyDeclaration(element.project, resultingDescriptor) as? KtDeclaration ?: return null
val callerMethodOrdinal = countExistingMethodCalls(declaration)
if (parameter.isSamLambdaParameterDescriptor()) {
val methodDescriptor = parameter.type.getFirstAbstractMethodDescriptor() ?: return null
return KotlinLambdaSmartStepTarget(
function,
declaration,
lines,
KotlinLambdaInfo(
resultingDescriptor,
parameter,
callerMethodOrdinal,
methodDescriptor.containsInlineClassInValueArguments(),
true,
methodDescriptor.getMethodName()
)
)
}
return KotlinLambdaSmartStepTarget(
function,
declaration,
lines,
KotlinLambdaInfo(
resultingDescriptor,
parameter,
callerMethodOrdinal,
parameter.type.arguments.any { it.type.isInlineClassType() }
)
)
}
private fun countExistingMethodCalls(declaration: KtDeclaration): Int {
return consumer
.filterIsInstance<KotlinMethodSmartStepTarget>()
.count {
val targetDeclaration = it.getDeclaration()
targetDeclaration != null && targetDeclaration === declaration
}
}
override fun visitObjectLiteralExpression(expression: KtObjectLiteralExpression) {
// Skip calls in object declarations
}
override fun visitIfExpression(expression: KtIfExpression) {
expression.condition?.accept(this)
}
override fun visitWhileExpression(expression: KtWhileExpression) {
expression.condition?.accept(this)
}
override fun visitDoWhileExpression(expression: KtDoWhileExpression) {
expression.condition?.accept(this)
}
override fun visitForExpression(expression: KtForExpression) {
expression.loopRange?.accept(this)
}
override fun visitWhenExpression(expression: KtWhenExpression) {
expression.subjectExpression?.accept(this)
}
override fun visitArrayAccessExpression(expression: KtArrayAccessExpression) {
super.visitArrayAccessExpression(expression)
recordFunctionCall(expression)
}
override fun visitUnaryExpression(expression: KtUnaryExpression) {
super.visitUnaryExpression(expression)
recordFunctionCall(expression.operationReference)
}
override fun visitBinaryExpression(expression: KtBinaryExpression) {
super.visitBinaryExpression(expression)
recordFunctionCall(expression.operationReference)
}
override fun visitCallExpression(expression: KtCallExpression) {
val calleeExpression = expression.calleeExpression
if (calleeExpression != null) {
recordFunctionCall(calleeExpression)
}
super.visitCallExpression(expression)
}
override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) {
val bindingContext = expression.analyze(BodyResolveMode.PARTIAL)
val resolvedCall = expression.getResolvedCall(bindingContext) ?: return
val propertyDescriptor = resolvedCall.resultingDescriptor as? PropertyDescriptor ?: return
recordGetter(expression, propertyDescriptor, bindingContext)
super.visitSimpleNameExpression(expression)
}
private fun recordFunctionCall(expression: KtExpression) {
val resolvedCall = expression.resolveToCall() ?: return
val descriptor = resolvedCall.resultingDescriptor
if (descriptor !is FunctionDescriptor || isIntrinsic(descriptor)) return
val declaration = DescriptorToSourceUtilsIde.getAnyDeclaration(element.project, descriptor)
if (descriptor.isFromJava) {
if (declaration is PsiMethod) {
append(MethodSmartStepTarget(declaration, null, expression, false, lines))
}
} else {
if (declaration == null && !isInvokeInBuiltinFunction(descriptor)) {
return
}
if (declaration !is KtDeclaration?) return
if (descriptor is ConstructorDescriptor && descriptor.isPrimary) {
if (declaration is KtClass && declaration.getAnonymousInitializers().isEmpty()) {
// There is no constructor or init block, so do not show it in smart step into
return
}
}
// We can't step into @InlineOnly callables as there is no LVT, so skip them
if (declaration is KtCallableDeclaration && declaration.isInlineOnly()) {
return
}
val callLabel = KotlinMethodSmartStepTarget.calcLabel(descriptor)
val label = when (descriptor) {
is FunctionInvokeDescriptor -> {
when (expression) {
is KtSimpleNameExpression -> "${runReadAction { expression.text }}.$callLabel"
else -> callLabel
}
}
else -> callLabel
}
val ordinal = if (declaration == null) 0 else countExistingMethodCalls(declaration)
append(
KotlinMethodSmartStepTarget(
lines,
expression,
label,
declaration,
ordinal,
CallableMemberInfo(descriptor)
)
)
}
}
private fun isIntrinsic(descriptor: CallableMemberDescriptor): Boolean {
return intrinsicMethods.getIntrinsic(descriptor) != null
}
}
private fun PropertyAccessorDescriptor.getJvmMethodName(): String {
return DescriptorUtils.getJvmName(this) ?: JvmAbi.getterName(correspondingProperty.name.asString())
}
fun DeclarationDescriptor.getMethodName() =
when (this) {
is ClassDescriptor, is ConstructorDescriptor -> "<init>"
is PropertyAccessorDescriptor -> getJvmMethodName()
else -> name.asString()
}
fun KtFunction.isSamLambda(): Boolean {
val (parameter, _) = getParameterAndResolvedCallDescriptor() ?: return false
return parameter.isSamLambdaParameterDescriptor()
}
private fun ValueParameterDescriptor.isSamLambdaParameterDescriptor(): Boolean {
val type = type
return !type.isFunctionType && type is SimpleType && type.isSingleClassifierType
}
private fun KtFunction.getParameterAndResolvedCallDescriptor(): Pair<ValueParameterDescriptor, CallableMemberDescriptor>? {
val context = analyze()
val resolvedCall = getParentCall(context).getResolvedCall(context) ?: return null
val descriptor = resolvedCall.resultingDescriptor as? CallableMemberDescriptor ?: return null
val arguments = resolvedCall.valueArguments
for ((param, argument) in arguments) {
if (argument.arguments.any { getArgumentExpression(it) == this }) {
return Pair(param, descriptor)
}
}
return null
}
private fun getArgumentExpression(it: ValueArgument): KtExpression? {
return (it.getArgumentExpression() as? KtLambdaExpression)?.functionLiteral ?: it.getArgumentExpression()
}
private fun KotlinType.getFirstAbstractMethodDescriptor(): CallableMemberDescriptor? =
memberScope
.getDescriptorsFiltered(DescriptorKindFilter.FUNCTIONS)
.asSequence()
.filterIsInstance<CallableMemberDescriptor>()
.firstOrNull {
it.modality == Modality.ABSTRACT
}
private fun isInvokeInBuiltinFunction(descriptor: DeclarationDescriptor): Boolean {
if (descriptor !is FunctionInvokeDescriptor) return false
val classDescriptor = descriptor.containingDeclaration as? ClassDescriptor ?: return false
return classDescriptor.defaultType.isBuiltinFunctionalType
}
| apache-2.0 | f6aea835995a0f5868002c632d1edc08 | 40.526738 | 158 | 0.679351 | 6.160651 | false | false | false | false |
micolous/metrodroid | src/commonMain/kotlin/au/id/micolous/metrodroid/transit/yargor/YarGorTransitData.kt | 1 | 2358 | /*
* YarGorTransitData.kt
*
* Copyright 2019 Google
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package au.id.micolous.metrodroid.transit.yargor
import au.id.micolous.metrodroid.card.classic.ClassicCard
import au.id.micolous.metrodroid.multi.Localizer
import au.id.micolous.metrodroid.multi.Parcelize
import au.id.micolous.metrodroid.multi.R
import au.id.micolous.metrodroid.time.MetroTimeZone
import au.id.micolous.metrodroid.transit.TransitBalance
import au.id.micolous.metrodroid.transit.TransitData
import au.id.micolous.metrodroid.util.NumberUtils
@Parcelize
class YarGorTransitData(private val mSerial: Long,
private val mLastTrip: YarGorTrip?,
private val mSub: YarGorSubscription) : TransitData() {
override val serialNumber: String?
get() = formatSerial(mSerial)
override val cardName: String
get() = Localizer.localizeString(R.string.card_name_yargor)
override val balance: TransitBalance?
get() = null
override val trips: List<YarGorTrip>
get() = listOfNotNull(mLastTrip)
override val subscriptions: List<YarGorSubscription>
get() = listOf(mSub)
companion object {
val TZ = MetroTimeZone.MOSCOW
fun parse(card: ClassicCard): YarGorTransitData {
return YarGorTransitData(
mSub = YarGorSubscription.parse(card[10]),
mLastTrip = YarGorTrip.parse(card[12, 0].data),
mSerial = getSerial(card)
)
}
fun getSerial(card: ClassicCard): Long = card.tagId.byteArrayToLongReversed()
fun formatSerial(serial: Long): String = NumberUtils.groupString((serial + 90000000000L).toString(), ".", 4)
}
}
| gpl-3.0 | 5c8f09e66352dcccf29621f137ac1e43 | 34.727273 | 116 | 0.699746 | 4.326606 | false | false | false | false |
iPoli/iPoli-android | app/src/main/java/io/ipoli/android/player/usecase/FindAverageFocusedDurationForPeriodUseCase.kt | 1 | 1297 | package io.ipoli.android.player.usecase
import io.ipoli.android.common.UseCase
import io.ipoli.android.common.datetime.Duration
import io.ipoli.android.common.datetime.Minute
import io.ipoli.android.common.datetime.minutes
import io.ipoli.android.quest.data.persistence.QuestRepository
import org.threeten.bp.LocalDate
class FindAverageFocusedDurationForPeriodUseCase(private val questRepository: QuestRepository) :
UseCase<FindAverageFocusedDurationForPeriodUseCase.Params, Duration<Minute>> {
override fun execute(parameters: Params): Duration<Minute> {
val startDate = parameters.currentDate.minusDays(parameters.dayPeriod.toLong() - 1)
val endDate = parameters.currentDate
val qs = if (parameters.friendId != null)
questRepository.findCompletedInPeriodOfFriend(parameters.friendId, startDate, endDate)
else
questRepository.findCompletedInPeriod(startDate, endDate)
val productiveMinutes = qs
.filter { it.hasTimer }
.sumBy { it.actualDuration.asMinutes.intValue }
return (productiveMinutes / parameters.dayPeriod).minutes
}
data class Params(
val dayPeriod: Int = 7,
val currentDate: LocalDate = LocalDate.now(),
val friendId: String? = null
)
} | gpl-3.0 | 01b5dab38a425f0701118d80a18fabc2 | 36.085714 | 98 | 0.733231 | 4.441781 | false | false | false | false |
iPoli/iPoli-android | app/src/main/java/io/ipoli/android/common/persistence/BaseFirestoreRepository.kt | 1 | 2953 | package io.ipoli.android.common.persistence
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.firestore.*
import io.ipoli.android.common.datetime.Duration
import io.ipoli.android.common.datetime.Millisecond
import io.ipoli.android.quest.Entity
/**
* Created by Venelin Valkov <[email protected]>
* on 02/05/2018.
*/
abstract class BaseFirestoreRepository<E, out T>(
protected val database: FirebaseFirestore
) : Repository<E> where E : Entity, T : FirestoreModel {
abstract val collectionReference: CollectionReference
protected val playerId: String
get() = FirebaseAuth.getInstance().currentUser!!.uid
override fun save(entity: E): E {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun save(entities: List<E>): List<E> {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun findAllForSync(lastSync: Duration<Millisecond>): List<E> {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
fun addToBatch(entities: List<E>, batch: WriteBatch) {
entities.forEach {
addToBatch(it, batch)
}
}
fun addToBatch(entity: E, batch: WriteBatch) {
batch.set(
collectionReference.document(entity.id),
toDatabaseObject(entity).map
)
}
protected abstract fun toEntityObject(dataMap: MutableMap<String, Any?>): E
protected abstract fun toDatabaseObject(entity: E): T
protected fun extractDocument(ref: DocumentReference): E? {
val result = ref.getSync()
if (!result.exists()) {
return null
}
return toEntityObject(result.data!!)
}
protected val Query.notRemovedEntities
get() =
toEntityObjects(whereEqualTo("removedAt", null).documents)
protected val Query.entities
get() =
toEntityObjects(documents)
protected fun toEntityObjects(snapshots: List<DocumentSnapshot>) =
snapshots.map { toEntityObject(it.data!!) }
}
abstract class BaseEntityFirestoreRepository<E, out T>(
database: FirebaseFirestore
) : BaseFirestoreRepository<E, T>(
database
) where E : Entity, T : FirestoreModel {
abstract val entityReference: DocumentReference
fun find(): E? =
extractDocument(entityReference)
}
abstract class BaseCollectionFirestoreRepository<E, out T>(
database: FirebaseFirestore
) : BaseFirestoreRepository<E, T>(
database
) where E : Entity, T : FirestoreModel {
fun findById(id: String): E? =
extractDocument(documentReference(id))
fun findAllNotRemoved() = collectionReference.notRemovedEntities
fun findAll() = collectionReference.entities
protected fun documentReference(id: String) = collectionReference.document(id)
} | gpl-3.0 | f01a0e8d0741d762b54bcee9ad5b17e4 | 28.838384 | 107 | 0.690484 | 4.460725 | false | false | false | false |
GunoH/intellij-community | python/python-psi-impl/src/com/jetbrains/python/codeInsight/PyDataclasses.kt | 3 | 15218 | /*
* Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
*/
package com.jetbrains.python.codeInsight
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.util.QualifiedName
import com.jetbrains.python.PyNames
import com.jetbrains.python.codeInsight.PyDataclassParameters.Type
import com.jetbrains.python.psi.*
import com.jetbrains.python.psi.PyKnownDecoratorUtil.KnownDecorator
import com.jetbrains.python.psi.impl.PyCallExpressionHelper
import com.jetbrains.python.psi.impl.PyEvaluator
import com.jetbrains.python.psi.impl.StubAwareComputation
import com.jetbrains.python.psi.impl.stubs.PyDataclassStubImpl
import com.jetbrains.python.psi.resolve.PyResolveUtil
import com.jetbrains.python.psi.stubs.PyDataclassStub
import com.jetbrains.python.psi.types.PyCallableParameter
import com.jetbrains.python.psi.types.PyCallableParameterImpl
import com.jetbrains.python.psi.types.PyCallableTypeImpl
import com.jetbrains.python.psi.types.TypeEvalContext
object PyDataclassNames {
object Dataclasses {
const val DATACLASSES_MISSING = "dataclasses.MISSING"
const val DATACLASSES_INITVAR = "dataclasses.InitVar"
const val DATACLASSES_FIELDS = "dataclasses.fields"
const val DATACLASSES_ASDICT = "dataclasses.asdict"
const val DATACLASSES_FIELD = "dataclasses.field"
const val DATACLASSES_REPLACE = "dataclasses.replace"
const val DUNDER_POST_INIT = "__post_init__"
val DECORATOR_PARAMETERS = listOf("init", "repr", "eq", "order", "unsafe_hash", "frozen")
val HELPER_FUNCTIONS = setOf(DATACLASSES_FIELDS, DATACLASSES_ASDICT, "dataclasses.astuple", DATACLASSES_REPLACE)
}
object Attrs {
val ATTRS_NOTHING = setOf("attr.NOTHING", "attrs.NOTHING")
val ATTRS_FACTORY = setOf("attr.Factory", "attrs.Factory")
val ATTRS_ASSOC = setOf("attr.assoc", "attrs.assoc")
val ATTRS_EVOLVE = setOf("attr.evolve", "attrs.evolve")
val ATTRS_FROZEN = setOf("attr.frozen", "attrs.frozen")
const val DUNDER_POST_INIT = "__attrs_post_init__"
val DECORATOR_PARAMETERS = listOf(
"these",
"repr_ns",
"repr",
"cmp",
"hash",
"init",
"slots",
"frozen",
"weakref_slot",
"str",
"auto_attribs",
"kw_only",
"cache_hash",
"auto_exc",
"eq",
"order",
)
val FIELD_FUNCTIONS = setOf(
"attr.ib",
"attr.attr",
"attr.attrib",
"attr.field",
"attrs.field",
)
val INSTANCE_HELPER_FUNCTIONS = setOf(
"attr.asdict",
"attr.astuple",
"attr.assoc",
"attr.evolve",
"attrs.asdict",
"attrs.astuple",
"attrs.assoc",
"attrs.evolve",
)
val CLASS_HELPERS_FUNCTIONS = setOf(
"attr.fields",
"attr.fields_dict",
"attrs.fields",
"attrs.fields_dict",
)
}
}
/**
* It should be used only to map arguments to parameters and
* determine what settings dataclass has.
*/
private val DECORATOR_AND_TYPE_AND_PARAMETERS = listOf(
Triple(KnownDecorator.DATACLASSES_DATACLASS, PyDataclassParameters.PredefinedType.STD, PyDataclassNames.Dataclasses.DECORATOR_PARAMETERS),
Triple(KnownDecorator.ATTR_S, PyDataclassParameters.PredefinedType.ATTRS, PyDataclassNames.Attrs.DECORATOR_PARAMETERS),
Triple(KnownDecorator.ATTR_ATTRS, PyDataclassParameters.PredefinedType.ATTRS, PyDataclassNames.Attrs.DECORATOR_PARAMETERS),
Triple(KnownDecorator.ATTR_ATTRIBUTES, PyDataclassParameters.PredefinedType.ATTRS, PyDataclassNames.Attrs.DECORATOR_PARAMETERS),
Triple(KnownDecorator.ATTR_DATACLASS, PyDataclassParameters.PredefinedType.ATTRS, PyDataclassNames.Attrs.DECORATOR_PARAMETERS),
Triple(KnownDecorator.ATTR_DEFINE, PyDataclassParameters.PredefinedType.ATTRS, PyDataclassNames.Attrs.DECORATOR_PARAMETERS),
Triple(KnownDecorator.ATTR_MUTABLE, PyDataclassParameters.PredefinedType.ATTRS, PyDataclassNames.Attrs.DECORATOR_PARAMETERS),
Triple(KnownDecorator.ATTR_FROZEN, PyDataclassParameters.PredefinedType.ATTRS, PyDataclassNames.Attrs.DECORATOR_PARAMETERS),
Triple(KnownDecorator.ATTRS_DEFINE, PyDataclassParameters.PredefinedType.ATTRS, PyDataclassNames.Attrs.DECORATOR_PARAMETERS),
Triple(KnownDecorator.ATTRS_MUTABLE, PyDataclassParameters.PredefinedType.ATTRS, PyDataclassNames.Attrs.DECORATOR_PARAMETERS),
Triple(KnownDecorator.ATTRS_FROZEN, PyDataclassParameters.PredefinedType.ATTRS, PyDataclassNames.Attrs.DECORATOR_PARAMETERS),
)
fun parseStdDataclassParameters(cls: PyClass, context: TypeEvalContext): PyDataclassParameters? {
return parseDataclassParameters(cls, context)?.takeIf { it.type.asPredefinedType == PyDataclassParameters.PredefinedType.STD }
}
fun parseDataclassParameters(cls: PyClass, context: TypeEvalContext): PyDataclassParameters? {
return PyUtil.getNullableParameterizedCachedValue(cls, context) {
StubAwareComputation.on(cls)
.withCustomStub { stub -> stub.getCustomStub(PyDataclassStub::class.java) }
.overStub(::parseDataclassParametersFromStub)
.overAst { parseDataclassParametersFromAST(it, context) }
.withStubBuilder { PyDataclassStubImpl.create(it) }
.compute(context)
}
}
/**
* This method MUST be used only while building stub for dataclass.
*
* @see parseStdDataclassParameters
* @see parseDataclassParameters
*/
fun parseDataclassParametersForStub(cls: PyClass): PyDataclassParameters? = parseDataclassParametersFromAST(cls, null)
fun resolvesToOmittedDefault(expression: PyExpression, type: Type): Boolean {
if (expression is PyReferenceExpression) {
val qNames = PyResolveUtil.resolveImportedElementQNameLocally(expression)
return when (type.asPredefinedType) {
PyDataclassParameters.PredefinedType.STD -> qNames.any { it.toString() == PyDataclassNames.Dataclasses.DATACLASSES_MISSING }
PyDataclassParameters.PredefinedType.ATTRS -> qNames.any { it.toString() in PyDataclassNames.Attrs.ATTRS_NOTHING }
else -> false
}
}
return false
}
/**
* It should be used only to map arguments to parameters and
* determine what settings dataclass has.
*/
private fun decoratorAndTypeAndMarkedCallee(project: Project): List<Triple<QualifiedName, Type, List<PyCallableParameter>>> {
val generator = PyElementGenerator.getInstance(project)
val ellipsis = generator.createEllipsis()
return PyDataclassParametersProvider.EP_NAME.extensionList.mapNotNull { it.getDecoratorAndTypeAndParameters(project) } +
DECORATOR_AND_TYPE_AND_PARAMETERS.map {
if (it.second == PyDataclassParameters.PredefinedType.STD) {
val parameters = mutableListOf(PyCallableParameterImpl.psi(generator.createSingleStarParameter()))
parameters.addAll(it.third.map { name -> PyCallableParameterImpl.nonPsi(name, null, ellipsis) })
Triple(it.first.qualifiedName, it.second, parameters)
}
else {
Triple(it.first.qualifiedName, it.second, it.third.map { name -> PyCallableParameterImpl.nonPsi(name, null, ellipsis) })
}
}
}
private fun parseDataclassParametersFromAST(cls: PyClass, context: TypeEvalContext?): PyDataclassParameters? {
val decorators = cls.decoratorList ?: return null
val provided = PyDataclassParametersProvider.EP_NAME.extensionList.asSequence().mapNotNull {
it.getDataclassParameters(cls, context)
}.firstOrNull()
if (provided != null) return provided
for (decorator in decorators.decorators) {
val callee = (decorator.callee as? PyReferenceExpression) ?: continue
for (decoratorQualifiedName in PyResolveUtil.resolveImportedElementQNameLocally(callee)) {
val types = decoratorAndTypeAndMarkedCallee(cls.project)
val decoratorAndTypeAndMarkedCallee = types.firstOrNull { it.first == decoratorQualifiedName } ?: continue
val mapping = PyCallExpressionHelper.mapArguments(
decorator,
PyCallableTypeImpl(decoratorAndTypeAndMarkedCallee.third, null),
context ?: TypeEvalContext.codeInsightFallback(cls.project)
)
val builder = PyDataclassParametersBuilder(decoratorAndTypeAndMarkedCallee.second, decoratorAndTypeAndMarkedCallee.first, cls)
mapping
.mappedParameters
.entries
.forEach {
builder.update(it.value.name, it.key)
}
return builder.build()
}
}
return null
}
private fun parseDataclassParametersFromStub(stub: PyDataclassStub?): PyDataclassParameters? {
return stub?.let {
val type =
PyDataclassParametersProvider.EP_NAME.extensionList.map { e -> e.getType() }.firstOrNull { t -> t.name == it.type }
?: PyDataclassParameters.PredefinedType.values().firstOrNull { t -> t.name == it.type }
?: PyDataclassParameters.PredefinedType.STD
PyDataclassParameters(
it.initValue(), it.reprValue(), it.eqValue(), it.orderValue(), it.unsafeHashValue(), it.frozenValue(), it.kwOnly(),
null, null, null, null, null, null, null,
type, emptyMap()
)
}
}
/**
* Data describing dataclass.
*
* A parameter has default value if it is omitted or its value could not be evaluated.
* A parameter has `null` expression if it is omitted or is taken from a stub.
*
* This class also describes [type] of the dataclass and
* contains key-value pairs of other parameters and their expressions.
*/
data class PyDataclassParameters(val init: Boolean,
val repr: Boolean,
val eq: Boolean,
val order: Boolean,
val unsafeHash: Boolean,
val frozen: Boolean,
val kwOnly: Boolean,
val initArgument: PyExpression?,
val reprArgument: PyExpression?,
val eqArgument: PyExpression?,
val orderArgument: PyExpression?,
val unsafeHashArgument: PyExpression?,
val frozenArgument: PyExpression?,
val kwOnlyArgument: PyExpression?,
val type: Type,
val others: Map<String, PyExpression>) {
interface Type {
val name: String
val asPredefinedType: PredefinedType?
}
enum class PredefinedType : Type {
STD, ATTRS;
override val asPredefinedType: PredefinedType? = this
}
}
interface PyDataclassParametersProvider {
companion object {
val EP_NAME: ExtensionPointName<PyDataclassParametersProvider> = ExtensionPointName.create("Pythonid.pyDataclassParametersProvider")
}
fun getType(): Type
fun getDecoratorAndTypeAndParameters(project: Project): Triple<QualifiedName, Type, List<PyCallableParameter>>? = null
fun getDataclassParameters(cls: PyClass, context: TypeEvalContext?): PyDataclassParameters? = null
}
private class PyDataclassParametersBuilder(private val type: Type, decorator: QualifiedName, anchor: PsiElement) {
companion object {
private const val DEFAULT_INIT = true
private const val DEFAULT_REPR = true
private const val DEFAULT_EQ = true
private const val DEFAULT_ORDER = false
private const val DEFAULT_UNSAFE_HASH = false
private const val DEFAULT_FROZEN = false
private const val DEFAULT_KW_ONLY = false
}
private var init = DEFAULT_INIT
private var repr = DEFAULT_REPR
private var eq = DEFAULT_EQ
private var order = if (type.asPredefinedType == PyDataclassParameters.PredefinedType.ATTRS) DEFAULT_EQ else DEFAULT_ORDER
private var unsafeHash = DEFAULT_UNSAFE_HASH
private var frozen = decorator.toString() in PyDataclassNames.Attrs.ATTRS_FROZEN || DEFAULT_FROZEN
private var kwOnly = DEFAULT_KW_ONLY
private var initArgument: PyExpression? = null
private var reprArgument: PyExpression? = null
private var eqArgument: PyExpression? = null
private var orderArgument: PyExpression? = null
private var unsafeHashArgument: PyExpression? = null
private var frozenArgument: PyExpression? = null
private var kwOnlyArgument: PyExpression? = null
private val others = mutableMapOf<String, PyExpression>()
init {
if (type.asPredefinedType == PyDataclassParameters.PredefinedType.ATTRS && decorator == KnownDecorator.ATTR_DATACLASS.qualifiedName) {
PyElementGenerator.getInstance(anchor.project)
.createExpressionFromText(LanguageLevel.forElement(anchor), PyNames.TRUE)
.also { others["auto_attribs"] = it }
}
}
fun update(name: String?, argument: PyExpression?) {
val value = PyUtil.peelArgument(argument)
when (name) {
"init" -> {
init = PyEvaluator.evaluateAsBoolean(value, DEFAULT_INIT)
initArgument = argument
return
}
"repr" -> {
repr = PyEvaluator.evaluateAsBoolean(value, DEFAULT_REPR)
reprArgument = argument
return
}
"frozen" -> {
frozen = PyEvaluator.evaluateAsBoolean(value, DEFAULT_FROZEN)
frozenArgument = argument
return
}
}
if (type.asPredefinedType == PyDataclassParameters.PredefinedType.STD) {
when (name) {
"eq" -> {
eq = PyEvaluator.evaluateAsBoolean(value, DEFAULT_EQ)
eqArgument = argument
return
}
"order" -> {
order = PyEvaluator.evaluateAsBoolean(value, DEFAULT_ORDER)
orderArgument = argument
return
}
"unsafe_hash" -> {
unsafeHash = PyEvaluator.evaluateAsBoolean(value, DEFAULT_UNSAFE_HASH)
unsafeHashArgument = argument
return
}
}
}
else if (type.asPredefinedType == PyDataclassParameters.PredefinedType.ATTRS) {
when (name) {
"eq" -> {
eq = PyEvaluator.evaluateAsBoolean(value, DEFAULT_EQ)
eqArgument = argument
if (orderArgument == null) {
order = eq
orderArgument = eqArgument
}
}
"order" -> {
if (argument !is PyNoneLiteralExpression) {
order = PyEvaluator.evaluateAsBoolean(value, DEFAULT_EQ)
orderArgument = argument
}
}
"cmp" -> {
eq = PyEvaluator.evaluateAsBoolean(value, DEFAULT_EQ)
eqArgument = argument
order = eq
orderArgument = eqArgument
return
}
"hash" -> {
unsafeHash = PyEvaluator.evaluateAsBoolean(value, DEFAULT_UNSAFE_HASH)
unsafeHashArgument = argument
return
}
"kw_only" -> {
kwOnly = PyEvaluator.evaluateAsBoolean(value, DEFAULT_KW_ONLY)
kwOnlyArgument = argument
return
}
}
}
if (name != null && argument != null) {
others[name] = argument
}
}
fun build() = PyDataclassParameters(
init, repr, eq, order, unsafeHash, frozen, kwOnly,
initArgument, reprArgument, eqArgument, orderArgument, unsafeHashArgument, frozenArgument, kwOnlyArgument,
type, others
)
}
| apache-2.0 | 0b61651b057056692eb9faaffeb3c5c4 | 37.332494 | 140 | 0.692272 | 4.763067 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/jvm-debugger/sequence/src/org/jetbrains/kotlin/idea/debugger/sequence/psi/KotlinPsiUtil.kt | 4 | 3098 | // 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.debugger.sequence.psi
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode
import org.jetbrains.kotlin.idea.util.approximateFlexibleTypes
import org.jetbrains.kotlin.psi.KtCallExpression
import org.jetbrains.kotlin.psi.KtDotQualifiedExpression
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.renderer.DescriptorRenderer
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue
import org.jetbrains.kotlin.types.FlexibleType
import org.jetbrains.kotlin.types.KotlinType
object KotlinPsiUtil {
fun getTypeName(type: KotlinType): String {
if (type is FlexibleType) {
return DescriptorRenderer.FQ_NAMES_IN_TYPES.renderType(type.approximateFlexibleTypes())
}
return DescriptorRenderer.FQ_NAMES_IN_TYPES.renderType(type)
}
fun getTypeWithoutTypeParameters(type: KotlinType): String {
val descriptor = type.constructor.declarationDescriptor ?: return getTypeName(type)
return descriptor.fqNameSafe.asString()
}
}
fun KtCallExpression.callName(): String = this.calleeExpression!!.text
// Used in JAICF plugin (https://plugins.jetbrains.com/plugin/17391-jaicf/)
@Deprecated(
"Function is semantically incorrect as there might be both dispatch and extension receivers. Replace call with appropriate logic.",
level = DeprecationLevel.ERROR
)
fun KtCallExpression.receiverValue(): ReceiverValue? {
val resolvedCall = getResolvedCall(analyze(BodyResolveMode.PARTIAL)) ?: return null
return resolvedCall.dispatchReceiver ?: resolvedCall.extensionReceiver
}
// Used in JAICF plugin (https://plugins.jetbrains.com/plugin/17391-jaicf/)
@Deprecated(
"Function is semantically incorrect as there might be both dispatch and extension receivers. Replace call with appropriate logic.",
level = DeprecationLevel.ERROR
)
fun KtCallExpression.receiverType(): KotlinType? {
@Suppress("DEPRECATION_ERROR")
return receiverValue()?.type
}
fun KtCallExpression.previousCall(): KtCallExpression? {
val parent = this.parent as? KtDotQualifiedExpression ?: return null
val receiverExpression = parent.receiverExpression
if (receiverExpression is KtCallExpression) return receiverExpression
if (receiverExpression is KtDotQualifiedExpression) return receiverExpression.selectorExpression as? KtCallExpression
return null
}
@Deprecated(
"Use org.jetbrains.kotlin.idea.core.analyze() instead.",
ReplaceWith("resolveType()", "org.jetbrains.kotlin.idea.core.analyze"),
level = DeprecationLevel.ERROR
)
fun KtExpression.resolveType(): KotlinType =
this.analyze(BodyResolveMode.PARTIAL).getType(this)!! | apache-2.0 | 10faf5dc72f8b7ac47d87b36fd066e1b | 43.271429 | 158 | 0.789864 | 4.788253 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/RedundantWithInspection.kt | 5 | 5350 | // 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.ProblemsHolder
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElementVisitor
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.core.moveCaret
import org.jetbrains.kotlin.idea.inspections.UnusedLambdaExpressionBodyInspection.Companion.replaceBlockExpressionWithLambdaBody
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.allChildren
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection
import org.jetbrains.kotlin.idea.codeinsight.utils.findExistingEditor
class RedundantWithInspection : AbstractKotlinInspection() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor =
callExpressionVisitor(fun(callExpression) {
val callee = callExpression.calleeExpression ?: return
if (callee.text != "with") return
val valueArguments = callExpression.valueArguments
if (valueArguments.size != 2) return
val receiver = valueArguments[0].getArgumentExpression() ?: return
val lambda = valueArguments[1].lambdaExpression() ?: return
val lambdaBody = lambda.bodyExpression ?: return
val context = callExpression.analyze(BodyResolveMode.PARTIAL_WITH_CFA)
if (lambdaBody.statements.size > 1 && callExpression.isUsedAsExpression(context)) return
if (callExpression.getResolvedCall(context)?.resultingDescriptor?.fqNameSafe != FqName("kotlin.with")) return
val lambdaDescriptor = context[BindingContext.FUNCTION, lambda.functionLiteral] ?: return
var used = false
lambda.functionLiteral.acceptChildren(object : KtVisitorVoid() {
override fun visitKtElement(element: KtElement) {
if (used) return
element.acceptChildren(this)
if (element is KtReturnExpression && element.getLabelName() == "with") {
used = true
return
}
if (isUsageOfDescriptor(lambdaDescriptor, element, context)) {
used = true
}
}
})
if (!used) {
val quickfix = when (receiver) {
is KtSimpleNameExpression, is KtStringTemplateExpression, is KtConstantExpression -> RemoveRedundantWithFix()
else -> null
}
holder.registerProblem(
callee,
KotlinBundle.message("inspection.redundant.with.display.name"),
quickfix
)
}
})
}
private fun KtValueArgument.lambdaExpression(): KtLambdaExpression? =
(this as? KtLambdaArgument)?.getLambdaExpression() ?: this.getArgumentExpression() as? KtLambdaExpression
private class RemoveRedundantWithFix : LocalQuickFix {
override fun getName() = KotlinBundle.message("remove.redundant.with.fix.text")
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val callExpression = descriptor.psiElement.parent as? KtCallExpression ?: return
val lambdaExpression = callExpression.valueArguments.getOrNull(1)?.lambdaExpression() ?: return
val lambdaBody = lambdaExpression.bodyExpression ?: return
val declaration = callExpression.getStrictParentOfType<KtDeclarationWithBody>()
val replaced = if (declaration?.equalsToken != null && KtPsiUtil.deparenthesize(declaration.bodyExpression) == callExpression) {
val singleReturnedExpression = (lambdaBody.statements.singleOrNull() as? KtReturnExpression)?.returnedExpression
if (singleReturnedExpression != null) {
callExpression.replaced(singleReturnedExpression)
} else {
declaration.replaceBlockExpressionWithLambdaBody(lambdaBody)
declaration.bodyExpression
}
} else {
val result = lambdaBody.allChildren.takeUnless { it.isEmpty }?.let { range ->
callExpression.parent.addRangeAfter(range.first, range.last, callExpression)
}
callExpression.delete()
result
}
if (replaced != null) {
replaced.findExistingEditor()?.moveCaret(replaced.startOffset)
}
}
}
| apache-2.0 | d8e2069eef3f816c7dec420b59ed33a0 | 46.767857 | 136 | 0.69028 | 5.667373 | false | false | false | false |
GunoH/intellij-community | platform/platform-api/src/com/intellij/util/ui/LafIconLookup.kt | 7 | 2863 | // 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.util.ui
import com.intellij.icons.AllIcons
import com.intellij.openapi.util.IconLoader
import com.intellij.ui.ColorUtil
import com.intellij.ui.JBColor
import javax.swing.Icon
import javax.swing.UIManager
/**
* @author Konstantin Bulenkov
*/
private const val ICONS_DIR_PREFIX = "com/intellij/ide/ui/laf/icons/"
private val defaultDirProver = DirProvider()
open class DirProvider {
open val defaultExtension: String
get() = "png"
open fun dir(): String = ICONS_DIR_PREFIX + if (StartupUiUtil.isUnderDarcula()) "darcula/" else "intellij/"
}
object LafIconLookup {
@JvmStatic
@JvmOverloads
fun getIcon(name: String,
selected: Boolean = false,
focused: Boolean = false,
enabled: Boolean = true,
editable: Boolean = false,
pressed: Boolean = false): Icon {
return findIcon(name,
selected = selected,
focused = focused,
enabled = enabled,
editable = editable,
pressed = pressed,
dirProvider = DirProvider())
?: AllIcons.Actions.Stub
}
fun findIcon(name: String,
selected: Boolean = false,
focused: Boolean = false,
enabled: Boolean = true,
editable: Boolean = false,
pressed: Boolean = false,
dirProvider: DirProvider = defaultDirProver): Icon? {
var key = name
if (editable) {
key += "Editable"
}
if (selected && !isUseRegularIconOnSelection(name)) {
key += "Selected"
}
when {
pressed -> key += "Pressed"
focused -> key += "Focused"
!enabled -> key += "Disabled"
}
// for Mac blue theme and other LAFs use default directory icons
val providerClass = dirProvider.javaClass
val classLoader = providerClass.classLoader
val dir = dirProvider.dir()
val path = if (dir.startsWith(ICONS_DIR_PREFIX)) {
// optimization - all icons are SVG
"$dir$key.svg"
}
else {
"$dir$key.${dirProvider.defaultExtension}"
}
return IconLoader.findIcon(path, classLoader)
}
private fun isUseRegularIconOnSelection(name: String): Boolean {
if (name == "checkmark") {
val selectionBg = UIManager.getColor("PopupMenu.selectionBackground")?: UIManager.getColor("List.selectionBackground")
return selectionBg != null && JBColor.isBright() && !ColorUtil.isDark(selectionBg)
}
return false
}
@JvmStatic
fun getDisabledIcon(name: String): Icon = getIcon(name, enabled = false)
@JvmStatic
fun getSelectedIcon(name: String): Icon = findIcon(name, selected = true) ?: getIcon(name)
} | apache-2.0 | 7c332a628a0ff4251a072e2f51a9e971 | 29.468085 | 124 | 0.626965 | 4.370992 | false | false | false | false |
google/flexbox-layout | demo-playground/src/main/java/com/google/android/flexbox/SettingsActivity.kt | 1 | 5870 | /*
* Copyright 2017 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.flexbox
import android.os.Bundle
import android.widget.Toast
import androidx.fragment.app.FragmentActivity
import androidx.preference.EditTextPreference
import androidx.preference.Preference
import androidx.preference.PreferenceFragmentCompat
import com.google.android.apps.flexbox.R
import com.google.android.flexbox.validators.DimensionInputValidator
import com.google.android.flexbox.validators.FlexBasisPercentInputValidator
import com.google.android.flexbox.validators.IntegerInputValidator
import com.google.android.flexbox.validators.NonNegativeDecimalInputValidator
internal class SettingsActivity : FragmentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Display the fragment as the main content.
supportFragmentManager.beginTransaction().replace(android.R.id.content,
SettingsFragment()).commit()
}
/**
* Fragment for settings.
*/
class SettingsFragment : PreferenceFragmentCompat() {
override fun onCreatePreferences(savedInstanceState: Bundle?, s: String?) {
addPreferencesFromResource(R.xml.new_flex_item_preferences)
val orderPreference = findPreference(
getString(R.string.new_flex_item_order_key)) as EditTextPreference?
orderPreference?.onPreferenceChangeListener = Preference.OnPreferenceChangeListener { _, newValue ->
val validator = IntegerInputValidator()
if (!validator.isValidInput(newValue.toString())) {
Toast.makeText(activity,
R.string.must_be_integer,
Toast.LENGTH_LONG).show()
return@OnPreferenceChangeListener false
}
true
}
val flexGrowPreference = findPreference(
getString(R.string.new_flex_grow_key)) as EditTextPreference?
flexGrowPreference?.onPreferenceChangeListener = Preference.OnPreferenceChangeListener { _, newValue ->
val validator = NonNegativeDecimalInputValidator()
if (!validator.isValidInput(newValue.toString())) {
Toast.makeText(activity,
R.string.must_be_non_negative_float,
Toast.LENGTH_LONG).show()
return@OnPreferenceChangeListener false
}
true
}
val flexShrinkPreference = findPreference(
getString(R.string.new_flex_shrink_key)) as EditTextPreference?
flexShrinkPreference?.onPreferenceChangeListener = Preference.OnPreferenceChangeListener { _, newValue ->
val validator = NonNegativeDecimalInputValidator()
if (!validator.isValidInput(newValue.toString())) {
Toast.makeText(activity,
R.string.must_be_non_negative_float,
Toast.LENGTH_LONG).show()
return@OnPreferenceChangeListener false
}
true
}
val flexBasisPercentPreference = findPreference(
getString(R.string.new_flex_basis_percent_key)) as EditTextPreference?
flexBasisPercentPreference?.onPreferenceChangeListener = Preference.OnPreferenceChangeListener { _, newValue ->
val validator = FlexBasisPercentInputValidator()
if (!validator.isValidInput(newValue.toString())) {
Toast.makeText(activity,
R.string.must_be_minus_one_or_non_negative_integer,
Toast.LENGTH_LONG).show()
return@OnPreferenceChangeListener false
}
true
}
val widthPreference = findPreference(
getString(R.string.new_width_key)) as EditTextPreference?
widthPreference?.onPreferenceChangeListener = Preference.OnPreferenceChangeListener { _, newValue ->
val validator = DimensionInputValidator()
if (!validator.isValidInput(newValue.toString())) {
Toast.makeText(activity,
R.string.must_be_minus_one_or_minus_two_or_non_negative_integer,
Toast.LENGTH_LONG).show()
return@OnPreferenceChangeListener false
}
true
}
val heightPreference = findPreference(
getString(R.string.new_height_key)) as EditTextPreference?
heightPreference?.onPreferenceChangeListener = Preference.OnPreferenceChangeListener { _, newValue ->
val validator = DimensionInputValidator()
if (!validator.isValidInput(newValue.toString())) {
Toast.makeText(activity,
R.string.must_be_minus_one_or_minus_two_or_non_negative_integer,
Toast.LENGTH_LONG).show()
return@OnPreferenceChangeListener false
}
true
}
}
}
}
| apache-2.0 | c01f411c6f98c2c41f332507c08fea3f | 44.503876 | 123 | 0.618569 | 5.738025 | false | false | false | false |
yongce/AndroidLib | baseLib/src/main/java/me/ycdev/android/lib/common/activity/ActivityMeta.kt | 1 | 1592 | package me.ycdev.android.lib.common.activity
import android.content.ComponentName
import android.content.Context
import android.content.pm.ActivityInfo
import android.content.pm.PackageManager
import androidx.annotation.VisibleForTesting
import java.util.concurrent.ConcurrentHashMap
data class ActivityMeta(
val componentName: ComponentName,
val taskAffinity: String,
val launchMode: Int,
val allowTaskReparenting: Boolean
) {
companion object {
private val cache = ConcurrentHashMap<String, ActivityMeta>()
/**
* @throws PackageManager.NameNotFoundException if component not found in the system
*/
fun get(context: Context, activity: ComponentName): ActivityMeta {
val key = activity.flattenToShortString()
var meta = cache[key]
if (meta != null) {
return meta
}
val info = context.packageManager.getActivityInfo(activity, 0)
val taskAffinity = info.taskAffinity ?: context.applicationInfo.taskAffinity
val allowTaskReparenting = (info.flags and ActivityInfo.FLAG_ALLOW_TASK_REPARENTING) > 0
meta = ActivityMeta(activity, taskAffinity, info.launchMode, allowTaskReparenting)
cache[key] = meta
return meta
}
@VisibleForTesting
internal fun initCache(vararg metas: ActivityMeta) {
cache.clear()
metas.forEach {
val key = it.componentName.flattenToShortString()
cache[key] = it
}
}
}
}
| apache-2.0 | a3b75b415089238cea60e2da673fcd26 | 33.608696 | 100 | 0.652638 | 4.975 | false | false | false | false |
ktorio/ktor | ktor-io/js/src/io/ktor/utils/io/core/ByteOrderJS.kt | 1 | 573 | // ktlint-disable filename
package io.ktor.utils.io.core
import org.khronos.webgl.*
public actual enum class ByteOrder {
BIG_ENDIAN, LITTLE_ENDIAN;
public actual companion object {
private val native: ByteOrder
init {
val buffer = ArrayBuffer(4)
val arr = Int32Array(buffer)
val view = DataView(buffer)
arr[0] = 0x11223344
native = if (view.getInt32(0, true) == 0x11223344) LITTLE_ENDIAN else BIG_ENDIAN
}
public actual fun nativeOrder(): ByteOrder = native
}
}
| apache-2.0 | 12f3089625f1874cc9d7fd74fb5b723e | 22.875 | 92 | 0.614311 | 4.06383 | false | false | false | false |
DemonWav/MinecraftDev | src/main/kotlin/com/demonwav/mcdev/error/ErrorReporter.kt | 1 | 4019 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2018 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.error
import com.demonwav.mcdev.update.PluginUtil
import com.intellij.diagnostic.LogMessage
import com.intellij.diagnostic.ReportMessages
import com.intellij.ide.DataManager
import com.intellij.ide.plugins.PluginManager
import com.intellij.idea.IdeaLogger
import com.intellij.notification.NotificationListener
import com.intellij.notification.NotificationType
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.application.ApplicationNamesInfo
import com.intellij.openapi.application.ex.ApplicationInfoEx
import com.intellij.openapi.diagnostic.ErrorReportSubmitter
import com.intellij.openapi.diagnostic.IdeaLoggingEvent
import com.intellij.openapi.diagnostic.SubmittedReportInfo
import com.intellij.openapi.progress.EmptyProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.util.Consumer
import java.awt.Component
class ErrorReporter : ErrorReportSubmitter() {
private val baseUrl = "https://github.com/minecraft-dev/MinecraftDev/issues"
override fun getReportActionText() = "Report to Minecraft Dev GitHub Issue Tracker"
override fun submit(
events: Array<out IdeaLoggingEvent>,
additionalInfo: String?,
parentComponent: Component,
consumer: Consumer<SubmittedReportInfo>
): Boolean {
val event = events[0]
val bean = ErrorBean(event.throwable, IdeaLogger.ourLastActionId)
val dataContext = DataManager.getInstance().getDataContext(parentComponent)
bean.description = additionalInfo
bean.message = event.message
PluginManager.getPlugin(PluginUtil.PLUGIN_ID)?.let { plugin ->
bean.pluginName = plugin.name
bean.pluginVersion = plugin.version
}
val data = event.data
if (data is LogMessage) {
bean.attachments = data.includedAttachments
}
val (reportValues, attachments) =
IdeaITNProxy.getKeyValuePairs(bean, ApplicationInfoEx.getInstanceEx(), ApplicationNamesInfo.getInstance())
val project = CommonDataKeys.PROJECT.getData(dataContext)
val task = AnonymousFeedbackTask(
project, "Submitting error report", true, reportValues, attachments,
{ htmlUrl, token, isDuplicate ->
val reportInfo = SubmittedReportInfo(htmlUrl, "Issue #$token", SubmittedReportInfo.SubmissionStatus.NEW_ISSUE)
consumer.consume(reportInfo)
val message = if (!isDuplicate) {
"<html>Created Issue #$token successfully. " +
"<a href=\"$htmlUrl\">View issue.</a></html>"
} else {
"<html>Commented on existing Issue #$token successfully. " +
"<a href=\"$htmlUrl\">View comment.</a></html>"
}
ReportMessages.GROUP.createNotification(
ReportMessages.ERROR_REPORT,
message,
NotificationType.INFORMATION,
NotificationListener.URL_OPENING_LISTENER
).setImportant(false).notify(project)
},
{ e ->
val message = "<html>Error Submitting Issue: ${e.message}<br>Consider opening an issue on " +
"<a href=\"$baseUrl\">the GitHub issue tracker.</a></html>"
ReportMessages.GROUP.createNotification(
ReportMessages.ERROR_REPORT,
message,
NotificationType.ERROR,
NotificationListener.URL_OPENING_LISTENER
).setImportant(false).notify(project)
}
)
if (project == null) {
task.run(EmptyProgressIndicator())
} else {
ProgressManager.getInstance().run(task)
}
return true
}
}
| mit | e3bb0566d086b0f312617de5c1fd1be3 | 37.27619 | 126 | 0.651157 | 5.226268 | false | false | false | false |
zhudyos/uia | server/src/main/kotlin/io/zhudy/uia/utils/weixin.kt | 1 | 3945 | package io.zhudy.uia.utils
import okhttp3.OkHttpClient
import okhttp3.Request
import org.slf4j.LoggerFactory
import java.util.*
/**
* @author Kevin Zou ([email protected])
*/
data class WeixinAccessToken(
val accessToken: String = "",
val refreshToken: String = "",
val expiresIn: Int = 0,
val openid: String = "",
val scope: String = "",
// =================================
val errcode: Int = 0,
val errmsg: String = ""
)
/**
* @property openid 与 APP 绑定的唯一 ID
* @property nickname
* @property sex
* @property language
* @property city
* @property province
* @property country
* @property headimgurl
* @property unionid
*/
data class WeixinProfile(
val openid: String = "",
val nickname: String = "",
val sex: Int = 0,
val language: String = "",
val city: String = "",
val province: String = "",
val country: String = "",
val headimgurl: String = "",
val unionid: String = "",
// =================================
val errcode: Int = 0,
val errmsg: String = ""
)
object WeixinUtils {
private val log = LoggerFactory.getLogger(WeixinUtils::class.java)
private val httpClient = OkHttpClient.Builder()
.build()
/**
*
*/
fun getAccessToken(appId: String, appSecret: String, code: String): WeixinAccessToken {
val requestId = UUID.randomUUID().toString()
try {
val req = Request.Builder().get()
.url("https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appId&secret=$appSecret&code=$code&grant_type=authorization_code")
.build()
log.debug("[{}] weixin getAccessToken: {}", requestId, req)
val resp = httpClient.newCall(req).execute()
if (!resp.isSuccessful) {
log.error("[{}] weixin getAccessToken fail. http status {}", requestId, resp.code())
throw ThirdException("ERROR")
}
val token = JacksonUtils.objectMapper.readValue(resp.body()?.bytes(), WeixinAccessToken::class.java)
if (token.errcode != 0) {
log.error("[{}] weixin getAccessToken error. response body: {}", requestId, token)
throw ThirdException("${token.errcode}")
}
log.debug("[{}] weixin getAccessToken success. response body: {}", requestId, token)
return token
} catch (e: RuntimeException) {
log.error("[{}] weixin getAccessToken fail.", requestId, e)
throw ThirdException(e)
}
}
/**
*
*/
fun getProfile(token: WeixinAccessToken): WeixinProfile {
val requestId = UUID.randomUUID().toString()
try {
val req = Request.Builder().get()
.url("https://api.weixin.qq.com/sns/userinfo?access_token=${token.accessToken}&openid=${token.openid}")
.build()
log.debug("[{}] weixin getProfile: {}", requestId, req)
val resp = httpClient.newCall(req).execute()
if (!resp.isSuccessful) {
log.error("[{}] weixin getProfile fail. http status {}", requestId, resp.code())
throw ThirdException("ERROR")
}
val profile = JacksonUtils.objectMapper.readValue(resp.body()?.bytes(), WeixinProfile::class.java)!!
if (profile.errcode != 0) {
log.error("[{}] weixin getProfile error. response body: {}", requestId, profile)
throw ThirdException("${profile.errcode}")
}
log.debug("[{}] weixin getProfile success. response body: {}", requestId, profile)
return profile
} catch (e: RuntimeException) {
log.error("[{}] weixin getProfile fail.", requestId, e)
throw ThirdException(e)
}
}
}
| apache-2.0 | f12f390727180ef4e7a5a3fc7b98b2c3 | 33.2 | 149 | 0.553013 | 4.409193 | false | false | false | false |
Talentica/AndroidWithKotlin | sqlitedatabase/src/main/java/com/talentica/androidkotlin/sqlitedatabase/adapter/LogCursorAdapter.kt | 1 | 1746 | package com.talentica.androidkotlin.sqlitedatabase.adapter
import android.content.Context
import android.database.Cursor
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CursorAdapter
import android.widget.TextView
import com.talentica.androidkotlin.sqlitedatabase.R
import com.talentica.androidkotlin.sqlitedatabase.helpers.DbHelper
import java.text.DateFormat
import java.text.SimpleDateFormat
import java.util.*
class LogCursorAdapter(context: Context, cursor: Cursor) : CursorAdapter(context, cursor, true) {
object DateHelper {
const val DF_SIMPLE_STRING = "dd-MM-yy HH:mm"
@JvmField val DF_SIMPLE_FORMAT = object : ThreadLocal<DateFormat>() {
override fun initialValue(): DateFormat {
return SimpleDateFormat(DF_SIMPLE_STRING, Locale.US)
}
}
}
override fun bindView(view: View, context: Context?, cursor: Cursor) {
val tvText = view.findViewById<TextView>(R.id.tvText)
tvText.setText(getString(cursor, DbHelper.TEXT))
val tvTimestamp = view.findViewById<TextView>(R.id.tvTimestamp)
val timeValue = getString(cursor, DbHelper.TIMESTAMP)
val time = timeValue.toLong()
val date = Date()
date.time = time
val dateText = DateHelper.DF_SIMPLE_FORMAT.get().format(date)
tvTimestamp.setText(dateText)
}
override fun newView(context: Context?, cursor: Cursor?, parent: ViewGroup?): View {
return LayoutInflater.from(context).inflate(R.layout.item_log, parent, false);
}
private fun getString(cursor: Cursor, key: String): String {
return cursor.getString(cursor.getColumnIndexOrThrow(key))
}
}
| apache-2.0 | 03d16b20914c66045a1432984f887860 | 35.375 | 97 | 0.713058 | 4.289926 | false | false | false | false |
mdanielwork/intellij-community | platform/lang-api/src/com/intellij/execution/filters/FileHyperlinkInfoBase.kt | 4 | 3117 | // 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 com.intellij.execution.filters
import com.intellij.ide.util.PsiNavigationSupport
import com.intellij.openapi.editor.Document
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.fileEditor.OpenFileDescriptor
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiManager
import java.io.File
abstract class FileHyperlinkInfoBase(private val myProject: Project,
private val myDocumentLine: Int,
private val myDocumentColumn: Int) : FileHyperlinkInfo {
protected abstract val virtualFile: VirtualFile?
override fun getDescriptor(): OpenFileDescriptor? {
val file = virtualFile
if (file == null || !file.isValid) return null
val document = FileDocumentManager.getInstance().getDocument(file) // need to load decompiler text
val line = file.getUserData(LineNumbersMapping.LINE_NUMBERS_MAPPING_KEY)?.let { mapping ->
val mappingLine = mapping.bytecodeToSource(myDocumentLine + 1) - 1
if (mappingLine < 0) null else mappingLine
} ?: myDocumentLine
val offset = calculateOffset(document, line, myDocumentColumn)
if (offset == null) {
// although document position != logical position, it seems better than returning 'null'
return OpenFileDescriptor(myProject, file, line, myDocumentColumn)
}
else {
return OpenFileDescriptor(myProject, file, offset)
}
}
override fun navigate(project: Project?) {
project ?: return
descriptor?.let {
if (it.file.isDirectory) {
val psiManager = PsiManager.getInstance(project)
val psiDirectory = psiManager.findDirectory(it.file)
if (psiDirectory != null && psiManager.isInProject(psiDirectory)) {
psiDirectory.navigate(true)
}
else {
PsiNavigationSupport.getInstance().openDirectoryInSystemFileManager(File(it.file.path))
}
}
else {
FileEditorManager.getInstance(project).navigateToTextEditor(it, true)
}
}
}
/**
* Calculates an offset, that matches given line and column of the document.
*
* @param document [Document] instance
* @param documentLine zero-based line of the document
* @param documentColumn zero-based column of the document
* @return calculated offset or `null` if it's impossible to calculate
*/
protected open fun calculateOffset(document: Document?, documentLine: Int, documentColumn: Int): Int? {
document ?: return null
if (documentLine < 0 || document.lineCount <= documentLine) return null
val lineStartOffset = document.getLineStartOffset(documentLine)
val lineEndOffset = document.getLineEndOffset(documentLine)
val fixedColumn = Math.min(Math.max(documentColumn, 0), lineEndOffset - lineStartOffset)
return lineStartOffset + fixedColumn
}
} | apache-2.0 | fd48ec0f95054dba684fe0abc5fc5d10 | 40.573333 | 140 | 0.717998 | 4.744292 | false | false | false | false |
dahlstrom-g/intellij-community | platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/ChildWithNullsOppositeMultipleImpl.kt | 2 | 9045 | package com.intellij.workspaceModel.storage.entities.test.api
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.ModifiableReferableWorkspaceEntity
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.EntityLink
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.extractOneToManyParent
import com.intellij.workspaceModel.storage.impl.updateOneToManyParentOfChild
import com.intellij.workspaceModel.storage.referrersx
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class ChildWithNullsOppositeMultipleImpl: ChildWithNullsOppositeMultiple, WorkspaceEntityBase() {
companion object {
internal val PARENTENTITY_CONNECTION_ID: ConnectionId = ConnectionId.create(ParentWithNullsOppositeMultiple::class.java, ChildWithNullsOppositeMultiple::class.java, ConnectionId.ConnectionType.ONE_TO_MANY, true)
val connections = listOf<ConnectionId>(
PARENTENTITY_CONNECTION_ID,
)
}
@JvmField var _childData: String? = null
override val childData: String
get() = _childData!!
override val parentEntity: ParentWithNullsOppositeMultiple?
get() = snapshot.extractOneToManyParent(PARENTENTITY_CONNECTION_ID, this)
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: ChildWithNullsOppositeMultipleData?): ModifiableWorkspaceEntityBase<ChildWithNullsOppositeMultiple>(), ChildWithNullsOppositeMultiple.Builder {
constructor(): this(ChildWithNullsOppositeMultipleData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity ChildWithNullsOppositeMultiple 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().isChildDataInitialized()) {
error("Field ChildWithNullsOppositeMultiple#childData should be initialized")
}
if (!getEntityData().isEntitySourceInitialized()) {
error("Field ChildWithNullsOppositeMultiple#entitySource should be initialized")
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
override var childData: String
get() = getEntityData().childData
set(value) {
checkModificationAllowed()
getEntityData().childData = value
changedProperty.add("childData")
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override var parentEntity: ParentWithNullsOppositeMultiple?
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToManyParent(PARENTENTITY_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] as? ParentWithNullsOppositeMultiple
} else {
this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] as? ParentWithNullsOppositeMultiple
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) {
// Setting backref of the list
if (value is ModifiableWorkspaceEntityBase<*>) {
val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this
value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) {
_diff.updateOneToManyParentOfChild(PARENTENTITY_CONNECTION_ID, this, value)
}
else {
// Setting backref of the list
if (value is ModifiableWorkspaceEntityBase<*>) {
val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this
value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] = value
}
changedProperty.add("parentEntity")
}
override fun getEntityData(): ChildWithNullsOppositeMultipleData = result ?: super.getEntityData() as ChildWithNullsOppositeMultipleData
override fun getEntityClass(): Class<ChildWithNullsOppositeMultiple> = ChildWithNullsOppositeMultiple::class.java
}
}
class ChildWithNullsOppositeMultipleData : WorkspaceEntityData<ChildWithNullsOppositeMultiple>() {
lateinit var childData: String
fun isChildDataInitialized(): Boolean = ::childData.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<ChildWithNullsOppositeMultiple> {
val modifiable = ChildWithNullsOppositeMultipleImpl.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): ChildWithNullsOppositeMultiple {
val entity = ChildWithNullsOppositeMultipleImpl()
entity._childData = childData
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
return entity
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return ChildWithNullsOppositeMultiple::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as ChildWithNullsOppositeMultipleData
if (this.childData != other.childData) return false
if (this.entitySource != other.entitySource) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as ChildWithNullsOppositeMultipleData
if (this.childData != other.childData) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + childData.hashCode()
return result
}
} | apache-2.0 | ca131077643a26f0f2b26890dccec243 | 42.282297 | 219 | 0.651078 | 6.042084 | false | false | false | false |
awsdocs/aws-doc-sdk-examples | kotlin/services/lex/src/main/kotlin/com/kotlin/lex/GetIntent.kt | 1 | 1892 | // snippet-sourcedescription:[GetIntent.kt demonstrates how to get intent information from an Amazon Lex conversational bot.]
// snippet-keyword:[AWS SDK for Kotlin]
// snippet-service:[Amazon Lex]
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package com.kotlin.lex
// snippet-start:[lex.kotlin.get_intent.import]
import aws.sdk.kotlin.services.lexmodelbuildingservice.LexModelBuildingClient
import aws.sdk.kotlin.services.lexmodelbuildingservice.model.GetIntentRequest
import kotlin.system.exitProcess
// snippet-end:[lex.kotlin.get_intent.import]
/**
Before running this Kotlin code example, set up your development environment,
including your credentials.
For more information, see the following documentation topic:
https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html
*/
suspend fun main(args: Array<String>) {
val usage = """
Usage:
<intentName> <intentVersion>
Where:
intentName - The name of an existing intent (for example, BookHotel).
intentVersion - The version of the intent (for example, 1).
"""
if (args.size != 2) {
println(usage)
exitProcess(0)
}
val intentName = args[0]
val intentVersion = args[1]
getSpecificIntent(intentName, intentVersion)
}
// snippet-start:[lex.kotlin.get_intent.main]
suspend fun getSpecificIntent(intentName: String?, intentVersion: String?) {
val request = GetIntentRequest {
name = intentName
version = intentVersion
}
LexModelBuildingClient { region = "us-west-2" }.use { lexClient ->
val intentResponse = lexClient.getIntent(request)
println("The description is ${intentResponse.description}.")
}
}
// snippet-end:[lex.kotlin.get_intent.main]
| apache-2.0 | 4a0ed71b1bc5a219403a3eda082c81f4 | 28.516129 | 125 | 0.690803 | 3.909091 | false | false | false | false |
eman-1111/GoogleCodelabs | android-topeka-start/src/main/java/com/google/samples/apps/topeka/fragment/QuizFragment.kt | 1 | 8159 | /*
* Copyright 2017 Google 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 com.google.samples.apps.topeka.fragment
import android.annotation.TargetApi
import android.os.Build
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.view.ViewCompat
import android.support.v4.view.animation.FastOutLinearInInterpolator
import android.view.ContextThemeWrapper
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterViewAnimator
import android.widget.ListView
import android.widget.ProgressBar
import android.widget.TextView
import com.google.samples.apps.topeka.R
import com.google.samples.apps.topeka.adapter.QuizAdapter
import com.google.samples.apps.topeka.adapter.ScoreAdapter
import com.google.samples.apps.topeka.helper.ApiLevelHelper
import com.google.samples.apps.topeka.helper.database
import com.google.samples.apps.topeka.helper.inflate
import com.google.samples.apps.topeka.helper.onLayoutChange
import com.google.samples.apps.topeka.helper.requestLogin
import com.google.samples.apps.topeka.model.Category
import com.google.samples.apps.topeka.widget.AvatarView
import com.google.samples.apps.topeka.widget.quiz.AbsQuizView
/**
* Encapsulates Quiz solving and displays it to the user.
*/
class QuizFragment : Fragment() {
private val category by lazy(LazyThreadSafetyMode.NONE) {
val categoryId = arguments!!.getString(Category.TAG)
activity!!.database().getCategoryWith(categoryId)
}
private val quizAdapter by lazy(LazyThreadSafetyMode.NONE) {
context?.run {
QuizAdapter(this, category)
}
}
val scoreAdapter by lazy(LazyThreadSafetyMode.NONE) {
context?.run {
ScoreAdapter(this, category)
}
}
val quizView by lazy(LazyThreadSafetyMode.NONE) {
view?.findViewById<AdapterViewAnimator>(R.id.quiz_view)
}
private val progressText by lazy(LazyThreadSafetyMode.NONE) {
view?.findViewById<TextView>(R.id.progress_text)
}
private val progressBar by lazy(LazyThreadSafetyMode.NONE) {
(view?.findViewById<ProgressBar>(R.id.progress))?.apply {
max = category.quizzes.size
}
}
private var solvedStateListener: SolvedStateListener? = null
override fun onCreateView(inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?): View {
// Create a themed Context and custom LayoutInflater
// to get custom themed views in this Fragment.
val context = ContextThemeWrapper(activity, category.theme.styleId)
return context.inflate(R.layout.fragment_quiz, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
setProgress(category.firstUnsolvedQuizPosition)
decideOnViewToDisplay()
setQuizViewAnimations()
setAvatarDrawable()
super.onViewCreated(view, savedInstanceState)
}
private fun decideOnViewToDisplay() {
if (category.solved) {
// display the summary
view?.let {
with(it.findViewById<ListView>(R.id.scorecard)) {
adapter = scoreAdapter
visibility = View.VISIBLE
}
quizView?.visibility = View.GONE
}
solvedStateListener?.onCategorySolved()
} else {
with(quizView ?: return) {
adapter = quizAdapter
setSelection(category.firstUnsolvedQuizPosition)
}
}
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private fun setQuizViewAnimations() {
if (ApiLevelHelper.isLowerThan(Build.VERSION_CODES.LOLLIPOP)) {
return
}
with(quizView ?: return) {
setInAnimation(activity, R.animator.slide_in_bottom)
setOutAnimation(activity, R.animator.slide_out_top)
}
}
private fun setAvatarDrawable(avatarView: AvatarView? = view?.findViewById(R.id.avatar)) {
activity?.requestLogin { player ->
if (player.valid()) {
avatarView?.setAvatar(player.avatar!!.drawableId)
with(ViewCompat.animate(avatarView)) {
interpolator = FastOutLinearInInterpolator()
startDelay = 500
scaleX(1f)
scaleY(1f)
start()
}
}
}
}
private fun setProgress(currentQuizPosition: Int) {
if (isAdded) {
progressText?.text = getString(R.string.quiz_of_quizzes, currentQuizPosition,
category.quizzes.size)
progressBar?.progress = currentQuizPosition
}
}
override fun onSaveInstanceState(outState: Bundle) {
val focusedChild = quizView?.focusedChild
if (focusedChild is ViewGroup) {
val currentView = focusedChild.getChildAt(0)
if (currentView is AbsQuizView<*>) {
outState.putBundle(KEY_USER_INPUT, currentView.userInput)
}
}
super.onSaveInstanceState(outState)
}
override fun onViewStateRestored(savedInstanceState: Bundle?) {
restoreQuizState(savedInstanceState)
super.onViewStateRestored(savedInstanceState)
}
private fun restoreQuizState(savedInstanceState: Bundle?) {
if (savedInstanceState == null) return
quizView?.onLayoutChange {
val currentChild = (this as ViewGroup).getChildAt(0)
if (currentChild is ViewGroup) {
val potentialQuizView = currentChild.getChildAt(0)
if (potentialQuizView is AbsQuizView<*>) {
potentialQuizView.userInput = savedInstanceState.getBundle(KEY_USER_INPUT)
?: Bundle.EMPTY
}
}
}
}
/**
* Displays the next page.
* @return `true` if there's another quiz to solve, else `false`.
*/
fun showNextPage(): Boolean {
quizView?.let {
val nextItem = it.displayedChild + 1
setProgress(nextItem)
if (nextItem < it.adapter.count) {
it.showNext()
activity?.database()?.updateCategory(category)
return true
}
}
markCategorySolved()
return false
}
private fun markCategorySolved() {
category.solved = true
activity?.database()?.updateCategory(category)
}
fun hasSolvedStateListener() = solvedStateListener != null
fun setSolvedStateListener(solvedStateListener: SolvedStateListener) {
this.solvedStateListener = solvedStateListener
if (category.solved) solvedStateListener.onCategorySolved()
}
/**
* Interface definition for a callback to be invoked when the quiz is started.
*/
interface SolvedStateListener {
/**
* This method will be invoked when the category has been solved.
*/
fun onCategorySolved()
}
companion object {
private const val KEY_USER_INPUT = "USER_INPUT"
fun newInstance(categoryId: String,
listener: SolvedStateListener?
): QuizFragment {
return QuizFragment().apply {
solvedStateListener = listener
arguments = Bundle().apply { putString(Category.TAG, categoryId) }
}
}
}
} | apache-2.0 | e17f9d59876006e96cbd212675ea3c0d | 33.285714 | 94 | 0.637946 | 4.906194 | false | false | false | false |
JuliaSoboleva/SmartReceiptsLibrary | app/src/main/java/co/smartreceipts/android/apis/SmartReceiptsRetrofitConverterFactory.kt | 2 | 1871 | package co.smartreceipts.android.apis
import co.smartreceipts.android.apis.gson.SmartReceiptsGsonBuilder
import co.smartreceipts.android.apis.moshi.SmartReceiptsMoshiBuilder
import okhttp3.RequestBody
import okhttp3.ResponseBody
import retrofit2.Converter
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.converter.moshi.MoshiConverterFactory
import java.lang.reflect.Type
import javax.inject.Inject
class SmartReceiptsRetrofitConverterFactory @Inject constructor(
moshiBuilder: SmartReceiptsMoshiBuilder,
gsonBuilder: SmartReceiptsGsonBuilder
) : Converter.Factory() {
@Retention(AnnotationRetention.RUNTIME)
annotation class MoshiType
private val moshi: MoshiConverterFactory = MoshiConverterFactory.create(moshiBuilder.create())
private val gson: GsonConverterFactory = GsonConverterFactory.create(gsonBuilder.create())
override fun responseBodyConverter(type: Type, annotations: Array<Annotation>, retrofit: Retrofit): Converter<ResponseBody, *>? {
for (annotation in annotations) {
if (annotation.annotationClass == MoshiType::class) {
return moshi.responseBodyConverter(type, annotations, retrofit)
}
}
return gson.responseBodyConverter(type, annotations, retrofit)
}
override fun requestBodyConverter(
type: Type, parameterAnnotations: Array<Annotation>, methodAnnotations: Array<Annotation>, retrofit: Retrofit
): Converter<*, RequestBody>? {
for (annotation in methodAnnotations) {
if (annotation.annotationClass == MoshiType::class) {
return moshi.requestBodyConverter(type, parameterAnnotations, methodAnnotations, retrofit)
}
}
return gson.requestBodyConverter(type, parameterAnnotations, methodAnnotations, retrofit)
}
} | agpl-3.0 | 4f12405e96335e4fef693b13b02765b1 | 37.204082 | 133 | 0.755746 | 5.376437 | false | false | false | false |
apache/isis | incubator/clients/kroviz/src/test/kotlin/org/apache/causeway/client/kroviz/snapshots/ResponseRegressionTest.kt | 2 | 2855 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.apache.causeway.client.kroviz.snapshots
/**
* This is an integration test that requires <Demo> running on http://localhost:8080
* automate via -> @link https://bmuschko.com/blog/docker-integration-testing/
* compare json -> @link https://stackoverflow.com/questions/26049303/how-to-compare-two-json-have-the-same-properties-without-order
* eventually use HttpClient? -> @link https://blog.kotlin-academy.com/how-to-create-a-rest-api-client-and-its-integration-tests-in-kotlin-multiplatform-d76c9a1be348
*/
class ResponseRegressionTest {
//TODO
/*
@BeforeTest
fun setup() {
val user = "sven"
val pw = "pass"
val url = "http://${user}:${pw}@localhost:8080/restful/"
SessionManager.login(url, user, pw)
}
@ExperimentalCoroutinesApi
@Test
fun testCompareSnapshotWithResponse() {
//given
val map = Response2Handler.map
val credentials = SessionManager.getCredentials()
//when
console.log("[RRT.testCompareSnapshotWithResponse]")
map.forEach { rh ->
val handler = rh.value
val jsonStr = rh.key.str
val expected = handler.parse(jsonStr)
val href = rh.key.url
console.log(href)
val link = Link(method = Method.GET.operation, href = href)
val response = invoke(link, credentials)
val actual = handler.parse(response)
assertEquals(expected, actual)
console.log("[RRT.testCompareSnapshotWithResponse]")
console.log(expected == actual)
}
//then
assertTrue(true, "no exception in loop")
}
@ExperimentalCoroutinesApi
private fun invoke(link: Link, credentials: String): String {
return "TODO"
// return TestRequest().fetch(link, credentials)
}
private fun invokeSync(link: Link, credentials: String): String {
// val hc = Client("id", link.href)
return "Why must this be so complicated?"
}
*/
}
| apache-2.0 | cd638b151a2df58f2ba03410c8666ea6 | 35.139241 | 165 | 0.662347 | 4.131693 | false | true | false | false |
StepicOrg/stepik-android | app/src/main/java/org/stepik/android/presentation/user_reviews/mapper/UserReviewsStateMapper.kt | 1 | 11658 | package org.stepik.android.presentation.user_reviews.mapper
import org.stepik.android.domain.course_reviews.model.CourseReview
import org.stepik.android.domain.user_reviews.model.UserCourseReviewItem
import org.stepik.android.presentation.user_reviews.UserReviewsFeature
import ru.nobird.app.core.model.mutate
import javax.inject.Inject
class UserReviewsStateMapper
@Inject
constructor() {
/**
* Operations from UserCourseReviewOperationBus
*/
fun mergeStateWithNewReview(state: UserReviewsFeature.State.Content, courseReview: CourseReview): UserReviewsFeature.State.Content? {
val indexOfReviewedCourse = state.userCourseReviewsResult.potentialReviewItems.indexOfFirst { it.id == courseReview.course }
return if (indexOfReviewedCourse == -1) {
null
} else {
val reviewedCourse = state.userCourseReviewsResult.potentialReviewItems[indexOfReviewedCourse]
val updatedReviewedItems = state.userCourseReviewsResult.reviewedReviewItems.mutate { add(0, UserCourseReviewItem.ReviewedItem(reviewedCourse.course, courseReview)) }
val updatedReviewedHeader = listOf(UserCourseReviewItem.ReviewedHeader(reviewedCount = updatedReviewedItems.size))
val updatedPotentialReviews = state.userCourseReviewsResult.potentialReviewItems.mutate { removeAt(indexOfReviewedCourse) }
val updatedPotentialReviewHeader = if (updatedPotentialReviews.isEmpty()) {
emptyList()
} else {
listOf(UserCourseReviewItem.PotentialReviewHeader(potentialReviewCount = updatedPotentialReviews.size))
}
state.copy(
userCourseReviewsResult = state.userCourseReviewsResult.copy(
userCourseReviewItems = updatedPotentialReviewHeader + updatedPotentialReviews + updatedReviewedHeader + updatedReviewedItems,
potentialHeader = updatedPotentialReviewHeader,
potentialReviewItems = updatedPotentialReviews,
reviewedHeader = updatedReviewedHeader,
reviewedReviewItems = updatedReviewedItems
)
)
}
}
fun mergeStateWithEditedReview(state: UserReviewsFeature.State.Content, courseReview: CourseReview): UserReviewsFeature.State.Content? {
val indexOfEditedReview = state.userCourseReviewsResult.reviewedReviewItems.indexOfFirst { it.id == courseReview.course }
return if (indexOfEditedReview == -1) {
null
} else {
val updatedReviewedItems = state
.userCourseReviewsResult
.reviewedReviewItems
.mutate {
val oldItem = get(indexOfEditedReview)
set(indexOfEditedReview, oldItem.copy(courseReview = courseReview))
}
state.copy(
userCourseReviewsResult = state.userCourseReviewsResult.copy(
userCourseReviewItems = with(state.userCourseReviewsResult) { potentialHeader + potentialReviewItems + reviewedHeader + updatedReviewedItems },
reviewedReviewItems = updatedReviewedItems
)
)
}
}
fun mergeStateWithDeletedReview(state: UserReviewsFeature.State.Content, courseReview: CourseReview): UserReviewsFeature.State.Content? {
val indexOfDeletedReview = state.userCourseReviewsResult.reviewedReviewItems.indexOfFirst { it.id == courseReview.course }
return if (indexOfDeletedReview == -1) {
null
} else {
val deletedReviewItem = state.userCourseReviewsResult.reviewedReviewItems[indexOfDeletedReview]
val updatedReviewedItems = state.userCourseReviewsResult.reviewedReviewItems.mutate { removeAt(indexOfDeletedReview) }
val updatedReviewedHeader = if (updatedReviewedItems.isEmpty()) {
emptyList()
} else {
listOf(UserCourseReviewItem.ReviewedHeader(reviewedCount = updatedReviewedItems.size))
}
val updatedPotentialItems = state.userCourseReviewsResult.potentialReviewItems.mutate { add(UserCourseReviewItem.PotentialReviewItem(deletedReviewItem.course)) }
val updatedPotentialReviewHeader = listOf(UserCourseReviewItem.PotentialReviewHeader(potentialReviewCount = updatedPotentialItems.size))
state.copy(
userCourseReviewsResult = state.userCourseReviewsResult.copy(
userCourseReviewItems = updatedPotentialReviewHeader + updatedPotentialItems + updatedReviewedHeader + updatedReviewedItems,
potentialHeader = updatedPotentialReviewHeader,
potentialReviewItems = updatedPotentialItems,
reviewedHeader = updatedReviewedHeader,
reviewedReviewItems = updatedReviewedItems
)
)
}
}
/**
* Operations from UserReviewsFragment screen
*/
fun mergeStateWithDeletedReviewPlaceholder(state: UserReviewsFeature.State.Content, courseReview: CourseReview): UserReviewsFeature.State.Content? {
val indexOfDeletedReview = state.userCourseReviewsResult.reviewedReviewItems.indexOfFirst { it.id == courseReview.course }
return if (indexOfDeletedReview == -1) {
null
} else {
val deletedReviewItem = state.userCourseReviewsResult.reviewedReviewItems[indexOfDeletedReview]
val updatedReviewedItemsDisplay = (state.userCourseReviewsResult.reviewedReviewItems as List<UserCourseReviewItem>).mutate {
set(indexOfDeletedReview, UserCourseReviewItem.Placeholder(courseId = deletedReviewItem.id, course = deletedReviewItem.course))
}
state.copy(
userCourseReviewsResult = state.userCourseReviewsResult.copy(
userCourseReviewItems = with(state.userCourseReviewsResult) { potentialHeader + potentialReviewItems + reviewedHeader + updatedReviewedItemsDisplay }
)
)
}
}
fun mergeStateWithDeletedReviewToSuccess(state: UserReviewsFeature.State.Content, courseReview: CourseReview): UserReviewsFeature.State.Content? {
val indexOfPlaceholder = state.userCourseReviewsResult.userCourseReviewItems.indexOfFirst { it is UserCourseReviewItem.Placeholder && it.id == courseReview.course }
return if (indexOfPlaceholder == -1) {
null
} else {
val course = (state.userCourseReviewsResult.userCourseReviewItems[indexOfPlaceholder] as UserCourseReviewItem.Placeholder).course ?: return null
val newPotentialReviewItem = UserCourseReviewItem.PotentialReviewItem(course = course)
val updatedPotentialItems = state.userCourseReviewsResult.potentialReviewItems.mutate { add(newPotentialReviewItem) }
val updatedPotentialReviewHeader = listOf(UserCourseReviewItem.PotentialReviewHeader(potentialReviewCount = updatedPotentialItems.size))
val deletedReviewedItemIndex = state.userCourseReviewsResult.reviewedReviewItems.indexOfFirst { it.id == courseReview.course }
val updatedReviewedItems =
if (deletedReviewedItemIndex == -1) {
state.userCourseReviewsResult.reviewedReviewItems
} else {
state.userCourseReviewsResult.reviewedReviewItems.mutate { removeAt(deletedReviewedItemIndex) }
}
val updatedReviewedHeader = if (updatedReviewedItems.isEmpty()) {
emptyList()
} else {
listOf(UserCourseReviewItem.ReviewedHeader(updatedReviewedItems.size))
}
state.copy(
userCourseReviewsResult = state.userCourseReviewsResult.copy(
userCourseReviewItems = updatedPotentialReviewHeader + updatedPotentialItems + updatedReviewedHeader + updatedReviewedItems,
potentialHeader = updatedPotentialReviewHeader,
potentialReviewItems = updatedPotentialItems,
reviewedHeader = updatedReviewedHeader,
reviewedReviewItems = updatedReviewedItems
)
)
}
}
fun mergeStateWithDeletedReviewToError(state: UserReviewsFeature.State.Content): UserReviewsFeature.State.Content =
state.copy(
userCourseReviewsResult = state.userCourseReviewsResult.copy(
userCourseReviewItems = with(state.userCourseReviewsResult) { potentialHeader + potentialReviewItems + reviewedHeader + reviewedReviewItems }
)
)
fun mergeStateWithDroppedCourse(state: UserReviewsFeature.State.Content, droppedCourseId: Long): UserReviewsFeature.State.Content {
val (updatedPotentialItems, updatedReviewedItems) = with(state.userCourseReviewsResult) {
potentialReviewItems.filterNot { it.id == droppedCourseId } to reviewedReviewItems.filterNot { it.id == droppedCourseId }
}
val updatedPotentialHeader = if (updatedPotentialItems.isEmpty()) {
emptyList()
} else {
listOf(UserCourseReviewItem.PotentialReviewHeader(updatedPotentialItems.size))
}
val updatedReviewedHeader = if (updatedReviewedItems.isEmpty()) {
emptyList()
} else {
listOf(UserCourseReviewItem.ReviewedHeader(updatedReviewedItems.size))
}
return state.copy(
userCourseReviewsResult = state.userCourseReviewsResult.copy(
userCourseReviewItems = updatedPotentialHeader + updatedPotentialItems + updatedReviewedHeader + updatedReviewedItems,
potentialHeader = updatedPotentialHeader,
potentialReviewItems = updatedPotentialItems,
reviewedHeader = updatedReviewedHeader,
reviewedReviewItems = updatedReviewedItems
)
)
}
fun mergeStateWithEnrolledReviewedItem(state: UserReviewsFeature.State.Content, reviewedItem: UserCourseReviewItem.ReviewedItem): UserReviewsFeature.State.Content {
val updatedReviewedItems = state.userCourseReviewsResult.reviewedReviewItems.mutate { add(reviewedItem) }
val updatedReviewedHeader = listOf(UserCourseReviewItem.ReviewedHeader(updatedReviewedItems.size))
return state.copy(
userCourseReviewsResult = state.userCourseReviewsResult.copy(
userCourseReviewItems = with(state.userCourseReviewsResult) { potentialHeader + potentialReviewItems + updatedReviewedHeader + updatedReviewedItems },
reviewedHeader = updatedReviewedHeader,
reviewedReviewItems = updatedReviewedItems
)
)
}
fun mergeStateWithEnrolledPotentialReviewItem(state: UserReviewsFeature.State.Content, potentialReviewItem: UserCourseReviewItem.PotentialReviewItem): UserReviewsFeature.State.Content {
val updatedPotentialItems = state.userCourseReviewsResult.potentialReviewItems.mutate { add(potentialReviewItem) }
val updatedPotentialHeader = listOf(UserCourseReviewItem.PotentialReviewHeader(updatedPotentialItems.size))
return state.copy(
userCourseReviewsResult = state.userCourseReviewsResult.copy(
userCourseReviewItems = with(state.userCourseReviewsResult) { updatedPotentialHeader + updatedPotentialItems + reviewedHeader + reviewedReviewItems },
potentialHeader = updatedPotentialHeader,
potentialReviewItems = updatedPotentialItems
)
)
}
} | apache-2.0 | e776d82123431ed3629c941fb4bec56b | 54.784689 | 189 | 0.697289 | 5.540875 | false | false | false | false |
allotria/intellij-community | platform/lang-impl/src/com/intellij/codeInsight/navigation/impl/directNavigation.kt | 3 | 1575 | // 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.codeInsight.navigation.impl
import com.intellij.codeInsight.navigation.BaseCtrlMouseInfo
import com.intellij.codeInsight.navigation.CtrlMouseDocInfo
import com.intellij.codeInsight.navigation.CtrlMouseInfo
import com.intellij.navigation.DirectNavigationProvider
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.util.elementsAroundOffsetUp
internal fun fromDirectNavigation(file: PsiFile, offset: Int): GTDActionData? {
for ((element, _) in file.elementsAroundOffsetUp(offset)) {
for (provider in DirectNavigationProvider.EP_NAME.extensions) {
val navigationElement = provider.getNavigationElement(element)
if (navigationElement != null) {
return DirectNavigationData(element, navigationElement, provider)
}
}
}
return null
}
private class DirectNavigationData(
private val sourceElement: PsiElement,
private val targetElement: PsiElement,
private val navigationProvider: DirectNavigationProvider
) : GTDActionData {
override fun ctrlMouseInfo(): CtrlMouseInfo = object : BaseCtrlMouseInfo(listOf(sourceElement.textRange)) {
override fun getDocInfo(): CtrlMouseDocInfo = CtrlMouseDocInfo.EMPTY
override fun isValid(): Boolean = true
}
override fun result(): GTDActionResult {
val navigatable = psiNavigatable(targetElement)
return GTDActionResult.SingleTarget(navigatable, navigationProvider)
}
}
| apache-2.0 | 29a69ad5a78068c7a1c5422743ed36c1 | 39.384615 | 140 | 0.790476 | 4.715569 | false | false | false | false |
scenerygraphics/scenery | src/main/kotlin/graphics/scenery/backends/opengl/OpenGLShaderModule.kt | 1 | 8740 | package graphics.scenery.backends.opengl
import cleargl.GLShader
import cleargl.GLShaderType
import com.jogamp.opengl.GL4
import graphics.scenery.backends.ShaderIntrospection
import graphics.scenery.backends.ShaderPackage
import graphics.scenery.backends.ShaderType
import graphics.scenery.utils.LazyLogger
import java.util.concurrent.ConcurrentHashMap
/**
* Vulkan Object State class. Saves texture, UBO, pipeline and vertex buffer state.
*
* @author Ulrik Günther <[email protected]>
*/
open class OpenGLShaderModule(gl: GL4, entryPoint: String, sp: ShaderPackage) {
protected val logger by LazyLogger()
var shader: GLShader
private set
var shaderType: ShaderType
private set
var uboSpecs = LinkedHashMap<String, ShaderIntrospection.UBOSpec>()
var source: String = ""
private set
init {
logger.debug("Creating OpenGLShaderModule $entryPoint, ${sp.toShortString()}")
val spirv = sp.getSPIRVOpcodes() ?: throw IllegalStateException("Shader Package is expected to have SPIRV bytecode at this point")
val intro = ShaderIntrospection(spirv, vulkanSemantics = false, version = 410)
logger.debug("Analysing uniform buffers ...")
intro.uniformBuffers().forEach { ubo ->
// only add the UBO spec if it doesn't already exist, and has more than 0 members
// SPIRV UBOs may have 0 members, if they are not used in the actual shader code
if(!uboSpecs.contains(ubo.name) && ubo.members.size > 0) {
uboSpecs[ubo.name] = ubo
}
}
/* Updated version:
for(i in 0..compiler.shaderResources.sampledImages.size()-1) {
// inputs are summarized into one descriptor set
val res = compiler.shaderResources.sampledImages.get(i.toInt())
logger.info("Adding textures ${res.name} with set=${compiler.getDecoration(res.id, Decoration.DecorationDescriptorSet)}")
// FIXME: Here we assume at the moment that we either have only input textures (from framebuffers), or only object textures
val name = if(res.name == "ObjectTextures" || res.name == "VolumeTextures") {
"ObjectTextures"
} else {
"inputs"
}
uboSpecs.put(res.name, UBOSpec(name,
set = compiler.getDecoration(res.id, Decoration.DecorationDescriptorSet),
binding = 0,
members = LinkedHashMap<String, UBOMemberSpec>()))
*/
// inputs are summarized into one descriptor set
intro.sampledImages().forEach { sampledImage ->
if (sampledImage.name != "ObjectTextures") {
uboSpecs[sampledImage.name] = ShaderIntrospection.UBOSpec(
"inputs",
set = sampledImage.set,
binding = 0,
members = LinkedHashMap(),
type = ShaderIntrospection.UBOSpecType.SampledImage2D
)
}
}
// val inputs = compiler.shaderResources.stageInputs
// if(inputs.capacity() > 0) {
// for (i in 0 until inputs.capacity()) {
// logger.debug("${sp.toShortString()}: ${inputs.get(i).name}")
// }
// }
this.shaderType = sp.type
source = intro.compile()
// remove binding and set qualifiers
var start = 0
var found = source.indexOf("layout(", start)
while(found != -1) {
logger.debug("Found match at $found with start index $start")
start = found + 7
val end = source.indexOf(")", start) + 1
if(source.substring(end, source.indexOf(";", end)).contains(" in ")) {
if(source.substring(end, source.indexOf(";", end)).contains("{")) {
logger.debug("Removing layout qualifier from interface block input")
source = source.replaceRange(start-7, end, "")
} else {
logger.debug("Not touching input layouts")
}
start = end
found = source.indexOf("layout(", start)
continue
}
if(source.substring(end, source.indexOf(";", end)).contains(" out ")) {
if(source.substring(end, source.indexOf(";", end)).contains("{")) {
logger.debug("Removing layout qualifier from interface block output")
source = source.replaceRange(start-7, end, "")
} else {
logger.debug("Not touching output layouts")
}
start = end
found = source.indexOf("layout(", start)
continue
}
if(source.substring(end, source.indexOf(";", end)).contains("sampler")) {
logger.debug("Converting sampler UBO to uniform")
source = source.replaceRange(start-7, end, "")
start = found
found = source.indexOf("layout(", start)
continue
}
if(source.substring(end, source.indexOf(";", end)).contains("vec")) {
logger.debug("Converting location-based struct to regular struct")
source = source.replaceRange(start-7, end, "")
start = found
found = source.indexOf("layout(", start)
continue
}
if(source.substring(end, source.indexOf(";", end)).contains("mat")) {
logger.debug("Converting location-based struct to regular struct")
source = source.replaceRange(start-7, end, "")
start = found
found = source.indexOf("layout(", start)
continue
}
if(source.substring(start, end).contains("set") || source.substring(start, end).contains("binding")) {
logger.debug("Replacing ${source.substring(start, end)}")
source = source.replaceRange(start-7, end, "layout(std140)")
start = found + 15
} else {
logger.debug("Skipping ${source.substring(start, end)}")
start = end
}
found = source.indexOf("layout(", start)
}
// add GL_ARB_seperate_shader_objects extension to use layout(location = ...) qualifier
source = source.replace("#version 410", "#version 410 core\n#extension GL_ARB_separate_shader_objects : require\n")
this.shader = GLShader(gl, source, toClearGLShaderType(this.shaderType))
if(this.shader.shaderInfoLog.isNotEmpty()) {
logger.warn("Shader compilation log:")
logger.warn(this.shader.shaderInfoLog)
if(this.shader.shaderInfoLog.lowercase().contains("error")) {
logger.error("Shader code follows:")
logger.error("--------------------\n$source")
}
}
}
private fun toClearGLShaderType(type: ShaderType): GLShaderType {
return when(type) {
ShaderType.VertexShader -> GLShaderType.VertexShader
ShaderType.FragmentShader -> GLShaderType.FragmentShader
ShaderType.TessellationControlShader -> GLShaderType.TesselationControlShader
ShaderType.TessellationEvaluationShader -> GLShaderType.TesselationEvaluationShader
ShaderType.GeometryShader -> GLShaderType.GeometryShader
ShaderType.ComputeShader -> GLShaderType.ComputeShader
}
}
/**
* Returns a string representation of this module.
*/
override fun toString(): String {
return "$shader: $shaderType with UBOs ${uboSpecs.keys.joinToString(", ") }}"
}
/**
* Factory methods and cache.
*/
companion object {
private data class ShaderSignature(val gl: GL4, val p: ShaderPackage)
private val shaderModuleCache = ConcurrentHashMap<ShaderSignature, OpenGLShaderModule>()
/**
* Creates a new [OpenGLShaderModule] or returns it from the cache.
* Must be given a [ShaderPackage] [sp], a [gl], and the name for the main [entryPoint].
*/
@JvmStatic fun getFromCacheOrCreate(gl: GL4, entryPoint: String, sp: ShaderPackage): OpenGLShaderModule {
val signature = ShaderSignature(gl, sp)
val module = shaderModuleCache[signature]
return if(module != null) {
module
} else {
val newModule = OpenGLShaderModule(gl, entryPoint, sp)
shaderModuleCache[signature] = newModule
newModule
}
}
}
}
| lgpl-3.0 | 78da8ee462b092ab8f266e6a67e21fa9 | 39.271889 | 138 | 0.579586 | 4.814876 | false | false | false | false |
allotria/intellij-community | build/tasks/src/org/jetbrains/intellij/build/io/ZipArchiveOutputStream.kt | 2 | 5806 | // 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 org.jetbrains.intellij.build.io
import java.io.Closeable
import java.io.IOException
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.nio.channels.FileChannel
import java.util.zip.ZipEntry
internal class ZipArchiveOutputStream(private val channel: FileChannel) : Closeable {
private var finished = false
private var entryCount = 0
private val metadataBuffer = ByteBuffer.allocateDirect(5 * 1024 * 1024).order(ByteOrder.LITTLE_ENDIAN)
// 128K should be enough for end of central directory record
private val buffer = ByteBuffer.allocateDirect(16_384).order(ByteOrder.LITTLE_ENDIAN)
private val tempArray = arrayOfNulls<ByteBuffer>(2)
fun addDirEntry(name: ByteArray) {
if (finished) {
throw IOException("Stream has already been finished")
}
val offset = channel.position()
entryCount++
buffer.clear()
buffer.putInt(0x04034b50)
// Version needed to extract (minimum)
buffer.putShort(0)
// General purpose bit flag
buffer.putShort(0)
// Compression method
buffer.putShort(ZipEntry.STORED.toShort())
// File last modification time
buffer.putShort(0)
// File last modification date
buffer.putShort(0)
// CRC-32 of uncompressed data
buffer.putInt(0)
// Compressed size
buffer.putInt(0)
// Uncompressed size
buffer.putInt(0)
// File name length
buffer.putShort((name.size and 0xffff).toShort())
// Extra field length
buffer.putShort(0)
buffer.put(name)
buffer.flip()
writeBuffer(buffer)
writeCentralFileHeader(0, 0, ZipEntry.STORED, 0, metadataBuffer, name, offset)
}
fun writeRawEntry(header: ByteBuffer, content: ByteBuffer, name: ByteArray, size: Int, compressedSize: Int, method: Int, crc: Long) {
@Suppress("DuplicatedCode")
if (finished) {
throw IOException("Stream has already been finished")
}
val offset = channel.position()
entryCount++
assert(method != -1)
if (size >= 0xFFFFFFFFL || compressedSize >= 0xFFFFFFFFL) {
throw UnsupportedOperationException("Entry is too big")
}
tempArray[0] = header
tempArray[1] = content
do {
channel.write(tempArray, 0, 2)
}
while (header.hasRemaining() || content.hasRemaining())
writeCentralFileHeader(size, compressedSize, method, crc, metadataBuffer, name, offset)
}
fun writeRawEntry(content: ByteBuffer, name: ByteArray, size: Int, compressedSize: Int, method: Int, crc: Long) {
if (finished) {
throw IOException("Stream has already been finished")
}
val offset = channel.position()
entryCount++
assert(method != -1)
if (size >= 0xFFFFFFFFL || compressedSize >= 0xFFFFFFFFL) {
throw UnsupportedOperationException("Entry is too big")
}
writeBuffer(content)
writeCentralFileHeader(size, compressedSize, method, crc, metadataBuffer, name, offset)
}
fun finish(comment: ByteBuffer?) {
if (finished) {
throw IOException("This archive has already been finished")
}
val centralDirectoryOffset = channel.position()
// write central directory file header
metadataBuffer.flip()
val centralDirectoryLength = metadataBuffer.limit()
writeBuffer(metadataBuffer)
// write end of central directory record (EOCD)
buffer.clear()
buffer.putInt(0x06054b50)
// write 0 to clear reused buffer content
// Number of this disk
buffer.putShort(0)
// Disk where central directory starts
buffer.putShort(0)
// Number of central directory records on this disk
val shortEntryCount = (entryCount.coerceAtMost(0xffff) and 0xffff).toShort()
buffer.putShort(shortEntryCount)
// Total number of central directory records
buffer.putShort(shortEntryCount)
buffer.putInt(centralDirectoryLength)
// Offset of start of central directory, relative to start of archive
buffer.putInt((centralDirectoryOffset and 0xffffffffL).toInt())
// Comment length
if (comment == null) {
buffer.putShort(0)
buffer.flip()
writeBuffer(buffer)
}
else {
buffer.putShort((comment.remaining() and 0xffff).toShort())
buffer.flip()
writeBuffer(buffer)
writeBuffer(comment)
}
finished = true
}
private fun writeBuffer(content: ByteBuffer) {
do {
channel.write(content)
}
while (content.hasRemaining())
}
override fun close() {
if (!finished) {
channel.use {
finish(null)
}
}
}
}
private fun writeCentralFileHeader(size: Int, compressedSize: Int, method: Int, crc: Long, buffer: ByteBuffer, name: ByteArray, offset: Long) {
buffer.putInt(0x02014b50)
// write 0 to clear reused buffer content
// Version made by
buffer.putShort(0)
// Version needed to extract (minimum)
buffer.putShort(0)
// General purpose bit flag
buffer.putShort(0)
// Compression method
buffer.putShort(method.toShort())
// File last modification time
buffer.putShort(0)
// File last modification date
buffer.putShort(0)
// CRC-32 of uncompressed data
buffer.putInt((crc and 0xffffffffL).toInt())
// Compressed size
buffer.putInt(compressedSize)
// Uncompressed size
buffer.putInt(size)
// File name length
buffer.putShort((name.size and 0xffff).toShort())
// Extra field length
buffer.putShort(0)
// File comment length
buffer.putShort(0)
// Disk number where file starts
buffer.putShort(0)
// Internal file attributes
buffer.putShort(0)
// External file attributes
buffer.putInt(0)
// Relative offset of local file header
buffer.putInt((offset and 0xffffffffL).toInt())
// File name
buffer.put(name)
} | apache-2.0 | 8584e59949ceb5ac7188f58f5690f563 | 28.477157 | 143 | 0.696176 | 4.19812 | false | false | false | false |
Homes-MinecraftServerMod/Homes | src/main/kotlin/com/masahirosaito/spigot/homes/strings/commands/HomeCommandStrings.kt | 1 | 791 | package com.masahirosaito.spigot.homes.strings.commands
import com.masahirosaito.spigot.homes.datas.strings.commands.HomeCommandStringData
import com.masahirosaito.spigot.homes.load
import com.masahirosaito.spigot.homes.loadData
import java.io.File
object HomeCommandStrings {
lateinit private var data: HomeCommandStringData
fun load(folderPath: String) {
data = loadData(File(folderPath, "home-command.json").load(), HomeCommandStringData::class.java)
}
fun DESCRIPTION() =
data.DESCRIPTION
fun USAGE_HOME() =
data.USAGE_HOME
fun USAGE_HOME_NAME() =
data.USAGE_HOME_NAME
fun USAGE_HOME_PLAYER() =
data.USAGE_HOME_PLAYER
fun USAGE_HOME_NAME_PLAYER() =
data.USAGE_HOME_NAME_PLAYER
}
| apache-2.0 | 1b16cc7fb5aecce13a0c832fb2714400 | 26.275862 | 104 | 0.696587 | 4.05641 | false | false | false | false |
leafclick/intellij-community | platform/built-in-server/src/org/jetbrains/ide/RestService.kt | 1 | 10403 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.ide
import com.google.common.base.Supplier
import com.google.common.cache.CacheBuilder
import com.google.common.cache.CacheLoader
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.google.gson.stream.JsonReader
import com.google.gson.stream.JsonWriter
import com.google.gson.stream.MalformedJsonException
import com.intellij.ide.IdeBundle
import com.intellij.ide.impl.ProjectUtil.showYesNoDialog
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.util.io.BufferExposingByteArrayOutputStream
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.util.text.StringUtilRt
import com.intellij.openapi.wm.IdeFocusManager
import com.intellij.ui.AppIcon
import com.intellij.util.ExceptionUtil
import com.intellij.util.io.origin
import com.intellij.util.io.referrer
import com.intellij.util.net.NetUtils
import com.intellij.util.text.nullize
import io.netty.buffer.ByteBufInputStream
import io.netty.buffer.Unpooled
import io.netty.channel.Channel
import io.netty.channel.ChannelHandlerContext
import io.netty.handler.codec.http.*
import org.jetbrains.builtInWebServer.isSignedRequest
import org.jetbrains.io.*
import java.awt.Window
import java.io.IOException
import java.io.OutputStream
import java.lang.reflect.InvocationTargetException
import java.net.InetAddress
import java.net.InetSocketAddress
import java.net.URI
import java.net.URISyntaxException
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicInteger
/**
* Document your service using [apiDoc](http://apidocjs.com). To extract big example from source code, consider to use *.coffee file near your source file.
* (or Python/Ruby, but coffee recommended because it's plugin is lightweight). See [AboutHttpService] for example.
*
* Don't create JsonReader/JsonWriter directly, use only provided [.createJsonReader], [.createJsonWriter] methods (to ensure that you handle in/out according to REST API guidelines).
*
* @see [Best Practices for Designing a Pragmatic REST API](http://www.vinaysahni.com/best-practices-for-a-pragmatic-restful-api).
*/
abstract class RestService : HttpRequestHandler() {
companion object {
@JvmField
val LOG = logger<RestService>()
const val PREFIX = "api"
@JvmStatic
fun activateLastFocusedFrame() {
(IdeFocusManager.getGlobalInstance().lastFocusedFrame as? Window)?.toFront()
}
@JvmStatic
fun createJsonReader(request: FullHttpRequest): JsonReader {
val reader = JsonReader(ByteBufInputStream(request.content()).reader())
reader.isLenient = true
return reader
}
@JvmStatic
fun createJsonWriter(out: OutputStream): JsonWriter {
val writer = JsonWriter(out.writer())
writer.setIndent(" ")
return writer
}
@JvmStatic
fun getLastFocusedOrOpenedProject(): Project? {
return IdeFocusManager.getGlobalInstance().lastFocusedFrame?.project ?: ProjectManager.getInstance().openProjects.firstOrNull()
}
@JvmStatic
fun sendOk(request: FullHttpRequest, context: ChannelHandlerContext) {
sendStatus(HttpResponseStatus.OK, HttpUtil.isKeepAlive(request), context.channel())
}
@JvmStatic
fun sendStatus(status: HttpResponseStatus, keepAlive: Boolean, channel: Channel) {
val response = DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status)
HttpUtil.setContentLength(response, 0)
response.addCommonHeaders()
response.addNoCache()
if (keepAlive) {
HttpUtil.setKeepAlive(response, true)
}
response.headers().set("X-Frame-Options", "Deny")
response.send(channel, !keepAlive)
}
@JvmStatic
fun send(byteOut: BufferExposingByteArrayOutputStream, request: HttpRequest, context: ChannelHandlerContext) {
val response = response("application/json", Unpooled.wrappedBuffer(byteOut.internalBuffer, 0, byteOut.size()))
sendResponse(request, context, response)
}
@JvmStatic
fun sendResponse(request: HttpRequest, context: ChannelHandlerContext, response: HttpResponse) {
response.addNoCache()
response.headers().set("X-Frame-Options", "Deny")
response.send(context.channel(), request)
}
@Suppress("SameParameterValue")
@JvmStatic
fun getStringParameter(name: String, urlDecoder: QueryStringDecoder): String? {
return urlDecoder.parameters().get(name)?.lastOrNull()
}
@JvmStatic
fun getIntParameter(name: String, urlDecoder: QueryStringDecoder): Int {
return StringUtilRt.parseInt(getStringParameter(name, urlDecoder).nullize(nullizeSpaces = true), -1)
}
@JvmOverloads
@JvmStatic
fun getBooleanParameter(name: String, urlDecoder: QueryStringDecoder, defaultValue: Boolean = false): Boolean {
val values = urlDecoder.parameters().get(name) ?: return defaultValue
// if just name specified, so, true
val value = values.lastOrNull() ?: return true
return value.toBoolean()
}
fun parameterMissedErrorMessage(name: String) = "Parameter \"$name\" is not specified"
}
protected val gson: Gson by lazy {
GsonBuilder()
.setPrettyPrinting()
.disableHtmlEscaping()
.create()
}
private val abuseCounter = CacheBuilder.newBuilder()
.expireAfterWrite(1, TimeUnit.MINUTES)
.build<InetAddress, AtomicInteger>(CacheLoader.from(Supplier { AtomicInteger() }))
private val trustedOrigins = CacheBuilder.newBuilder()
.maximumSize(1024)
.expireAfterWrite(1, TimeUnit.DAYS)
.build<String, Boolean>()
/**
* Service url must be "/api/$serviceName", but to preserve backward compatibility, prefixless path could be also supported
*/
protected open val isPrefixlessAllowed: Boolean
get() = false
/**
* Use human-readable name or UUID if it is an internal service.
*/
protected abstract fun getServiceName(): String
override fun isSupported(request: FullHttpRequest): Boolean {
if (!isMethodSupported(request.method())) {
return false
}
val uri = request.uri()
if (isPrefixlessAllowed && checkPrefix(uri, getServiceName())) {
return true
}
val serviceName = getServiceName()
val minLength = 1 + PREFIX.length + 1 + serviceName.length
if (uri.length >= minLength &&
uri[0] == '/' &&
uri.regionMatches(1, PREFIX, 0, PREFIX.length, ignoreCase = true) &&
uri.regionMatches(2 + PREFIX.length, serviceName, 0, serviceName.length, ignoreCase = true)) {
if (uri.length == minLength) {
return true
}
else {
val c = uri[minLength]
return c == '/' || c == '?'
}
}
return false
}
protected open fun isMethodSupported(method: HttpMethod): Boolean {
return method === HttpMethod.GET
}
override fun process(urlDecoder: QueryStringDecoder, request: FullHttpRequest, context: ChannelHandlerContext): Boolean {
try {
val counter = abuseCounter.get((context.channel().remoteAddress() as InetSocketAddress).address)
if (counter.incrementAndGet() > Registry.intValue("ide.rest.api.requests.per.minute", 30)) {
HttpResponseStatus.TOO_MANY_REQUESTS.orInSafeMode(HttpResponseStatus.OK).send(context.channel(), request)
return true
}
if (!isHostTrusted(request, urlDecoder)) {
HttpResponseStatus.FORBIDDEN.orInSafeMode(HttpResponseStatus.OK).send(context.channel(), request)
return true
}
val error = execute(urlDecoder, request, context)
if (error != null) {
HttpResponseStatus.BAD_REQUEST.send(context.channel(), request, error)
}
}
catch (e: Throwable) {
val status: HttpResponseStatus?
// JsonReader exception
if (e is MalformedJsonException || e is IllegalStateException && e.message!!.startsWith("Expected a ")) {
LOG.warn(e)
status = HttpResponseStatus.BAD_REQUEST
}
else {
LOG.error(e)
status = HttpResponseStatus.INTERNAL_SERVER_ERROR
}
status.send(context.channel(), request, ExceptionUtil.getThrowableText(e))
}
return true
}
@Throws(InterruptedException::class, InvocationTargetException::class)
protected open fun isHostTrusted(request: FullHttpRequest, urlDecoder: QueryStringDecoder): Boolean {
@Suppress("DEPRECATION")
return isHostTrusted(request)
}
@Deprecated("Use {@link #isHostTrusted(FullHttpRequest, QueryStringDecoder)}")
@Throws(InterruptedException::class, InvocationTargetException::class)
// e.g. upsource trust to configured host
protected open fun isHostTrusted(request: FullHttpRequest): Boolean {
if (request.isSignedRequest()) {
return true
}
val referrer = request.origin ?: request.referrer
val host = try {
if (referrer == null) null else URI(referrer).host.nullize()
}
catch (ignored: URISyntaxException) {
return false
}
if (host != null) {
if (NetUtils.isLocalhost(host)) {
return true
}
else {
trustedOrigins.getIfPresent(host)?.let {
return it
}
}
}
var isTrusted = false
ApplicationManager.getApplication().invokeAndWait({
AppIcon.getInstance().requestAttention(null, true)
isTrusted = showYesNoDialog(IdeBundle.message("warning.use.rest.api", getServiceName(), host ?: "unknown host"), "title.use.rest.api")
if (host != null) {
trustedOrigins.put(host, isTrusted)
}
}, ModalityState.any())
return isTrusted
}
/**
* Return error or send response using [sendOk], [send]
*/
@Throws(IOException::class)
abstract fun execute(urlDecoder: QueryStringDecoder, request: FullHttpRequest, context: ChannelHandlerContext): String?
}
| apache-2.0 | c30ee68ea545d2b23fe70641694304db | 35.759717 | 190 | 0.695857 | 4.665022 | false | false | false | false |
leafclick/intellij-community | plugins/terminal/src/org/jetbrains/plugins/terminal/TerminalOptionsProvider.kt | 1 | 4149 | // 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 org.jetbrains.plugins.terminal
import com.intellij.execution.configuration.EnvironmentVariablesData
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.components.State
import com.intellij.openapi.components.Storage
import com.intellij.openapi.util.SystemInfo
import com.intellij.util.xmlb.annotations.Property
import java.io.File
@State(name = "TerminalOptionsProvider", storages = [(Storage("terminal.xml"))])
class TerminalOptionsProvider : PersistentStateComponent<TerminalOptionsProvider.State> {
private var myState = State()
override fun getState(): State? {
return myState
}
override fun loadState(state: State) {
myState = state
}
fun getShellPath(): String = getEffectiveShellPath(myState.myShellPath)
fun setShellPath(shellPath: String) {
myState.myShellPath = if (shellPath == defaultShellPath()) null else shellPath
}
fun closeSessionOnLogout(): Boolean {
return myState.myCloseSessionOnLogout
}
fun enableMouseReporting(): Boolean {
return myState.myReportMouse
}
fun audibleBell(): Boolean {
return myState.mySoundBell
}
var tabName: String
get() = myState.myTabName
set(tabName) {
myState.myTabName = tabName
}
fun overrideIdeShortcuts(): Boolean {
return myState.myOverrideIdeShortcuts
}
fun setOverrideIdeShortcuts(overrideIdeShortcuts: Boolean) {
myState.myOverrideIdeShortcuts = overrideIdeShortcuts
}
fun shellIntegration(): Boolean {
return myState.myShellIntegration
}
fun setShellIntegration(shellIntegration: Boolean) {
myState.myShellIntegration = shellIntegration
}
class State {
var myShellPath: String? = null
var myTabName: String = "Local"
var myCloseSessionOnLogout: Boolean = true
var myReportMouse: Boolean = true
var mySoundBell: Boolean = true
var myCopyOnSelection: Boolean = true
var myPasteOnMiddleMouseButton: Boolean = true
var myOverrideIdeShortcuts: Boolean = true
var myShellIntegration: Boolean = true
var myHighlightHyperlinks: Boolean = true
@get:Property(surroundWithTag = false, flat = true)
var envDataOptions = EnvironmentVariablesDataOptions()
}
fun setCloseSessionOnLogout(closeSessionOnLogout: Boolean) {
myState.myCloseSessionOnLogout = closeSessionOnLogout
}
fun setReportMouse(reportMouse: Boolean) {
myState.myReportMouse = reportMouse
}
fun setSoundBell(soundBell: Boolean) {
myState.mySoundBell = soundBell
}
fun copyOnSelection(): Boolean {
return myState.myCopyOnSelection
}
fun setCopyOnSelection(copyOnSelection: Boolean) {
myState.myCopyOnSelection = copyOnSelection
}
fun pasteOnMiddleMouseButton(): Boolean {
return myState.myPasteOnMiddleMouseButton
}
fun setPasteOnMiddleMouseButton(pasteOnMiddleMouseButton: Boolean) {
myState.myPasteOnMiddleMouseButton = pasteOnMiddleMouseButton
}
fun highlightHyperlinks(): Boolean {
return myState.myHighlightHyperlinks
}
fun setHighlightHyperlinks(highlight: Boolean) {
myState.myHighlightHyperlinks = highlight
}
fun getEnvData(): EnvironmentVariablesData {
return myState.envDataOptions.get()
}
fun setEnvData(envData: EnvironmentVariablesData) {
myState.envDataOptions.set(envData)
}
fun defaultShellPath(): String {
val shell = System.getenv("SHELL")
if (shell != null && File(shell).canExecute()) {
return shell
}
if (SystemInfo.isUnix) {
val bashPath = "/bin/bash"
if (File(bashPath).exists()) {
return bashPath
}
return "/bin/sh"
}
return "cmd.exe"
}
fun getEffectiveShellPath(shellPath: String?): String {
return if (shellPath.isNullOrEmpty()) defaultShellPath() else shellPath
}
companion object {
val instance: TerminalOptionsProvider
@JvmStatic
get() = ServiceManager.getService(TerminalOptionsProvider::class.java)
}
}
| apache-2.0 | af77848cf588ae0d7d4db40bd9948be2 | 27.033784 | 140 | 0.740419 | 4.344503 | false | false | false | false |
romannurik/muzei | main/src/main/java/com/google/android/apps/muzei/MainFragment.kt | 1 | 9452 | /*
* Copyright 2017 Google 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 com.google.android.apps.muzei
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.view.View
import androidx.core.content.ContextCompat
import androidx.core.graphics.Insets
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.ui.setupWithNavController
import com.google.android.apps.muzei.browse.BrowseProviderFragment
import com.google.android.apps.muzei.settings.EffectsFragment
import com.google.android.apps.muzei.util.autoCleared
import com.google.android.apps.muzei.util.collectIn
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.google.android.material.navigation.NavigationBarView
import com.google.android.material.navigationrail.NavigationRailView
import com.google.firebase.analytics.FirebaseAnalytics
import com.google.firebase.analytics.ktx.analytics
import com.google.firebase.analytics.ktx.logEvent
import com.google.firebase.ktx.Firebase
import kotlinx.coroutines.flow.map
import net.nurik.roman.muzei.R
import net.nurik.roman.muzei.databinding.MainFragmentBinding
/**
* Fragment which controls the main view of the Muzei app and handles the bottom navigation
* between various screens.
*/
class MainFragment : Fragment(R.layout.main_fragment), ChooseProviderFragment.Callbacks {
private val darkStatusBarColor by lazy {
ContextCompat.getColor(requireContext(), R.color.md_theme_background)
}
private var binding: MainFragmentBinding by autoCleared()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
// Set up the container for the child fragments
binding = MainFragmentBinding.bind(view)
val navHostFragment = binding.container.getFragment<NavHostFragment>()
val navController = navHostFragment.navController
val navGraph = navController.navInflater.inflate(R.navigation.main_navigation)
if (requireActivity().isPreviewMode) {
// Make the Effects screen the start destination when
// coming from the Settings button on the Live Wallpaper picker
navGraph.setStartDestination(R.id.main_effects)
}
navController.graph = navGraph
// Set up the bottom nav
(binding.navBar as NavigationBarView).setupWithNavController(navController)
// React to the destination changing to update the status bar color
navController.currentBackStackEntryFlow.map { backStackEntry ->
backStackEntry.arguments
}.collectIn(viewLifecycleOwner) { args ->
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
requireActivity().window.statusBarColor =
if (args?.getBoolean("useDarkStatusBar") == true) {
darkStatusBarColor
} else {
Color.TRANSPARENT
}
}
}
// React to the destination changing for analytics
navController.currentBackStackEntryFlow.map { backStackEntry ->
backStackEntry.destination.id
}.collectIn(viewLifecycleOwner) { destinationId ->
when (destinationId) {
R.id.main_art_details -> {
Firebase.analytics.logEvent(FirebaseAnalytics.Event.SCREEN_VIEW) {
param(FirebaseAnalytics.Param.SCREEN_NAME, "ArtDetail")
param(FirebaseAnalytics.Param.SCREEN_CLASS,
ArtDetailFragment::class.java.simpleName)
}
}
R.id.main_choose_provider -> {
Firebase.analytics.logEvent(FirebaseAnalytics.Event.SCREEN_VIEW) {
param(FirebaseAnalytics.Param.SCREEN_NAME, "ChooseProvider")
param(FirebaseAnalytics.Param.SCREEN_CLASS,
ChooseProviderFragment::class.java.simpleName)
}
}
R.id.browse_provider -> {
Firebase.analytics.logEvent(FirebaseAnalytics.Event.SCREEN_VIEW) {
param(FirebaseAnalytics.Param.SCREEN_NAME, "BrowseProvider")
param(FirebaseAnalytics.Param.SCREEN_CLASS,
BrowseProviderFragment::class.java.simpleName)
}
}
R.id.main_effects -> {
Firebase.analytics.logEvent(FirebaseAnalytics.Event.SCREEN_VIEW) {
param(FirebaseAnalytics.Param.SCREEN_NAME, "Effects")
param(FirebaseAnalytics.Param.SCREEN_CLASS,
EffectsFragment::class.java.simpleName)
}
}
}
}
(binding.navBar as NavigationBarView).setOnItemReselectedListener { item ->
if (item.itemId == R.id.main_art_details) {
@Suppress("DEPRECATION")
activity?.window?.decorView?.systemUiVisibility = (View.SYSTEM_UI_FLAG_LOW_PROFILE
or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
or View.SYSTEM_UI_FLAG_FULLSCREEN
or View.SYSTEM_UI_FLAG_IMMERSIVE
or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
or View.SYSTEM_UI_FLAG_LAYOUT_STABLE)
}
}
// Send the correct window insets to each view
@Suppress("DEPRECATION")
ViewCompat.setOnApplyWindowInsetsListener(view) { _, insets ->
// Ensure the container gets the appropriate insets
if (binding.navBar is BottomNavigationView) {
ViewCompat.dispatchApplyWindowInsets(binding.container,
WindowInsetsCompat.Builder(insets).setSystemWindowInsets(Insets.of(
insets.systemWindowInsetLeft,
insets.systemWindowInsetTop,
insets.systemWindowInsetRight,
0)).build())
} else if (binding.navBar is NavigationRailView) {
ViewCompat.dispatchApplyWindowInsets(binding.container,
WindowInsetsCompat.Builder(insets).setSystemWindowInsets(Insets.of(
0,
insets.systemWindowInsetTop,
insets.systemWindowInsetRight,
insets.systemWindowInsetBottom)).build())
}
ViewCompat.dispatchApplyWindowInsets(binding.navBar,
WindowInsetsCompat.Builder(insets).setSystemWindowInsets(Insets.of(
insets.systemWindowInsetLeft,
insets.systemWindowInsetTop,
insets.systemWindowInsetRight,
insets.systemWindowInsetBottom)).build())
insets.consumeSystemWindowInsets().consumeDisplayCutout()
}
// Listen for visibility changes to know when to hide our views
@Suppress("DEPRECATION")
view.setOnSystemUiVisibilityChangeListener { vis ->
val visible = vis and View.SYSTEM_UI_FLAG_LOW_PROFILE == 0
with(binding.navBar) {
visibility = View.VISIBLE
animate()
.alpha(if (visible) 1f else 0f)
.setDuration(200)
.withEndAction {
if (!visible) {
visibility = View.GONE
}
updateNavigationBarColor()
}
}
}
}
override fun onViewStateRestored(savedInstanceState: Bundle?) {
super.onViewStateRestored(savedInstanceState)
updateNavigationBarColor()
}
private fun updateNavigationBarColor() {
activity?.window?.apply {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val lightNavigationBar = resources.getBoolean(R.bool.light_navigation_bar)
if (lightNavigationBar) {
@Suppress("DEPRECATION")
decorView.systemUiVisibility = decorView.systemUiVisibility or
View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR
} else {
@Suppress("DEPRECATION")
decorView.systemUiVisibility = decorView.systemUiVisibility and
View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR.inv()
}
}
}
}
override fun onRequestCloseActivity() {
(binding.navBar as NavigationBarView).selectedItemId = R.id.main_art_details
}
} | apache-2.0 | 33a65b2de860a98e52a3429384bc8886 | 45.112195 | 98 | 0.618705 | 5.454126 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/boxInline/nonLocalReturns/tryFinally/nonLocalReturnToCatchBlock.kt | 3 | 762 | // MODULE: lib
// FILE: lib.kt
package utils
inline fun foo(a: Int) {
try {
if (a > 0) throw Exception()
log("foo($a)")
}
catch (e: Exception) {
bar(a)
}
}
inline fun bar(a: Int) {
myRun {
log("bar($a) #1")
if (a == 2) return
log("bar($a) #2")
}
}
var LOG: String = ""
fun log(s: String): String {
LOG += s + ";"
return LOG
}
inline fun myRun(f: () -> Unit) = f()
// MODULE: main(lib)
// FILE: main.kt
import utils.*
fun box(): String {
foo(0)
if (LOG != "foo(0);") return "fail1: $LOG"
LOG = ""
foo(1)
if (LOG != "bar(1) #1;bar(1) #2;") return "fail2: $LOG"
LOG = ""
foo(2)
if (LOG != "bar(2) #1;") return "fail3: $LOG"
return "OK"
} | apache-2.0 | 806a657f5122925201237c404941ba04 | 13.960784 | 59 | 0.461942 | 2.69258 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/platformTypes/primitives/identityEquals.kt | 2 | 370 | // TODO: muted automatically, investigate should it be ran for JS or not
// IGNORE_BACKEND: JS, NATIVE
fun box(): String {
val l = java.util.ArrayList<Int>()
l.add(1000)
val x = l[0] === 1000
if (x) return "Fail: $x"
val x1 = l[0] === 1
if (x1) return "Fail 1: $x"
val x2 = l[0] === l[0]
if (!x2) return "Fail 2: $x"
return "OK"
}
| apache-2.0 | d5302dd1bf5dbb34fb1d9b492e45d2b2 | 22.125 | 72 | 0.545946 | 2.781955 | false | false | false | false |
Bluexin/mek-re | src/main/java/be/bluexin/mekre/blocks/Ore.kt | 1 | 826 | package be.bluexin.mekre.blocks
import be.bluexin.mekre.OreType
import be.bluexin.mekre.blocks.states.BSOre
import net.minecraft.block.material.Material
import net.minecraft.block.properties.PropertyEnum
import net.minecraft.block.state.IBlockState
/**
* Part of mek_re by Bluexin, released under GNU GPLv3.
*
* @author Bluexin
*/
object Ore : MVariantBlock<OreType>("oreBlock", Material.ROCK, hardness = 3.0F, resistance = 5.0F) {
override fun createBlockState() = BSOre(this)
override fun getHarvestLevel(state: IBlockState) = state.getValue(BSOre.typeProperty).harvestLevel
override fun getHarvestTool(state: IBlockState?) = "pickaxe"
override val variants: Array<OreType>
get() = OreType.values()
override val typeProperty: PropertyEnum<OreType>
get() = BSOre.typeProperty
}
| gpl-3.0 | 7f489482bd4298b8d6aef804533f84f4 | 29.592593 | 102 | 0.748184 | 3.485232 | false | false | false | false |
anitawoodruff/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/models/user/Hair.kt | 1 | 791 | package com.habitrpg.android.habitica.models.user
import io.realm.RealmObject
import io.realm.annotations.PrimaryKey
open class Hair : RealmObject {
@PrimaryKey
var userId: String? = null
var preferences: Preferences? = null
var mustache: Int = 0
var beard: Int = 0
var bangs: Int = 0
var base: Int = 0
var flower: Int = 0
var color: String? = null
constructor()
constructor(mustache: Int, beard: Int, bangs: Int, base: Int, color: String, flower: Int) {
this.mustache = mustache
this.beard = beard
this.bangs = bangs
this.base = base
this.color = color
this.flower = flower
}
fun isAvailable(hairId: Int): Boolean {
return hairId > 0
}
}
| gpl-3.0 | 6b18878ece0e593de581878f71b6936f | 21.969697 | 95 | 0.597977 | 3.915842 | false | false | false | false |
kickstarter/android-oss | app/src/main/java/com/kickstarter/viewmodels/SettingsViewModel.kt | 1 | 3506 | package com.kickstarter.viewmodels
import androidx.annotation.NonNull
import com.kickstarter.libs.ActivityViewModel
import com.kickstarter.libs.Environment
import com.kickstarter.libs.rx.transformers.Transformers
import com.kickstarter.models.User
import com.kickstarter.ui.activities.SettingsActivity
import rx.Observable
import rx.subjects.BehaviorSubject
import rx.subjects.PublishSubject
interface SettingsViewModel {
interface Inputs {
/** Call when the user dismiss the logout confirmation dialog. */
fun closeLogoutConfirmationClicked()
/** Call when the user has confirmed that they want to log out. */
fun confirmLogoutClicked()
/** Call when the user taps the logout button. */
fun logoutClicked()
}
interface Outputs {
/** Emits the user avatar image to be displayed. */
fun avatarImageViewUrl(): Observable<String>
/** Emits when its time to log the user out. */
fun logout(): Observable<Void>
/** Emits a boolean that determines if the logout confirmation should be displayed. */
fun showConfirmLogoutPrompt(): Observable<Boolean>
/** Emits the user name to be displayed. */
fun userNameTextViewText(): Observable<String>
}
class ViewModel(@NonNull val environment: Environment) : ActivityViewModel<SettingsActivity>(environment), Inputs, Outputs {
private val client = requireNotNull(environment.apiClient())
private val confirmLogoutClicked = PublishSubject.create<Void>()
private val currentUser = requireNotNull(environment.currentUser())
private val logout = BehaviorSubject.create<Void>()
private val showConfirmLogoutPrompt = BehaviorSubject.create<Boolean>()
private val userOutput = BehaviorSubject.create<User>()
private val avatarImageViewUrl: Observable<String>
private val userNameTextViewText: Observable<String>
val inputs: Inputs = this
val outputs: Outputs = this
private val analytics = this.environment.analytics()
init {
this.client.fetchCurrentUser()
.retry(2)
.compose(Transformers.neverError())
.compose(bindToLifecycle())
.subscribe { this.currentUser.refresh(it) }
this.currentUser.observable()
.take(1)
.compose(bindToLifecycle())
.subscribe({ this.userOutput.onNext(it) })
this.confirmLogoutClicked
.compose(bindToLifecycle())
.subscribe {
this.analytics?.reset()
this.logout.onNext(null)
}
this.avatarImageViewUrl = this.currentUser.loggedInUser().map { u -> u.avatar().medium() }
this.userNameTextViewText = this.currentUser.loggedInUser().map({ it.name() })
}
override fun avatarImageViewUrl() = this.avatarImageViewUrl
override fun closeLogoutConfirmationClicked() = this.showConfirmLogoutPrompt.onNext(false)
override fun confirmLogoutClicked() = this.confirmLogoutClicked.onNext(null)
override fun logoutClicked() = this.showConfirmLogoutPrompt.onNext(true)
override fun logout(): Observable<Void> = this.logout
override fun showConfirmLogoutPrompt(): Observable<Boolean> = this.showConfirmLogoutPrompt
override fun userNameTextViewText() = this.userNameTextViewText
}
}
| apache-2.0 | bbc76169bb7187a901257018c745bb9d | 35.905263 | 128 | 0.668853 | 5.232836 | false | false | false | false |
mtransitapps/mtransit-for-android | src/main/java/org/mtransit/android/ui/home/HomeViewModel.kt | 1 | 14784 | package org.mtransit.android.ui.home
import android.location.Location
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.distinctUntilChanged
import androidx.lifecycle.liveData
import androidx.lifecycle.map
import androidx.lifecycle.switchMap
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.launch
import org.mtransit.android.ad.IAdManager
import org.mtransit.android.commons.CollectionUtils
import org.mtransit.android.commons.LocationUtils
import org.mtransit.android.commons.MTLog
import org.mtransit.android.commons.data.RouteTripStop
import org.mtransit.android.commons.provider.GTFSProviderContract
import org.mtransit.android.commons.provider.POIProviderContract
import org.mtransit.android.data.AgencyBaseProperties
import org.mtransit.android.data.DataSourceType
import org.mtransit.android.data.IAgencyNearbyProperties
import org.mtransit.android.data.POIManager
import org.mtransit.android.datasource.DataSourcesRepository
import org.mtransit.android.datasource.POIRepository
import org.mtransit.android.dev.DemoModeManager
import org.mtransit.android.provider.FavoriteRepository
import org.mtransit.android.provider.location.MTLocationProvider
import org.mtransit.android.ui.MTViewModelWithLocation
import org.mtransit.android.ui.favorites.FavoritesViewModel
import org.mtransit.android.ui.view.common.Event
import org.mtransit.android.ui.view.common.IActivity
import org.mtransit.android.ui.view.common.PairMediatorLiveData
import java.util.SortedMap
import javax.inject.Inject
@HiltViewModel
class HomeViewModel @Inject constructor(
private val dataSourcesRepository: DataSourcesRepository,
private val poiRepository: POIRepository,
private val locationProvider: MTLocationProvider,
private val favoriteRepository: FavoriteRepository,
private val adManager: IAdManager,
private val demoModeManager: DemoModeManager,
) : MTViewModelWithLocation() {
companion object {
private val LOG_TAG = HomeViewModel::class.java.simpleName
private const val NB_MAX_BY_TYPE = 2
private const val NB_MAX_BY_TYPE_ONE_TYPE = 6
private const val NB_MAX_BY_TYPE_TWO_TYPES = 4
private val POI_ALPHA_COMPARATOR = FavoritesViewModel.POIAlphaComparator()
private const val IGNORE_SAME_LOCATION_CHECK = false
// private const val IGNORE_SAME_LOCATION_CHECK = true // DEBUG
}
override fun getLogTag(): String = LOG_TAG
private val _nearbyLocationForceReset = MutableLiveData(Event(false))
val nearbyLocation: LiveData<Location?> =
PairMediatorLiveData(deviceLocation, _nearbyLocationForceReset).switchMap { (lastDeviceLocation, forceResetEvent) ->
liveData(context = viewModelScope.coroutineContext + Dispatchers.IO) {
val forceReset: Boolean = forceResetEvent?.getContentIfNotHandled() ?: false
if (forceReset) {
emit(null) // force reset
}
emit(getNearbyLocation(lastDeviceLocation, forceReset))
}
}.distinctUntilChanged()
private fun getNearbyLocation(lastDeviceLocation: Location?, forceReset: Boolean): Location? {
if (!forceReset) {
nearbyLocation.value?.let {
MTLog.d(this, "getNearbyLocation() > keep same ($it)")
return it
}
}
MTLog.d(this, "getNearbyLocation() > use last device location ($lastDeviceLocation)")
return lastDeviceLocation
}
val nearbyLocationAddress: LiveData<String?> = nearbyLocation.switchMap { nearbyLocation ->
liveData(context = viewModelScope.coroutineContext + Dispatchers.IO) {
emit(getNearbyLocationAddress(nearbyLocation))
}
}
private fun getNearbyLocationAddress(location: Location?): String? {
return location?.let {
locationProvider.getLocationAddressString(it)
}
}
val newLocationAvailable: LiveData<Boolean?> =
PairMediatorLiveData(nearbyLocation, deviceLocation).map { (nearbyLocation, newDeviceLocation) ->
if (nearbyLocation == null) {
null // not new if current unknown
} else {
newDeviceLocation != null
&& !LocationUtils.areAlmostTheSame(nearbyLocation, newDeviceLocation, LocationUtils.LOCATION_CHANGED_NOTIFY_USER_IN_METERS)
}
}.distinctUntilChanged()
private val _allAgencies = this.dataSourcesRepository.readingAllAgenciesBase() // #onModulesUpdated
private val _dstToHomeAgencies: LiveData<SortedMap<DataSourceType, List<AgencyBaseProperties>>?> = _allAgencies.map { allAgencies ->
if (allAgencies.isNullOrEmpty()) {
null
} else {
allAgencies
.filter { it.type.isHomeScreen }
.groupBy { it.type }
.toSortedMap(dataSourcesRepository.defaultDataSourceTypeComparator)
}
}.distinctUntilChanged()
private val _loadingPOIs = MutableLiveData(true)
val loadingPOIs: LiveData<Boolean?> = _loadingPOIs
private val _nearbyPOIsTrigger = MutableLiveData<Event<Boolean>>()
val nearbyPOIsTrigger: LiveData<Event<Boolean>> = _nearbyPOIsTrigger
val nearbyPOIsTriggerListener: LiveData<Void> = PairMediatorLiveData(_dstToHomeAgencies, nearbyLocation).switchMap { (dstToHomeAgencies, nearbyLocation) ->
liveData {
if (dstToHomeAgencies?.isNotEmpty() == true && nearbyLocation != null) {
nearbyPOIsLoadJob?.cancel()
nearbyPOIsLoadJob = viewModelScope.launch(context = viewModelScope.coroutineContext + Dispatchers.IO) {
getNearbyPOIs(this, dstToHomeAgencies, nearbyLocation)
}
}
}
}
private val _nearbyPOIs = MutableLiveData<List<POIManager>?>(null)
val nearbyPOIs: LiveData<List<POIManager>?> = _nearbyPOIs
private var nearbyPOIsLoadJob: Job? = null
private suspend fun getNearbyPOIs(
scope: CoroutineScope,
dstToHomeAgencies: SortedMap<DataSourceType, List<AgencyBaseProperties>>?,
nearbyLocation: Location?,
) {
if (dstToHomeAgencies.isNullOrEmpty() || nearbyLocation == null) {
MTLog.d(this@HomeViewModel, "loadNearbyPOIs() > SKIP (no agencies OR no location)")
_loadingPOIs.postValue(false)
_nearbyPOIs.postValue(null)
_nearbyPOIsTrigger.postValue(Event(true))
return
}
_nearbyPOIsTrigger.postValue(Event(true))
_loadingPOIs.postValue(true)
if (!_nearbyPOIs.value.isNullOrEmpty()) {
delay(333L) // debounce / throttle (agencies being updated)
}
val favoriteUUIDs = favoriteRepository.findFavoriteUUIDs()
val nbMaxByType = when (dstToHomeAgencies.keys.size) {
in 0..1 -> NB_MAX_BY_TYPE_ONE_TYPE
2 -> NB_MAX_BY_TYPE_TWO_TYPES
else -> NB_MAX_BY_TYPE
}
val lat = nearbyLocation.latitude
val lng = nearbyLocation.longitude
val accuracyInMeters = nearbyLocation.accuracy
val minDistanceInMeters = maxOf(
LocationUtils.getAroundCoveredDistanceInMeters(lat, lng, LocationUtils.MIN_AROUND_DIFF),
LocationUtils.MIN_NEARBY_LIST_COVERAGE_IN_METERS.toFloat(),
accuracyInMeters
)
val nearbyPOIs = mutableListOf<POIManager>()
_nearbyPOIs.postValue(nearbyPOIs)
dstToHomeAgencies.forEach { (_, typeAgencies) ->
scope.ensureActive()
val typePOIs = getTypeNearbyPOIs(scope, typeAgencies, lat, lng, minDistanceInMeters, nbMaxByType)
filterTypePOIs(favoriteUUIDs, typePOIs, minDistanceInMeters, nbMaxByType)
CollectionUtils.sort(typePOIs, POI_ALPHA_COMPARATOR)
scope.ensureActive()
_nearbyPOIs.postValue(typePOIs)
nearbyPOIs.addAll(typePOIs)
}
scope.ensureActive()
_nearbyPOIs.postValue(nearbyPOIs)
_loadingPOIs.postValue(false)
}
private fun filterTypePOIs(favoriteUUIDs: Collection<String>, typePOIs: MutableList<POIManager>, minDistanceInMeters: Float, nbMaxByType: Int) {
val it = typePOIs.iterator()
var nbKept = 0
var lastKeptDistance = -1f
val routeTripKept = mutableSetOf<String>()
while (it.hasNext()) {
val poim = it.next()
if (!favoriteUUIDs.contains(poim.poi.uuid)) {
if (poim.poi is RouteTripStop) {
val rts = poim.poi
val routeTripId = "${rts.route.id}-${rts.trip.id}"
if (routeTripKept.contains(routeTripId)) {
it.remove()
continue
}
} else if (nbKept >= nbMaxByType && lastKeptDistance != poim.distance) {
it.remove()
continue
}
}
if (nbKept >= nbMaxByType && lastKeptDistance != poim.distance && poim.distance > minDistanceInMeters) {
it.remove()
continue
}
if (poim.poi is RouteTripStop) {
routeTripKept += "${poim.poi.route.id}-${poim.poi.trip.id}"
}
lastKeptDistance = poim.distance
nbKept++
}
}
private fun getTypeNearbyPOIs(
scope: CoroutineScope,
typeAgencies: List<IAgencyNearbyProperties>,
typeLat: Double,
typeLng: Double,
typeMinCoverageInMeters: Float,
nbMaxByType: Int
): MutableList<POIManager> {
var typePOIs: MutableList<POIManager>
val typeAd = LocationUtils.getNewDefaultAroundDiff()
var lastTypeAroundDiff: Double? = null
val typeMaxSize = LocationUtils.MAX_NEARBY_LIST
while (true) {
scope.ensureActive()
typePOIs = getAreaTypeNearbyPOIs(scope, typeLat, typeLng, typeAd, lastTypeAroundDiff, typeMaxSize, typeMinCoverageInMeters, typeAgencies)
if (this.demoModeManager.enabled) { // filter now to get min number of POI
typePOIs = typePOIs.distinctBy { poim ->
if (poim.poi is RouteTripStop) {
"${poim.poi.route.id}-${poim.poi.trip.id}"
} else {
poim.poi.uuid // keep all
}
}.toMutableList()
}
if (!shouldContinueSearching(typeLat, typeLng, typeAd, typePOIs, typeMinCoverageInMeters, nbMaxByType)) {
break
}
lastTypeAroundDiff = if (typePOIs.isNullOrEmpty()) typeAd.aroundDiff else null
LocationUtils.incAroundDiff(typeAd)
}
return typePOIs
}
private fun shouldContinueSearching(
typeLat: Double,
typeLng: Double,
typeAd: LocationUtils.AroundDiff,
typePOIs: List<POIManager>,
typeMinCoverageInMeters: Float,
nbMaxByType: Int,
) = when {
LocationUtils.searchComplete(typeLat, typeLng, typeAd.aroundDiff) -> false // world exploration completed
this.demoModeManager.enabled && typePOIs.size < DemoModeManager.MIN_POI_HOME_SCREEN -> true // continue
typePOIs.size > nbMaxByType
&& LocationUtils.getAroundCoveredDistanceInMeters(typeLat, typeLng, typeAd.aroundDiff) >= typeMinCoverageInMeters -> {
false // enough POIs / type & enough distance covered
}
else -> true // continue
}
private fun getAreaTypeNearbyPOIs(
scope: CoroutineScope,
lat: Double,
lng: Double,
ad: LocationUtils.AroundDiff, // TODO latter optimize
@Suppress("UNUSED_PARAMETER") optLastAroundDiff: Double? = null,
@Suppress("SameParameterValue") maxSize: Int,
typeMinCoverageInMeters: Float,
typeAgencies: List<IAgencyNearbyProperties>
): MutableList<POIManager> {
val typePOIs = mutableListOf<POIManager>()
val area = LocationUtils.getArea(lat, lng, ad.aroundDiff)
// TODO latter optimize val optLastArea = if (optLastAroundDiff == null) null else LocationUtils.getArea(lat, lng, optLastAroundDiff)
val aroundDiff = ad.aroundDiff
val maxDistance = LocationUtils.getAroundCoveredDistanceInMeters(lat, lng, aroundDiff)
val poiFilter = POIProviderContract.Filter.getNewAroundFilter(lat, lng, aroundDiff).apply {
addExtra(POIProviderContract.POI_FILTER_EXTRA_AVOID_LOADING, true)
addExtra(GTFSProviderContract.POI_FILTER_EXTRA_DESCENT_ONLY, true)
}
typeAgencies
.filter { LocationUtils.Area.areOverlapping(it.area, area) } // TODO latter optimize && !agency.isEntirelyInside(optLastArea)
.forEach { agency ->
scope.ensureActive()
poiRepository.findPOIMs(agency.authority, poiFilter)?.let { agencyPOIs ->
scope.ensureActive()
LocationUtils.updateDistance(agencyPOIs, lat, lng)
LocationUtils.removeTooFar(agencyPOIs, maxDistance)
LocationUtils.removeTooMuchWhenNotInCoverage(
agencyPOIs,
typeMinCoverageInMeters,
if (this.demoModeManager.enabled) Int.MAX_VALUE else maxSize // keep all
)
typePOIs.addAll(agencyPOIs)
}
}
LocationUtils.removeTooMuchWhenNotInCoverage(
typePOIs,
typeMinCoverageInMeters,
if (this.demoModeManager.enabled) Int.MAX_VALUE else maxSize // keep all
)
return typePOIs
}
fun initiateRefresh(): Boolean {
val newDeviceLocation = this.deviceLocation.value ?: return false
val currentNearbyLocation = this.nearbyLocation.value
if (!IGNORE_SAME_LOCATION_CHECK
&& LocationUtils.areAlmostTheSame(currentNearbyLocation, newDeviceLocation, LocationUtils.LOCATION_CHANGED_ALLOW_REFRESH_IN_METERS)
) {
MTLog.d(this, "initiateRefresh() > SKIP (same location)")
return false
}
this._nearbyLocationForceReset.value = Event(true)
MTLog.d(this, "initiateRefresh() > use NEW location")
return true
}
fun getAdBannerHeightInPx(activity: IActivity?): Int {
return this.adManager.getBannerHeightInPx(activity)
}
} | apache-2.0 | 387e61a432a00756fa6ff094aa955c0b | 42.872404 | 159 | 0.657873 | 4.675522 | false | false | false | false |
androidx/androidx | compose/ui/ui-test/src/androidAndroidTest/kotlin/androidx/compose/ui/test/injectionscope/PositionsTest.kt | 3 | 6390 | /*
* 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.compose.ui.test.injectionscope
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.requiredSize
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.test.center
import androidx.compose.ui.test.height
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.test.performGesture
import androidx.compose.ui.test.performMultiModalInput
import androidx.compose.ui.test.topLeft
import androidx.compose.ui.test.util.ClickableTestBox
import androidx.compose.ui.test.util.ClickableTestBox.defaultTag
import androidx.compose.ui.test.width
import androidx.compose.ui.unit.Density
import androidx.test.filters.MediumTest
import com.google.common.truth.Truth.assertThat
import org.junit.Rule
import org.junit.Test
@MediumTest
class PositionsTest {
@get:Rule
val rule = createComposeRule()
@Test
fun testCornersEdgesAndCenter() {
rule.setContent { ClickableTestBox(width = 3f, height = 100f) }
rule.onNodeWithTag(defaultTag).performMultiModalInput {
assertThat(width).isEqualTo(3)
assertThat(height).isEqualTo(100)
assertThat(left).isEqualTo(0f)
assertThat(centerX).isEqualTo(1.5f)
assertThat(right).isEqualTo(2f)
assertThat(top).isEqualTo(0f)
assertThat(centerY).isEqualTo(50f)
assertThat(bottom).isEqualTo(99f)
assertThat(topLeft).isEqualTo(Offset(0f, 0f))
assertThat(topCenter).isEqualTo(Offset(1.5f, 0f))
assertThat(topRight).isEqualTo(Offset(2f, 0f))
assertThat(centerLeft).isEqualTo(Offset(0f, 50f))
assertThat(center).isEqualTo(Offset(1.5f, 50f))
assertThat(centerRight).isEqualTo(Offset(2f, 50f))
assertThat(bottomLeft).isEqualTo(Offset(0f, 99f))
assertThat(bottomCenter).isEqualTo(Offset(1.5f, 99f))
assertThat(bottomRight).isEqualTo(Offset(2f, 99f))
}
}
@Test
fun testRelativeOffset() {
rule.setContent { ClickableTestBox() }
rule.onNodeWithTag(defaultTag).performMultiModalInput {
assertThat(percentOffset(.1f, .1f)).isEqualTo(Offset(10f, 10f))
assertThat(percentOffset(-.2f, 0f)).isEqualTo(Offset(-20f, 0f))
assertThat(percentOffset(.25f, -.5f)).isEqualTo(Offset(25f, -50f))
assertThat(percentOffset(0f, .5f)).isEqualTo(Offset(0f, 50f))
assertThat(percentOffset(2f, -2f)).isEqualTo(Offset(200f, -200f))
}
}
@Test
fun testDensity() {
val expectedDensity = Density(0.8238974f, 0.923457f) // random value
rule.setContent {
CompositionLocalProvider(
LocalDensity provides expectedDensity
) {
ClickableTestBox(width = 3f, height = 100f)
}
}
rule.onNodeWithTag(defaultTag).performMultiModalInput {
assertThat(this.density).isEqualTo(expectedDensity.density)
assertThat(this.fontScale).isEqualTo(expectedDensity.fontScale)
}
}
@Test
fun testSizeInViewport_column_startAtStart() {
testPositionsInViewport(isVertical = true, reverseScrollDirection = false)
}
@Test
fun testSizeInViewport_column_startAtEnd() {
testPositionsInViewport(isVertical = true, reverseScrollDirection = true)
}
@Test
fun testSizeInViewport_row_startAtStart() {
testPositionsInViewport(isVertical = false, reverseScrollDirection = false)
}
@Test
fun testSizeInViewport_row_startAtEnd() {
testPositionsInViewport(isVertical = false, reverseScrollDirection = true)
}
private fun testPositionsInViewport(isVertical: Boolean, reverseScrollDirection: Boolean) {
rule.setContent {
with(LocalDensity.current) {
if (isVertical) {
Column(
Modifier.requiredSize(100.toDp())
.testTag("viewport")
.verticalScroll(
rememberScrollState(),
reverseScrolling = reverseScrollDirection
)
) {
ClickableTestBox(width = 200f, height = 200f)
ClickableTestBox(width = 200f, height = 200f)
}
} else {
Row(
Modifier.requiredSize(100.toDp())
.testTag("viewport")
.horizontalScroll(
rememberScrollState(),
reverseScrolling = reverseScrollDirection
)
) {
ClickableTestBox(width = 200f, height = 200f)
ClickableTestBox(width = 200f, height = 200f)
}
}
}
}
@Suppress("DEPRECATION")
rule.onNodeWithTag("viewport").performGesture {
assertThat(width).isEqualTo(100)
assertThat(height).isEqualTo(100)
assertThat(center).isEqualTo(Offset(50f, 50f))
assertThat(topLeft).isEqualTo(Offset.Zero)
}
}
}
| apache-2.0 | 9301b7136000367ae442f0907c60c0e2 | 37.035714 | 95 | 0.638811 | 4.643895 | false | true | false | false |
androidx/androidx | compose/ui/ui-tooling-preview/src/androidMain/kotlin/androidx/compose/ui/tooling/preview/Device.kt | 3 | 3507 | /*
* 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.compose.ui.tooling.preview
import androidx.annotation.StringDef
/**
* List with the pre-defined devices available to be used in the preview.
*/
object Devices {
const val DEFAULT = ""
const val NEXUS_7 = "id:Nexus 7"
const val NEXUS_7_2013 = "id:Nexus 7 2013"
const val NEXUS_5 = "id:Nexus 5"
const val NEXUS_6 = "id:Nexus 6"
const val NEXUS_9 = "id:Nexus 9"
const val NEXUS_10 = "name:Nexus 10"
const val NEXUS_5X = "id:Nexus 5X"
const val NEXUS_6P = "id:Nexus 6P"
const val PIXEL_C = "id:pixel_c"
const val PIXEL = "id:pixel"
const val PIXEL_XL = "id:pixel_xl"
const val PIXEL_2 = "id:pixel_2"
const val PIXEL_2_XL = "id:pixel_2_xl"
const val PIXEL_3 = "id:pixel_3"
const val PIXEL_3_XL = "id:pixel_3_xl"
const val PIXEL_3A = "id:pixel_3a"
const val PIXEL_3A_XL = "id:pixel_3a_xl"
const val PIXEL_4 = "id:pixel_4"
const val PIXEL_4_XL = "id:pixel_4_xl"
const val AUTOMOTIVE_1024p = "id:automotive_1024p_landscape"
const val WEAR_OS_LARGE_ROUND = "id:wearos_large_round"
const val WEAR_OS_SMALL_ROUND = "id:wearos_small_round"
const val WEAR_OS_SQUARE = "id:wearos_square"
const val WEAR_OS_RECT = "id:wearos_rect"
// Reference devices
const val PHONE = "spec:id=reference_phone,shape=Normal,width=411,height=891,unit=dp,dpi=420"
const val FOLDABLE = "spec:shape=Normal,width=673,height=841,unit=dp,dpi=480"
const val TABLET = "spec:shape=Normal,width=1280,height=800,unit=dp,dpi=420"
const val DESKTOP = "spec:shape=Normal,width=1920,height=1080,unit=dp,dpi=420"
// TV devices (not adding 4K since it will be very heavy for preview)
const val TV_720p = "spec:shape=Normal,width=1280,height=720,unit=dp,dpi=420"
const val TV_1080p = "spec:shape=Normal,width=1920,height=1080,unit=dp,dpi=420"
}
/**
* Annotation for defining the [Preview] device to use.
* @suppress
*/
@Retention(AnnotationRetention.SOURCE)
@StringDef(
open = true,
value = [
Devices.DEFAULT,
Devices.NEXUS_7,
Devices.NEXUS_7_2013,
Devices.NEXUS_5,
Devices.NEXUS_6,
Devices.NEXUS_9,
Devices.NEXUS_10,
Devices.NEXUS_5X,
Devices.NEXUS_6P,
Devices.PIXEL_C,
Devices.PIXEL,
Devices.PIXEL_XL,
Devices.PIXEL_2,
Devices.PIXEL_2_XL,
Devices.PIXEL_3,
Devices.PIXEL_3_XL,
Devices.PIXEL_3A,
Devices.PIXEL_3A_XL,
Devices.PIXEL_4,
Devices.PIXEL_4_XL,
Devices.AUTOMOTIVE_1024p,
Devices.WEAR_OS_LARGE_ROUND,
Devices.WEAR_OS_SMALL_ROUND,
Devices.WEAR_OS_SQUARE,
Devices.WEAR_OS_RECT,
Devices.PHONE,
Devices.FOLDABLE,
Devices.TABLET,
Devices.DESKTOP,
Devices.TV_720p,
Devices.TV_1080p,
]
)
annotation class Device
| apache-2.0 | e54ce16774d3424d9050af581f34f91d | 30.594595 | 97 | 0.65412 | 3.238227 | false | false | false | false |
GunoH/intellij-community | plugins/ide-features-trainer/src/training/lang/LangSupport.kt | 8 | 4355 | // 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 training.lang
import com.intellij.ide.impl.OpenProjectTask
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.wm.ToolWindowAnchor
import com.intellij.util.concurrency.annotations.RequiresBackgroundThread
import training.dsl.LessonContext
import training.learn.course.KLesson
import training.learn.exceptons.InvalidSdkException
import training.learn.exceptons.NoSdkException
import training.util.OnboardingFeedbackData
import java.io.File
import java.io.FileFilter
import java.nio.file.Path
interface LangSupport {
/** It should be a language ID */
val primaryLanguage: String
val defaultProductName: String?
get() = null
/** It is a name for content root for learning files. In most cases it is just a learning project name. */
val contentRootDirectoryName: String
val langCourseFeedback: String?
get() = null
/** The onboarding leson can set this variable to non-null value to invoke feedback dialog and include corresponding data */
var onboardingFeedbackData: OnboardingFeedbackData?
/**
* Should be true iff this language support will not create its own demo project and
* will use current user project even for non-scratch lessons.
*/
val useUserProjects: Boolean get() = false
/** Relative path inside plugin resources */
val projectResourcePath: String
get() = "learnProjects/${primaryLanguage.toLowerCase()}/$contentRootDirectoryName"
/** Language can specify default sandbox-like file to be used for lessons with modifications but also with project support */
val sampleFilePath: String?
get() = null
/** Language can specify default scratch file name for scratch lessons */
val scratchFileName: String
get() = "Learning"
/** Language support can add tasks to check SDK configuration */
val sdkConfigurationTasks: LessonContext.(lesson: KLesson) -> Unit
get() = {}
/** Check that the project has needed SDK configured */
fun isSdkConfigured(project: Project): Boolean
companion object {
const val EP_NAME = "training.ift.language.extension"
}
fun installAndOpenLearningProject(contentRoot: Path, projectToClose: Project?, postInitCallback: (learnProject: Project) -> Unit)
fun openOrImportLearningProject(projectRootDirectory: VirtualFile, openProjectTask: OpenProjectTask): Project
fun copyLearningProjectFiles(projectDirectory: File, destinationFilter: FileFilter? = null): Boolean
/**
* Implement that method to define SDK lookup depending on a given project.
*
* @return an SDK instance which (existing or newly created) should be applied to the project given. Return `null`
* if no SDK is okay for this project.
*
* @throws NoSdkException in the case no valid SDK is available, yet it's required for the given project
*/
@Throws(NoSdkException::class)
fun getSdkForProject(project: Project, selectedSdk: Sdk?): Sdk?
fun applyProjectSdk(sdk: Sdk, project: Project)
fun applyToProjectAfterConfigure(): (Project) -> Unit
/**
* <p> Implement that method to require some checks for the SDK in the learning project.
* The easiest check is to check the presence and SdkType, but other checks like language level
* might be applied as well.
*
* <p> The method should not return anything, but might throw exceptions subclassing InvalidSdkException which
* will be handled by a UI.
*/
@Throws(InvalidSdkException::class)
fun checkSdk(sdk: Sdk?, project: Project)
fun getProjectFilePath(projectName: String): String
fun getToolWindowAnchor(): ToolWindowAnchor = ToolWindowAnchor.LEFT
/** true means block source code modification in demo learning projects (scratches can be modified anyway)*/
fun blockProjectFileModification(project: Project, file: VirtualFile): Boolean = false
@RequiresBackgroundThread
fun cleanupBeforeLessons(project: Project) = Unit
fun startFromWelcomeFrame(startCallback: (Sdk?) -> Unit) {
startCallback(null)
}
fun getLearningProjectPath(contentRoot: Path): Path {
return contentRoot
}
fun getContentRootPath(projectPath: Path): Path {
return projectPath
}
}
| apache-2.0 | 60b9eae43d63938a1b9d641d4be3e4f5 | 36.543103 | 140 | 0.760276 | 4.682796 | false | false | false | false |
GunoH/intellij-community | java/java-impl/src/com/intellij/lang/java/actions/PropertyRenderer.kt | 1 | 5474 | // 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 com.intellij.lang.java.actions
import com.intellij.codeInsight.CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement
import com.intellij.codeInsight.ExpectedTypeInfo
import com.intellij.codeInsight.daemon.impl.quickfix.CreateFromUsageBaseFix.positionCursor
import com.intellij.codeInsight.daemon.impl.quickfix.CreateFromUsageUtils.ParameterNameExpression
import com.intellij.codeInsight.daemon.impl.quickfix.GuessTypeParameters
import com.intellij.codeInsight.template.TemplateBuilderImpl
import com.intellij.codeInsight.template.TemplateManager
import com.intellij.codeInsight.template.impl.VariableNode
import com.intellij.lang.java.beans.PropertyKind
import com.intellij.lang.java.request.CreateMethodFromJavaUsageRequest
import com.intellij.lang.jvm.JvmModifier
import com.intellij.lang.jvm.actions.CreateMethodRequest
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.*
import com.intellij.psi.codeStyle.JavaCodeStyleManager
import com.intellij.psi.codeStyle.VariableKind
internal abstract class PropertyRenderer(
private val project: Project,
private val target: PsiClass,
private val request: CreateMethodRequest,
nameKind: Pair<String, PropertyKind>
) {
private val factory = JavaPsiFacade.getInstance(project).elementFactory
private val codeStyleManager = JavaCodeStyleManager.getInstance(project)!!
private val javaUsage = request as? CreateMethodFromJavaUsageRequest
private val isStatic = JvmModifier.STATIC in request.modifiers
private val propertyName = nameKind.first
protected val propertyKind = nameKind.second
private val suggestedFieldName = run {
val kind = if (isStatic) VariableKind.STATIC_FIELD else VariableKind.FIELD
codeStyleManager.propertyNameToVariableName(propertyName, kind)
}
fun generatePrototypeField(): PsiField {
val prototypeType = if (propertyKind == PropertyKind.BOOLEAN_GETTER || isBooleanSetter()) PsiType.BOOLEAN else PsiType.VOID
return factory.createField(suggestedFieldName, prototypeType).setStatic(isStatic)
}
private fun isBooleanSetter(): Boolean {
if (propertyKind == PropertyKind.SETTER) {
val expectedType = request.expectedParameters.single().expectedTypes.singleOrNull()
return expectedType != null && PsiType.BOOLEAN == JvmPsiConversionHelper.getInstance(project).convertType(expectedType.theType)
}
return false
}
private val expectedTypes: List<ExpectedTypeInfo> = when (propertyKind) {
PropertyKind.GETTER -> extractExpectedTypes(project, request.returnType).orObject(target)
PropertyKind.BOOLEAN_GETTER -> listOf(PsiType.BOOLEAN.toExpectedType())
PropertyKind.SETTER -> extractExpectedTypes(project, request.expectedParameters.single().expectedTypes).orObject(target)
}
private lateinit var targetDocument: Document
private lateinit var targetEditor: Editor
private fun navigate(): Boolean {
val targetFile = target.containingFile ?: return false
targetDocument = targetFile.viewProvider.document ?: return false
targetEditor = positionCursor(project, targetFile, target) ?: return false
return true
}
fun doRender() {
if (!navigate()) return
val builder = TemplateBuilderImpl(target)
builder.setGreedyToRight(true)
val typeExpression = fillTemplate(builder) ?: return
val template = builder.buildInlineTemplate().apply {
isToShortenLongNames = true
}
val listener = InsertMissingFieldTemplateListener(project, target, typeExpression, isStatic)
TemplateManager.getInstance(project).startTemplate(targetEditor, template, listener)
}
protected abstract fun fillTemplate(builder: TemplateBuilderImpl): RangeExpression?
protected fun insertAccessor(prototype: PsiMethod): PsiMethod? {
val method = target.add(prototype) as PsiMethod
return forcePsiPostprocessAndRestoreElement(method)
}
private fun TemplateBuilderImpl.createTemplateContext(): TemplateContext {
val substitutor = request.targetSubstitutor.toPsiSubstitutor(project)
val guesser = GuessTypeParameters(project, factory, this, substitutor)
return TemplateContext(project, factory, target, this, guesser, javaUsage?.context)
}
protected fun TemplateBuilderImpl.setupInput(input: AccessorTemplateData): RangeExpression {
val templateTypeElement = createTemplateContext().setupTypeElement(input.typeElement, expectedTypes)
val typeExpression = RangeExpression(targetDocument, templateTypeElement.textRange)
val fieldExpression = FieldExpression(project, target, suggestedFieldName) { typeExpression.text }
replaceElement(input.fieldRef, FIELD_VARIABLE, fieldExpression, true)
input.endElement?.let(::setEndVariableAfter)
return typeExpression
}
protected fun TemplateBuilderImpl.setupSetterParameter(data: SetterTemplateData) {
val suggestedNameInfo = codeStyleManager.suggestVariableName(VariableKind.PARAMETER, propertyName, null, null)
val setterParameterExpression = ParameterNameExpression(suggestedNameInfo.names)
replaceElement(data.parameterName, SETTER_PARAM_NAME, setterParameterExpression, true)
replaceElement(data.parameterRef, VariableNode(SETTER_PARAM_NAME, null), false) // copy setter parameter name to mirror
}
}
| apache-2.0 | 86ccbaab97d23b4901e9ecd1190a4cd3 | 47.442478 | 158 | 0.803069 | 5.049815 | false | false | false | false |
siosio/intellij-community | platform/platform-impl/src/com/intellij/openapi/wm/impl/ToolWindowManagerImpl.kt | 1 | 83322 | // 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.openapi.wm.impl
import com.intellij.BundleBase
import com.intellij.DynamicBundle
import com.intellij.diagnostic.LoadingState
import com.intellij.diagnostic.runActivity
import com.intellij.icons.AllIcons
import com.intellij.ide.IdeBundle
import com.intellij.ide.IdeEventQueue
import com.intellij.ide.UiActivity
import com.intellij.ide.UiActivityMonitor
import com.intellij.ide.actions.ActivateToolWindowAction
import com.intellij.ide.actions.MaximizeActiveDialogAction
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.internal.statistic.collectors.fus.actions.persistence.ToolWindowCollector
import com.intellij.notification.impl.NotificationsManagerImpl
import com.intellij.openapi.Disposable
import com.intellij.openapi.MnemonicHelper
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.KeyboardShortcut
import com.intellij.openapi.actionSystem.ex.AnActionListener
import com.intellij.openapi.actionSystem.impl.ActionButton
import com.intellij.openapi.application.Application
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.components.*
import com.intellij.openapi.diagnostic.debug
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.extensions.ExtensionPointListener
import com.intellij.openapi.extensions.PluginDescriptor
import com.intellij.openapi.extensions.impl.ExtensionPointImpl
import com.intellij.openapi.extensions.impl.ExtensionsAreaImpl
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.fileEditor.FileEditorManagerListener
import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx
import com.intellij.openapi.fileEditor.impl.EditorsSplitters
import com.intellij.openapi.keymap.Keymap
import com.intellij.openapi.keymap.KeymapManager
import com.intellij.openapi.keymap.KeymapManagerListener
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.project.*
import com.intellij.openapi.project.ex.ProjectEx
import com.intellij.openapi.startup.StartupActivity
import com.intellij.openapi.ui.FrameWrapper
import com.intellij.openapi.ui.MessageType
import com.intellij.openapi.ui.Splitter
import com.intellij.openapi.ui.popup.Balloon
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.openapi.util.*
import com.intellij.openapi.util.registry.ExperimentalUI
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.wm.*
import com.intellij.openapi.wm.ex.ToolWindowEx
import com.intellij.openapi.wm.ex.ToolWindowManagerEx
import com.intellij.openapi.wm.ex.ToolWindowManagerListener
import com.intellij.openapi.wm.ex.WindowManagerEx
import com.intellij.ui.BalloonImpl
import com.intellij.ui.ComponentUtil
import com.intellij.ui.awt.RelativePoint
import com.intellij.util.*
import com.intellij.util.concurrency.AppExecutorUtil
import com.intellij.util.containers.addIfNotNull
import com.intellij.util.ui.*
import org.intellij.lang.annotations.JdkConstants
import org.jdom.Element
import org.jetbrains.annotations.ApiStatus
import java.awt.*
import java.awt.event.*
import java.beans.PropertyChangeListener
import java.util.*
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicReference
import java.util.function.Supplier
import javax.swing.*
import javax.swing.event.HyperlinkEvent
import javax.swing.event.HyperlinkListener
private val LOG = logger<ToolWindowManagerImpl>()
@State(
name = "ToolWindowManager",
defaultStateAsResource = true,
storages = [Storage(StoragePathMacros.PRODUCT_WORKSPACE_FILE)]
)
open class ToolWindowManagerImpl(val project: Project) : ToolWindowManagerEx(), PersistentStateComponent<Element?>, Disposable {
private val dispatcher = EventDispatcher.create(ToolWindowManagerListener::class.java)
private var layout = DesktopLayout()
private val idToEntry: MutableMap<String, ToolWindowEntry> = HashMap()
private val activeStack = ActiveStack()
private val sideStack = SideStack()
private var toolWindowPane: ToolWindowsPane? = null
private var frame: ProjectFrameHelper? = null
private var layoutToRestoreLater: DesktopLayout? = null
private var currentState = KeyState.WAITING
private var waiterForSecondPress: SingleAlarm? = null
private val recentToolWindows: MutableList<String> = LinkedList<String>()
private val pendingSetLayoutTask = AtomicReference<Runnable?>()
fun isToolWindowRegistered(id: String) = idToEntry.containsKey(id)
init {
if (project.isDefault) {
waiterForSecondPress = null
}
else {
runActivity("toolwindow factory class preloading") {
processDescriptors { bean, pluginDescriptor ->
bean.getToolWindowFactory(pluginDescriptor)
}
}
}
}
override fun dispose() = Unit
companion object {
/**
* Setting this [client property][JComponent.putClientProperty] allows to specify 'effective' parent for a component which will be used
* to find a tool window to which component belongs (if any). This can prevent tool windows in non-default view modes (e.g. 'Undock')
* to close when focus is transferred to a component not in tool window hierarchy, but logically belonging to it (e.g. when component
* is added to the window's layered pane).
*
* @see ComponentUtil.putClientProperty
*/
@JvmField
val PARENT_COMPONENT: Key<JComponent> = Key.create("tool.window.parent.component")
@JvmStatic
@ApiStatus.Internal
fun getRegisteredMutableInfoOrLogError(decorator: InternalDecoratorImpl): WindowInfoImpl {
val toolWindow = decorator.toolWindow
return toolWindow.toolWindowManager.getRegisteredMutableInfoOrLogError(toolWindow.id)
}
fun getAdjustedRatio(partSize: Int, totalSize: Int, direction: Int): Float {
var ratio = partSize.toFloat() / totalSize
ratio += (((partSize.toFloat() + direction) / totalSize) - ratio) / 2
return ratio
}
}
internal fun getFrame() = frame
private fun runPendingLayoutTask() {
pendingSetLayoutTask.getAndSet(null)?.run()
}
@Service
private class ToolWindowManagerAppLevelHelper {
companion object {
private fun handleFocusEvent(event: FocusEvent) {
if (event.id == FocusEvent.FOCUS_LOST) {
if (event.oppositeComponent == null || event.isTemporary) {
return
}
val project = IdeFocusManager.getGlobalInstance().lastFocusedFrame?.project ?: return
if (project.isDisposed || project.isDefault) {
return
}
val toolWindowManager = getInstance(project) as ToolWindowManagerImpl
val toolWindowId = toolWindowManager.activeToolWindowId ?: return
val activeEntry = toolWindowManager.idToEntry[toolWindowId] ?: return
val windowInfo = activeEntry.readOnlyWindowInfo
// just removed
if (!windowInfo.isVisible) {
return
}
if (!(windowInfo.isAutoHide || windowInfo.type == ToolWindowType.SLIDING)) {
return
}
// let's check that it is a toolwindow who loses the focus
if (isInActiveToolWindow(event.source, activeEntry.toolWindow) && !isInActiveToolWindow(event.oppositeComponent,
activeEntry.toolWindow)) {
// a toolwindow lost focus
val focusGoesToPopup = JBPopupFactory.getInstance().getParentBalloonFor(event.oppositeComponent) != null
if (!focusGoesToPopup) {
val info = toolWindowManager.getRegisteredMutableInfoOrLogError(toolWindowId)
toolWindowManager.doDeactivateToolWindow(info, activeEntry)
}
}
}
else if (event.id == FocusEvent.FOCUS_GAINED) {
val component = event.component ?: return
processOpenedProjects { project ->
for (composite in FileEditorManagerEx.getInstanceEx(project).splitters.editorComposites) {
if (composite.editors.any { SwingUtilities.isDescendingFrom(component, it.component) }) {
(getInstance(project) as ToolWindowManagerImpl).activeStack.clear()
}
}
}
}
}
private inline fun process(processor: (manager: ToolWindowManagerImpl) -> Unit) {
processOpenedProjects { project ->
processor(getInstance(project) as ToolWindowManagerImpl)
}
}
class MyListener : AWTEventListener {
override fun eventDispatched(event: AWTEvent?) {
if (event is FocusEvent) {
handleFocusEvent(event)
}
else if (event is WindowEvent && event.getID() == WindowEvent.WINDOW_LOST_FOCUS) {
process { manager ->
val frame = event.getSource() as? JFrame
if (frame === manager.frame?.frame) {
manager.resetHoldState()
}
}
}
}
}
}
init {
val awtFocusListener = MyListener()
Toolkit.getDefaultToolkit().addAWTEventListener(awtFocusListener, AWTEvent.FOCUS_EVENT_MASK or AWTEvent.WINDOW_FOCUS_EVENT_MASK)
val updateHeadersAlarm = SingleAlarm(Runnable {
processOpenedProjects { project ->
(getInstance(project) as ToolWindowManagerImpl).updateToolWindowHeaders()
}
}, 50, ApplicationManager.getApplication())
val focusListener = PropertyChangeListener { updateHeadersAlarm.cancelAndRequest() }
KeyboardFocusManager.getCurrentKeyboardFocusManager().addPropertyChangeListener("focusOwner", focusListener)
Disposer.register(ApplicationManager.getApplication()) {
KeyboardFocusManager.getCurrentKeyboardFocusManager().removePropertyChangeListener("focusOwner", focusListener)
}
val connection = ApplicationManager.getApplication().messageBus.connect()
connection.subscribe(ProjectManager.TOPIC, object : ProjectManagerListener {
override fun projectClosingBeforeSave(project: Project) {
val manager = (project.serviceIfCreated<ToolWindowManager>() as ToolWindowManagerImpl?) ?: return
for (entry in manager.idToEntry.values) {
manager.saveFloatingOrWindowedState(entry, manager.layout.getInfo(entry.id) ?: continue)
}
}
override fun projectClosed(project: Project) {
(project.serviceIfCreated<ToolWindowManager>() as ToolWindowManagerImpl?)?.projectClosed()
}
})
connection.subscribe(KeymapManagerListener.TOPIC, object : KeymapManagerListener {
override fun activeKeymapChanged(keymap: Keymap?) {
process { manager ->
manager.idToEntry.values.forEach {
it.stripeButton.updatePresentation()
}
}
}
})
connection.subscribe(AnActionListener.TOPIC, object : AnActionListener {
override fun beforeActionPerformed(action: AnAction, event: AnActionEvent) {
process { manager ->
if (manager.currentState != KeyState.HOLD) {
manager.resetHoldState()
}
}
}
})
IdeEventQueue.getInstance().addDispatcher(IdeEventQueue.EventDispatcher { event ->
if (event is KeyEvent) {
process { manager ->
manager.dispatchKeyEvent(event)
}
}
false
}, ApplicationManager.getApplication())
}
}
private fun updateToolWindowHeaders() {
focusManager.doWhenFocusSettlesDown(ExpirableRunnable.forProject(project) {
for (entry in idToEntry.values) {
if (entry.readOnlyWindowInfo.isVisible) {
entry.toolWindow.decoratorComponent?.repaint()
}
}
})
}
private fun dispatchKeyEvent(e: KeyEvent): Boolean {
if ((e.keyCode != KeyEvent.VK_CONTROL) && (
e.keyCode != KeyEvent.VK_ALT) && (e.keyCode != KeyEvent.VK_SHIFT) && (e.keyCode != KeyEvent.VK_META)) {
if (e.modifiers == 0) {
resetHoldState()
}
return false
}
if (e.id != KeyEvent.KEY_PRESSED && e.id != KeyEvent.KEY_RELEASED) {
return false
}
val parent = UIUtil.findUltimateParent(e.component)
if (parent is IdeFrame) {
if ((parent as IdeFrame).project !== project) {
resetHoldState()
return false
}
}
val vks = activateToolWindowVKsMask
if (vks == 0) {
resetHoldState()
return false
}
val mouseMask = InputEvent.BUTTON1_DOWN_MASK or InputEvent.BUTTON2_DOWN_MASK or InputEvent.BUTTON3_DOWN_MASK
if (BitUtil.isSet(vks, keyCodeToInputMask(e.keyCode)) && (e.modifiersEx and mouseMask) == 0) {
val pressed = e.id == KeyEvent.KEY_PRESSED
val modifiers = e.modifiers
if (areAllModifiersPressed(modifiers, vks) || !pressed) {
processState(pressed)
}
else {
resetHoldState()
}
}
return false
}
private fun resetHoldState() {
currentState = KeyState.WAITING
processHoldState()
}
private fun processState(pressed: Boolean) {
if (pressed) {
if (currentState == KeyState.WAITING) {
currentState = KeyState.PRESSED
}
else if (currentState == KeyState.RELEASED) {
currentState = KeyState.HOLD
processHoldState()
}
}
else {
if (currentState == KeyState.PRESSED) {
currentState = KeyState.RELEASED
waiterForSecondPress?.cancelAndRequest()
}
else {
resetHoldState()
}
}
}
private fun processHoldState() {
toolWindowPane?.setStripesOverlayed(currentState == KeyState.HOLD)
}
@ApiStatus.Internal
override fun init(frameHelper: ProjectFrameHelper): ToolWindowsPane {
toolWindowPane?.let {
return it
}
// manager is used in light tests (light project is never disposed), so, earlyDisposable must be used
val disposable = (project as ProjectEx).earlyDisposable
waiterForSecondPress = SingleAlarm(task = Runnable {
if (currentState != KeyState.HOLD) {
resetHoldState()
}
}, delay = SystemProperties.getIntProperty("actionSystem.keyGestureDblClickTime", 650), parentDisposable = disposable)
val connection = project.messageBus.connect(disposable)
connection.subscribe(ToolWindowManagerListener.TOPIC, dispatcher.multicaster)
connection.subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER, object : FileEditorManagerListener {
override fun fileClosed(source: FileEditorManager, file: VirtualFile) {
focusManager.doWhenFocusSettlesDown(ExpirableRunnable.forProject(project) {
if (!FileEditorManager.getInstance(project).hasOpenFiles()) {
focusToolWindowByDefault()
}
})
}
})
frame = frameHelper
val rootPane = frameHelper.rootPane!!
val toolWindowPane = rootPane.toolWindowPane
toolWindowPane.initDocumentComponent(project)
this.toolWindowPane = toolWindowPane
return toolWindowPane
}
// must be executed in EDT
private fun beforeProjectOpenedTask(
tasks: List<RegisterToolWindowTask>,
app: Application,
) = Runnable {
frame!!.rootPane!!.updateToolbar()
runPendingLayoutTask()
// FacetDependentToolWindowManager - strictly speaking, computeExtraToolWindowBeans should be executed not in EDT, but for now it is not safe because:
// 1. read action is required to read facet list (might cause a deadlock)
// 2. delay between collection and adding ProjectWideFacetListener (should we introduce a new method in RegisterToolWindowTaskProvider to add listeners?)
val list = ArrayList(tasks) +
(app.extensionArea as ExtensionsAreaImpl)
.getExtensionPoint<RegisterToolWindowTaskProvider>("com.intellij.registerToolWindowTaskProvider")
.computeExtraToolWindowBeans()
if (toolWindowPane == null) {
if (!app.isUnitTestMode) {
LOG.error("ProjectFrameAllocator is not used - use ProjectManager.openProject to open project in a correct way")
}
val toolWindowsPane = init((WindowManager.getInstance() as WindowManagerImpl).allocateFrame(project))
// cannot be executed because added layered pane is not yet validated and size is not known
app.invokeLater(Runnable {
runPendingLayoutTask()
initToolWindows(list, toolWindowsPane)
}, project.disposed)
}
else {
initToolWindows(list, toolWindowPane!!)
}
registerEPListeners()
}
private fun computeToolWindowBeans(): List<RegisterToolWindowTask> {
val list = mutableListOf<RegisterToolWindowTask>()
processDescriptors { bean, pluginDescriptor ->
val condition = bean.getCondition(pluginDescriptor)
if (condition == null ||
condition.value(project)) {
list.addIfNotNull(beanToTask(bean, pluginDescriptor))
}
}
return list
}
private fun ExtensionPointImpl<RegisterToolWindowTaskProvider>.computeExtraToolWindowBeans(): List<RegisterToolWindowTask> {
val list = mutableListOf<RegisterToolWindowTask>()
this.processImplementations(true) { supplier, epPluginDescriptor ->
if (epPluginDescriptor.pluginId == PluginManagerCore.CORE_ID) {
for (bean in (supplier.get() ?: return@processImplementations).getTasks(project)) {
list.addIfNotNull(beanToTask(bean))
}
}
else {
LOG.error("Only bundled plugin can define registerToolWindowTaskProvider: $epPluginDescriptor")
}
}
return list
}
private fun beanToTask(
bean: ToolWindowEP,
pluginDescriptor: PluginDescriptor = bean.pluginDescriptor,
): RegisterToolWindowTask? {
val factory = bean.getToolWindowFactory(pluginDescriptor)
return if (factory != null &&
factory.isApplicable(project))
beanToTask(bean, pluginDescriptor, factory)
else
null
}
private fun beanToTask(
bean: ToolWindowEP,
pluginDescriptor: PluginDescriptor,
factory: ToolWindowFactory,
) = RegisterToolWindowTask(
id = bean.id,
icon = findIconFromBean(bean, factory, pluginDescriptor),
anchor = getToolWindowAnchor(factory, bean),
sideTool = bean.secondary || (@Suppress("DEPRECATION") bean.side),
canCloseContent = bean.canCloseContents,
canWorkInDumbMode = DumbService.isDumbAware(factory),
shouldBeAvailable = factory.shouldBeAvailable(project),
contentFactory = factory,
stripeTitle = getStripeTitleSupplier(bean.id, pluginDescriptor),
)
// This method cannot be inlined because of magic Kotlin compilation bug: it 'captured' "list" local value and cause class-loader leak
// See IDEA-CR-61904
private fun registerEPListeners() {
ToolWindowEP.EP_NAME.addExtensionPointListener(object : ExtensionPointListener<ToolWindowEP> {
override fun extensionAdded(extension: ToolWindowEP, pluginDescriptor: PluginDescriptor) {
initToolWindow(extension, pluginDescriptor)
}
override fun extensionRemoved(extension: ToolWindowEP, pluginDescriptor: PluginDescriptor) {
doUnregisterToolWindow(extension.id)
}
}, project)
}
private fun getToolWindowAnchor(factory: ToolWindowFactory?, bean: ToolWindowEP) =
(factory as? ToolWindowFactoryEx)?.anchor ?: ToolWindowAnchor.fromText(bean.anchor ?: ToolWindowAnchor.LEFT.toString())
private fun initToolWindows(list: List<RegisterToolWindowTask>, toolWindowsPane: ToolWindowsPane) {
runActivity("toolwindow creating") {
val entries = ArrayList<String>(list.size)
for (task in list) {
try {
entries.add(doRegisterToolWindow(task, toolWindowsPane).id)
}
catch (e: ProcessCanceledException) {
throw e
}
catch (t: Throwable) {
LOG.error("Cannot init toolwindow ${task.contentFactory}", t)
}
}
project.messageBus.syncPublisher(ToolWindowManagerListener.TOPIC).toolWindowsRegistered(entries, this)
toolWindowPane!!.revalidateNotEmptyStripes()
}
toolWindowsPane.putClientProperty(UIUtil.NOT_IN_HIERARCHY_COMPONENTS, Iterable {
idToEntry.values.asSequence().mapNotNull {
val component = it.toolWindow.decoratorComponent
if (component != null && component.parent == null) component else null
}.iterator()
})
service<ToolWindowManagerAppLevelHelper>()
}
override fun initToolWindow(bean: ToolWindowEP) {
initToolWindow(bean, bean.pluginDescriptor)
}
private fun initToolWindow(bean: ToolWindowEP, pluginDescriptor: PluginDescriptor) {
val condition = bean.getCondition(pluginDescriptor)
if (condition != null && !condition.value(project)) {
return
}
val factory = bean.getToolWindowFactory(bean.pluginDescriptor) ?: return
if (!factory.isApplicable(project)) {
return
}
val toolWindowPane = toolWindowPane ?: init((WindowManager.getInstance() as WindowManagerImpl).allocateFrame(project))
val anchor = getToolWindowAnchor(factory, bean)
@Suppress("DEPRECATION")
val sideTool = bean.secondary || bean.side
val entry = doRegisterToolWindow(RegisterToolWindowTask(
id = bean.id,
icon = findIconFromBean(bean, factory, pluginDescriptor),
anchor = anchor,
sideTool = sideTool,
canCloseContent = bean.canCloseContents,
canWorkInDumbMode = DumbService.isDumbAware(factory),
shouldBeAvailable = factory.shouldBeAvailable(project),
contentFactory = factory,
stripeTitle = getStripeTitleSupplier(bean.id, pluginDescriptor)
), toolWindowPane)
project.messageBus.syncPublisher(ToolWindowManagerListener.TOPIC).toolWindowsRegistered(listOf(entry.id), this)
toolWindowPane.getStripeFor(anchor).revalidate()
toolWindowPane.validate()
toolWindowPane.repaint()
}
fun projectClosed() {
if (frame == null) {
return
}
frame!!.releaseFrame()
toolWindowPane!!.putClientProperty(UIUtil.NOT_IN_HIERARCHY_COMPONENTS, null)
// hide all tool windows - frame maybe reused for another project
for (entry in idToEntry.values) {
try {
removeDecoratorWithoutUpdatingState(entry, layout.getInfo(entry.id) ?: continue, dirtyMode = true)
}
catch (e: ProcessCanceledException) {
throw e
}
catch (e: Throwable) {
LOG.error(e)
}
finally {
Disposer.dispose(entry.disposable)
}
}
toolWindowPane!!.reset()
frame = null
}
override fun addToolWindowManagerListener(listener: ToolWindowManagerListener) {
dispatcher.addListener(listener)
}
override fun addToolWindowManagerListener(listener: ToolWindowManagerListener, parentDisposable: Disposable) {
project.messageBus.connect(parentDisposable).subscribe(ToolWindowManagerListener.TOPIC, listener)
}
override fun removeToolWindowManagerListener(listener: ToolWindowManagerListener) {
dispatcher.removeListener(listener)
}
override fun activateEditorComponent() {
if (!EditorsSplitters.focusDefaultComponentInSplittersIfPresent(project)) {
// see note about requestFocus in focusDefaultComponentInSplittersIfPresent
frame?.rootPane?.requestFocus()
}
}
open fun activateToolWindow(id: String, runnable: Runnable?, autoFocusContents: Boolean, source: ToolWindowEventSource? = null) {
ApplicationManager.getApplication().assertIsDispatchThread()
val activity = UiActivity.Focus("toolWindow:$id")
UiActivityMonitor.getInstance().addActivity(project, activity, ModalityState.NON_MODAL)
activateToolWindow(idToEntry[id]!!, getRegisteredMutableInfoOrLogError(id), autoFocusContents, source)
ApplicationManager.getApplication().invokeLater(Runnable {
runnable?.run()
UiActivityMonitor.getInstance().removeActivity(project, activity)
}, project.disposed)
}
private fun activateToolWindow(entry: ToolWindowEntry,
info: WindowInfoImpl,
autoFocusContents: Boolean = true,
source: ToolWindowEventSource? = null) {
LOG.debug { "activateToolWindow($entry)" }
if (source != null) {
ToolWindowCollector.getInstance().recordActivation(project, entry.id, info, source)
}
recentToolWindows.remove(entry.id)
recentToolWindows.add(0, entry.id)
if (!entry.toolWindow.isAvailable) {
// Tool window can be "logically" active but not focused. For example,
// when the user switched to another application. So we just need to bring
// tool window's window to front.
if (autoFocusContents && !entry.toolWindow.hasFocus) {
entry.toolWindow.requestFocusInToolWindow()
}
return
}
if (!entry.readOnlyWindowInfo.isVisible) {
showToolWindowImpl(entry, info, dirtyMode = false, source = source)
}
if (autoFocusContents && ApplicationManager.getApplication().isActive) {
entry.toolWindow.requestFocusInToolWindow()
}
else {
activeStack.push(entry)
}
fireStateChanged()
}
fun getRecentToolWindows() = ArrayList(recentToolWindows)
internal fun updateToolWindow(toolWindow: ToolWindowImpl, component: Component) {
toolWindow.setFocusedComponent(component)
if (toolWindow.isAvailable && !toolWindow.isActive) {
activateToolWindow(toolWindow.id, null, autoFocusContents = true)
}
activeStack.push(idToEntry[toolWindow.id] ?: return)
}
// mutate operation must use info from layout and not from decorator
private fun getRegisteredMutableInfoOrLogError(id: String): WindowInfoImpl {
val info = layout.getInfo(id)
?: throw IllegalThreadStateException("window with id=\"$id\" is unknown")
if (!isToolWindowRegistered(id)) {
LOG.error("window with id=\"$id\" isn't registered")
}
return info
}
private fun doDeactivateToolWindow(info: WindowInfoImpl,
entry: ToolWindowEntry,
dirtyMode: Boolean = false,
source: ToolWindowEventSource? = null) {
LOG.debug { "enter: deactivateToolWindowImpl(${info.id})" }
setHiddenState(info, entry, source)
updateStateAndRemoveDecorator(info, entry, dirtyMode = dirtyMode)
entry.applyWindowInfo(info.copy())
}
private fun setHiddenState(info: WindowInfoImpl, entry: ToolWindowEntry, source: ToolWindowEventSource?) {
ToolWindowCollector.getInstance().recordHidden(project, info, source)
info.isActiveOnStart = false
info.isVisible = false
activeStack.remove(entry, false)
}
override val toolWindowIds: Array<String>
get() = idToEntry.keys.toTypedArray()
override val toolWindowIdSet: Set<String>
get() = HashSet(idToEntry.keys)
override val activeToolWindowId: String?
get() {
EDT.assertIsEdt()
val frame = frame?.frame ?: return null
if (frame.isActive) {
val focusOwner = focusManager.getLastFocusedFor(frame) ?: return null
var parent: Component? = focusOwner
while (parent != null) {
if (parent is InternalDecoratorImpl) {
return parent.toolWindow.id
}
parent = parent.parent
}
}
else {
// let's check floating and windowed
for (entry in idToEntry.values) {
if (entry.floatingDecorator?.isActive == true || entry.windowedDecorator?.isActive == true) {
return entry.id
}
}
}
return null
}
override val lastActiveToolWindowId: String?
get() = getLastActiveToolWindows().firstOrNull()?.id
fun getLastActiveToolWindows(): Iterable<ToolWindow> {
EDT.assertIsEdt()
return (0 until activeStack.persistentSize).asSequence()
.map { activeStack.peekPersistent(it).toolWindow }
.filter { it.isAvailable }
.asIterable()
}
/**
* @return floating decorator for the tool window with specified `ID`.
*/
private fun getFloatingDecorator(id: String) = idToEntry[id]?.floatingDecorator
/**
* @return windowed decorator for the tool window with specified `ID`.
*/
private fun getWindowedDecorator(id: String) = idToEntry[id]?.windowedDecorator
/**
* @return tool button for the window with specified `ID`.
*/
@ApiStatus.Internal
fun getStripeButton(id: String) = idToEntry[id]?.stripeButton
override fun getIdsOn(anchor: ToolWindowAnchor) = getVisibleToolWindowsOn(anchor).map { it.id }.toList()
@ApiStatus.Internal
fun getToolWindowsOn(anchor: ToolWindowAnchor, excludedId: String): List<ToolWindowEx> {
return getVisibleToolWindowsOn(anchor)
.filter { it.id != excludedId }
.map { it.toolWindow }
.toList()
}
@ApiStatus.Internal
fun getDockedInfoAt(anchor: ToolWindowAnchor?, side: Boolean): WindowInfo? {
for (entry in idToEntry.values) {
val info = entry.readOnlyWindowInfo
if (info.isVisible && info.isDocked && info.anchor == anchor && side == info.isSplit) {
return info
}
}
return null
}
override fun getLocationIcon(id: String, fallbackIcon: Icon): Icon {
val info = layout.getInfo(id) ?: return fallbackIcon
val type = info.type
if (type == ToolWindowType.FLOATING || type == ToolWindowType.WINDOWED) {
return AllIcons.Actions.MoveToWindow
}
val anchor = info.anchor
val splitMode = info.isSplit
return when (anchor) {
ToolWindowAnchor.BOTTOM -> {
if (splitMode) AllIcons.Actions.MoveToBottomRight else AllIcons.Actions.MoveToBottomLeft
}
ToolWindowAnchor.LEFT -> {
if (splitMode) AllIcons.Actions.MoveToLeftBottom else AllIcons.Actions.MoveToLeftTop
}
ToolWindowAnchor.RIGHT -> {
if (splitMode) AllIcons.Actions.MoveToRightBottom else AllIcons.Actions.MoveToRightTop
}
ToolWindowAnchor.TOP -> {
if (splitMode) AllIcons.Actions.MoveToTopRight else AllIcons.Actions.MoveToTopLeft
}
else -> fallbackIcon
}
}
private fun getVisibleToolWindowsOn(anchor: ToolWindowAnchor): Sequence<ToolWindowEntry> {
return idToEntry.values
.asSequence()
.filter { it.readOnlyWindowInfo.anchor == anchor && it.toolWindow.isAvailable }
}
// cannot be ToolWindowEx because of backward compatibility
override fun getToolWindow(id: String?): ToolWindow? {
return idToEntry[id ?: return null]?.toolWindow
}
open fun showToolWindow(id: String) {
LOG.debug { "enter: showToolWindow($id)" }
EDT.assertIsEdt()
val info = layout.getInfo(id) ?: throw IllegalThreadStateException("window with id=\"$id\" is unknown")
val entry = idToEntry[id]!!
if (entry.readOnlyWindowInfo.isVisible) {
LOG.assertTrue(entry.toolWindow.getComponentIfInitialized() != null)
return
}
if (showToolWindowImpl(entry, info, dirtyMode = false)) {
checkInvariants("id: $id")
fireStateChanged()
}
}
internal fun removeFromSideBar(id: String, source: ToolWindowEventSource?) {
val info = getRegisteredMutableInfoOrLogError(id)
if (!info.isShowStripeButton) {
return
}
val entry = idToEntry[info.id!!]!!
info.isShowStripeButton = false
setHiddenState(info, entry, source)
updateStateAndRemoveDecorator(info, entry, dirtyMode = false)
entry.applyWindowInfo(info.copy())
if (ExperimentalUI.isNewToolWindowsStripes()) {
toolWindowPane?.onStripeButtonRemoved(project, entry.toolWindow)
}
fireStateChanged()
}
override fun hideToolWindow(id: String, hideSide: Boolean) {
hideToolWindow(id, hideSide, moveFocus = true)
}
open fun hideToolWindow(id: String, hideSide: Boolean, moveFocus: Boolean, source: ToolWindowEventSource? = null) {
EDT.assertIsEdt()
val entry = idToEntry[id]!!
if (!entry.readOnlyWindowInfo.isVisible) {
return
}
val info = getRegisteredMutableInfoOrLogError(id)
val moveFocusAfter = moveFocus && entry.toolWindow.isActive
doHide(entry, info, dirtyMode = false, hideSide = hideSide, source = source)
fireStateChanged()
if (moveFocusAfter) {
activateEditorComponent()
}
}
private fun doHide(entry: ToolWindowEntry,
info: WindowInfoImpl,
dirtyMode: Boolean,
hideSide: Boolean = false,
source: ToolWindowEventSource? = null) {
// hide and deactivate
doDeactivateToolWindow(info, entry, dirtyMode = dirtyMode, source = source)
if (hideSide && info.type != ToolWindowType.FLOATING && info.type != ToolWindowType.WINDOWED) {
for (each in getVisibleToolWindowsOn(info.anchor)) {
activeStack.remove(each, false)
}
if (isStackEnabled) {
while (!sideStack.isEmpty(info.anchor)) {
sideStack.pop(info.anchor)
}
}
for (otherEntry in idToEntry.values) {
val otherInfo = layout.getInfo(otherEntry.id) ?: continue
if (otherInfo.isVisible && otherInfo.anchor == info.anchor) {
doDeactivateToolWindow(otherInfo, otherEntry, dirtyMode = dirtyMode, source = ToolWindowEventSource.HideSide)
}
}
}
else {
// first of all we have to find tool window that was located at the same side and was hidden
if (isStackEnabled) {
var info2: WindowInfoImpl? = null
while (!sideStack.isEmpty(info.anchor)) {
val storedInfo = sideStack.pop(info.anchor)
if (storedInfo.isSplit != info.isSplit) {
continue
}
val currentInfo = getRegisteredMutableInfoOrLogError(storedInfo.id!!)
// SideStack contains copies of real WindowInfos. It means that
// these stored infos can be invalid. The following loop removes invalid WindowInfos.
if (storedInfo.anchor == currentInfo.anchor && storedInfo.type == currentInfo.type && storedInfo.isAutoHide == currentInfo.isAutoHide) {
info2 = storedInfo
break
}
}
if (info2 != null) {
val entry2 = idToEntry[info2.id!!]!!
if (!entry2.readOnlyWindowInfo.isVisible) {
showToolWindowImpl(entry2, info2, dirtyMode = dirtyMode)
}
}
}
activeStack.remove(entry, false)
}
}
/**
* @param dirtyMode if `true` then all UI operations are performed in dirty mode.
*/
private fun showToolWindowImpl(entry: ToolWindowEntry,
toBeShownInfo: WindowInfoImpl,
dirtyMode: Boolean,
source: ToolWindowEventSource? = null): Boolean {
if (!entry.toolWindow.isAvailable) {
return false
}
ToolWindowCollector.getInstance().recordShown(project, source, toBeShownInfo)
toBeShownInfo.isVisible = true
toBeShownInfo.isShowStripeButton = true
val snapshotInfo = toBeShownInfo.copy()
entry.applyWindowInfo(snapshotInfo)
doShowWindow(entry, snapshotInfo, dirtyMode)
if (entry.readOnlyWindowInfo.type == ToolWindowType.WINDOWED && entry.toolWindow.getComponentIfInitialized() != null) {
UIUtil.toFront(ComponentUtil.getWindow(entry.toolWindow.component))
}
return true
}
private fun doShowWindow(entry: ToolWindowEntry, info: WindowInfo, dirtyMode: Boolean) {
if (entry.readOnlyWindowInfo.type == ToolWindowType.FLOATING) {
addFloatingDecorator(entry, info)
}
else if (entry.readOnlyWindowInfo.type == ToolWindowType.WINDOWED) {
addWindowedDecorator(entry, info)
}
else {
// docked and sliding windows
// If there is tool window on the same side then we have to hide it, i.e.
// clear place for tool window to be shown.
//
// We store WindowInfo of hidden tool window in the SideStack (if the tool window
// is docked and not auto-hide one). Therefore it's possible to restore the
// hidden tool window when showing tool window will be closed.
for (otherEntry in idToEntry.values) {
if (entry.id == otherEntry.id) {
continue
}
val otherInfo = otherEntry.readOnlyWindowInfo
if (otherInfo.isVisible && otherInfo.type == info.type && otherInfo.anchor == info.anchor && otherInfo.isSplit == info.isSplit) {
val otherLayoutInto = layout.getInfo(otherEntry.id)!!
// hide and deactivate tool window
setHiddenState(otherLayoutInto, otherEntry, ToolWindowEventSource.HideOnShowOther)
val otherInfoCopy = otherLayoutInto.copy()
otherEntry.applyWindowInfo(otherInfoCopy)
otherEntry.toolWindow.decoratorComponent?.let { decorator ->
toolWindowPane!!.removeDecorator(otherInfoCopy, decorator, false, this)
}
// store WindowInfo into the SideStack
if (isStackEnabled && otherInfo.isDocked && !otherInfo.isAutoHide) {
sideStack.push(otherInfoCopy)
}
}
}
toolWindowPane!!.addDecorator(entry.toolWindow.getOrCreateDecoratorComponent(), info, dirtyMode, this)
// remove tool window from the SideStack
if (isStackEnabled) {
sideStack.remove(entry.id)
}
}
entry.toolWindow.scheduleContentInitializationIfNeeded()
fireToolWindowShown(entry.toolWindow)
}
override fun registerToolWindow(task: RegisterToolWindowTask): ToolWindow {
val toolWindowPane = toolWindowPane ?: init((WindowManager.getInstance() as WindowManagerImpl).allocateFrame(project))
val entry = doRegisterToolWindow(task, toolWindowPane = toolWindowPane)
project.messageBus.syncPublisher(ToolWindowManagerListener.TOPIC).toolWindowsRegistered(listOf(entry.id), this)
toolWindowPane.getStripeFor(entry.toolWindow.anchor).revalidate()
toolWindowPane.validate()
toolWindowPane.repaint()
fireStateChanged()
return entry.toolWindow
}
private fun doRegisterToolWindow(task: RegisterToolWindowTask, toolWindowPane: ToolWindowsPane): ToolWindowEntry {
LOG.debug { "enter: installToolWindow($task)" }
ApplicationManager.getApplication().assertIsDispatchThread()
if (idToEntry.containsKey(task.id)) {
throw IllegalArgumentException("window with id=\"${task.id}\" is already registered")
}
val info = layout.getOrCreate(task)
val disposable = Disposer.newDisposable(task.id)
Disposer.register(project, disposable)
val contentFactory = task.contentFactory
val windowInfoSnapshot = info.copy()
if (windowInfoSnapshot.isVisible && (contentFactory == null || !task.shouldBeAvailable)) {
// isVisible cannot be true if contentFactory is null, because we cannot show toolwindow without content
windowInfoSnapshot.isVisible = false
}
@Suppress("HardCodedStringLiteral")
val stripeTitle = task.stripeTitle?.get() ?: task.id
val toolWindow = ToolWindowImpl(this, task.id, task.canCloseContent, task.canWorkInDumbMode, task.component, disposable,
windowInfoSnapshot, contentFactory, isAvailable = task.shouldBeAvailable, stripeTitle = stripeTitle)
toolWindow.windowInfoDuringInit = windowInfoSnapshot
try {
contentFactory?.init(toolWindow)
}
finally {
toolWindow.windowInfoDuringInit = null
}
// contentFactory.init can set icon
if (toolWindow.icon == null) {
task.icon?.let {
toolWindow.doSetIcon(it)
}
}
ActivateToolWindowAction.ensureToolWindowActionRegistered(toolWindow)
val button = StripeButton(toolWindowPane, toolWindow)
val entry = ToolWindowEntry(button, toolWindow, disposable)
idToEntry[task.id] = entry
// only after added to idToEntry map
button.isSelected = windowInfoSnapshot.isVisible
button.updatePresentation()
addStripeButton(button, toolWindowPane.getStripeFor((contentFactory as? ToolWindowFactoryEx)?.anchor ?: info.anchor))
if (ExperimentalUI.isNewToolWindowsStripes()) {
toolWindow.largeStripeAnchor = if (toolWindow.largeStripeAnchor == ToolWindowAnchor.NONE) task.anchor else toolWindow.largeStripeAnchor
}
// If preloaded info is visible or active then we have to show/activate the installed
// tool window. This step has sense only for windows which are not in the auto hide
// mode. But if tool window was active but its mode doesn't allow to activate it again
// (for example, tool window is in auto hide mode) then we just activate editor component.
if (contentFactory != null /* not null on init tool window from EP */) {
if (windowInfoSnapshot.isVisible) {
showToolWindowImpl(entry, info, dirtyMode = false)
// do not activate tool window that is the part of project frame - default component should be focused
if (windowInfoSnapshot.isActiveOnStart && (windowInfoSnapshot.type == ToolWindowType.WINDOWED || windowInfoSnapshot.type == ToolWindowType.FLOATING) && ApplicationManager.getApplication().isActive) {
entry.toolWindow.requestFocusInToolWindow()
}
}
}
return entry
}
@Suppress("OverridingDeprecatedMember")
override fun unregisterToolWindow(id: String) {
doUnregisterToolWindow(id)
fireStateChanged()
}
internal fun doUnregisterToolWindow(id: String) {
LOG.debug { "enter: unregisterToolWindow($id)" }
ApplicationManager.getApplication().assertIsDispatchThread()
ActivateToolWindowAction.unregister(id)
val entry = idToEntry.remove(id) ?: return
val toolWindow = entry.toolWindow
val info = layout.getInfo(id)
if (info != null) {
// remove decorator and tool button from the screen - removing will also save current bounds
updateStateAndRemoveDecorator(info, entry, false)
// save recent appearance of tool window
activeStack.remove(entry, true)
if (isStackEnabled) {
sideStack.remove(id)
}
removeStripeButton(entry.stripeButton)
toolWindowPane!!.validate()
toolWindowPane!!.repaint()
}
if (!project.isDisposed) {
project.messageBus.syncPublisher(ToolWindowManagerListener.TOPIC).toolWindowUnregistered(id, (toolWindow))
}
Disposer.dispose(entry.disposable)
}
private fun updateStateAndRemoveDecorator(info: WindowInfoImpl, entry: ToolWindowEntry, dirtyMode: Boolean) {
saveFloatingOrWindowedState(entry, info)
removeDecoratorWithoutUpdatingState(entry, info, dirtyMode)
}
private fun removeDecoratorWithoutUpdatingState(entry: ToolWindowEntry, info: WindowInfoImpl, dirtyMode: Boolean) {
entry.windowedDecorator?.let {
entry.windowedDecorator = null
Disposer.dispose(it)
return
}
entry.floatingDecorator?.let {
entry.floatingDecorator = null
it.dispose()
return
}
entry.toolWindow.decoratorComponent?.let {
toolWindowPane!!.removeDecorator(info, it, dirtyMode, this)
return
}
}
private fun saveFloatingOrWindowedState(entry: ToolWindowEntry, info: WindowInfoImpl) {
entry.floatingDecorator?.let {
info.floatingBounds = it.bounds
info.isActiveOnStart = it.isActive
return
}
entry.windowedDecorator?.let { windowedDecorator ->
info.isActiveOnStart = windowedDecorator.isActive
val frame = windowedDecorator.getFrame()
if (frame.isShowing) {
val maximized = (frame as JFrame).extendedState == Frame.MAXIMIZED_BOTH
if (maximized) {
frame.extendedState = Frame.NORMAL
frame.invalidate()
frame.revalidate()
}
val bounds = getRootBounds(frame)
info.floatingBounds = bounds
info.isMaximized = maximized
}
return
}
}
override fun getLayout(): DesktopLayout {
ApplicationManager.getApplication().assertIsDispatchThread()
return layout
}
override fun setLayoutToRestoreLater(layout: DesktopLayout?) {
layoutToRestoreLater = layout
}
override fun getLayoutToRestoreLater() = layoutToRestoreLater
override fun setLayout(newLayout: DesktopLayout) {
ApplicationManager.getApplication().assertIsDispatchThread()
if (idToEntry.isEmpty()) {
layout = newLayout
return
}
data class LayoutData(val old: WindowInfoImpl, val new: WindowInfoImpl, val entry: ToolWindowEntry)
val list = mutableListOf<LayoutData>()
for (entry in idToEntry.values) {
val old = layout.getInfo(entry.id) ?: entry.readOnlyWindowInfo as WindowInfoImpl
val new = newLayout.getInfo(entry.id)
// just copy if defined in the old layout but not in the new
if (new == null) {
newLayout.addInfo(entry.id, old.copy())
}
else if (old != new) {
list.add(LayoutData(old = old, new = new, entry = entry))
}
}
this.layout = newLayout
if (list.isEmpty()) {
return
}
for (item in list) {
item.entry.applyWindowInfo(item.new)
if (item.old.isVisible && !item.new.isVisible) {
updateStateAndRemoveDecorator(item.new, item.entry, dirtyMode = true)
}
if (item.old.anchor != item.new.anchor || item.old.order != item.new.order) {
setToolWindowAnchorImpl(item.entry, item.old, item.new, item.new.anchor, item.new.order)
}
var toShowWindow = false
if (item.old.isSplit != item.new.isSplit) {
val wasVisible = item.old.isVisible
// we should hide the window and show it in a 'new place' to automatically hide possible window that is already located in a 'new place'
if (wasVisible) {
hideToolWindow(item.entry.id, hideSide = false, moveFocus = true)
}
if (wasVisible) {
toShowWindow = true
}
}
if (item.old.type != item.new.type) {
val dirtyMode = item.old.type == ToolWindowType.DOCKED || item.old.type == ToolWindowType.SLIDING
updateStateAndRemoveDecorator(item.old, item.entry, dirtyMode)
if (item.new.isVisible) {
toShowWindow = true
}
}
else if (!item.old.isVisible && item.new.isVisible) {
toShowWindow = true
}
if (toShowWindow) {
doShowWindow(item.entry, item.new, dirtyMode = true)
}
}
val toolWindowPane = toolWindowPane!!
toolWindowPane.revalidateNotEmptyStripes()
toolWindowPane.validate()
toolWindowPane.repaint()
activateEditorComponent()
val frame = frame!!
val rootPane = frame.rootPane ?: return
rootPane.revalidate()
rootPane.repaint()
fireStateChanged()
checkInvariants("")
}
override fun invokeLater(runnable: Runnable) {
ApplicationManager.getApplication().invokeLater(runnable, project.disposed)
}
override val focusManager: IdeFocusManager
get() = IdeFocusManager.getInstance(project)!!
override fun canShowNotification(toolWindowId: String): Boolean {
return toolWindowPane?.getStripeFor(idToEntry[toolWindowId]?.readOnlyWindowInfo?.anchor ?: return false)?.getButtonFor(toolWindowId) != null
}
override fun notifyByBalloon(toolWindowId: String, type: MessageType, @NlsContexts.NotificationContent htmlBody: String) {
notifyByBalloon(toolWindowId, type, htmlBody, null, null)
}
override fun notifyByBalloon(options: ToolWindowBalloonShowOptions) {
if (ExperimentalUI.isNewToolWindowsStripes()) {
notifySquareButtonByBalloon(options)
return
}
val entry = idToEntry[options.toolWindowId]!!
val existing = entry.balloon
if (existing != null) {
Disposer.dispose(existing)
}
val stripe = toolWindowPane!!.getStripeFor(entry.readOnlyWindowInfo.anchor)
if (!entry.toolWindow.isAvailable) {
entry.toolWindow.isPlaceholderMode = true
stripe.updatePresentation()
stripe.revalidate()
stripe.repaint()
}
val anchor = entry.readOnlyWindowInfo.anchor
val position = Ref.create(Balloon.Position.below)
when {
ToolWindowAnchor.TOP == anchor -> position.set(Balloon.Position.below)
ToolWindowAnchor.BOTTOM == anchor -> position.set(Balloon.Position.above)
ToolWindowAnchor.LEFT == anchor -> position.set(Balloon.Position.atRight)
ToolWindowAnchor.RIGHT == anchor -> position.set(Balloon.Position.atLeft)
}
val balloon = createBalloon(options, entry)
val button = stripe.getButtonFor(options.toolWindowId)
LOG.assertTrue(button != null, ("Button was not found, popup won't be shown. $options"))
if (button == null) {
return
}
val show = Runnable {
val tracker: PositionTracker<Balloon>
if (entry.toolWindow.isVisible &&
(entry.toolWindow.type == ToolWindowType.WINDOWED ||
entry.toolWindow.type == ToolWindowType.FLOATING)) {
tracker = createPositionTracker(entry.toolWindow.component, ToolWindowAnchor.BOTTOM)
}
else if (!button.isShowing) {
tracker = createPositionTracker(toolWindowPane!!, anchor)
}
else {
tracker = object : PositionTracker<Balloon>(button) {
override fun recalculateLocation(`object`: Balloon): RelativePoint? {
val otherEntry = idToEntry[options.toolWindowId] ?: return null
val stripeButton = otherEntry.stripeButton
if (otherEntry.readOnlyWindowInfo.anchor != anchor) {
`object`.hide()
return null
}
return RelativePoint(stripeButton, Point(stripeButton.bounds.width / 2, stripeButton.height / 2 - 2))
}
}
}
if (!balloon.isDisposed) {
balloon.show(tracker, position.get())
}
}
if (button.isValid) {
show.run()
}
else {
SwingUtilities.invokeLater(show)
}
}
fun notifySquareButtonByBalloon(options: ToolWindowBalloonShowOptions) {
val entry = idToEntry[options.toolWindowId]!!
val existing = entry.balloon
if (existing != null) {
Disposer.dispose(existing)
}
val anchor = entry.readOnlyWindowInfo.largeStripeAnchor
val position = Ref.create(Balloon.Position.atLeft)
when (anchor) {
ToolWindowAnchor.TOP -> position.set(Balloon.Position.atRight)
ToolWindowAnchor.RIGHT -> position.set(Balloon.Position.atRight)
ToolWindowAnchor.BOTTOM -> position.set(Balloon.Position.atLeft)
ToolWindowAnchor.LEFT -> position.set(Balloon.Position.atLeft)
}
val balloon = createBalloon(options, entry)
var button = toolWindowPane!!.getSquareStripeFor(entry.readOnlyWindowInfo.largeStripeAnchor)?.getButtonFor(options.toolWindowId) as ActionButton?
if (button == null || !button.isShowing) {
button = (toolWindowPane!!.getSquareStripeFor(ToolWindowAnchor.LEFT) as? ToolwindowLeftToolbar)?.moreButton!!
position.set(Balloon.Position.atLeft)
}
val show = Runnable {
val tracker: PositionTracker<Balloon>
if (entry.toolWindow.isVisible &&
(entry.toolWindow.type == ToolWindowType.WINDOWED ||
entry.toolWindow.type == ToolWindowType.FLOATING)) {
tracker = createPositionTracker(entry.toolWindow.component, ToolWindowAnchor.BOTTOM)
}
else {
tracker = object : PositionTracker<Balloon>(button) {
override fun recalculateLocation(`object`: Balloon): RelativePoint? {
val otherEntry = idToEntry[options.toolWindowId] ?: return null
if (otherEntry.readOnlyWindowInfo.largeStripeAnchor != anchor) {
`object`.hide()
return null
}
return RelativePoint(button,
Point(if (position.get() == Balloon.Position.atRight) 0 else button.bounds.width, button.height / 2))
}
}
}
if (!balloon.isDisposed) {
balloon.show(tracker, position.get())
}
}
if (button.isValid) {
show.run()
}
else {
SwingUtilities.invokeLater(show)
}
}
private fun createPositionTracker(component: Component, anchor: ToolWindowAnchor): PositionTracker<Balloon> {
return object : PositionTracker<Balloon>(component) {
override fun recalculateLocation(`object`: Balloon): RelativePoint {
val bounds = component.bounds
val target = StartupUiUtil.getCenterPoint(bounds, Dimension(1, 1))
when {
ToolWindowAnchor.TOP == anchor -> target.y = 0
ToolWindowAnchor.BOTTOM == anchor -> target.y = bounds.height - 3
ToolWindowAnchor.LEFT == anchor -> target.x = 0
ToolWindowAnchor.RIGHT == anchor -> target.x = bounds.width
}
return RelativePoint(component, target)
}
}
}
private fun createBalloon(options: ToolWindowBalloonShowOptions, entry: ToolWindowEntry): Balloon {
val listenerWrapper = BalloonHyperlinkListener(options.listener)
@Suppress("HardCodedStringLiteral")
val content = options.htmlBody.replace("\n", "<br>")
val balloonBuilder = JBPopupFactory.getInstance()
.createHtmlTextBalloonBuilder(content, options.icon, options.type.titleForeground, options.type.popupBackground, listenerWrapper)
.setBorderColor(options.type.borderColor)
.setHideOnClickOutside(false)
.setHideOnFrameResize(false)
options.balloonCustomizer?.accept(balloonBuilder)
val balloon = balloonBuilder.createBalloon()
if (balloon is BalloonImpl) {
NotificationsManagerImpl.frameActivateBalloonListener(balloon, Runnable {
AppExecutorUtil.getAppScheduledExecutorService().schedule({ balloon.setHideOnClickOutside(true) }, 100, TimeUnit.MILLISECONDS)
})
}
listenerWrapper.balloon = balloon
entry.balloon = balloon
Disposer.register(balloon, Disposable {
entry.toolWindow.isPlaceholderMode = false
entry.balloon = null
})
Disposer.register(entry.disposable, balloon)
return balloon
}
override fun getToolWindowBalloon(id: String) = idToEntry[id]?.balloon
override val isEditorComponentActive: Boolean
get() {
ApplicationManager.getApplication().assertIsDispatchThread()
return ComponentUtil.getParentOfType(EditorsSplitters::class.java, focusManager.focusOwner) != null
}
fun setToolWindowAnchor(id: String, anchor: ToolWindowAnchor) {
ApplicationManager.getApplication().assertIsDispatchThread()
setToolWindowAnchor(id, anchor, -1)
}
// used by Rider
@Suppress("MemberVisibilityCanBePrivate")
fun setToolWindowAnchor(id: String, anchor: ToolWindowAnchor, order: Int) {
val entry = idToEntry[id]!!
val info = entry.readOnlyWindowInfo
if (anchor == info.anchor && (order == info.order || order == -1)) {
return
}
ApplicationManager.getApplication().assertIsDispatchThread()
setToolWindowAnchorImpl(entry, info, getRegisteredMutableInfoOrLogError(id), anchor, order)
toolWindowPane!!.validateAndRepaint()
fireStateChanged()
}
fun setLargeStripeAnchor(id: String, anchor: ToolWindowAnchor) {
val entry = idToEntry[id]!!
val info = entry.readOnlyWindowInfo
ApplicationManager.getApplication().assertIsDispatchThread()
setToolWindowLargeAnchorImpl(entry, info, getRegisteredMutableInfoOrLogError(id), anchor)
toolWindowPane!!.validateAndRepaint()
fireStateChanged()
}
fun setVisibleOnLargeStripe(id: String, visible: Boolean) {
val info = getRegisteredMutableInfoOrLogError(id)
info.isVisibleOnLargeStripe = visible
idToEntry[info.id]!!.applyWindowInfo(info.copy())
fireStateChanged()
}
private fun setToolWindowAnchorImpl(entry: ToolWindowEntry,
currentInfo: WindowInfo,
layoutInfo: WindowInfoImpl,
anchor: ToolWindowAnchor,
order: Int) {
// if tool window isn't visible or only order number is changed then just remove/add stripe button
val toolWindowPane = toolWindowPane!!
if (!currentInfo.isVisible || anchor == currentInfo.anchor || currentInfo.type == ToolWindowType.FLOATING || currentInfo.type == ToolWindowType.WINDOWED) {
doSetAnchor(entry, layoutInfo, anchor, order)
}
else {
val wasFocused = entry.toolWindow.isActive
// for docked and sliding windows we have to move buttons and window's decorators
layoutInfo.isVisible = false
toolWindowPane.removeDecorator(currentInfo, entry.toolWindow.decoratorComponent, /* dirtyMode = */ true, this)
doSetAnchor(entry, layoutInfo, anchor, order)
showToolWindowImpl(entry, layoutInfo, false)
if (wasFocused) {
entry.toolWindow.requestFocusInToolWindow()
}
}
}
private fun doSetAnchor(entry: ToolWindowEntry, layoutInfo: WindowInfoImpl, anchor: ToolWindowAnchor, order: Int) {
val toolWindowPane = toolWindowPane!!
removeStripeButton(entry.stripeButton)
layout.setAnchor(layoutInfo, anchor, order)
// update infos for all window. Actually we have to update only infos affected by setAnchor method
for (otherEntry in idToEntry.values) {
val otherInfo = layout.getInfo(otherEntry.id)?.copy() ?: continue
otherEntry.applyWindowInfo(otherInfo)
}
val stripe = toolWindowPane.getStripeFor(anchor)
addStripeButton(entry.stripeButton, stripe)
stripe.revalidate()
}
private fun setToolWindowLargeAnchorImpl(entry: ToolWindowEntry,
currentInfo: WindowInfo,
layoutInfo: WindowInfoImpl,
anchor: ToolWindowAnchor) {
val toolWindowPane = toolWindowPane!!
if (!currentInfo.isVisible || anchor == currentInfo.largeStripeAnchor || currentInfo.type == ToolWindowType.FLOATING || currentInfo.type == ToolWindowType.WINDOWED) {
doSetLargeAnchor(entry, layoutInfo, anchor)
}
else {
val wasFocused = entry.toolWindow.isActive
// for docked and sliding windows we have to move buttons and window's decorators
layoutInfo.isVisible = false
toolWindowPane.removeDecorator(currentInfo, entry.toolWindow.decoratorComponent, true, this)
doSetLargeAnchor(entry, layoutInfo, anchor)
showToolWindowImpl(entry, layoutInfo, false)
if (wasFocused) {
entry.toolWindow.requestFocusInToolWindow()
}
}
}
private fun doSetLargeAnchor(entry: ToolWindowEntry, layoutInfo: WindowInfoImpl, anchor: ToolWindowAnchor) {
toolWindowPane!!.onStripeButtonAdded(project, entry.toolWindow, anchor, layoutInfo)
layout.setAnchor(layoutInfo, anchor, -1)
// update infos for all window. Actually we have to update only infos affected by setAnchor method
for (otherEntry in idToEntry.values) {
val otherInfo = layout.getInfo(otherEntry.id)?.copy() ?: continue
otherEntry.applyWindowInfo(otherInfo)
}
}
fun setOrderOnLargeStripe(id: String, order: Int) {
val info = getRegisteredMutableInfoOrLogError(id)
info.orderOnLargeStripe = order
idToEntry[info.id]!!.applyWindowInfo(info.copy())
fireStateChanged()
}
internal fun setSideTool(id: String, isSplit: Boolean) {
val entry = idToEntry[id]
if (entry == null) {
LOG.error("Cannot set side tool: toolwindow $id is not registered")
return
}
if (entry.readOnlyWindowInfo.isSplit != isSplit) {
setSideTool(entry, getRegisteredMutableInfoOrLogError(id), isSplit)
fireStateChanged()
}
}
private fun setSideTool(entry: ToolWindowEntry, info: WindowInfoImpl, isSplit: Boolean) {
if (isSplit == info.isSplit) {
return
}
// we should hide the window and show it in a 'new place' to automatically hide possible window that is already located in a 'new place'
hideIfNeededAndShowAfterTask(entry, info) {
info.isSplit = isSplit
for (otherEntry in idToEntry.values) {
otherEntry.applyWindowInfo((layout.getInfo(otherEntry.id) ?: continue).copy())
}
}
toolWindowPane!!.getStripeFor(entry.readOnlyWindowInfo.anchor).revalidate()
}
fun setContentUiType(id: String, type: ToolWindowContentUiType) {
val info = getRegisteredMutableInfoOrLogError(id)
info.contentUiType = type
idToEntry[info.id!!]!!.applyWindowInfo(info.copy())
fireStateChanged()
}
fun setSideToolAndAnchor(id: String, anchor: ToolWindowAnchor, order: Int, isSplit: Boolean) {
val entry = idToEntry[id]!!
val info = getRegisteredMutableInfoOrLogError(id)
if (anchor == entry.readOnlyWindowInfo.anchor && order == entry.readOnlyWindowInfo.order && entry.readOnlyWindowInfo.isSplit == isSplit) {
return
}
hideIfNeededAndShowAfterTask(entry, info) {
info.isSplit = isSplit
doSetAnchor(entry, info, anchor, order)
}
fireStateChanged()
}
private fun hideIfNeededAndShowAfterTask(entry: ToolWindowEntry,
info: WindowInfoImpl,
source: ToolWindowEventSource? = null,
task: () -> Unit) {
val wasVisible = entry.readOnlyWindowInfo.isVisible
val wasFocused = entry.toolWindow.isActive
if (wasVisible) {
doHide(entry, info, dirtyMode = true)
}
task()
if (wasVisible) {
ToolWindowCollector.getInstance().recordShown(project, source, info)
info.isVisible = true
val infoSnapshot = info.copy()
entry.applyWindowInfo(infoSnapshot)
doShowWindow(entry, infoSnapshot, dirtyMode = true)
if (wasFocused) {
getShowingComponentToRequestFocus(entry.toolWindow)?.requestFocusInWindow()
}
}
toolWindowPane!!.validateAndRepaint()
}
protected open fun fireStateChanged() {
project.messageBus.syncPublisher(ToolWindowManagerListener.TOPIC).stateChanged(this)
}
private fun fireToolWindowShown(toolWindow: ToolWindow) {
project.messageBus.syncPublisher(ToolWindowManagerListener.TOPIC).toolWindowShown(toolWindow)
}
internal fun setToolWindowAutoHide(id: String, autoHide: Boolean) {
ApplicationManager.getApplication().assertIsDispatchThread()
val info = getRegisteredMutableInfoOrLogError(id)
if (info.isAutoHide == autoHide) {
return
}
info.isAutoHide = autoHide
val entry = idToEntry[id] ?: return
val newInfo = info.copy()
entry.applyWindowInfo(newInfo)
fireStateChanged()
}
fun setToolWindowType(id: String, type: ToolWindowType) {
ApplicationManager.getApplication().assertIsDispatchThread()
val entry = idToEntry[id]!!
if (entry.readOnlyWindowInfo.type == type) {
return
}
setToolWindowTypeImpl(entry, getRegisteredMutableInfoOrLogError(entry.id), type)
fireStateChanged()
}
private fun setToolWindowTypeImpl(entry: ToolWindowEntry, info: WindowInfoImpl, type: ToolWindowType) {
if (!entry.readOnlyWindowInfo.isVisible) {
info.type = type
entry.applyWindowInfo(info.copy())
return
}
val dirtyMode = entry.readOnlyWindowInfo.type == ToolWindowType.DOCKED || entry.readOnlyWindowInfo.type == ToolWindowType.SLIDING
updateStateAndRemoveDecorator(info, entry, dirtyMode)
info.type = type
val newInfo = info.copy()
entry.applyWindowInfo(newInfo)
doShowWindow(entry, newInfo, dirtyMode)
if (ApplicationManager.getApplication().isActive) {
entry.toolWindow.requestFocusInToolWindow()
}
val frame = frame!!
val rootPane = frame.rootPane ?: return
rootPane.revalidate()
rootPane.repaint()
}
override fun clearSideStack() {
if (isStackEnabled) {
sideStack.clear()
}
}
override fun getState(): Element? {
// do nothing if the project was not opened
if (frame == null) {
return null
}
val element = Element("state")
if (isEditorComponentActive) {
element.addContent(Element(EDITOR_ELEMENT).setAttribute(ACTIVE_ATTR_VALUE, "true"))
}
// save layout of tool windows
layout.writeExternal(DesktopLayout.TAG)?.let {
element.addContent(it)
}
layoutToRestoreLater?.writeExternal(LAYOUT_TO_RESTORE)?.let {
element.addContent(it)
}
if (recentToolWindows.isNotEmpty()) {
val recentState = Element(RECENT_TW_TAG)
recentToolWindows.forEach {
recentState.addContent(Element("value").apply { addContent(it) })
}
element.addContent(recentState)
}
return element
}
override fun noStateLoaded() {
scheduleSetLayout(WindowManagerEx.getInstanceEx().layout.copy())
}
override fun loadState(state: Element) {
for (element in state.children) {
if (DesktopLayout.TAG == element.name) {
val layout = DesktopLayout()
layout.readExternal(element)
scheduleSetLayout(layout)
}
else if (LAYOUT_TO_RESTORE == element.name) {
layoutToRestoreLater = DesktopLayout()
layoutToRestoreLater!!.readExternal(element)
}
else if (RECENT_TW_TAG == element.name) {
recentToolWindows.clear()
element.content.forEach {
recentToolWindows.add(it.value)
}
}
}
}
private fun scheduleSetLayout(newLayout: DesktopLayout) {
val app = ApplicationManager.getApplication()
val task = Runnable {
setLayout(newLayout)
}
if (app.isDispatchThread) {
pendingSetLayoutTask.set(null)
task.run()
}
else {
pendingSetLayoutTask.set(task)
app.invokeLater(Runnable {
runPendingLayoutTask()
}, project.disposed)
}
}
internal fun setDefaultState(toolWindow: ToolWindowImpl, anchor: ToolWindowAnchor?, type: ToolWindowType?, floatingBounds: Rectangle?) {
val info = getRegisteredMutableInfoOrLogError(toolWindow.id)
if (info.isFromPersistentSettings) {
return
}
if (floatingBounds != null) {
info.floatingBounds = floatingBounds
}
if (anchor != null) {
toolWindow.setAnchor(anchor, null)
}
if (type != null) {
toolWindow.setType(type, null)
}
}
internal fun setDefaultContentUiType(toolWindow: ToolWindowImpl, type: ToolWindowContentUiType) {
val info = getRegisteredMutableInfoOrLogError(toolWindow.id)
if (info.isFromPersistentSettings) {
return
}
toolWindow.setContentUiType(type, null)
}
internal fun stretchWidth(toolWindow: ToolWindowImpl, value: Int) {
toolWindowPane!!.stretchWidth(toolWindow, value)
}
override fun isMaximized(window: ToolWindow) = toolWindowPane!!.isMaximized(window)
override fun setMaximized(window: ToolWindow, maximized: Boolean) {
if (window.type == ToolWindowType.FLOATING && window is ToolWindowImpl) {
MaximizeActiveDialogAction.doMaximize(getFloatingDecorator(window.id))
return
}
if (window.type == ToolWindowType.WINDOWED && window is ToolWindowImpl) {
val decorator = getWindowedDecorator(window.id)
val frame = if (decorator != null && decorator.getFrame() is Frame) decorator.getFrame() as Frame else return
val state = frame.state
if (state == Frame.NORMAL) {
frame.state = Frame.MAXIMIZED_BOTH
}
else if (state == Frame.MAXIMIZED_BOTH) {
frame.state = Frame.NORMAL
}
return
}
toolWindowPane!!.setMaximized(window, maximized)
}
internal fun stretchHeight(toolWindow: ToolWindowImpl?, value: Int) {
toolWindowPane!!.stretchHeight((toolWindow)!!, value)
}
private class BalloonHyperlinkListener constructor(private val listener: HyperlinkListener?) : HyperlinkListener {
var balloon: Balloon? = null
override fun hyperlinkUpdate(e: HyperlinkEvent) {
val balloon = balloon
if (balloon != null && e.eventType == HyperlinkEvent.EventType.ACTIVATED) {
balloon.hide()
}
listener?.hyperlinkUpdate(e)
}
}
private fun addFloatingDecorator(entry: ToolWindowEntry, info: WindowInfo) {
val frame = frame!!.frame
val floatingDecorator = FloatingDecorator(frame!!, entry.toolWindow.getOrCreateDecoratorComponent() as InternalDecoratorImpl)
floatingDecorator.apply(info)
entry.floatingDecorator = floatingDecorator
val bounds = info.floatingBounds
if ((bounds != null && bounds.width > 0 && bounds.height > 0 &&
WindowManager.getInstance().isInsideScreenBounds(bounds.x, bounds.y, bounds.width))) {
floatingDecorator.bounds = Rectangle(bounds)
}
else {
val decorator = entry.toolWindow.decorator
// place new frame at the center of main frame if there are no floating bounds
var size = decorator.size
if (size.width == 0 || size.height == 0) {
size = decorator.preferredSize
}
floatingDecorator.size = size
floatingDecorator.setLocationRelativeTo(frame)
}
@Suppress("DEPRECATION")
floatingDecorator.show()
}
private fun addWindowedDecorator(entry: ToolWindowEntry, info: WindowInfo) {
if (ApplicationManager.getApplication().isHeadlessEnvironment) {
return
}
val id = entry.id
val decorator = entry.toolWindow.getOrCreateDecoratorComponent()
val windowedDecorator = FrameWrapper(project, title = "$id - ${project.name}", component = decorator)
windowedDecorator.setIsDecorated(false)
val window = windowedDecorator.getFrame()
MnemonicHelper.init((window as RootPaneContainer).contentPane)
val shouldBeMaximized = info.isMaximized
val bounds = info.floatingBounds
if ((bounds != null && bounds.width > 0 && (bounds.height > 0) &&
WindowManager.getInstance().isInsideScreenBounds(bounds.x, bounds.y, bounds.width))) {
window.bounds = Rectangle(bounds)
}
else {
// place new frame at the center of main frame if there are no floating bounds
var size = decorator.size
if (size.width == 0 || size.height == 0) {
size = decorator.preferredSize
}
window.size = size
window.setLocationRelativeTo(frame!!.frame)
}
entry.windowedDecorator = windowedDecorator
Disposer.register(windowedDecorator, Disposable {
if (idToEntry[id]?.windowedDecorator != null) {
hideToolWindow(id, false)
}
})
windowedDecorator.show(false)
val rootPane = (window as RootPaneContainer).rootPane
val rootPaneBounds = rootPane.bounds
val point = rootPane.locationOnScreen
val windowBounds = window.bounds
window.setLocation(2 * windowBounds.x - point.x, 2 * windowBounds.y - point.y)
window.setSize(2 * windowBounds.width - rootPaneBounds.width, 2 * windowBounds.height - rootPaneBounds.height)
if (shouldBeMaximized && window is Frame) {
window.extendedState = Frame.MAXIMIZED_BOTH
}
window.toFront()
}
/**
* Notifies window manager about focus traversal in a tool window
*/
internal class ToolWindowFocusWatcher(private val toolWindow: ToolWindowImpl, component: JComponent) : FocusWatcher() {
private val id = toolWindow.id
init {
install(component)
Disposer.register(toolWindow.disposable, Disposable { deinstall(component) })
}
override fun isFocusedComponentChangeValid(component: Component?, cause: AWTEvent?) = component != null
override fun focusedComponentChanged(component: Component?, cause: AWTEvent?) {
if (component == null || !toolWindow.isActive) {
return
}
val toolWindowManager = toolWindow.toolWindowManager
toolWindowManager.focusManager
.doWhenFocusSettlesDown(ExpirableRunnable.forProject(toolWindowManager.project) {
ModalityUiUtil.invokeLaterIfNeeded(Runnable {
val entry = toolWindowManager.idToEntry[id] ?: return@Runnable
val windowInfo = entry.readOnlyWindowInfo
if (!windowInfo.isVisible) {
return@Runnable
}
toolWindowManager.activateToolWindow(entry, toolWindowManager.getRegisteredMutableInfoOrLogError(entry.id),
autoFocusContents = false)
}, ModalityState.defaultModalityState(), toolWindowManager.project.disposed)
})
}
}
/**
* Spies on IdeToolWindow properties and applies them to the window
* state.
*/
@ApiStatus.Internal
open fun toolWindowPropertyChanged(toolWindow: ToolWindow, property: ToolWindowProperty) {
val entry = idToEntry[toolWindow.id]
if (property == ToolWindowProperty.AVAILABLE && !toolWindow.isAvailable && entry?.readOnlyWindowInfo?.isVisible == true) {
hideToolWindow(toolWindow.id, false)
}
val stripeButton = entry?.stripeButton
if (stripeButton != null) {
if (property == ToolWindowProperty.ICON) {
stripeButton.updateIcon(toolWindow.icon)
}
else {
stripeButton.updatePresentation()
}
}
ActivateToolWindowAction.updateToolWindowActionPresentation(toolWindow)
}
internal fun activated(toolWindow: ToolWindowImpl, source: ToolWindowEventSource?) {
activateToolWindow(idToEntry[toolWindow.id]!!, getRegisteredMutableInfoOrLogError(toolWindow.id), source = source)
}
/**
* Handles event from decorator and modify weight/floating bounds of the
* tool window depending on decoration type.
*/
@ApiStatus.Internal
fun resized(source: InternalDecoratorImpl) {
if (!source.isShowing) {
// do not recalculate the tool window size if it is not yet shown (and, therefore, has 0,0,0,0 bounds)
return
}
val toolWindow = source.toolWindow
val info = getRegisteredMutableInfoOrLogError(toolWindow.id)
if (info.type == ToolWindowType.FLOATING) {
val owner = SwingUtilities.getWindowAncestor(source)
if (owner != null) {
info.floatingBounds = owner.bounds
}
}
else if (info.type == ToolWindowType.WINDOWED) {
val decorator = getWindowedDecorator(toolWindow.id)
val frame = decorator?.getFrame()
if (frame == null || !frame.isShowing) {
return
}
info.floatingBounds = getRootBounds(frame as JFrame)
info.isMaximized = frame.extendedState == Frame.MAXIMIZED_BOTH
}
else {
// docked and sliding windows
val anchor = info.anchor
var another: InternalDecoratorImpl? = null
val wholeSize = toolWindowPane!!.rootPane.size
if (source.parent is Splitter) {
var sizeInSplit = if (anchor.isSplitVertically) source.height else source.width
val splitter = source.parent as Splitter
if (splitter.secondComponent === source) {
sizeInSplit += splitter.dividerWidth
another = splitter.firstComponent as InternalDecoratorImpl
}
else {
another = splitter.secondComponent as InternalDecoratorImpl
}
info.sideWeight = getAdjustedRatio(sizeInSplit,
if (anchor.isSplitVertically) splitter.height else splitter.width,
if (splitter.secondComponent === source) -1 else 1)
}
val paneWeight = getAdjustedRatio(if (anchor.isHorizontal) source.height else source.width,
if (anchor.isHorizontal) wholeSize.height else wholeSize.width, 1)
info.weight = paneWeight
if (another != null) {
getRegisteredMutableInfoOrLogError(another.toolWindow.id).weight = paneWeight
}
}
}
private fun focusToolWindowByDefault() {
var toFocus: ToolWindowEntry? = null
for (each in activeStack.stack) {
if (each.readOnlyWindowInfo.isVisible) {
toFocus = each
break
}
}
if (toFocus == null) {
for (each in activeStack.persistentStack) {
if (each.readOnlyWindowInfo.isVisible) {
toFocus = each
break
}
}
}
if (toFocus != null && !ApplicationManager.getApplication().isDisposed) {
activateToolWindow(toFocus, getRegisteredMutableInfoOrLogError(toFocus.id))
}
}
fun setShowStripeButton(id: String, visibleOnPanel: Boolean) {
val info = getRegisteredMutableInfoOrLogError(id)
if (visibleOnPanel == info.isShowStripeButton) {
return
}
info.isShowStripeButton = visibleOnPanel
idToEntry[info.id!!]!!.applyWindowInfo(info.copy())
fireStateChanged()
}
internal class InitToolWindowsActivity : StartupActivity {
override fun runActivity(project: Project) {
val app = ApplicationManager.getApplication()
if (app.isUnitTestMode || app.isHeadlessEnvironment) {
return
}
LOG.assertTrue(!app.isDispatchThread)
val manager = getInstance(project) as ToolWindowManagerImpl
val tasks = runActivity("toolwindow init command creation") {
manager.computeToolWindowBeans()
}
app.invokeLater(
manager.beforeProjectOpenedTask(tasks, app),
project.disposed,
)
}
}
private fun checkInvariants(additionalMessage: String) {
if (!ApplicationManager.getApplication().isEAP && !ApplicationManager.getApplication().isInternal) {
return
}
val violations = mutableListOf<String>()
for (entry in idToEntry.values) {
val info = layout.getInfo(entry.id) ?: continue
if (!info.isVisible) {
continue
}
if (info.type == ToolWindowType.FLOATING) {
if (entry.floatingDecorator == null) {
violations.add("Floating window has no decorator: ${entry.id}")
}
}
else if (info.type == ToolWindowType.WINDOWED) {
if (entry.windowedDecorator == null) {
violations.add("Windowed window has no decorator: ${entry.id}")
}
}
}
if (violations.isNotEmpty()) {
LOG.error("Invariants failed: \n${violations.joinToString("\n")}\nContext: $additionalMessage")
}
}
private inline fun processDescriptors(crossinline handler: (bean: ToolWindowEP, pluginDescriptor: PluginDescriptor) -> Unit) {
ToolWindowEP.EP_NAME.processWithPluginDescriptor { bean, pluginDescriptor ->
try {
handler(bean, pluginDescriptor)
}
catch (e: ProcessCanceledException) {
throw e
}
catch (e: Throwable) {
LOG.error("Cannot process toolwindow ${bean.id}", e)
}
}
}
}
private enum class KeyState {
WAITING, PRESSED, RELEASED, HOLD
}
private fun areAllModifiersPressed(@JdkConstants.InputEventMask modifiers: Int, @JdkConstants.InputEventMask mask: Int): Boolean {
return (modifiers xor mask) == 0
}
@JdkConstants.InputEventMask
private fun keyCodeToInputMask(code: Int): Int {
return when (code) {
KeyEvent.VK_SHIFT -> Event.SHIFT_MASK
KeyEvent.VK_CONTROL -> Event.CTRL_MASK
KeyEvent.VK_META -> Event.META_MASK
KeyEvent.VK_ALT -> Event.ALT_MASK
else -> 0
}
}
// We should filter out 'mixed' mask like InputEvent.META_MASK | InputEvent.META_DOWN_MASK
@get:JdkConstants.InputEventMask
private val activateToolWindowVKsMask: Int
get() {
if (!LoadingState.COMPONENTS_LOADED.isOccurred) {
return 0
}
if (Registry.`is`("toolwindow.disable.overlay.by.double.key")) {
return 0
}
val keymap = KeymapManager.getInstance().activeKeymap
val baseShortcut = keymap.getShortcuts("ActivateProjectToolWindow")
var baseModifiers = if (SystemInfo.isMac) InputEvent.META_MASK else InputEvent.ALT_MASK
for (each in baseShortcut) {
if (each is KeyboardShortcut) {
val keyStroke = each.firstKeyStroke
baseModifiers = keyStroke.modifiers
if (baseModifiers > 0) {
break
}
}
}
// We should filter out 'mixed' mask like InputEvent.META_MASK | InputEvent.META_DOWN_MASK
return baseModifiers and (InputEvent.SHIFT_MASK or InputEvent.CTRL_MASK or InputEvent.META_MASK or InputEvent.ALT_MASK)
}
private val isStackEnabled: Boolean
get() = Registry.`is`("ide.enable.toolwindow.stack")
private fun getRootBounds(frame: JFrame): Rectangle {
val rootPane = frame.rootPane
val bounds = rootPane.bounds
bounds.setLocation(frame.x + rootPane.x, frame.y + rootPane.y)
return bounds
}
private const val EDITOR_ELEMENT = "editor"
private const val ACTIVE_ATTR_VALUE = "active"
private const val LAYOUT_TO_RESTORE = "layout-to-restore"
private const val RECENT_TW_TAG = "recentWindows"
enum class ToolWindowProperty {
TITLE, ICON, AVAILABLE, STRIPE_TITLE
}
private fun isInActiveToolWindow(component: Any?, activeToolWindow: ToolWindowImpl): Boolean {
var source = if (component is JComponent) component else null
val activeToolWindowComponent = activeToolWindow.getComponentIfInitialized()
if (activeToolWindowComponent != null) {
while (source != null && source !== activeToolWindowComponent) {
source = ComponentUtil.getClientProperty(source, ToolWindowManagerImpl.PARENT_COMPONENT) ?: source.parent as? JComponent
}
}
return source != null
}
fun findIconFromBean(bean: ToolWindowEP, factory: ToolWindowFactory, pluginDescriptor: PluginDescriptor): Icon? {
try {
return IconLoader.findIcon(bean.icon ?: return null, factory.javaClass, pluginDescriptor.pluginClassLoader, null, true)
}
catch (e: Exception) {
LOG.error(e)
return EmptyIcon.ICON_13
}
}
fun getStripeTitleSupplier(id: String, pluginDescriptor: PluginDescriptor): Supplier<String>? {
val classLoader = pluginDescriptor.pluginClassLoader
val bundleName = when (pluginDescriptor.pluginId) {
PluginManagerCore.CORE_ID -> IdeBundle.BUNDLE
else -> pluginDescriptor.resourceBundleBaseName ?: return null
}
try {
val bundle = DynamicBundle.INSTANCE.getResourceBundle(bundleName, classLoader)
val key = "toolwindow.stripe.${id}".replace(" ", "_")
@Suppress("HardCodedStringLiteral", "UnnecessaryVariable")
val fallback = id
val label = BundleBase.messageOrDefault(bundle, key, fallback)
return Supplier { label }
}
catch (e: MissingResourceException) {
LOG.warn("Missing bundle $bundleName at $classLoader", e)
}
return null
}
private fun addStripeButton(button: StripeButton, stripe: Stripe) {
stripe.addButton(button) { o1, o2 -> windowInfoComparator.compare(o1.windowInfo, o2.windowInfo) }
}
private fun removeStripeButton(button: StripeButton) {
(button.parent as? Stripe)?.removeButton(button)
}
@ApiStatus.Internal
interface RegisterToolWindowTaskProvider {
fun getTasks(project: Project): Collection<ToolWindowEP>
}
//Adding or removing items? Don't forget to increment the version in ToolWindowEventLogGroup.GROUP
enum class ToolWindowEventSource {
StripeButton, SquareStripeButton, ToolWindowHeader, ToolWindowHeaderAltClick, Content, Switcher, SwitcherSearch,
ToolWindowsWidget, RemoveStripeButtonAction,
HideOnShowOther, HideSide, CloseFromSwitcher,
ActivateActionMenu, ActivateActionKeyboardShortcut, ActivateActionGotoAction, ActivateActionOther,
CloseAction, HideButton, HideToolWindowAction, HideSideWindowsAction, HideAllWindowsAction, JumpToLastWindowAction, ToolWindowSwitcher,
InspectionsWidget
}
| apache-2.0 | 05cab4d042c2e6ebeb98c19aaefc8f98 | 34.976684 | 207 | 0.69115 | 4.969108 | false | false | false | false |
JetBrains/kotlin-native | klib/src/test/testData/TopLevelPropertiesWithClassesRootPackage.kt | 4 | 823 | /*
* Copyright 2010-2018 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:Suppress("UNUSED_PARAMETER")
class Foo
typealias MyTransformer = (String) -> Int
// top-level properties
val v1 = 1
val v2 = "hello"
val v3: (String) -> Int = { it.length }
val v4: MyTransformer = v3
object Bar
| apache-2.0 | fe25b02d2b15952f99d64b8024ab8183 | 27.37931 | 75 | 0.72418 | 3.674107 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/PublicApiImplicitTypeInspection.kt | 5 | 2169 | // 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.ui.MultipleCheckboxOptionsPanel
import org.jetbrains.kotlin.config.AnalysisFlags
import org.jetbrains.kotlin.config.ExplicitApiMode
import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.resolve.checkers.ExplicitApiDeclarationChecker
import javax.swing.JComponent
class PublicApiImplicitTypeInspection(
@JvmField var reportInternal: Boolean = false,
@JvmField var reportPrivate: Boolean = false
) : AbstractImplicitTypeInspection(
{ element, inspection ->
val shouldCheckForPublic = element.languageVersionSettings.getFlag(AnalysisFlags.explicitApiMode) == ExplicitApiMode.DISABLED
val callableMemberDescriptor = element.resolveToDescriptorIfAny() as? CallableMemberDescriptor
val forInternal = (inspection as PublicApiImplicitTypeInspection).reportInternal
val forPrivate = inspection.reportPrivate
ExplicitApiDeclarationChecker.returnTypeRequired(element, callableMemberDescriptor, shouldCheckForPublic, forInternal, forPrivate)
}
) {
override val problemText: String
get() {
return if (!reportInternal && !reportPrivate)
KotlinBundle.message("for.api.stability.it.s.recommended.to.specify.explicitly.public.protected.declaration.types")
else
KotlinBundle.message("for.api.stability.it.s.recommended.to.specify.explicitly.declaration.types")
}
override fun createOptionsPanel(): JComponent {
val panel = MultipleCheckboxOptionsPanel(this)
panel.addCheckbox(KotlinBundle.message("apply.also.to.internal.members"), "reportInternal")
panel.addCheckbox(KotlinBundle.message("apply.also.to.private.members"), "reportPrivate")
return panel
}
} | apache-2.0 | d4faf32493da627850ccaa5b400b2191 | 50.666667 | 138 | 0.779161 | 4.997696 | false | false | false | false |
GunoH/intellij-community | plugins/stats-collector/src/com/intellij/stats/completion/sender/StatisticSenderImpl.kt | 7 | 1768 | // Copyright 2000-2022 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.stats.completion.sender
import com.intellij.ide.util.PropertiesComponent
import com.intellij.openapi.components.service
import com.intellij.stats.completion.network.assertNotEDT
import com.intellij.stats.completion.network.service.RequestService
import com.intellij.stats.completion.storage.FilePathProvider
import java.io.File
class StatisticSenderImpl: StatisticSender {
companion object {
const val DAILY_LIMIT = 20 * 1024 * 1024 // 20 mb
}
private val limitWatcher = DailyLimitSendingWatcher(DAILY_LIMIT, PersistentSentDataInfo(PropertiesComponent.getInstance()))
override fun sendStatsData(url: String) {
assertNotEDT()
if (limitWatcher.isLimitReached()) return
val filesToSend = service<FilePathProvider>().getDataFiles()
filesToSend.forEach {
if (it.length() > 0 && !limitWatcher.isLimitReached()) {
val result = sendContent(url, it)
if (result.isSuccessful || result.responseCode != 404) {
it.delete()
}
}
}
}
private fun sendContent(url: String, file: File): SendingResult {
val data = service<RequestService>().postZipped(url, file)
if (data != null && data.code >= 200 && data.code < 300) {
if (data.sentDataSize != null) {
limitWatcher.dataSent(data.sentDataSize)
}
return SendingResult(true, data.code)
}
return SendingResult(false, data?.code)
}
private data class SendingResult(val isSuccessful: Boolean, val responseCode: Int?)
} | apache-2.0 | 9296e352963738d9c0ce8a77ac2942a0 | 38.311111 | 140 | 0.668552 | 4.453401 | false | false | false | false |
mglukhikh/intellij-community | platform/platform-impl/src/com/intellij/ide/actions/project/convertModuleGroupsToQualifiedNames.kt | 1 | 9053 | // 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 com.intellij.ide.actions.project
import com.intellij.CommonBundle
import com.intellij.codeInsight.intention.IntentionManager
import com.intellij.codeInspection.ex.InspectionProfileImpl
import com.intellij.codeInspection.ex.InspectionProfileWrapper
import com.intellij.codeInspection.ex.InspectionToolWrapper
import com.intellij.codeInspection.ex.LocalInspectionToolWrapper
import com.intellij.lang.StdLanguages
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.application.ApplicationNamesInfo
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.LineExtensionInfo
import com.intellij.openapi.editor.SpellCheckingEditorCustomizationProvider
import com.intellij.openapi.editor.event.DocumentEvent
import com.intellij.openapi.editor.event.DocumentListener
import com.intellij.openapi.editor.impl.EditorImpl
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.module.ModulePointerManager
import com.intellij.openapi.module.impl.ModulePointerManagerImpl
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectBundle
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.PsiDocumentManager
import com.intellij.ui.*
import com.intellij.ui.components.JBLabel
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import com.intellij.xml.util.XmlStringUtil
import java.awt.Color
import java.awt.Font
import java.util.function.Function
import java.util.function.Supplier
import javax.swing.Action
import javax.swing.JCheckBox
import javax.swing.JPanel
class ConvertModuleGroupsToQualifiedNamesDialog(val project: Project) : DialogWrapper(project) {
private val editorArea: EditorTextField
private val document: Document
get() = editorArea.document
private lateinit var modules: List<Module>
private val recordPreviousNamesCheckBox: JCheckBox
private var modified = false
init {
title = ProjectBundle.message("convert.module.groups.dialog.title")
isModal = false
setOKButtonText(ProjectBundle.message("convert.module.groups.button.text"))
editorArea = EditorTextFieldProvider.getInstance().getEditorField(StdLanguages.TEXT, project, listOf(EditorCustomization {
it.settings.apply {
isLineNumbersShown = false
isLineMarkerAreaShown = false
isFoldingOutlineShown = false
isRightMarginShown = false
additionalLinesCount = 0
additionalColumnsCount = 0
isAdditionalPageAtBottom = false
isShowIntentionBulb = false
}
(it as? EditorImpl)?.registerLineExtensionPainter(this::generateLineExtension)
setupHighlighting(it)
}, MonospaceEditorCustomization.getInstance()))
document.addDocumentListener(object: DocumentListener {
override fun documentChanged(event: DocumentEvent?) {
modified = true
}
}, disposable)
recordPreviousNamesCheckBox = JCheckBox(ProjectBundle.message("convert.module.groups.record.previous.names.text"), true)
importRenamingScheme(emptyMap())
init()
}
private fun setupHighlighting(editor: Editor) {
editor.putUserData(IntentionManager.SHOW_INTENTION_OPTIONS_KEY, false)
val inspections = Supplier<List<InspectionToolWrapper<*, *>>> {
listOf(LocalInspectionToolWrapper(ModuleNamesListInspection()))
}
val file = PsiDocumentManager.getInstance(project).getPsiFile(document)
file?.putUserData(InspectionProfileWrapper.CUSTOMIZATION_KEY, Function {
val profile = InspectionProfileImpl("Module names", inspections, null)
for (spellCheckingToolName in SpellCheckingEditorCustomizationProvider.getInstance().spellCheckingToolNames) {
profile.getToolsOrNull(spellCheckingToolName, project)?.isEnabled = false
}
InspectionProfileWrapper(profile)
})
}
override fun createCenterPanel(): JPanel {
val text = XmlStringUtil.wrapInHtml(ProjectBundle.message("convert.module.groups.description.text"))
val recordPreviousNames = com.intellij.util.ui.UI.PanelFactory.panel(recordPreviousNamesCheckBox)
.withTooltip(ProjectBundle.message("convert.module.groups.record.previous.names.tooltip",
ApplicationNamesInfo.getInstance().fullProductName)).createPanel()
return JBUI.Panels.simplePanel(0, UIUtil.DEFAULT_VGAP)
.addToCenter(editorArea)
.addToTop(JBLabel(text))
.addToBottom(recordPreviousNames)
}
override fun getPreferredFocusedComponent() = editorArea.focusTarget
private fun generateLineExtension(line: Int): Collection<LineExtensionInfo> {
val lineText = document.charsSequence.subSequence(document.getLineStartOffset(line), document.getLineEndOffset(line)).toString()
if (line !in modules.indices || modules[line].name == lineText) return emptyList()
val name = LineExtensionInfo(" <- ${modules[line].name}", JBColor.GRAY, null, null, Font.PLAIN)
val groupPath = ModuleManager.getInstance(project).getModuleGroupPath(modules[line])
if (groupPath == null) {
return listOf(name)
}
val group = LineExtensionInfo(groupPath.joinToString(separator = "/", prefix = " (", postfix = ")"), Color.GRAY, null, null, Font.PLAIN)
return listOf(name, group)
}
fun importRenamingScheme(renamingScheme: Map<String, String>) {
val moduleManager = ModuleManager.getInstance(project)
fun getDefaultName(module: Module) = (moduleManager.getModuleGroupPath(module)?.let { it.joinToString(".") + "." } ?: "") + module.name
val names = moduleManager.modules.associateBy({ it }, { renamingScheme.getOrElse(it.name, { getDefaultName(it) }) })
modules = moduleManager.modules.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER, { names[it]!! }))
runWriteAction {
document.setText(modules.joinToString("\n") { names[it]!! })
}
modified = false
}
fun getRenamingScheme(): Map<String, String> {
val lines = document.charsSequence.split('\n')
return modules.withIndex().filter { lines[it.index] != it.value.name }.associateByTo(LinkedHashMap(), { it.value.name }, {
if (it.index in lines.indices) lines[it.index] else it.value.name
})
}
override fun doCancelAction() {
if (modified) {
val answer = Messages.showYesNoCancelDialog(project,
ProjectBundle.message("convert.module.groups.do.you.want.to.save.scheme"),
ProjectBundle.message("convert.module.groups.dialog.title"), null)
when (answer) {
Messages.CANCEL -> return
Messages.YES -> {
if (!saveModuleRenamingScheme(this)) {
return
}
}
}
}
super.doCancelAction()
}
override fun doOKAction() {
ModuleNamesListInspection.checkModuleNames(document.charsSequence.lines(), project) { line, message ->
Messages.showErrorDialog(project,
ProjectBundle.message("convert.module.groups.error.at.text", line + 1, StringUtil.decapitalize(message)),
CommonBundle.getErrorTitle())
return
}
val renamingScheme = getRenamingScheme()
if (renamingScheme.isNotEmpty()) {
val model = ModuleManager.getInstance(project).modifiableModel
val byName = modules.associateBy { it.name }
for (entry in renamingScheme) {
model.renameModule(byName[entry.key]!!, entry.value)
}
modules.forEach {
model.setModuleGroupPath(it, null)
}
runWriteAction {
model.commit()
}
if (recordPreviousNamesCheckBox.isSelected) {
(ModulePointerManager.getInstance(project) as ModulePointerManagerImpl).setRenamingScheme(renamingScheme)
}
project.save()
}
super.doOKAction()
}
override fun createActions(): Array<Action> {
return arrayOf(okAction, SaveModuleRenamingSchemeAction(this, { modified = false }),
LoadModuleRenamingSchemeAction(this), cancelAction)
}
}
class ConvertModuleGroupsToQualifiedNamesAction : DumbAwareAction(ProjectBundle.message("convert.module.groups.action.text"),
ProjectBundle.message("convert.module.groups.action.description"), null) {
override fun actionPerformed(e: AnActionEvent) {
val project = e.project ?: return
ConvertModuleGroupsToQualifiedNamesDialog(project).show()
}
override fun update(e: AnActionEvent) {
e.presentation.isEnabledAndVisible = e.project != null && ModuleManager.getInstance(e.project!!).hasModuleGroups()
}
}
| apache-2.0 | def75b50138c61fb0c3428fb03cfb9c9 | 42.946602 | 140 | 0.731581 | 4.729885 | false | false | false | false |
smmribeiro/intellij-community | java/java-impl/src/com/intellij/psi/impl/JavaPlatformModuleSystem.kt | 1 | 12215 | // 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 com.intellij.psi.impl
import com.intellij.codeInsight.JavaModuleSystemEx
import com.intellij.codeInsight.JavaModuleSystemEx.ErrorWithFixes
import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer
import com.intellij.codeInsight.daemon.JavaErrorBundle
import com.intellij.codeInsight.daemon.QuickFixBundle
import com.intellij.codeInsight.daemon.impl.analysis.JavaModuleGraphUtil
import com.intellij.codeInsight.daemon.impl.quickfix.AddExportsDirectiveFix
import com.intellij.codeInsight.daemon.impl.quickfix.AddRequiresDirectiveFix
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.java.JavaBundle
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.JdkOrderEntry
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.roots.ProjectFileIndex
import com.intellij.psi.*
import com.intellij.psi.impl.light.LightJavaModule
import com.intellij.psi.util.PsiUtil
import org.jetbrains.annotations.NonNls
/**
* Checks package accessibility according to JLS 7 "Packages and Modules".
*
* @see <a href="https://docs.oracle.com/javase/specs/jls/se9/html/jls-7.html">JLS 7 "Packages and Modules"</a>
* @see <a href="http://openjdk.java.net/jeps/261">JEP 261: Module System</a>
*/
class JavaPlatformModuleSystem : JavaModuleSystemEx {
override fun getName(): String = JavaBundle.message("java.platform.module.system.name")
override fun isAccessible(targetPackageName: String, targetFile: PsiFile?, place: PsiElement): Boolean =
checkAccess(targetPackageName, targetFile?.originalFile, place, quick = true) == null
override fun checkAccess(targetPackageName: String, targetFile: PsiFile?, place: PsiElement): ErrorWithFixes? =
checkAccess(targetPackageName, targetFile?.originalFile, place, quick = false)
private fun checkAccess(targetPackageName: String, targetFile: PsiFile?, place: PsiElement, quick: Boolean): ErrorWithFixes? {
val useFile = place.containingFile?.originalFile
if (useFile != null && PsiUtil.isLanguageLevel9OrHigher(useFile)) {
val useVFile = useFile.virtualFile
val index = ProjectFileIndex.getInstance(useFile.project)
if (useVFile == null || !index.isInLibrarySource(useVFile)) {
if (targetFile != null && targetFile.isPhysical) {
return checkAccess(targetFile, useFile, targetPackageName, quick)
}
else if (useVFile != null) {
val target = JavaPsiFacade.getInstance(useFile.project).findPackage(targetPackageName)
if (target != null) {
val module = index.getModuleForFile(useVFile)
if (module != null) {
val test = index.isInTestSourceContent(useVFile)
val moduleScope = module.getModuleWithDependenciesAndLibrariesScope(test)
val dirs = target.getDirectories(moduleScope)
if (dirs.isEmpty()) {
if (target.getFiles(moduleScope).isEmpty()) {
return if (quick) ERR else ErrorWithFixes(JavaErrorBundle.message("package.not.found", target.qualifiedName))
}
else {
return null
}
}
val error = checkAccess(dirs[0], useFile, target.qualifiedName, quick)
return when {
error == null -> null
dirs.size == 1 -> error
dirs.asSequence().drop(1).any { checkAccess(it, useFile, target.qualifiedName, true) == null } -> null
else -> error
}
}
}
}
}
}
return null
}
private val ERR = ErrorWithFixes("-")
private fun checkAccess(target: PsiFileSystemItem, place: PsiFileSystemItem, packageName: String, quick: Boolean): ErrorWithFixes? {
val targetModule = JavaModuleGraphUtil.findDescriptorByElement(target)
val useModule = JavaModuleGraphUtil.findDescriptorByElement(place)
if (targetModule != null) {
if (targetModule == useModule) {
return null
}
val targetName = targetModule.name
val useName = useModule?.name ?: "ALL-UNNAMED"
val module = place.virtualFile?.let { ProjectFileIndex.getInstance(place.project).getModuleForFile(it) }
if (useModule == null) {
val origin = targetModule.containingFile?.virtualFile
if (origin == null || module == null || ModuleRootManager.getInstance(module).fileIndex.getOrderEntryForFile(origin) !is JdkOrderEntry) {
return null // a target is not on the mandatory module path
}
var isRoot = !targetName.startsWith("java.") || inAddedModules(module, targetName) || hasUpgrade(module, targetName, packageName, place)
if (!isRoot) {
val root = JavaPsiFacade.getInstance(place.project).findModule("java.se", module.moduleWithLibrariesScope)
isRoot = root == null || JavaModuleGraphUtil.reads(root, targetModule)
}
if (!isRoot) {
return if (quick) ERR else ErrorWithFixes(
JavaErrorBundle.message("module.access.not.in.graph", packageName, targetName),
listOf(AddModulesOptionFix(module, targetName)))
}
}
if (!(targetModule is LightJavaModule ||
JavaModuleGraphUtil.exports(targetModule, packageName, useModule) ||
module != null && inAddedExports(module, targetName, packageName, useName))) {
if (quick) return ERR
val fixes = when {
packageName.isEmpty() -> emptyList()
targetModule is PsiCompiledElement && module != null -> listOf(AddExportsOptionFix(module, targetName, packageName, useName))
targetModule !is PsiCompiledElement && useModule != null -> listOf(AddExportsDirectiveFix(targetModule, packageName, useName))
else -> emptyList()
}
return when (useModule) {
null -> ErrorWithFixes(JavaErrorBundle.message("module.access.from.unnamed", packageName, targetName), fixes)
else -> ErrorWithFixes(JavaErrorBundle.message("module.access.from.named", packageName, targetName, useName), fixes)
}
}
if (useModule != null && !(targetName == PsiJavaModule.JAVA_BASE || JavaModuleGraphUtil.reads(useModule, targetModule))) {
return when {
quick -> ERR
PsiNameHelper.isValidModuleName(targetName, useModule) -> ErrorWithFixes(
JavaErrorBundle.message("module.access.does.not.read", packageName, targetName, useName),
listOf(AddRequiresDirectiveFix(useModule, targetName)))
else -> ErrorWithFixes(JavaErrorBundle.message("module.access.bad.name", packageName, targetName))
}
}
}
else if (useModule != null) {
return if (quick) ERR else ErrorWithFixes(JavaErrorBundle.message("module.access.to.unnamed", packageName, useModule.name))
}
return null
}
private fun hasUpgrade(module: Module, targetName: String, packageName: String, place: PsiFileSystemItem): Boolean {
if (PsiJavaModule.UPGRADEABLE.contains(targetName)) {
val target = JavaPsiFacade.getInstance(module.project).findPackage(packageName)
if (target != null) {
val useVFile = place.virtualFile
if (useVFile != null) {
val index = ModuleRootManager.getInstance(module).fileIndex
val test = index.isInTestSourceContent(useVFile)
val dirs = target.getDirectories(module.getModuleWithDependenciesAndLibrariesScope(test))
return dirs.any { index.getOrderEntryForFile(it.virtualFile) !is JdkOrderEntry }
}
}
}
return false
}
private fun inAddedExports(module: Module, targetName: String, packageName: String, useName: String): Boolean {
val options = JavaCompilerConfigurationProxy.getAdditionalOptions(module.project, module)
if (options.isEmpty()) return false
val prefix = "${targetName}/${packageName}="
return optionValues(options, "--add-exports")
.filter { it.startsWith(prefix) }
.map { it.substring(prefix.length) }
.flatMap { it.splitToSequence(",") }
.any { it == useName }
}
private fun inAddedModules(module: Module, moduleName: String): Boolean {
val options = JavaCompilerConfigurationProxy.getAdditionalOptions(module.project, module)
return optionValues(options, "--add-modules")
.flatMap { it.splitToSequence(",") }
.any { it == moduleName || it == "ALL-SYSTEM" || it == "ALL-MODULE-PATH" }
}
private fun optionValues(options: List<String>, name: String) =
if (options.isEmpty()) emptySequence()
else {
var useValue = false
options.asSequence()
.map {
when {
it == name -> { useValue = true; "" }
useValue -> { useValue = false; it }
it.startsWith(name) && it[name.length] == '=' -> it.substring(name.length + 1)
else -> ""
}
}
.filterNot { it.isEmpty() }
}
private abstract class CompilerOptionFix(private val module: Module) : IntentionAction {
@NonNls override fun getFamilyName() = "Fix compiler option" // not visible
override fun isAvailable(project: Project, editor: Editor?, file: PsiFile?) = !module.isDisposed
override fun invoke(project: Project, editor: Editor?, file: PsiFile?) {
if (isAvailable(project, editor, file)) {
val options = JavaCompilerConfigurationProxy.getAdditionalOptions(module.project, module).toMutableList()
update(options)
JavaCompilerConfigurationProxy.setAdditionalOptions(module.project, module, options)
PsiManager.getInstance(project).dropPsiCaches()
DaemonCodeAnalyzer.getInstance(project).restart()
}
}
protected abstract fun update(options: MutableList<String>)
override fun getElementToMakeWritable(currentFile: PsiFile): PsiElement? = null
override fun startInWriteAction() = true
}
private class AddExportsOptionFix(module: Module, targetName: String, packageName: String, private val useName: String) : CompilerOptionFix(module) {
private val qualifier = "${targetName}/${packageName}"
override fun getText() = QuickFixBundle.message("add.compiler.option.fix.name", "--add-exports ${qualifier}=${useName}")
override fun update(options: MutableList<String>) {
var idx = -1; var candidate = -1; var offset = 0
val prefix = "--add-exports"
for ((i, option) in options.withIndex()) {
if (option.startsWith(prefix)) {
if (option.length == prefix.length) { candidate = i + 1 ; offset = 0 }
else if (option[prefix.length] == '=') { candidate = i; offset = prefix.length + 1 }
}
if (i == candidate && option.startsWith(qualifier, offset)) {
val qualifierEnd = qualifier.length + offset
if (option.length == qualifierEnd || option[qualifierEnd] == '=') {
idx = i
}
}
}
when (idx) {
-1 -> options += listOf(prefix, "${qualifier}=${useName}")
else -> options[idx] = "${options[idx].trimEnd(',')},${useName}"
}
}
}
private class AddModulesOptionFix(module: Module, private val moduleName: String) : CompilerOptionFix(module) {
override fun getText() = QuickFixBundle.message("add.compiler.option.fix.name", "--add-modules ${moduleName}")
override fun update(options: MutableList<String>) {
var idx = -1
val prefix = "--add-modules"
for ((i, option) in options.withIndex()) {
if (option.startsWith(prefix)) {
if (option.length == prefix.length) idx = i + 1
else if (option[prefix.length] == '=') idx = i
}
}
when (idx) {
-1 -> options += listOf(prefix, moduleName)
options.size -> options += moduleName
else -> {
val value = options[idx]
options[idx] = if (value.endsWith('=') || value.endsWith(',')) value + moduleName else "${value},${moduleName}"
}
}
}
}
}
| apache-2.0 | 56ed5faf7d8a701f9da34b647d6b1ff2 | 44.240741 | 158 | 0.667704 | 4.721685 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/intentions/simplifyBooleanWithConstants/inapplicableUsesVals2.kt | 13 | 103 | // IS_APPLICABLE: false
fun foo(y: Boolean) {
val x = 4
val z = 5
<caret>x == z || x != z
} | apache-2.0 | f1385b154a6a2a67a634f5d8a16127e1 | 16.333333 | 27 | 0.485437 | 2.710526 | false | false | false | false |
smmribeiro/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/changes/committed/RefreshCommittedAction.kt | 7 | 1025 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vcs.changes.committed
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.vcs.changes.committed.ClearCommittedAction.Companion.getSelectedChangesViewContent
class RefreshCommittedAction : DumbAwareAction() {
override fun update(e: AnActionEvent) {
val panel = e.getSelectedChangesViewContent<CommittedChangesPanel>()
val isLoading = panel is RepositoryLocationCommittedChangesPanel<*> && panel.isLoading
e.presentation.isEnabled = panel != null && !isLoading
}
override fun actionPerformed(e: AnActionEvent) {
val panel = e.getSelectedChangesViewContent<CommittedChangesPanel>()!!
if (panel is RepositoryLocationCommittedChangesPanel<*>)
panel.refreshChanges()
else
RefreshIncomingChangesAction.doRefresh(panel.project)
}
} | apache-2.0 | 2039ffa34f2cce6272e92e3f7a44570a | 41.75 | 140 | 0.79122 | 4.680365 | false | false | false | false |
malteschmitz/AndroidSoundboard | app/src/main/java/de/mlte/soundboard/PlayerService.kt | 1 | 1397 | package de.mlte.soundboard
import android.app.Service
import android.content.Intent
import android.media.MediaPlayer
import android.net.Uri
import android.os.Binder
import android.os.IBinder
class PlayerService : Service() {
private val binder = PlayerServiceBinder()
private var player: MediaPlayer? = null
val currentPosition: Int
get() = player?.currentPosition ?: 0
val duration: Int
get() = player?.duration ?: 0
val playing: Boolean
get() = player?.isPlaying ?: false
inner class PlayerServiceBinder : Binder() {
internal
val service: PlayerService
get() = this@PlayerService
}
override fun onBind(intent: Intent): IBinder = binder
fun stop() {
player?.let { mp ->
mp.stop()
mp.reset()
mp.release()
player = null
}
}
fun start(soundId: Long) {
stop()
val file = getFileStreamPath("audio" + soundId)
if (file.exists()) {
val mp = MediaPlayer.create(this, Uri.fromFile(file))
mp.setOnCompletionListener {
mp.reset()
mp.release()
player = null
}
mp.start()
player = mp
}
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
return START_STICKY
}
}
| gpl-3.0 | 4bd94244b8157bb1d10acebc8c564953 | 22.677966 | 81 | 0.574803 | 4.625828 | false | false | false | false |
hsz/idea-gitignore | src/main/kotlin/mobi/hsz/idea/gitignore/actions/IgnoreFileAction.kt | 1 | 6000 | // 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 mobi.hsz.idea.gitignore.actions
import com.intellij.notification.NotificationType
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.guessProjectDir
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiDirectory
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiManager
import com.intellij.util.text.nullize
import mobi.hsz.idea.gitignore.IgnoreBundle
import mobi.hsz.idea.gitignore.command.AppendFileCommandAction
import mobi.hsz.idea.gitignore.command.CreateFileCommandAction
import mobi.hsz.idea.gitignore.file.type.IgnoreFileType
import mobi.hsz.idea.gitignore.util.Notify
import mobi.hsz.idea.gitignore.util.Utils
import org.jetbrains.annotations.PropertyKey
/**
* Action that adds currently selected [VirtualFile] to the specified Ignore [VirtualFile].
* Action is added to the IDE context menus not directly but with [IgnoreFileGroupAction] action.
*/
open class IgnoreFileAction(
private val ignoreFile: VirtualFile? = null,
private val fileType: IgnoreFileType? = getFileType(ignoreFile),
@PropertyKey(resourceBundle = IgnoreBundle.BUNDLE_NAME) textKey: String = "action.addToIgnore",
@PropertyKey(resourceBundle = IgnoreBundle.BUNDLE_NAME) descriptionKey: String = "action.addToIgnore.description"
) : DumbAwareAction(
IgnoreBundle.message(textKey, fileType?.ignoreLanguage?.filename),
IgnoreBundle.message(descriptionKey, fileType?.ignoreLanguage?.filename),
fileType?.icon
) {
companion object {
/**
* Returns [IgnoreFileType] basing on the [VirtualFile] file.
*
* @param virtualFile current file
* @return file type
*/
fun getFileType(virtualFile: VirtualFile?) = virtualFile?.run {
fileType.takeIf { it is IgnoreFileType } as? IgnoreFileType
}
}
/**
* Adds currently selected [VirtualFile] to the [.ignoreFile].
* If [.ignoreFile] is null, default project's Gitignore file will be used.
* Files that cannot be covered with Gitignore file produces error notification.
* When action is performed, Gitignore file is opened with additional content added using [AppendFileCommandAction].
*
* @param e action event
*/
@Suppress("NestedBlockDepth")
override fun actionPerformed(e: AnActionEvent) {
val files = e.getRequiredData(CommonDataKeys.VIRTUAL_FILE_ARRAY)
val project = e.getRequiredData(CommonDataKeys.PROJECT)
ignoreFile?.let {
Utils.getPsiFile(project, it)
} ?: fileType?.let {
getIgnoreFile(project, it, null, true)
}?.let { ignore ->
val paths = mutableSetOf<String>()
files.forEach { file ->
val path = getPath(ignore.virtualFile.parent, file)
if (path.isEmpty()) {
Utils.getModuleRootForFile(file, project)?.let { baseDir ->
Notify.show(
project,
IgnoreBundle.message("action.ignoreFile.addError", Utils.getRelativePath(baseDir, file)),
IgnoreBundle.message("action.ignoreFile.addError.to", Utils.getRelativePath(baseDir, ignore.virtualFile)),
NotificationType.ERROR
)
}
} else {
paths.add(path)
}
}
Utils.openFile(project, ignore)
try {
AppendFileCommandAction(project, ignore, paths).execute()
} catch (e: Throwable) {
e.printStackTrace()
}
}
}
override fun update(e: AnActionEvent) {
val files = e.getData(CommonDataKeys.VIRTUAL_FILE_ARRAY)
if (e.project == null || files == null) {
e.presentation.isVisible = false
}
}
/**
* Gets the file's path relative to the specified root directory.
*
* @param root root directory
* @param file file used for generating output path
* @return relative path
*/
protected open fun getPath(root: VirtualFile, file: VirtualFile) =
StringUtil.notNullize(Utils.getRelativePath(root, file))
.run { StringUtil.escapeChar(this, '[') }
.run { StringUtil.escapeChar(this, ']') }
.run { StringUtil.trimLeading(this, '/') }
.nullize()?.run { "/$this" } ?: ""
/**
* Gets Ignore file for given [Project] and root [PsiDirectory].
* If file is missing - creates new one.
*
* @param project current project
* @param fileType current ignore file type
* @param createIfMissing create new file if missing
* @return Ignore file
*/
@Suppress("ReturnCount")
private fun getIgnoreFile(project: Project, fileType: IgnoreFileType, psiDirectory: PsiDirectory?, createIfMissing: Boolean): PsiFile? {
val projectDir = project.guessProjectDir() ?: return null
val directory = psiDirectory ?: PsiManager.getInstance(project).findDirectory(projectDir) ?: return null
val filename = fileType.ignoreLanguage.filename
var file = directory.findFile(filename)
val virtualFile = file?.virtualFile ?: directory.virtualFile.findChild(filename)
if (file == null && virtualFile == null && createIfMissing) {
try {
file = CreateFileCommandAction(project, directory, fileType).execute()
} catch (throwable: Throwable) {
throwable.printStackTrace()
}
}
return file
}
}
| mit | 77d9358a0705a861dce8b8892de079d5 | 40.09589 | 140 | 0.652833 | 4.874086 | false | false | false | false |
Waboodoo/HTTP-Shortcuts | HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/activities/categories/CategoryAdapter.kt | 1 | 4153 | package ch.rmy.android.http_shortcuts.activities.categories
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.LinearLayout
import androidx.core.view.isVisible
import androidx.recyclerview.widget.RecyclerView
import ch.rmy.android.framework.extensions.context
import ch.rmy.android.framework.extensions.dimen
import ch.rmy.android.framework.extensions.setText
import ch.rmy.android.framework.ui.BaseAdapter
import ch.rmy.android.http_shortcuts.R
import ch.rmy.android.http_shortcuts.data.domains.categories.CategoryId
import ch.rmy.android.http_shortcuts.data.enums.CategoryLayoutType
import ch.rmy.android.http_shortcuts.databinding.ListItemCategoryBinding
import ch.rmy.android.http_shortcuts.extensions.applyTheme
import ch.rmy.android.http_shortcuts.icons.IconView
import ch.rmy.android.http_shortcuts.icons.ShortcutIcon
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.receiveAsFlow
class CategoryAdapter : BaseAdapter<CategoryListItem>() {
sealed interface UserEvent {
data class CategoryClicked(val id: String) : UserEvent
}
private val userEventChannel = Channel<UserEvent>(capacity = Channel.UNLIMITED)
val userEvents: Flow<UserEvent> = userEventChannel.receiveAsFlow()
override fun areItemsTheSame(oldItem: CategoryListItem, newItem: CategoryListItem): Boolean =
oldItem.id == newItem.id
override fun createViewHolder(viewType: Int, parent: ViewGroup, layoutInflater: LayoutInflater): RecyclerView.ViewHolder =
CategoryViewHolder(ListItemCategoryBinding.inflate(layoutInflater, parent, false))
override fun bindViewHolder(holder: RecyclerView.ViewHolder, position: Int, item: CategoryListItem, payloads: List<Any>) {
(holder as CategoryViewHolder).setItem(item)
}
inner class CategoryViewHolder(
private val binding: ListItemCategoryBinding,
) : RecyclerView.ViewHolder(binding.root) {
lateinit var categoryId: CategoryId
private set
init {
binding.root.setOnClickListener {
userEventChannel.trySend(UserEvent.CategoryClicked(categoryId))
}
}
fun setItem(item: CategoryListItem) {
categoryId = item.id
binding.name.setText(item.name)
binding.description.setText(item.description)
binding.name.alpha = if (item.hidden) 0.7f else 1f
updateIcons(item.icons)
updateLayoutTypeIcon(item.layoutType)
}
private fun updateIcons(icons: List<ShortcutIcon>) {
updateIconNumber(icons.size)
icons
.forEachIndexed { index, shortcutIcon ->
val iconView = binding.smallIcons.getChildAt(index) as IconView
iconView.setIcon(shortcutIcon)
}
}
private fun updateIconNumber(number: Int) {
val size = dimen(context, R.dimen.small_icon_size)
while (binding.smallIcons.childCount < number) {
val icon = IconView(context)
icon.layoutParams = LinearLayout.LayoutParams(size, size)
binding.smallIcons.addView(icon)
}
while (binding.smallIcons.childCount > number) {
binding.smallIcons.removeViewAt(0)
}
}
private fun updateLayoutTypeIcon(layoutType: CategoryLayoutType?) {
if (layoutType == null) {
binding.layoutTypeIcon.isVisible = false
} else {
binding.layoutTypeIcon.isVisible = true
binding.layoutTypeIcon.setImageResource(
when (layoutType) {
CategoryLayoutType.LINEAR_LIST -> R.drawable.ic_list
CategoryLayoutType.DENSE_GRID,
CategoryLayoutType.MEDIUM_GRID,
CategoryLayoutType.WIDE_GRID,
-> R.drawable.ic_grid
}
)
binding.layoutTypeIcon.applyTheme()
}
}
}
}
| mit | b2063c044e192b16295dc5e4d02ec4ef | 38.552381 | 126 | 0.665061 | 4.891637 | false | false | false | false |
junkdog/transducers-kotlin | src/main/kotlin/net/onedaybeard/transducers/experimental.kt | 1 | 19241 | package net.onedaybeard.transducers
import java.lang.reflect.Field
import java.util.*
import java.util.concurrent.atomic.AtomicBoolean
import kotlin.reflect.KClass
typealias Xf<A, B> = Transducer<A, B>
typealias Rf<R, A> = ReducingFunction<R, A>
typealias RfOn<R, A, B> = ReducingFunctionOn<R, A, B>
/**
* Conditional transducer, primarily useful for branching transducers.
*
* @see [wires]
* @see [mux]
* @see [resultGate]
*/
data class Signal<out A, B>(val selector: (B) -> Boolean,
val xf: Transducer<A, B>)
private data class SignalRf<in A, in B, R>(val test: (B) -> Boolean,
val rf: ReducingFunction<R, A>)
/**
* Creates a [Signal].
*
* @see [mux]
*/
infix fun <A, B> ((B) -> Boolean).wires(xf: Transducer<A, B>) : Signal<A, B> {
return Signal(this, xf)
}
/**
* Returns a branching transducer, routing each input through
* either [xfTrue] or [xfFalse], depending on the value returned
* by [test].
*
* @sample samples.Samples.branch_a
* @see [mux]
*/
fun <A, B> branch(test: (B) -> Boolean,
xfTrue: Transducer<A, B>,
xfFalse: Transducer<A, B>): Transducer<A, B> {
return mux(test wires xfTrue,
{ _: B -> true } wires xfFalse)
}
/**
* Returns a transducer consuming all input, and then releases the
* input as an [Iterable] collection.
*
* The transducer collects into a list by default, can be changed by
* supplying another [collector]. [collector] is reset after producing the
* final result.
*
* [sort] may change the type of underlying collection. This implies allocation.
*
* @sample samples.Samples.collect_a
* @sample samples.Samples.collect_b
*/
fun <A> collect(
collector: () -> MutableCollection<A> = { mutableListOf<A>() },
sort: (A, A) -> Int
): Xf<Iterable<A>, A> = collect(collector, Comparator(sort))
/**
* Returns a transducer consuming all input, before releasing the
* accumulated input as an [Iterable] collection.
*
* The transducer collects into a list by default; this can be changed by
* supplying another [collector]. [collector] is reset after producing the
* final result.
*
* [sort] may change the type of underlying collection. This implies allocation.
*/
fun <A> collect(
collector: () -> MutableCollection<A> = { mutableListOf<A>() },
sort: Comparator<A>? = null
) = object : Transducer<Iterable<A>, A> {
override fun <R> apply(rf: Rf<R, Iterable<A>>) = object : Rf<R, A> {
var accumulator: MutableCollection<A> = collector()
override fun apply(): R = rf.apply()
override fun apply(result: R): R {
if (accumulator.isEmpty())
return result
val input = if (sort != null)
accumulator.sortedWith(sort) else accumulator
val ret = rf.apply(result, input, AtomicBoolean())
val r = rf.apply(ret)
accumulator = collector()
return r
}
override fun apply(result: R,
input: A,
reduced: AtomicBoolean): R {
accumulator.add(input)
return result
}
}
}
/**
* Returns a transducer counting the number of input.
*/
fun <A> count(): Transducer<Int, A> = sum { _ -> 1 }
/**
* Returns a debug-assisting transducer. This transducer
* prints each input, and the initial plus final results.
*/
fun <A> debug(tag: String, indent: Int = 0) = object : Transducer<A, A> {
override fun <R> apply(rf: ReducingFunction<R, A>): ReducingFunction<R, A> {
val length = 15 + indent
val tagColumn = tag.padEnd(length).replace(' ', '.')
return object : ReducingFunction<R, A> {
override fun apply(): R {
val result = rf.apply()
println("# $tagColumn $result")
return result
}
override fun apply(result: R): R {
val ret = rf.apply(result)
println("!! $tagColumn $ret")
return ret
}
override fun apply(result: R,
input: A,
reduced: AtomicBoolean): R {
println("- $tagColumn $input")
return rf.apply(result, input, reduced)
}
}
}
}
/**
* Returns a transducer which only takes the first [n] elements. Acts
* similar to `cat() + take(n)`, but does not end the reduction process
* after each batch of input.
*
* @see tail
* @see cat
*/
fun <A> head(n: Int): Xf<A, Iterable<A>> = object : Xf<A, Iterable<A>> {
override fun <R> apply(rf: Rf<R, A>) = object : RfOn<R, A, Iterable<A>>(rf) {
override fun apply(result: R,
input: Iterable<A>,
reduced: AtomicBoolean): R {
return transduce(xf = take(n),
rf = { res: R, a: A -> rf.apply(res, a, reduced) },
init = result,
input = input)
}
}
}
private fun <A> headcat(n: Int,
inputOp: (Iterable<A>) -> Iterable<A>)
= object : Xf<A, Iterable<A>> {
override fun <R> apply(rf: Rf<R, A>): Rf<R, Iterable<A>>
= object : RfOn<R, A, Iterable<A>>(rf) {
override fun apply(result: R,
input: Iterable<A>,
reduced: AtomicBoolean): R {
return transduce(xf = take(n),
rf = { res: R, a: A -> rf.apply(res, a, AtomicBoolean()) },
init = result,
input = input)
}
}
}
/**
* Takes a list of transducers producing [A], and turns it into a
* single composed transducer producing a list of [A]. Supplied
* transducers can produce zero or more output per input value,
* and rely on completion to flush any internal state.
*
* If transducers require conditional evaluation, working with [mux]
* in `promiscuous` mode may be an alternative approach, as
* it supports input routing using predicates.
*
* Note that each of the supplied transducers reset the transduction (?)
* state between inputs, thus stateful transducers, such as [distinct], are
* scoped to each input value
*
* @see mux
*/
fun <A, B> join(xfs: List<Xf<A, B>>): Xf<List<A>, B> = object : Xf<List<A>, B> {
override fun <R> apply(rf: Rf<R, List<A>>) = object : RfOn<R, List<A>, B>(rf) {
val subXf = xfs.map { Signal({ true }, it) }
.toTypedArray()
.let { mux(*it, promiscuous = true) }
override fun apply(result: R,
input: B,
reduced: AtomicBoolean): R {
return rf.apply(result,
listOf(subXf, input.withIterable()),
reduced)
}
}
}
fun <A, B> join(vararg xfs: Xf<A, B>): Xf<List<A>, B> = join(xfs.toList())
/**
* Returns a transducer creating [Pair]s, with values provided
* via transducers [l] and [r]. Each value transducer runs a full
* transducible process/lifecycle per input, allowing for
* more sophisticated transducers at the cost of performance.
*
* @see [subduce]
* @sample net.onedaybeard.transducers.ExperimentalTransducersTest.test_subduce
*/
inline fun <B, reified K, reified V> mapPair(l: Xf<K, B>,
r: Xf<V, B>): Xf<Pair<K, V>, B>
where K : Any, V : Any {
return object : Transducer<Pair<K, V>, B> {
override fun <R> apply(rf: Rf<R, Pair<K, V>>): Rf<R, B> {
return object : ReducingFunction<R, B> {
val lRf: Rf<K, B> = subducing(l)
val rRf: Rf<V, B> = subducing(r)
override fun apply(result: R): R = rf.apply(result)
override fun apply(result: R,
input: B,
reduced: AtomicBoolean): R {
return rf.apply(result,
Pair(subduce(lRf, input),
subduce(rRf, input)),
reduced)
}
}
}
}
}
/**
* Returns a multiplexing transducer, routing input through different
* transducers. Transducer route is selected based on the outcome of
* [Signal.selector], evaluated in sequential order. Unmatched input
* are discarded.
*
* Per default, each input is associated with at most _one_ transducer
* route. If [promiscuous] is `true`, input passes through every
* matching transducer.
*
* When all input has been exhausted, each route processes the final
* result. Subsequent transducers are [guarded][resultGate] against
* multiple invocations of `ReducingFunction::apply(result)`.
*
* ```
* <A,B> <B,C> (<B,C>) <C,D>
*
* +-------+
* +-->+ Xf 3a +---+
* | +-------+ |
* | |
* +-------+ +-------+ | +-------+ | +-------+
* | Xf 1 +---->+ mux +------->+ Xf 3b +------>+ Xf 4 |
* +-------+ +-------+ | +-------+ | +-------+
* | |
* | +-------+ |
* +-->+ Xf 3c +---+
* +-------+
*
* ```
*
* Depicted transducers `3a`, `3b` and `3c` may be composed of one or more
* transducers, and can produce zero or many outputs per input value.
* Transducer signature is the same for each route, as given by [mux].
*
* @sample samples.Samples.mux_a
* @sample samples.Samples.mux_b
* @see join
*/
fun <A, B> mux(xfs: List<Signal<A, B>>,
promiscuous: Boolean = false) = muxing(xfs, promiscuous) +
resultGate(xfs.size)
fun <A, B> mux(vararg xfs: Signal<A, B>,
promiscuous: Boolean = false) = muxing(xfs.asIterable(), promiscuous) +
resultGate(xfs.size)
private fun <A, B> muxing(xfs: Iterable<Signal<A, B>>,
promiscuous: Boolean = false) = object : Xf<A, B> {
override fun <R> apply(rf: Rf<R, A>) = object : Rf<R, B> {
val rfs = xfs.map { SignalRf(it.selector, it.xf.apply(rf)) }
override fun apply(result: R): R {
var r = result
for (mux in rfs)
r = mux.rf.apply(r)
return r
}
override fun apply(result: R,
input: B,
reduced: AtomicBoolean): R {
val maxMatchedRfs = if (promiscuous) rfs.size else 1
return transduce(xf = filter { s: SignalRf<B, B, R> -> s.test(input) } +
take(maxMatchedRfs),
rf = { _: R, mux -> mux.rf.apply(result, input, reduced) },
init = result,
input = rfs)
}
}
}
/**
* Returns a transducer concatenating pairs of `Pair<A, Iterable<B>>` into
* `Pair<A, B>`.
*/
fun <F, A> pairCat() = object : Xf<Pair<F, A>, Pair<F, Iterable<A>>> {
override fun <R> apply(rf: ReducingFunction<R, Pair<F, A>>)
= object : RfOn<R, Pair<F, A>, Pair<F, Iterable<A>>>(rf) {
override fun apply(result: R,
input: Pair<F, Iterable<A>>,
reduced: AtomicBoolean) = reducePair(rf,
result,
input,
reduced)
}
}
/**
* Returns a transducer ensuring _completion_ is calculated once, used
* by [branch]ing/[mux]ing transducers.
*/
fun <A> resultGate(count: Int) = object : Transducer<A, A> {
override fun <R> apply(rf: ReducingFunction<R, A>) = object : RfOn<R, A, A>(rf) {
var remaining = count
override fun apply(result: R): R {
remaining--
return when (remaining) {
0 -> rf.apply(result)
!in 0..count -> throw UnsupportedOperationException("negative: $remaining")
else -> result
}
}
override fun apply(result: R,
input: A,
reduced: AtomicBoolean): R {
return rf.apply(result, input, reduced)
}
}
}
/**
* Returns a transducer collecting all input, before releasing
* each element in sorted order.
*/
fun <A> sort(sort: (o1: A, o2: A) -> Int) = collect(sort = sort) +
cat<A>()
/**
* Calculates sum of all input.
*/
fun <A : Number> sum() = sum { i: A -> i }
/**
* Calculates sum based on values produced by [f].
*
* @sample samples.sum_a
*
* Testing for fun...
*
* @sample samples.sum_b
*/
fun <A : Number, B> sum(f: (b: B) -> A) = object : Transducer<A, B> {
override fun <R> apply(rf: Rf<R, A>) = object : Rf<R, B> {
var accumulator: A? = null
override fun apply(): R = rf.apply()
override fun apply(result: R): R {
if (accumulator == null)
return result
val ret = rf.apply(result, accumulator!!, AtomicBoolean())
val r = rf.apply(ret)
accumulator = null
return r
}
override fun apply(result: R,
input: B,
reduced: AtomicBoolean): R {
if (accumulator != null) {
accumulator = accumulator!! + f(input)
} else {
accumulator = f(input)
}
return result
}
@Suppress("UNCHECKED_CAST", "IMPLICIT_CAST_TO_ANY")
private operator fun A.plus(other: A): A {
return when (this) {
is Int -> this + other as Int
is Float -> this + other as Float
is Double -> this + other as Double
is Long -> this + other as Long
is Byte -> this + other as Byte
is Short -> this + other as Short
else -> 0
} as A
}
}
}
/**
* Applies given reducing function to current result and each T in input, using
* the result returned from each reduction step as input to the next step. Returns
* final result.
* @param f a reducing function
* @param result an initial result value
* @param input the input to process
* @param reduced a boolean flag that can be set to indicate that the reducing process
* should stop, even though there is still input to process
* @param <R> the type of the result
* @param <T> the type of each item in input
* @return the final reduced result
*/
fun <R, F, T> reducePair(f: ReducingFunction<R, Pair<F, T>>,
result: R,
input: Pair<F, Iterable<T>>,
reduced: AtomicBoolean = AtomicBoolean()): R {
var ret = result
for (t in input.second) {
ret = f.apply(ret, Pair(input.first, t), reduced)
if (reduced.get()) break
}
return ret
}
/**
* Performs a full transduction on a single input. Typically,
* used in conjunction with [subduce]. Useful for construction
* of pairs, tuples and similar data structures - using
* separate transducers per field.
*
* @see subducing
*/
inline fun <reified A : Any, B> subduce(rf: ReducingFunction<A, B>,
input: B,
reduced: AtomicBoolean = AtomicBoolean()): A {
val r = rf.apply(rf.apply(), input, reduced)
return rf.apply(r)
}
/**
* Returns a specialized [ReducingFunction] for [xf], treating each
* input as a full transducible process - invoking each of the
* three [ReducingFunction.apply] functions once.
*
* An initial result is computed based on the type of [A].
*
* @see subduce
*/
@Suppress("IMPLICIT_CAST_TO_ANY")
inline fun <reified A : Any, B> subducing(xf: Xf<A, B>): Rf<A, B> {
return subducing(xf) {
when (A::class) {
Boolean::class -> false
Byte::class -> 0
Char::class -> ' '
Short::class -> 0
Int::class -> 0
Long::class -> 0
Float::class -> 0
Double::class -> 0
KClass::class -> KClass::class
Field::class -> Dummy().field
Iterable::class -> mutableListOf<Any>()
else -> A::class.java.newInstance()
} as A
}
}
/**
* Returns a specialized [ReducingFunction], treating each
* input as a full transducible process - invoking each of the
* three [ReducingFunction.apply] functions once.
*
* Initial result supplied by [init], invoked once during
* initialization.
*/
inline fun <reified A : Any, B> subducing(xf: Xf<A, B>,
crossinline init: () -> A): Rf<A, B> {
return xf.apply(object : ReducingFunction<A, A> {
var hasDeliveredResult = false
val initial: A = init()
override fun apply(): A {
hasDeliveredResult = false
return initial
}
override fun apply(result: A): A {
if (hasDeliveredResult)
throw RuntimeException("final result already computed")
hasDeliveredResult = true
return result
}
override fun apply(result: A,
input: A,
reduced: AtomicBoolean): A = input
})
}
/**
* Creates a transducer which only processes the last [n] elements
* per input iterable.
*
* @see head
* @see cat
*/
fun <A> tail(n: Int): Xf<A, Iterable<A>> = object : Xf<A, Iterable<A>> {
override fun <R> apply(rf: Rf<R, A>) = object : RfOn<R, A, Iterable<A>>(rf) {
val tailed = LinkedList<A>()
override fun apply(result: R,
input: Iterable<A>,
reduced: AtomicBoolean): R {
var res = result
val reduceAction: (A) -> Unit = { res = rf.apply(res, it, reduced) }
when (input) {
is List<A> -> {
input.takeLast(n).forEach(reduceAction)
}
else -> {
input.forEach { tailed.push(it, maxSize = n) }
tailed.forEach(reduceAction)
tailed.clear()
}
}
return res
}
}
}
internal fun <A> MutableList<A>.push(element: A, maxSize: Int) {
val diff = (size + 1) - maxSize
if (diff > 0)
(1..diff).forEach { removeAt(0) }
add(element)
}
class Dummy {
val field: Field = Dummy::class.java.getDeclaredField("field")
}
| apache-2.0 | 65f3bdb565d35741e6c679c46bcac864 | 30.961794 | 91 | 0.512343 | 3.997715 | false | false | false | false |
solokot/Simple-Gallery | app/src/main/kotlin/com/simplemobiletools/gallery/pro/dialogs/SaveAsDialog.kt | 1 | 3798 | package com.simplemobiletools.gallery.pro.dialogs
import androidx.appcompat.app.AlertDialog
import com.simplemobiletools.commons.activities.BaseSimpleActivity
import com.simplemobiletools.commons.dialogs.ConfirmationDialog
import com.simplemobiletools.commons.dialogs.FilePickerDialog
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.gallery.pro.R
import kotlinx.android.synthetic.main.dialog_save_as.view.*
class SaveAsDialog(val activity: BaseSimpleActivity, val path: String, val appendFilename: Boolean, val cancelCallback: (() -> Unit)? = null,
val callback: (savePath: String) -> Unit) {
init {
var realPath = path.getParentPath()
val view = activity.layoutInflater.inflate(R.layout.dialog_save_as, null).apply {
save_as_path.text = "${activity.humanizePath(realPath).trimEnd('/')}/"
val fullName = path.getFilenameFromPath()
val dotAt = fullName.lastIndexOf(".")
var name = fullName
if (dotAt > 0) {
name = fullName.substring(0, dotAt)
val extension = fullName.substring(dotAt + 1)
save_as_extension.setText(extension)
}
if (appendFilename) {
name += "_1"
}
save_as_name.setText(name)
save_as_path.setOnClickListener {
activity.hideKeyboard(save_as_path)
FilePickerDialog(activity, realPath, false, false, true, true) {
save_as_path.text = activity.humanizePath(it)
realPath = it
}
}
}
AlertDialog.Builder(activity)
.setPositiveButton(R.string.ok, null)
.setNegativeButton(R.string.cancel) { dialog, which -> cancelCallback?.invoke() }
.setOnCancelListener { cancelCallback?.invoke() }
.create().apply {
activity.setupDialogStuff(view, this, R.string.save_as) {
showKeyboard(view.save_as_name)
getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener {
val filename = view.save_as_name.value
val extension = view.save_as_extension.value
if (filename.isEmpty()) {
activity.toast(R.string.filename_cannot_be_empty)
return@setOnClickListener
}
if (extension.isEmpty()) {
activity.toast(R.string.extension_cannot_be_empty)
return@setOnClickListener
}
val newFilename = "$filename.$extension"
val newPath = "${realPath.trimEnd('/')}/$newFilename"
if (!newFilename.isAValidFilename()) {
activity.toast(R.string.filename_invalid_characters)
return@setOnClickListener
}
if (activity.getDoesFilePathExist(newPath)) {
val title = String.format(activity.getString(R.string.file_already_exists_overwrite), newFilename)
ConfirmationDialog(activity, title) {
callback(newPath)
dismiss()
}
} else {
callback(newPath)
dismiss()
}
}
}
}
}
}
| gpl-3.0 | 2c7c3de621f9b205cf27fe02227f2887 | 43.162791 | 141 | 0.506582 | 5.67713 | false | false | false | false |
cnsgcu/KotlinKoans | src/iii_conventions/_30_MultiAssignment.kt | 1 | 519 | package iii_conventions.multiAssignemnt
import util.*
fun todoTask30(): Nothing = TODO(
"""
Task 30.
Read about multi-declarations and make the following code compile by adding one word (after uncommenting it).
""",
documentation = doc30()
)
data class MyDate(val year: Int, val month: Int, val dayOfMonth: Int)
fun isLeapDay(date: MyDate): Boolean {
val (year, month, dayOfMonth) = date
// 29 February of a leap year
return year % 4 == 0 && month == 2 && dayOfMonth == 29
} | mit | 3ebd17c0cd546a0e765335aaa5c35dcc | 25 | 117 | 0.65896 | 3.902256 | false | false | false | false |
ibinti/intellij-community | uast/uast-java/src/org/jetbrains/uast/java/expressions/JavaUSimpleNameReferenceExpression.kt | 6 | 2222 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.uast.java
import com.intellij.psi.*
import org.jetbrains.uast.UElement
import org.jetbrains.uast.USimpleNameReferenceExpression
import org.jetbrains.uast.UTypeReferenceExpression
class JavaUSimpleNameReferenceExpression(
override val psi: PsiElement?,
override val identifier: String,
override val uastParent: UElement?,
val reference: PsiReference? = null
) : JavaAbstractUExpression(), USimpleNameReferenceExpression {
override fun resolve() = (reference ?: psi as? PsiReference)?.resolve()
override val resolvedName: String?
get() = ((reference ?: psi as? PsiReference)?.resolve() as? PsiNamedElement)?.name
}
class JavaUTypeReferenceExpression(
override val psi: PsiTypeElement,
override val uastParent: UElement?
) : JavaAbstractUExpression(), UTypeReferenceExpression {
override val type: PsiType
get() = psi.type
}
class LazyJavaUTypeReferenceExpression(
override val psi: PsiElement,
override val uastParent: UElement?,
private val typeSupplier: () -> PsiType
) : JavaAbstractUExpression(), UTypeReferenceExpression {
override val type: PsiType by lz { typeSupplier() }
}
class JavaClassUSimpleNameReferenceExpression(
override val identifier: String,
val ref: PsiJavaReference,
override val psi: PsiElement,
override val uastParent: UElement?
) : JavaAbstractUExpression(), USimpleNameReferenceExpression {
override fun resolve() = ref.resolve()
override val resolvedName: String?
get() = (ref.resolve() as? PsiNamedElement)?.name
} | apache-2.0 | 31d0d0d1f4c3c7ec18af9d06e92cf96c | 36.677966 | 90 | 0.729073 | 4.982063 | false | false | false | false |
sriharshaarangi/BatteryChargeLimit | app/src/main/java/com/slash/batterychargelimit/ForegroundService.kt | 1 | 5505 | package com.slash.batterychargelimit
import android.app.PendingIntent
import android.app.Service
import android.content.Intent
import android.content.IntentFilter
import android.media.RingtoneManager
import android.os.IBinder
import androidx.core.app.NotificationCompat
import androidx.core.content.ContextCompat
import com.slash.batterychargelimit.Constants.INTENT_DISABLE_ACTION
import com.slash.batterychargelimit.Constants.NOTIFICATION_LIVE
import com.slash.batterychargelimit.Constants.NOTIF_CHARGE
import com.slash.batterychargelimit.Constants.NOTIF_MAINTAIN
import com.slash.batterychargelimit.Constants.SETTINGS
import com.slash.batterychargelimit.activities.MainActivity
import com.slash.batterychargelimit.receivers.BatteryReceiver
import com.slash.batterychargelimit.settings.PrefsFragment
/**
* Created by harsha on 30/1/17.
*
* This is a Service that shows the notification about the current charging state
* and supplies the context to the BatteryReceiver it is registering.
*
* 24/4/17 milux: Changed to make "restart" more efficient by avoiding the need to stop the service
*/
class ForegroundService : Service() {
private val settings by lazy(LazyThreadSafetyMode.NONE) {this.getSharedPreferences(SETTINGS, 0)}
private val prefs by lazy(LazyThreadSafetyMode.NONE) {Utils.getPrefs(this)}
private val mNotifyBuilder by lazy(LazyThreadSafetyMode.NONE) { NotificationCompat.Builder(this, "Charge Limit State") }
private var notifyID = 1
private var autoResetActive = false
private var batteryReceiver: BatteryReceiver? = null
/**
* Enables the automatic reset on service shutdown
*/
fun enableAutoReset() {
autoResetActive = true
}
override fun onCreate() {
isRunning = true
notifyID = 1
settings.edit().putBoolean(NOTIFICATION_LIVE, true).apply()
val notification = mNotifyBuilder
.setPriority(NotificationCompat.PRIORITY_MAX)
.setCategory(NotificationCompat.CATEGORY_SYSTEM)
.setOngoing(true)
.setContentTitle(getString(R.string.please_wait))
.setContentInfo(getString(R.string.please_wait))
.setSmallIcon(R.drawable.ic_notif_charge)
.setColor(ContextCompat.getColor(this, R.color.colorPrimary))
.build()
startForeground(notifyID, notification)
batteryReceiver = BatteryReceiver(this@ForegroundService)
registerReceiver(batteryReceiver, IntentFilter(Intent.ACTION_BATTERY_CHANGED))
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
ignoreAutoReset = false
return super.onStartCommand(intent, flags, startId)
}
fun setNotificationActionText(actionText: String) {
// Clear old actions via reflection
mNotifyBuilder.javaClass.getDeclaredField("mActions").let {
it.isAccessible = true
it.set(mNotifyBuilder, ArrayList<NotificationCompat.Action>())
}
val notificationIntent = Intent(this, MainActivity::class.java)
val pendingIntentApp = PendingIntent.getActivity(this, 0, notificationIntent, 0)
val pendingIntentDisable = PendingIntent.getBroadcast(this, 0, Intent().setAction(INTENT_DISABLE_ACTION), PendingIntent.FLAG_UPDATE_CURRENT)
mNotifyBuilder.addAction(0, actionText, pendingIntentDisable)
.addAction(0, getString(R.string.open_app), pendingIntentApp)
}
fun setNotificationTitle(title: String) {
mNotifyBuilder.setContentTitle(title)
}
fun setNotificationContentText(contentText: String) {
mNotifyBuilder.setContentText(contentText)
}
fun setNotificationIcon(iconType: String) {
if (iconType == NOTIF_MAINTAIN) {
mNotifyBuilder.setSmallIcon(R.drawable.ic_notif_maintain)
} else if (iconType == NOTIF_CHARGE) {
mNotifyBuilder.setSmallIcon(R.drawable.ic_notif_charge)
}
}
fun updateNotification() {
startForeground(notifyID, mNotifyBuilder.build())
}
fun setNotificationSound() {
val soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
mNotifyBuilder.setSound(soundUri)
}
fun removeNotificationSound() {
mNotifyBuilder.setSound(null)
}
override fun onDestroy() {
if (autoResetActive && !ignoreAutoReset && prefs.getBoolean(PrefsFragment.KEY_AUTO_RESET_STATS, false)) {
Utils.resetBatteryStats(this)
}
ignoreAutoReset = false
settings.edit().putBoolean(NOTIFICATION_LIVE, false).apply()
// unregister the battery event receiver
unregisterReceiver(batteryReceiver)
// make the BatteryReceiver and dependencies ready for garbage-collection
batteryReceiver!!.detach(this)
// clear the reference to the battery receiver for GC
batteryReceiver = null
isRunning = false
}
override fun onBind(intent: Intent): IBinder? {
return null
}
companion object {
/**
* Returns whether the service is running right now
*
* @return Whether service is running
*/
var isRunning = false
private var ignoreAutoReset = false
/**
* Ignore the automatic reset when service is shut down the next time
*/
internal fun ignoreAutoReset() {
ignoreAutoReset = true
}
}
}
| gpl-3.0 | 9486acea2175257fee28a029ea0f4cd9 | 35.456954 | 148 | 0.697366 | 4.867374 | false | false | false | false |
elect86/modern-jogl-examples | src/main/kotlin/glNext/tut04/matrixPerspective.kt | 2 | 5506 | package glNext.tut04
import com.jogamp.newt.event.KeyEvent
import com.jogamp.opengl.GL.*
import com.jogamp.opengl.GL3
import glNext.*
import glm.size
import main.framework.Framework
import uno.buffer.destroyBuffers
import uno.buffer.floatBufferOf
import uno.buffer.intBufferBig
import uno.glsl.programOf
/**
* Created by GBarbieri on 22.02.2017.
*/
fun main(args: Array<String>) {
MatrixPerspective_Next().setup("Tutorial 04 - Matrix Perspective")
}
class MatrixPerspective_Next : Framework() {
var theProgram = 0
var offsetUniform = 0
val vertexBufferObject = intBufferBig(1)
val vao = intBufferBig(1)
var perspectiveMatrix = FloatArray(16)
override fun init(gl: GL3) = with(gl) {
initializeProgram(gl)
initializeVertexBuffer(gl)
glGenVertexArray(vao)
glBindVertexArray(vao)
cullFace {
enable()
cullFace = back
frontFace = cw
}
}
fun initializeProgram(gl: GL3) = with(gl) {
theProgram = programOf(gl, javaClass, "tut04", "matrix-perspective.vert", "standard-colors.frag")
withProgram(theProgram) {
offsetUniform = "offset".location
val perspectiveMatrixUnif = "perspectiveMatrix".location
val frustumScale = 1.0f
val zNear = 0.5f
val zFar = 3.0f
perspectiveMatrix[0] = frustumScale
perspectiveMatrix[5] = frustumScale
perspectiveMatrix[10] = (zFar + zNear) / (zNear - zFar)
perspectiveMatrix[14] = 2f * zFar * zNear / (zNear - zFar)
perspectiveMatrix[11] = -1.0f
use { glUniformMatrix4f(perspectiveMatrixUnif, perspectiveMatrix) }
}
}
fun initializeVertexBuffer(gl: GL3) = gl.initArrayBuffer(vertexBufferObject){data(vertexData, GL_STATIC_DRAW)}
override fun display(gl: GL3) = with(gl) {
clear { color(0) }
usingProgram(theProgram) {
glUniform2f(offsetUniform, 0.5f)
val colorData = vertexData.size / 2
withVertexLayout(vertexBufferObject, glf.pos4_col4, 0, colorData) { glDrawArrays(36) }
}
}
override fun reshape(gl: GL3, w: Int, h: Int) = with(gl) {
glViewport(w, h)
}
override fun end(gl: GL3) = with(gl) {
glDeleteProgram(theProgram)
glDeleteBuffer(vertexBufferObject)
glDeleteVertexArray(vao)
destroyBuffers(vao, vertexBufferObject, vertexData)
}
override fun keyPressed(keyEvent: KeyEvent) {
when (keyEvent.keyCode) {
KeyEvent.VK_ESCAPE -> quit()
}
}
val vertexData = floatBufferOf(
+0.25f, +0.25f, -1.25f, 1.0f,
+0.25f, -0.25f, -1.25f, 1.0f,
-0.25f, +0.25f, -1.25f, 1.0f,
+0.25f, -0.25f, -1.25f, 1.0f,
-0.25f, -0.25f, -1.25f, 1.0f,
-0.25f, +0.25f, -1.25f, 1.0f,
+0.25f, +0.25f, -2.75f, 1.0f,
-0.25f, +0.25f, -2.75f, 1.0f,
+0.25f, -0.25f, -2.75f, 1.0f,
+0.25f, -0.25f, -2.75f, 1.0f,
-0.25f, +0.25f, -2.75f, 1.0f,
-0.25f, -0.25f, -2.75f, 1.0f,
-0.25f, +0.25f, -1.25f, 1.0f,
-0.25f, -0.25f, -1.25f, 1.0f,
-0.25f, -0.25f, -2.75f, 1.0f,
-0.25f, +0.25f, -1.25f, 1.0f,
-0.25f, -0.25f, -2.75f, 1.0f,
-0.25f, +0.25f, -2.75f, 1.0f,
+0.25f, +0.25f, -1.25f, 1.0f,
+0.25f, -0.25f, -2.75f, 1.0f,
+0.25f, -0.25f, -1.25f, 1.0f,
+0.25f, +0.25f, -1.25f, 1.0f,
+0.25f, +0.25f, -2.75f, 1.0f,
+0.25f, -0.25f, -2.75f, 1.0f,
+0.25f, +0.25f, -2.75f, 1.0f,
+0.25f, +0.25f, -1.25f, 1.0f,
-0.25f, +0.25f, -1.25f, 1.0f,
+0.25f, +0.25f, -2.75f, 1.0f,
-0.25f, +0.25f, -1.25f, 1.0f,
-0.25f, +0.25f, -2.75f, 1.0f,
+0.25f, -0.25f, -2.75f, 1.0f,
-0.25f, -0.25f, -1.25f, 1.0f,
+0.25f, -0.25f, -1.25f, 1.0f,
+0.25f, -0.25f, -2.75f, 1.0f,
-0.25f, -0.25f, -2.75f, 1.0f,
-0.25f, -0.25f, -1.25f, 1.0f,
0.0f, 0.0f, 1.0f, 1.0f,
0.0f, 0.0f, 1.0f, 1.0f,
0.0f, 0.0f, 1.0f, 1.0f,
0.0f, 0.0f, 1.0f, 1.0f,
0.0f, 0.0f, 1.0f, 1.0f,
0.0f, 0.0f, 1.0f, 1.0f,
0.8f, 0.8f, 0.8f, 1.0f,
0.8f, 0.8f, 0.8f, 1.0f,
0.8f, 0.8f, 0.8f, 1.0f,
0.8f, 0.8f, 0.8f, 1.0f,
0.8f, 0.8f, 0.8f, 1.0f,
0.8f, 0.8f, 0.8f, 1.0f,
0.0f, 1.0f, 0.0f, 1.0f,
0.0f, 1.0f, 0.0f, 1.0f,
0.0f, 1.0f, 0.0f, 1.0f,
0.0f, 1.0f, 0.0f, 1.0f,
0.0f, 1.0f, 0.0f, 1.0f,
0.0f, 1.0f, 0.0f, 1.0f,
0.5f, 0.5f, 0.0f, 1.0f,
0.5f, 0.5f, 0.0f, 1.0f,
0.5f, 0.5f, 0.0f, 1.0f,
0.5f, 0.5f, 0.0f, 1.0f,
0.5f, 0.5f, 0.0f, 1.0f,
0.5f, 0.5f, 0.0f, 1.0f,
1.0f, 0.0f, 0.0f, 1.0f,
1.0f, 0.0f, 0.0f, 1.0f,
1.0f, 0.0f, 0.0f, 1.0f,
1.0f, 0.0f, 0.0f, 1.0f,
1.0f, 0.0f, 0.0f, 1.0f,
1.0f, 0.0f, 0.0f, 1.0f,
0.0f, 1.0f, 1.0f, 1.0f,
0.0f, 1.0f, 1.0f, 1.0f,
0.0f, 1.0f, 1.0f, 1.0f,
0.0f, 1.0f, 1.0f, 1.0f,
0.0f, 1.0f, 1.0f, 1.0f,
0.0f, 1.0f, 1.0f, 1.0f)
} | mit | 0919ce1367f5534f706c9dfdbc51bc50 | 26.262376 | 114 | 0.483109 | 2.450378 | false | false | false | false |
willowtreeapps/assertk | assertk/src/commonTest/kotlin/test/assertk/assertions/ThrowableTest.kt | 1 | 4191 | package test.assertk.assertions
import assertk.assertThat
import assertk.assertions.*
import test.assertk.exceptionPackageName
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFails
class ThrowableTest {
val rootCause = Exception("rootCause")
val cause = Exception("cause", rootCause)
val subject = Exception("test", cause)
@Test fun extracts_message() {
assertEquals(subject.message, assertThat(subject).message().valueOrFail)
}
@Test fun extracts_cause() {
assertEquals(cause, assertThat(subject).cause().valueOrFail)
}
@Test fun extracts_root_cause() {
assertEquals(rootCause, assertThat(subject).rootCause().valueOrFail)
}
//region hasMessage
@Test fun hasMessage_same_message_passes() {
assertThat(subject).hasMessage("test")
}
@Test fun hasMessage_different_message_fails() {
val error = assertFails {
assertThat(subject).hasMessage("not test")
}
assertEquals("expected [message]:<\"[not ]test\"> but was:<\"[]test\"> ($subject)", error.message)
}
//endregion
//region messageContains
@Test fun messageContains_similar_message_passes() {
assertThat(subject).messageContains("es")
}
@Test fun messageContains_different_message_fails() {
val error = assertFails {
assertThat(subject).messageContains("not")
}
assertEquals("expected [message] to contain:<\"not\"> but was:<\"test\"> ($subject)", error.message)
}
//endregion
//region hasCause
@Test fun hasCause_same_type_and_message_passes() {
assertThat(subject).hasCause(Exception("cause"))
}
@Test fun hasCause_no_cause_fails() {
val causeless = Exception("test")
val error = assertFails {
assertThat(causeless).hasCause(cause)
}
assertEquals(
"expected [cause] to not be null ($subject)",
error.message
)
}
@Test fun hasCause_different_message_fails() {
val wrongCause = Exception("wrong")
val error = assertFails {
assertThat(subject).hasCause(wrongCause)
}
assertEquals(
"expected [cause.message]:<\"[wrong]\"> but was:<\"[cause]\"> ($subject)",
error.message
)
}
@Test fun hasCause_different_type_fails() {
val wrongCause = IllegalArgumentException("cause")
val error = assertFails {
assertThat(subject).hasCause(wrongCause)
}
assertEquals(
"expected [cause.class]:<class $exceptionPackageName[IllegalArgument]Exception> but was:<class $exceptionPackageName[]Exception> ($subject)",
error.message
)
}
//endregion
//region hasNoCause
@Test fun hasNoCause_no_cause_passes() {
val causeless = Exception("test")
assertThat(causeless).hasNoCause()
}
@Test fun hasNoCause_cause_fails() {
val error = assertFails {
assertThat(subject).hasNoCause()
}
assertEquals("expected [cause] to be null but was:<$cause> ($subject)", error.message)
}
//endregion
//region hasRootCause
@Test fun hasRootCause_same_root_cause_type_and_message_passes() {
assertThat(subject).hasRootCause(Exception("rootCause"))
}
@Test fun hasRootCause_wrong_cause_type_fails() {
val wrongCause = IllegalArgumentException("rootCause")
val error = assertFails {
assertThat(subject).hasRootCause(wrongCause)
}
assertEquals(
"expected [rootCause.class]:<class $exceptionPackageName[IllegalArgument]Exception> but was:<class $exceptionPackageName[]Exception> ($subject)",
error.message
)
}
@Test fun hasRootCause_wrong_cause_message_fails() {
val wrongCause = Exception("wrong")
val error = assertFails {
assertThat(subject).hasRootCause(wrongCause)
}
assertEquals(
"expected [rootCause.message]:<\"[wrong]\"> but was:<\"[rootCause]\"> ($subject)",
error.message
)
}
//endregion
}
| mit | 2630da5f636af98009ca5855d6443aba | 30.276119 | 157 | 0.622524 | 4.521036 | false | true | false | false |
itachi1706/CheesecakeUtilities | app/src/main/java/com/itachi1706/cheesecakeutilities/modules/barcodeTools/BarcodeHistoryActivity.kt | 1 | 2336 | package com.itachi1706.cheesecakeutilities.modules.barcodeTools
import android.content.Context
import android.os.Bundle
import android.view.MenuItem
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import com.itachi1706.cheesecakeutilities.R
import com.itachi1706.cheesecakeutilities.modules.barcodeTools.fragments.BarcodeHistoryFragment
import com.itachi1706.helperlib.helpers.PrefHelper
import kotlinx.android.synthetic.main.activity_viewpager_frag.*
class BarcodeHistoryActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_viewpager_frag)
setSupportActionBar(toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
tab_layout.tabMode = TabLayout.MODE_FIXED
tab_layout.tabGravity = TabLayout.GRAVITY_FILL
view_pager.adapter = BarcodeHistoryTabAdapter(this)
val tabs = arrayOf("Scanned", "Generated")
TabLayoutMediator(tab_layout, view_pager) { tab, position -> tab.text = tabs[position] }.attach()
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
return if (item?.itemId == android.R.id.home) { finish(); true }
else super.onOptionsItemSelected(item)
}
class BarcodeHistoryTabAdapter(val activity: FragmentActivity): FragmentStateAdapter(activity) {
override fun getItemCount(): Int { return 2 }
override fun createFragment(position: Int): Fragment {
return BarcodeHistoryFragment.newInstance(getBarcodeString(activity.applicationContext, position), if (position == 0) BarcodeHelper.SP_BARCODE_SCANNED else BarcodeHelper.SP_BARCODE_GENERATED)
}
}
companion object {
@JvmStatic
fun getBarcodeString(context: Context, pos: Int): String {
val sp = PrefHelper.getSharedPreferences(context, "BarcodeHistory")
return if (pos == 0) sp.getString(BarcodeHelper.SP_BARCODE_SCANNED, "")!!
else sp.getString(BarcodeHelper.SP_BARCODE_GENERATED, "")!!
}
}
}
| mit | a4fd1083856494899b1f9ef7716523ee | 43.923077 | 203 | 0.746147 | 4.709677 | false | false | false | false |
kittinunf/ReactiveAndroid | reactiveandroid-ui/src/main/kotlin/com/github/kittinunf/reactiveandroid/widget/PopupMenuEvent.kt | 1 | 1075 | package com.github.kittinunf.reactiveandroid.widget
import android.view.MenuItem
import android.widget.PopupMenu
import com.github.kittinunf.reactiveandroid.subscription.AndroidMainThreadSubscription
import io.reactivex.Observable
//================================================================================
// Events
//================================================================================
fun PopupMenu.rx_dismiss(): Observable<PopupMenu> {
return Observable.create { subscriber ->
setOnDismissListener {
subscriber.onNext(it)
}
subscriber.setDisposable(AndroidMainThreadSubscription {
setOnDismissListener(null)
})
}
}
fun PopupMenu.rx_menuItemClick(consumed: Boolean): Observable<MenuItem> {
return Observable.create { subscriber ->
setOnMenuItemClickListener {
subscriber.onNext(it)
consumed
}
subscriber.setDisposable(AndroidMainThreadSubscription {
setOnMenuItemClickListener(null)
})
}
}
| mit | aa52da63c5f254047729b34c6f7490d1 | 28.861111 | 86 | 0.580465 | 6.39881 | false | false | false | false |
quarck/CalendarNotification | app/src/main/java/com/github/quarck/calnotify/ui/AboutActivity.kt | 1 | 2974 | //
// Calendar Notifications Plus
// Copyright (C) 2016 Sergey Parshin ([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, write to the Free Software Foundation,
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
package com.github.quarck.calnotify.ui
import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.Toolbar
import android.view.View
import android.widget.TextView
import com.github.quarck.calnotify.BuildConfig
import com.github.quarck.calnotify.R
import com.github.quarck.calnotify.utils.find
import java.text.SimpleDateFormat
import java.util.*
//TODO include kotlin runtime and language version in the about dialog
class AboutActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_about)
setSupportActionBar(find<Toolbar?>(R.id.toolbar))
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setDisplayShowHomeEnabled(true)
val versionText = find<TextView?>(R.id.text_view_app_version)
val pInfo = packageManager.getPackageInfo(packageName, 0);
versionText?.text = pInfo.versionName
val buildTime = find<TextView?>(R.id.text_view_app_build_time)
buildTime?.text = String.format(resources.getString(R.string.build_time_string_format), getBuildDate())
}
fun getBuildDate(): String {
return SimpleDateFormat.getInstance().format(Date(BuildConfig.TIMESTAMP));
}
@Suppress("UNUSED_PARAMETER", "unused")
fun OnTextViewCreditsClick(v: View) = startActivity(Intent.parseUri(imageCreditUri, 0))
@Suppress("UNUSED_PARAMETER", "unused")
fun OnTextViewKotlinClick(v: View) = startActivity(Intent.parseUri(kotlinUri, 0))
@Suppress("UNUSED_PARAMETER", "unused")
fun OnTextViewGitHubClick(v: View) = startActivity(Intent.parseUri(githubUri, 0))
@Suppress("UNUSED_PARAMETER", "unused")
fun onPrivacyPolicy(v: View) = startActivity(Intent(this, PrivacyPolicyActivity::class.java))
companion object {
val imageCreditUri = "http://cornmanthe3rd.deviantart.com/"
val kotlinUri = "https://kotlinlang.org/"
val githubUri = "https://github.com/quarck/CalendarNotification"
}
}
| gpl-3.0 | 1dcc5955cbf0e01d2c4cff03d3cf3b09 | 37.623377 | 111 | 0.734364 | 4.182841 | false | false | false | false |
Blankj/AndroidUtilCode | feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/permission/PermissionActivity.kt | 1 | 8247 | package com.blankj.utilcode.pkg.feature.permission
import android.Manifest.permission
import android.content.Context
import android.content.Intent
import android.os.Build
import com.blankj.common.activity.CommonActivity
import com.blankj.common.helper.PermissionHelper
import com.blankj.common.item.CommonItem
import com.blankj.common.item.CommonItemClick
import com.blankj.common.item.CommonItemSwitch
import com.blankj.common.item.CommonItemTitle
import com.blankj.utilcode.constant.PermissionConstants
import com.blankj.utilcode.pkg.R
import com.blankj.utilcode.util.*
/**
* ```
* author: Blankj
* blog : http://blankj.com
* time : 2018/01/01
* desc : demo about PermissionUtils
* ```
*/
class PermissionActivity : CommonActivity() {
companion object {
fun start(context: Context) {
val starter = Intent(context, PermissionActivity::class.java)
context.startActivity(starter)
}
}
private val permissions: String
init {
val permissionList = PermissionUtils.getPermissions()
if (permissionList.isEmpty()) {
permissions = ""
} else {
val sb = StringBuilder()
for (permission in permissionList) {
sb.append("\n").append(permission.substring(permission.lastIndexOf('.') + 1))
}
permissions = sb.deleteCharAt(0).toString()
}
}
override fun bindTitleRes(): Int {
return R.string.demo_permission
}
override fun bindItems(): MutableList<CommonItem<*>> {
return CollectionUtils.newArrayList<CommonItem<*>>().apply {
add(CommonItemTitle("Permissions", permissions))
add(CommonItemClick(R.string.permission_open_app_settings, true) { PermissionUtils.launchAppDetailsSettings() })
add(CommonItemSwitch(
R.string.permission_calendar_status,
{ PermissionUtils.isGranted(PermissionConstants.CALENDAR) },
{ requestCalendar() }
))
add(CommonItemSwitch(
R.string.permission_record_audio_status,
{ PermissionUtils.isGranted(PermissionConstants.MICROPHONE) },
{ requestRecordAudio() }
))
add(CommonItemSwitch(
R.string.permission_calendar_and_record_audio_status,
{ PermissionUtils.isGranted(PermissionConstants.CALENDAR, PermissionConstants.MICROPHONE) },
{ requestCalendarAndRecordAudio() }
))
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
add(CommonItemSwitch(
R.string.permission_write_settings_status,
{ PermissionUtils.isGrantedWriteSettings() },
{ requestWriteSettings() }
))
add(CommonItemSwitch(
R.string.permission_write_settings_status,
{ PermissionUtils.isGrantedDrawOverlays() },
{ requestDrawOverlays() }
))
}
}
}
private fun requestCalendar() {
PermissionUtils.permissionGroup(PermissionConstants.CALENDAR)
.rationale { activity, shouldRequest -> PermissionHelper.showRationaleDialog(activity, shouldRequest) }
.callback(object : PermissionUtils.FullCallback {
override fun onGranted(permissionsGranted: List<String>) {
LogUtils.d(permissionsGranted)
showSnackbar(true, "Calendar is granted")
itemsView.updateItems(bindItems())
}
override fun onDenied(permissionsDeniedForever: List<String>,
permissionsDenied: List<String>) {
LogUtils.d(permissionsDeniedForever, permissionsDenied)
if (permissionsDeniedForever.isNotEmpty()) {
showSnackbar(false, "Calendar is denied forever")
} else {
showSnackbar(false, "Calendar is denied")
}
itemsView.updateItems(bindItems())
}
})
.theme { activity -> ScreenUtils.setFullScreen(activity) }
.request()
}
private fun requestRecordAudio() {
PermissionUtils.permissionGroup(PermissionConstants.MICROPHONE)
.rationale { activity, shouldRequest -> PermissionHelper.showRationaleDialog(activity, shouldRequest) }
.callback(object : PermissionUtils.FullCallback {
override fun onGranted(permissionsGranted: List<String>) {
LogUtils.d(permissionsGranted)
showSnackbar(true, "Microphone is granted")
itemsView.updateItems(bindItems())
}
override fun onDenied(permissionsDeniedForever: List<String>,
permissionsDenied: List<String>) {
LogUtils.d(permissionsDeniedForever, permissionsDenied)
if (permissionsDeniedForever.isNotEmpty()) {
showSnackbar(false, "Microphone is denied forever")
} else {
showSnackbar(false, "Microphone is denied")
}
itemsView.updateItems(bindItems())
}
})
.request()
}
private fun requestCalendarAndRecordAudio() {
PermissionUtils.permission(permission.READ_CALENDAR, permission.RECORD_AUDIO)
.explain { activity, denied, shouldRequest -> PermissionHelper.showExplainDialog(activity, denied, shouldRequest) }
.callback { isAllGranted, granted, deniedForever, denied ->
LogUtils.d(granted, deniedForever, denied)
itemsView.updateItems(bindItems())
if (isAllGranted) {
showSnackbar(true, "Calendar and Microphone are granted")
return@callback
}
if (deniedForever.isNotEmpty()) {
showSnackbar(false, "Calendar or Microphone is denied forever")
} else {
showSnackbar(false, "Calendar or Microphone is denied")
}
}
.request()
}
private fun requestWriteSettings() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
PermissionUtils.requestWriteSettings(object : PermissionUtils.SimpleCallback {
override fun onGranted() {
showSnackbar(true, "Write Settings is granted")
itemsView.updateItems(bindItems())
}
override fun onDenied() {
showSnackbar(false, "Write Settings is denied")
itemsView.updateItems(bindItems())
}
})
}
}
private fun requestDrawOverlays() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
PermissionUtils.requestDrawOverlays(object : PermissionUtils.SimpleCallback {
override fun onGranted() {
showSnackbar(true, "Draw Overlays is granted")
itemsView.updateItems(bindItems())
}
override fun onDenied() {
showSnackbar(false, "Draw Overlays is denied")
itemsView.updateItems(bindItems())
}
})
}
}
private fun showSnackbar(isSuccess: Boolean, msg: String) {
SnackbarUtils.with(mContentView)
.setDuration(SnackbarUtils.LENGTH_LONG)
.setMessage(msg)
.apply {
if (isSuccess) {
showSuccess()
} else {
showError()
}
}
}
}
| apache-2.0 | 09504c96231b43019202ebdbc7cf0179 | 40.235 | 131 | 0.548078 | 5.767133 | false | false | false | false |
MaibornWolff/codecharta | analysis/tools/ccsh/src/main/kotlin/de/maibornwolff/codecharta/tools/ccsh/Ccsh.kt | 1 | 5241 | package de.maibornwolff.codecharta.tools.ccsh
import de.maibornwolff.codecharta.exporter.csv.CSVExporter
import de.maibornwolff.codecharta.filter.edgefilter.EdgeFilter
import de.maibornwolff.codecharta.filter.mergefilter.MergeFilter
import de.maibornwolff.codecharta.filter.structuremodifier.StructureModifier
import de.maibornwolff.codecharta.importer.codemaat.CodeMaatImporter
import de.maibornwolff.codecharta.importer.csv.CSVImporter
import de.maibornwolff.codecharta.importer.gitlogparser.GitLogParser
import de.maibornwolff.codecharta.importer.metricgardenerimporter.MetricGardenerImporter
import de.maibornwolff.codecharta.importer.sonar.SonarImporterMain
import de.maibornwolff.codecharta.importer.sourcecodeparser.SourceCodeParserMain
import de.maibornwolff.codecharta.importer.sourcemonitor.SourceMonitorImporter
import de.maibornwolff.codecharta.importer.svnlogparser.SVNLogParser
import de.maibornwolff.codecharta.importer.tokeiimporter.TokeiImporter
import de.maibornwolff.codecharta.parser.rawtextparser.RawTextParser
import de.maibornwolff.codecharta.tools.ccsh.parser.ParserService
import de.maibornwolff.codecharta.tools.validation.ValidationTool
import mu.KotlinLogging
import picocli.CommandLine
import java.util.concurrent.Callable
import kotlin.system.exitProcess
@CommandLine.Command(
name = "ccsh",
description = ["Command Line Interface for CodeCharta analysis"],
subcommands = [
ValidationTool::class,
MergeFilter::class,
EdgeFilter::class,
StructureModifier::class,
CSVImporter::class,
SonarImporterMain::class,
SourceMonitorImporter::class,
SVNLogParser::class,
GitLogParser::class,
Installer::class,
CSVExporter::class,
SourceCodeParserMain::class,
CodeMaatImporter::class,
TokeiImporter::class,
RawTextParser::class,
MetricGardenerImporter::class
],
versionProvider = Ccsh.ManifestVersionProvider::class,
footer = ["Copyright(c) 2022, MaibornWolff GmbH"]
)
class Ccsh : Callable<Void?> {
@CommandLine.Option(
names = ["-v", "--version"],
versionHelp = true,
description = ["prints version info and exits"]
)
var versionRequested: Boolean = false
@CommandLine.Option(names = ["-h", "--help"], usageHelp = true, description = ["displays this help and exit"])
var help: Boolean = false
override fun call(): Void? {
// info: always run
return null
}
companion object {
private val logger = KotlinLogging.logger {}
@JvmStatic
fun main(args: Array<String>) {
exitProcess(executeCommandLine(args))
}
fun executeCommandLine(args: Array<String>): Int {
val commandLine = CommandLine(Ccsh())
commandLine.executionStrategy = CommandLine.RunAll()
if (args.isEmpty() || isParserUnknown(args, commandLine)) {
return executeInteractiveParser(commandLine)
} else {
return commandLine.execute(*sanitizeArgs(args))
}
}
private fun executeInteractiveParser(commandLine: CommandLine): Int {
val selectedParser = ParserService.selectParser(commandLine)
logger.info { "Executing $selectedParser" }
return ParserService.executeSelectedParser(commandLine, selectedParser)
}
private fun isParserUnknown(args: Array<String>, commandLine: CommandLine): Boolean {
if (args.isNotEmpty()) {
val firstArg = args.first()
val parserList = commandLine.subcommands.keys
val optionsList = commandLine.commandSpec.options().map { it.names().toMutableList() }.flatten()
return !parserList.contains(firstArg) && !optionsList.contains(firstArg)
}
return false
}
private fun sanitizeArgs(args: Array<String>): Array<String> {
return args.map { argument ->
var sanitizedArg = ""
if (argument.length > 1 && argument.substring(0, 2) == ("--")) {
var skip = false
argument.forEach {
if (it == '=') skip = true
if (it.isUpperCase() && !skip) sanitizedArg += "-" + it.lowercaseChar()
else sanitizedArg += it
}
} else {
sanitizedArg = argument
}
return@map sanitizedArg
}.toTypedArray()
}
}
object ManifestVersionProvider : CommandLine.IVersionProvider {
override fun getVersion(): Array<String> {
return arrayOf(
Ccsh::class.java.`package`.implementationTitle + "\n" +
"version \"" + Ccsh::class.java.`package`.implementationVersion + "\"\n" +
"Copyright(c) 2022, MaibornWolff GmbH"
)
}
}
}
@CommandLine.Command(name = "install", description = ["[deprecated]: does nothing"])
class Installer : Callable<Void?> {
override fun call(): Void? {
println("[deprecated]: does nothing")
return null
}
}
| bsd-3-clause | f428dea422bf2577d8fa32458d82138d | 37.255474 | 114 | 0.647968 | 4.834871 | false | false | false | false |
NoodleMage/tachiyomi | app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryController.kt | 2 | 17860 | package eu.kanade.tachiyomi.ui.library
import android.app.Activity
import android.content.Intent
import android.content.res.Configuration
import android.graphics.Color
import android.os.Bundle
import android.support.design.widget.TabLayout
import android.support.v4.graphics.drawable.DrawableCompat
import android.support.v4.widget.DrawerLayout
import android.support.v7.app.AppCompatActivity
import android.support.v7.view.ActionMode
import android.support.v7.widget.SearchView
import android.view.*
import com.bluelinelabs.conductor.ControllerChangeHandler
import com.bluelinelabs.conductor.ControllerChangeType
import com.f2prateek.rx.preferences.Preference
import com.jakewharton.rxbinding.support.v4.view.pageSelections
import com.jakewharton.rxbinding.support.v7.widget.queryTextChanges
import com.jakewharton.rxrelay.BehaviorRelay
import com.jakewharton.rxrelay.PublishRelay
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.database.models.Category
import eu.kanade.tachiyomi.data.database.models.Manga
import eu.kanade.tachiyomi.data.library.LibraryUpdateService
import eu.kanade.tachiyomi.data.preference.PreferencesHelper
import eu.kanade.tachiyomi.data.preference.getOrDefault
import eu.kanade.tachiyomi.ui.base.controller.NucleusController
import eu.kanade.tachiyomi.ui.base.controller.SecondaryDrawerController
import eu.kanade.tachiyomi.ui.base.controller.TabbedController
import eu.kanade.tachiyomi.ui.base.controller.withFadeTransaction
import eu.kanade.tachiyomi.ui.category.CategoryController
import eu.kanade.tachiyomi.ui.main.MainActivity
import eu.kanade.tachiyomi.ui.manga.MangaController
import eu.kanade.tachiyomi.ui.migration.MigrationController
import eu.kanade.tachiyomi.util.inflate
import eu.kanade.tachiyomi.util.toast
import kotlinx.android.synthetic.main.library_controller.*
import kotlinx.android.synthetic.main.main_activity.*
import rx.Subscription
import timber.log.Timber
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get
import java.io.IOException
class LibraryController(
bundle: Bundle? = null,
private val preferences: PreferencesHelper = Injekt.get()
) : NucleusController<LibraryPresenter>(bundle),
TabbedController,
SecondaryDrawerController,
ActionMode.Callback,
ChangeMangaCategoriesDialog.Listener,
DeleteLibraryMangasDialog.Listener {
/**
* Position of the active category.
*/
var activeCategory: Int = preferences.lastUsedCategory().getOrDefault()
private set
/**
* Action mode for selections.
*/
private var actionMode: ActionMode? = null
/**
* Library search query.
*/
private var query = ""
/**
* Currently selected mangas.
*/
val selectedMangas = mutableListOf<Manga>()
private var selectedCoverManga: Manga? = null
/**
* Relay to notify the UI of selection updates.
*/
val selectionRelay: PublishRelay<LibrarySelectionEvent> = PublishRelay.create()
/**
* Relay to notify search query changes.
*/
val searchRelay: BehaviorRelay<String> = BehaviorRelay.create()
/**
* Relay to notify the library's viewpager for updates.
*/
val libraryMangaRelay: BehaviorRelay<LibraryMangaEvent> = BehaviorRelay.create()
/**
* Number of manga per row in grid mode.
*/
var mangaPerRow = 0
private set
/**
* Adapter of the view pager.
*/
private var adapter: LibraryAdapter? = null
/**
* Navigation view containing filter/sort/display items.
*/
private var navView: LibraryNavigationView? = null
/**
* Drawer listener to allow swipe only for closing the drawer.
*/
private var drawerListener: DrawerLayout.DrawerListener? = null
private var tabsVisibilityRelay: BehaviorRelay<Boolean> = BehaviorRelay.create(false)
private var tabsVisibilitySubscription: Subscription? = null
private var searchViewSubscription: Subscription? = null
init {
setHasOptionsMenu(true)
retainViewMode = RetainViewMode.RETAIN_DETACH
}
override fun getTitle(): String? {
return resources?.getString(R.string.label_library)
}
override fun createPresenter(): LibraryPresenter {
return LibraryPresenter()
}
override fun inflateView(inflater: LayoutInflater, container: ViewGroup): View {
return inflater.inflate(R.layout.library_controller, container, false)
}
override fun onViewCreated(view: View) {
super.onViewCreated(view)
adapter = LibraryAdapter(this)
library_pager.adapter = adapter
library_pager.pageSelections().skip(1).subscribeUntilDestroy {
preferences.lastUsedCategory().set(it)
activeCategory = it
}
getColumnsPreferenceForCurrentOrientation().asObservable()
.doOnNext { mangaPerRow = it }
.skip(1)
// Set again the adapter to recalculate the covers height
.subscribeUntilDestroy { reattachAdapter() }
if (selectedMangas.isNotEmpty()) {
createActionModeIfNeeded()
}
}
override fun onChangeStarted(handler: ControllerChangeHandler, type: ControllerChangeType) {
super.onChangeStarted(handler, type)
if (type.isEnter) {
activity?.tabs?.setupWithViewPager(library_pager)
presenter.subscribeLibrary()
}
}
override fun onDestroyView(view: View) {
adapter?.onDestroy()
adapter = null
actionMode = null
tabsVisibilitySubscription?.unsubscribe()
tabsVisibilitySubscription = null
super.onDestroyView(view)
}
override fun createSecondaryDrawer(drawer: DrawerLayout): ViewGroup {
val view = drawer.inflate(R.layout.library_drawer) as LibraryNavigationView
navView = view
drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED, Gravity.END)
navView?.onGroupClicked = { group ->
when (group) {
is LibraryNavigationView.FilterGroup -> onFilterChanged()
is LibraryNavigationView.SortGroup -> onSortChanged()
is LibraryNavigationView.DisplayGroup -> reattachAdapter()
is LibraryNavigationView.BadgeGroup -> onDownloadBadgeChanged()
}
}
return view
}
override fun cleanupSecondaryDrawer(drawer: DrawerLayout) {
navView = null
}
override fun configureTabs(tabs: TabLayout) {
with(tabs) {
tabGravity = TabLayout.GRAVITY_CENTER
tabMode = TabLayout.MODE_SCROLLABLE
}
tabsVisibilitySubscription?.unsubscribe()
tabsVisibilitySubscription = tabsVisibilityRelay.subscribe { visible ->
val tabAnimator = (activity as? MainActivity)?.tabAnimator
if (visible) {
tabAnimator?.expand()
} else {
tabAnimator?.collapse()
}
}
}
override fun cleanupTabs(tabs: TabLayout) {
tabsVisibilitySubscription?.unsubscribe()
tabsVisibilitySubscription = null
}
fun onNextLibraryUpdate(categories: List<Category>, mangaMap: Map<Int, List<LibraryItem>>) {
val view = view ?: return
val adapter = adapter ?: return
// Show empty view if needed
if (mangaMap.isNotEmpty()) {
empty_view.hide()
} else {
empty_view.show(R.drawable.ic_book_black_128dp, R.string.information_empty_library)
}
// Get the current active category.
val activeCat = if (adapter.categories.isNotEmpty())
library_pager.currentItem
else
activeCategory
// Set the categories
adapter.categories = categories
// Restore active category.
library_pager.setCurrentItem(activeCat, false)
tabsVisibilityRelay.call(categories.size > 1)
// Delay the scroll position to allow the view to be properly measured.
view.post {
if (isAttached) {
activity?.tabs?.setScrollPosition(library_pager.currentItem, 0f, true)
}
}
// Send the manga map to child fragments after the adapter is updated.
libraryMangaRelay.call(LibraryMangaEvent(mangaMap))
}
/**
* Returns a preference for the number of manga per row based on the current orientation.
*
* @return the preference.
*/
private fun getColumnsPreferenceForCurrentOrientation(): Preference<Int> {
return if (resources?.configuration?.orientation == Configuration.ORIENTATION_PORTRAIT)
preferences.portraitColumns()
else
preferences.landscapeColumns()
}
/**
* Called when a filter is changed.
*/
private fun onFilterChanged() {
presenter.requestFilterUpdate()
activity?.invalidateOptionsMenu()
}
private fun onDownloadBadgeChanged() {
presenter.requestDownloadBadgesUpdate()
}
/**
* Called when the sorting mode is changed.
*/
private fun onSortChanged() {
presenter.requestSortUpdate()
}
/**
* Reattaches the adapter to the view pager to recreate fragments
*/
private fun reattachAdapter() {
val adapter = adapter ?: return
val position = library_pager.currentItem
adapter.recycle = false
library_pager.adapter = adapter
library_pager.currentItem = position
adapter.recycle = true
}
/**
* Creates the action mode if it's not created already.
*/
fun createActionModeIfNeeded() {
if (actionMode == null) {
actionMode = (activity as AppCompatActivity).startSupportActionMode(this)
}
}
/**
* Destroys the action mode.
*/
fun destroyActionModeIfNeeded() {
actionMode?.finish()
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.library, menu)
val searchItem = menu.findItem(R.id.action_search)
val searchView = searchItem.actionView as SearchView
if (!query.isEmpty()) {
searchItem.expandActionView()
searchView.setQuery(query, true)
searchView.clearFocus()
}
// Mutate the filter icon because it needs to be tinted and the resource is shared.
menu.findItem(R.id.action_filter).icon.mutate()
searchViewSubscription?.unsubscribe()
searchViewSubscription = searchView.queryTextChanges()
// Ignore events if this controller isn't at the top
.filter { router.backstack.lastOrNull()?.controller() == this }
.subscribeUntilDestroy {
query = it.toString()
searchRelay.call(query)
}
searchItem.fixExpand()
}
override fun onPrepareOptionsMenu(menu: Menu) {
val navView = navView ?: return
val filterItem = menu.findItem(R.id.action_filter)
// Tint icon if there's a filter active
val filterColor = if (navView.hasActiveFilters()) Color.rgb(255, 238, 7) else Color.WHITE
DrawableCompat.setTint(filterItem.icon, filterColor)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_filter -> {
navView?.let { activity?.drawer?.openDrawer(Gravity.END) }
}
R.id.action_update_library -> {
activity?.let { LibraryUpdateService.start(it) }
}
R.id.action_edit_categories -> {
router.pushController(CategoryController().withFadeTransaction())
}
R.id.action_source_migration -> {
router.pushController(MigrationController().withFadeTransaction())
}
else -> return super.onOptionsItemSelected(item)
}
return true
}
/**
* Invalidates the action mode, forcing it to refresh its content.
*/
fun invalidateActionMode() {
actionMode?.invalidate()
}
override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean {
mode.menuInflater.inflate(R.menu.library_selection, menu)
return true
}
override fun onPrepareActionMode(mode: ActionMode, menu: Menu): Boolean {
val count = selectedMangas.size
if (count == 0) {
// Destroy action mode if there are no items selected.
destroyActionModeIfNeeded()
} else {
mode.title = resources?.getString(R.string.label_selected, count)
menu.findItem(R.id.action_edit_cover)?.isVisible = count == 1
}
return false
}
override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_edit_cover -> {
changeSelectedCover()
destroyActionModeIfNeeded()
}
R.id.action_move_to_category -> showChangeMangaCategoriesDialog()
R.id.action_delete -> showDeleteMangaDialog()
else -> return false
}
return true
}
override fun onDestroyActionMode(mode: ActionMode?) {
// Clear all the manga selections and notify child views.
selectedMangas.clear()
selectionRelay.call(LibrarySelectionEvent.Cleared())
actionMode = null
}
fun openManga(manga: Manga) {
// Notify the presenter a manga is being opened.
presenter.onOpenManga()
router.pushController(MangaController(manga).withFadeTransaction())
}
/**
* Sets the selection for a given manga.
*
* @param manga the manga whose selection has changed.
* @param selected whether it's now selected or not.
*/
fun setSelection(manga: Manga, selected: Boolean) {
if (selected) {
selectedMangas.add(manga)
selectionRelay.call(LibrarySelectionEvent.Selected(manga))
} else {
selectedMangas.remove(manga)
selectionRelay.call(LibrarySelectionEvent.Unselected(manga))
}
}
/**
* Move the selected manga to a list of categories.
*/
private fun showChangeMangaCategoriesDialog() {
// Create a copy of selected manga
val mangas = selectedMangas.toList()
// Hide the default category because it has a different behavior than the ones from db.
val categories = presenter.categories.filter { it.id != 0 }
// Get indexes of the common categories to preselect.
val commonCategoriesIndexes = presenter.getCommonCategories(mangas)
.map { categories.indexOf(it) }
.toTypedArray()
ChangeMangaCategoriesDialog(this, mangas, categories, commonCategoriesIndexes)
.showDialog(router)
}
private fun showDeleteMangaDialog() {
DeleteLibraryMangasDialog(this, selectedMangas.toList()).showDialog(router)
}
override fun updateCategoriesForMangas(mangas: List<Manga>, categories: List<Category>) {
presenter.moveMangasToCategories(categories, mangas)
destroyActionModeIfNeeded()
}
override fun deleteMangasFromLibrary(mangas: List<Manga>, deleteChapters: Boolean) {
presenter.removeMangaFromLibrary(mangas, deleteChapters)
destroyActionModeIfNeeded()
}
/**
* Changes the cover for the selected manga.
*/
private fun changeSelectedCover() {
val manga = selectedMangas.firstOrNull() ?: return
selectedCoverManga = manga
if (manga.favorite) {
val intent = Intent(Intent.ACTION_GET_CONTENT)
intent.type = "image/*"
startActivityForResult(Intent.createChooser(intent,
resources?.getString(R.string.file_select_cover)), REQUEST_IMAGE_OPEN)
} else {
activity?.toast(R.string.notification_first_add_to_library)
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == REQUEST_IMAGE_OPEN) {
if (data == null || resultCode != Activity.RESULT_OK) return
val activity = activity ?: return
val manga = selectedCoverManga ?: return
try {
// Get the file's input stream from the incoming Intent
activity.contentResolver.openInputStream(data.data).use {
// Update cover to selected file, show error if something went wrong
if (presenter.editCoverWithStream(it, manga)) {
// TODO refresh cover
} else {
activity.toast(R.string.notification_cover_update_failed)
}
}
} catch (error: IOException) {
activity.toast(R.string.notification_cover_update_failed)
Timber.e(error)
}
selectedCoverManga = null
}
}
private companion object {
/**
* Key to change the cover of a manga in [onActivityResult].
*/
const val REQUEST_IMAGE_OPEN = 101
}
}
| apache-2.0 | 5ba2f78085ba8f9cf7faf0413d869c2f | 32.28023 | 97 | 0.627884 | 5.052334 | false | false | false | false |
Citrus-CAF/packages_apps_Margarita | app/src/main/kotlin/com/citrus/theme/SubstratumLauncher.kt | 1 | 8705 | @file:Suppress("ConstantConditionIf")
package com.citrus.theme
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import com.github.javiersantos.piracychecker.*
import com.github.javiersantos.piracychecker.enums.*
import com.github.javiersantos.piracychecker.utils.apkSignature
import com.citrus.theme.AdvancedConstants.ORGANIZATION_THEME_SYSTEMS
import com.citrus.theme.AdvancedConstants.OTHER_THEME_SYSTEMS
import com.citrus.theme.AdvancedConstants.SHOW_DIALOG_REPEATEDLY
import com.citrus.theme.AdvancedConstants.SHOW_LAUNCH_DIALOG
import com.citrus.theme.ThemeFunctions.checkApprovedSignature
import com.citrus.theme.ThemeFunctions.getSelfSignature
import com.citrus.theme.ThemeFunctions.getSelfVerifiedPirateTools
import com.citrus.theme.ThemeFunctions.isCallingPackageAllowed
/**
* NOTE TO THEMERS
*
* This class is a TEMPLATE of how you should be launching themes. As long as you keep the structure
* of launching themes the same, you can avoid easy script crackers by changing how
* functions/methods are coded, as well as boolean variable placement.
*
* The more you play with this the harder it would be to decompile and crack!
*/
class SubstratumLauncher : Activity() {
private val debug = false
private val tag = "SubstratumThemeReport"
private val substratumIntentData = "projekt.substratum.THEME"
private val getKeysIntent = "projekt.substratum.GET_KEYS"
private val receiveKeysIntent = "projekt.substratum.RECEIVE_KEYS"
private val themePiracyCheck by lazy {
if (BuildConfig.ENABLE_APP_BLACKLIST_CHECK) {
getSelfVerifiedPirateTools(applicationContext)
} else {
false
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
/* STEP 1: Block hijackers */
val caller = callingActivity!!.packageName
val organizationsSystem = ORGANIZATION_THEME_SYSTEMS.contains(caller)
val supportedSystem = organizationsSystem || OTHER_THEME_SYSTEMS.contains(caller)
if (!BuildConfig.SUPPORTS_THIRD_PARTY_SYSTEMS && !supportedSystem) {
Log.e(tag, "This theme does not support the launching theme system. [HIJACK] ($caller)")
Toast.makeText(this,
String.format(getString(R.string.unauthorized_theme_client_hijack), caller),
Toast.LENGTH_LONG).show()
finish()
}
if (debug) {
Log.d(tag, "'$caller' has been authorized to launch this theme. (Phase 1)")
}
val action = intent.action
val sharedPref = getPreferences(Context.MODE_PRIVATE)
var verified = false
if ((action == substratumIntentData) or (action == getKeysIntent)) {
// Assume this called from organization's app
if (organizationsSystem) {
verified = when {
BuildConfig.ALLOW_THIRD_PARTY_SUBSTRATUM_BUILDS -> true
else -> checkApprovedSignature(this, caller)
}
}
} else {
OTHER_THEME_SYSTEMS
.filter { action?.startsWith(prefix = it, ignoreCase = true) ?: false }
.forEach { verified = true }
}
if (!verified) {
Log.e(tag, "This theme does not support the launching theme system. ($action)")
Toast.makeText(this, R.string.unauthorized_theme_client, Toast.LENGTH_LONG).show()
finish()
return
}
if (debug) {
Log.d(tag, "'$action' has been authorized to launch this theme. (Phase 2)")
}
if (SHOW_LAUNCH_DIALOG) run {
if (SHOW_DIALOG_REPEATEDLY) {
showDialog()
sharedPref.edit().remove("dialog_showed").apply()
} else if (!sharedPref.getBoolean("dialog_showed", false)) {
showDialog()
sharedPref.edit().putBoolean("dialog_showed", true).apply()
} else {
startAntiPiracyCheck()
}
} else {
startAntiPiracyCheck()
}
}
private fun startAntiPiracyCheck() {
if (BuildConfig.BASE_64_LICENSE_KEY.isEmpty() && debug && !BuildConfig.DEBUG) {
Log.e(tag, apkSignature)
}
if (!themePiracyCheck) {
piracyChecker {
if (BuildConfig.ENFORCE_GOOGLE_PLAY_INSTALL) {
enableInstallerId(InstallerID.GOOGLE_PLAY)
}
if (BuildConfig.BASE_64_LICENSE_KEY.isNotEmpty()) {
enableGooglePlayLicensing(BuildConfig.BASE_64_LICENSE_KEY)
}
if (BuildConfig.APK_SIGNATURE_PRODUCTION.isNotEmpty()) {
enableSigningCertificate(BuildConfig.APK_SIGNATURE_PRODUCTION)
}
callback {
allow {
val returnIntent = if (intent.action == getKeysIntent) {
Intent(receiveKeysIntent)
} else {
Intent()
}
val themeName = getString(R.string.ThemeName)
val themeAuthor = getString(R.string.ThemeAuthor)
val themePid = packageName
returnIntent.putExtra("theme_name", themeName)
returnIntent.putExtra("theme_author", themeAuthor)
returnIntent.putExtra("theme_pid", themePid)
returnIntent.putExtra("theme_debug", BuildConfig.DEBUG)
returnIntent.putExtra("theme_piracy_check", themePiracyCheck)
returnIntent.putExtra("encryption_key", BuildConfig.DECRYPTION_KEY)
returnIntent.putExtra("iv_encrypt_key", BuildConfig.IV_KEY)
val callingPackage = intent.getStringExtra("calling_package_name")
if (!isCallingPackageAllowed(callingPackage)) {
finish()
} else {
returnIntent.`package` = callingPackage
}
if (intent.action == substratumIntentData) {
setResult(getSelfSignature(applicationContext), returnIntent)
} else if (intent.action == getKeysIntent) {
returnIntent.action = receiveKeysIntent
sendBroadcast(returnIntent)
}
destroy()
finish()
}
doNotAllow { _, _ ->
val parse = String.format(
getString(R.string.toast_unlicensed),
getString(R.string.ThemeName))
Toast.makeText(this@SubstratumLauncher, parse, Toast.LENGTH_SHORT).show()
destroy()
finish()
}
onError { error ->
Toast.makeText(this@SubstratumLauncher, error.toString(), Toast.LENGTH_LONG)
.show()
destroy()
finish()
}
}
}.start()
} else {
Toast.makeText(this, R.string.unauthorized, Toast.LENGTH_LONG).show()
finish()
}
}
private fun showDialog() {
val dialog = AlertDialog.Builder(this, R.style.DialogStyle)
.setCancelable(false)
.setIcon(R.mipmap.ic_launcher)
.setTitle(R.string.launch_dialog_title)
.setMessage(R.string.launch_dialog_content)
.setPositiveButton(R.string.launch_dialog_positive) { _, _ -> startAntiPiracyCheck() }
if (getString(R.string.launch_dialog_negative).isNotEmpty()) {
if (getString(R.string.launch_dialog_negative_url).isNotEmpty()) {
dialog.setNegativeButton(R.string.launch_dialog_negative) { _, _ ->
startActivity(Intent(Intent.ACTION_VIEW,
Uri.parse(getString(R.string.launch_dialog_negative_url))))
finish()
}
} else {
dialog.setNegativeButton(R.string.launch_dialog_negative) { _, _ -> finish() }
}
}
dialog.show()
}
} | apache-2.0 | 009650f775ce208d8246c0a32398a1ea | 41.8867 | 102 | 0.567145 | 4.960114 | false | true | false | false |
ruuvi/Android_RuuvitagScanner | app/src/main/java/com/ruuvi/station/util/ShakeEventListener.kt | 1 | 1272 | package com.ruuvi.station.util
import android.hardware.*
import com.ruuvi.station.util.extensions.diffGreaterThan
import timber.log.Timber
import java.util.*
class ShakeEventListener(
var shakeCallback: (Int) -> Unit
): SensorEventListener {
private var acceleration = 10f
private var currentAcceleration = SensorManager.GRAVITY_EARTH
private var lastAcceleration = SensorManager.GRAVITY_EARTH
private var lastShake: Date? = null
private var shakeCount: Int = 0
override fun onSensorChanged(event: SensorEvent) {
val x = event.values[0]
val y = event.values[1]
val z = event.values[2]
lastAcceleration = currentAcceleration
currentAcceleration = kotlin.math.sqrt((x * x + y * y + z * z).toDouble()).toFloat()
val delta: Float = currentAcceleration - lastAcceleration
acceleration = acceleration * 0.9f + delta
Timber.d("onSensorChanged $acceleration")
if (acceleration > 12 && lastShake?.diffGreaterThan(2500) ?: true) {
shakeCount++
lastShake = Date()
Timber.d("Shake event detected $shakeCount")
shakeCallback.invoke(shakeCount)
}
}
override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {}
} | mit | 432911b2ad72316da023d5cea3134208 | 34.361111 | 92 | 0.673742 | 4.341297 | false | false | false | false |
nisrulz/android-examples | NestingModules/app/src/main/java/github/nisrulz/example/nesting_modules/ui/theme/Type.kt | 1 | 815 | package github.nisrulz.example.nesting_modules.ui.theme
import androidx.compose.material.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Set of Material typography styles to start with
val Typography = Typography(
body1 = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp
)
/* Other default text styles to override
button = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.W500,
fontSize = 14.sp
),
caption = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 12.sp
)
*/
) | apache-2.0 | 68594f5c5333e3b25a1fcf283acb84ff | 28.142857 | 55 | 0.695706 | 4.429348 | false | false | false | false |
anton-okolelov/intellij-rust | src/main/kotlin/org/rust/lang/core/types/infer/Fold.kt | 2 | 3931 | /*
* 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.infer
import org.rust.lang.core.types.ty.*
typealias TypeFolder = (Ty) -> Ty
typealias TypeVisitor = (Ty) -> Boolean
/**
* Despite a scary name, [TypeFoldable] is a rather simple thing.
*
* It allows to map type variables within a type (or another object,
* containing a type, like a [Predicate]) to other types.
*/
interface TypeFoldable<out Self> {
/**
* Fold `this` type with the folder.
*
* This works for:
* ```
* A.foldWith { C } == C
* A<B>.foldWith { C } == C
* ```
*
* `a.foldWith(folder)` is equivalent to `folder(a)` in cases where `a` is `Ty`.
* In other cases the call delegates to [superFoldWith]
*
* The folding basically is not deep. If you want to fold type deeply, you should write a folder
* somehow like this:
* ```kotlin
* // We initially have `ty = A<B<C>, B<C>>` and want replace C to D to get `A<B<D>, B<D>>`
* ty.foldWith(object : TypeFolder {
* override fun invoke(ty: Ty): Ty =
* if (it == C) D else it.superFoldWith(this)
* })
* ```
*/
fun foldWith(folder: TypeFolder): Self = superFoldWith(folder)
/**
* Fold inner types (not this type) with the folder.
* `A<A<B>>.foldWith { C } == A<C>`
* This method should be used only by a folder implementations internally.
*/
fun superFoldWith(folder: TypeFolder): Self
/** Similar to [superVisitWith], but just visit types without folding */
fun visitWith(visitor: TypeVisitor): Boolean = superVisitWith(visitor)
/** Similar to [foldWith], but just visit types without folding */
fun superVisitWith(visitor: TypeVisitor): Boolean
}
/** Deeply replace any [TyInfer] with the function [folder] */
fun <T> TypeFoldable<T>.foldTyInferWith(folder: (TyInfer) -> Ty): T =
foldWith(object : TypeFolder {
override fun invoke(ty: Ty): Ty {
val foldedTy = if (ty is TyInfer) folder(ty) else ty
return if (foldedTy.hasTyInfer) foldedTy.superFoldWith(this) else foldedTy
}
})
/** Deeply replace any [TyTypeParameter] with the function [folder] */
fun <T> TypeFoldable<T>.foldTyTypeParameterWith(folder: (TyTypeParameter) -> Ty): T =
foldWith(object : TypeFolder {
override fun invoke(ty: Ty): Ty = when {
ty is TyTypeParameter -> folder(ty)
ty.hasTyTypeParameters -> ty.superFoldWith(this)
else -> ty
}
})
/** Deeply replace any [TyProjection] with the function [folder] */
fun <T> TypeFoldable<T>.foldTyProjectionWith(folder: (TyProjection) -> Ty): T =
foldWith(object : TypeFolder {
override fun invoke(ty: Ty): Ty = when {
ty is TyProjection -> folder(ty)
ty.hasTyProjection -> ty.superFoldWith(this)
else -> ty
}
})
/**
* Deeply replace any [TyTypeParameter] by [subst] mapping.
*/
fun <T> TypeFoldable<T>.substitute(subst: Substitution): T =
foldWith(object : TypeFolder {
override fun invoke(ty: Ty): Ty =
subst[ty] ?: if (ty.hasTyTypeParameters) ty.superFoldWith(this) else ty
})
fun <T> TypeFoldable<T>.containsTyOfClass(classes: List<Class<*>>): Boolean =
visitWith(object : TypeVisitor {
override fun invoke(ty: Ty): Boolean =
if (classes.any { it.isInstance(ty) }) true else ty.superVisitWith(this)
})
fun <T> TypeFoldable<T>.collectInferTys(): List<TyInfer> {
val list = mutableListOf<TyInfer>()
visitWith(object : TypeVisitor {
override fun invoke(ty: Ty): Boolean = when {
ty is TyInfer -> {
list.add(ty)
false
}
ty.hasTyInfer -> ty.superVisitWith(this)
else -> false
}
})
return list
}
| mit | 3fcd36a9a77631595ccd7ffbccec1924 | 33.182609 | 100 | 0.610532 | 3.880553 | false | false | false | false |
square/leakcanary | shark-graph/src/main/java/shark/HeapValue.kt | 2 | 3737 | package shark
import shark.ValueHolder.BooleanHolder
import shark.ValueHolder.ByteHolder
import shark.ValueHolder.CharHolder
import shark.ValueHolder.DoubleHolder
import shark.ValueHolder.FloatHolder
import shark.ValueHolder.IntHolder
import shark.ValueHolder.LongHolder
import shark.ValueHolder.ReferenceHolder
import shark.ValueHolder.ShortHolder
/**
* Represents a value in the heap dump, which can be an object reference or
* a primitive type.
*/
class HeapValue(
/**
* The graph of objects in the heap, which you can use to navigate the heap.
*/
val graph: HeapGraph,
/**
* Holds the actual value that this [HeapValue] represents.
*/
val holder: ValueHolder
) {
/**
* This [HeapValue] as a [Boolean] if it represents one, or null otherwise.
*/
val asBoolean: Boolean?
get() = if (holder is BooleanHolder) holder.value else null
/**
* This [HeapValue] as a [Char] if it represents one, or null otherwise.
*/
val asChar: Char?
get() = if (holder is CharHolder) holder.value else null
/**
* This [HeapValue] as a [Float] if it represents one, or null otherwise.
*/
val asFloat: Float?
get() = if (holder is FloatHolder) holder.value else null
/**
* This [HeapValue] as a [Double] if it represents one, or null otherwise.
*/
val asDouble: Double?
get() = if (holder is DoubleHolder) holder.value else null
/**
* This [HeapValue] as a [Byte] if it represents one, or null otherwise.
*/
val asByte: Byte?
get() = if (holder is ByteHolder) holder.value else null
/**
* This [HeapValue] as a [Short] if it represents one, or null otherwise.
*/
val asShort: Short?
get() = if (holder is ShortHolder) holder.value else null
/**
* This [HeapValue] as an [Int] if it represents one, or null otherwise.
*/
val asInt: Int?
get() = if (holder is IntHolder) holder.value else null
/**
* This [HeapValue] as a [Long] if it represents one, or null otherwise.
*/
val asLong: Long?
get() = if (holder is LongHolder) holder.value else null
/**
* This [HeapValue] as a [Long] if it represents an object reference, or null otherwise.
*/
val asObjectId: Long?
get() = if (holder is ReferenceHolder) holder.value else null
/**
* This [HeapValue] as a [Long] if it represents a non null object reference, or null otherwise.
*/
val asNonNullObjectId: Long?
get() = if (holder is ReferenceHolder && !holder.isNull) holder.value else null
/**
* True is this [HeapValue] represents a null object reference, false otherwise.
*/
val isNullReference: Boolean
get() = holder is ReferenceHolder && holder.isNull
/**
* True is this [HeapValue] represents a non null object reference, false otherwise.
*/
val isNonNullReference: Boolean
get() = holder is ReferenceHolder && !holder.isNull
/**
* The [HeapObject] referenced by this [HeapValue] if it represents a non null object reference,
* or null otherwise.
*/
val asObject: HeapObject?
get() {
return if (holder is ReferenceHolder && !holder.isNull) {
return graph.findObjectById(holder.value)
} else {
null
}
}
/**
* If this [HeapValue] if it represents a non null object reference to an instance of the
* [String] class that exists in the heap dump, returns a [String] instance with content that
* matches the string in the heap dump. Otherwise returns null.
*
* This may trigger IO reads.
*/
fun readAsJavaString(): String? {
if (holder is ReferenceHolder && !holder.isNull) {
val heapObject = graph.findObjectByIdOrNull(holder.value)
return heapObject?.asInstance?.readAsJavaString()
}
return null
}
}
| apache-2.0 | 6cdaedaf0de482aa39ac5f1ab5333d7e | 28.425197 | 98 | 0.678352 | 3.971307 | false | false | false | false |
toastkidjp/Jitte | app/src/main/java/jp/toastkid/yobidashi/search/history/SearchHistoryCardView.kt | 1 | 3682 | /*
* Copyright (c) 2018 toastkidjp.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompany this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html.
*/
package jp.toastkid.yobidashi.search.history
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import androidx.cardview.widget.CardView
import androidx.core.view.isVisible
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import jp.toastkid.lib.ContentViewModel
import jp.toastkid.lib.view.swipe.SwipeActionAttachment
import jp.toastkid.yobidashi.R
import jp.toastkid.yobidashi.databinding.ViewCardSearchHistoryBinding
import jp.toastkid.yobidashi.libs.db.DatabaseFinder
import jp.toastkid.yobidashi.search.SearchFragmentViewModel
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
/**
* Search history module.
*
* @author toastkidjp
*/
class SearchHistoryCardView
@JvmOverloads
constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : CardView(context, attrs, defStyleAttr) {
/**
* RecyclerView's moduleAdapter.
*/
private val moduleAdapter: ModuleAdapter
private var binding: ViewCardSearchHistoryBinding? = null
/**
* Last subscription.
*/
private var disposable: Job? = null
init {
binding = DataBindingUtil.inflate(
LayoutInflater.from(context),
R.layout.view_card_search_history,
this,
true
)
binding?.module = this
binding?.searchHistories?.layoutManager =
LinearLayoutManager(context, RecyclerView.VERTICAL, false)
val repository = DatabaseFinder().invoke(context).searchHistoryRepository()
moduleAdapter = ModuleAdapter(
context,
repository,
{ if (it) show() else hide() },
true,
5
)
binding?.searchHistories?.adapter = moduleAdapter
CoroutineScope(Dispatchers.Main).launch {
val recyclerView = binding?.searchHistories ?: return@launch
SwipeActionAttachment().invoke(recyclerView)
}
}
/**
* Query table with passed word.
*
* @param s query string
*/
fun query(s: CharSequence) {
disposable?.cancel()
disposable = moduleAdapter.query(s)
}
fun openHistory() {
(context as? FragmentActivity)?.let {
ViewModelProvider(it).get(ContentViewModel::class.java)
.nextFragment(SearchHistoryFragment::class.java)
}
}
fun clear() {
moduleAdapter.clear()
hide()
}
/**
* Show this module.
*/
fun show() {
if (!isVisible && isEnabled) {
runOnMainThread { isVisible = true }
}
}
/**
* Hide this module.
*/
fun hide() {
if (isVisible) {
runOnMainThread { isVisible = false }
}
}
fun setViewModel(viewModel: SearchFragmentViewModel) {
moduleAdapter.setViewModel(viewModel)
}
private fun runOnMainThread(action: () -> Unit) = post { action() }
/**
* Dispose last subscription.
*/
fun dispose() {
disposable?.cancel()
binding = null
}
}
| epl-1.0 | 8b3454e93189ae6c6b8505c56454c856 | 25.489209 | 88 | 0.661597 | 4.813072 | false | false | false | false |
Deletescape-Media/Lawnchair | lawnchair/src/app/lawnchair/ui/preferences/components/PreferenceLayout.kt | 1 | 3184 | /*
* Copyright 2021, Lawnchair
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package app.lawnchair.ui.preferences.components
import androidx.compose.foundation.ScrollState
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.lazy.LazyListScope
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.rememberScrollState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
@Composable
fun PreferenceLayout(
verticalArrangement: Arrangement.Vertical = Arrangement.spacedBy(8.dp),
horizontalAlignment: Alignment.Horizontal = Alignment.Start,
scrollState: ScrollState? = rememberScrollState(),
label: String,
actions: @Composable RowScope.() -> Unit = {},
backArrowVisible: Boolean = true,
content: @Composable ColumnScope.() -> Unit
) {
PreferenceScaffold(
backArrowVisible = backArrowVisible,
floating = rememberFloatingState(scrollState),
label = label,
actions = actions,
) {
PreferenceColumn(
verticalArrangement = verticalArrangement,
horizontalAlignment = horizontalAlignment,
scrollState = scrollState,
content = content
)
}
}
@Composable
fun PreferenceLayoutLazyColumn(
modifier: Modifier = Modifier,
enabled: Boolean = true,
state: LazyListState = rememberLazyListState(),
label: String,
actions: @Composable RowScope.() -> Unit = {},
backArrowVisible: Boolean = true,
content: LazyListScope.() -> Unit
) {
PreferenceScaffold(
backArrowVisible = backArrowVisible,
floating = rememberFloatingState(state),
label = label,
actions = actions,
) {
PreferenceLazyColumn(
modifier = modifier,
enabled = enabled,
state = state,
content = content
)
}
}
@Composable
fun rememberFloatingState(state: ScrollState?) =
remember(state) {
if (state != null) derivedStateOf { state.value > 0 } else mutableStateOf(false)
}
@Composable
fun rememberFloatingState(state: LazyListState) =
remember(state) {
derivedStateOf { state.firstVisibleItemIndex > 0 || state.firstVisibleItemScrollOffset > 0 }
}
| gpl-3.0 | 896474eda99178dcdbbfeb52a7bab9a1 | 32.515789 | 100 | 0.720163 | 4.838906 | false | false | false | false |
andreas-oberheim/universal-markup-converter | src/main/kotlin/org/universal_markup_converter/api/Convert.kt | 1 | 4177 | /*
* MIT License
* Copyright (c) 2016 Andreas M. Oberheim
*
* 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 org.universal_markup_converter.api
class Convert(private val inputType: InputType,
private val outputType: OutputType,
private val fromFile: String,
private val toFile: String) {
companion object {
fun from(from: InputType) = Convert(from, OutputType.NONE, "", "")
}
fun to(to: OutputType) = Convert(inputType, to, fromFile, toFile)
fun fromFile(file: String) = Convert(inputType, outputType, file, toFile)
fun toFile(file: String) = Convert(inputType, outputType, fromFile, file).convert()
private fun convert() {
val converter: AbstractMarkupConverter
when (inputType) {
InputType.MARKDOWN -> {
when (outputType) {
OutputType.HTML -> converter = FlexmarkMarkdownToHtmlConverter(fromFile, toFile)
else -> throw Exception("unknown input type $inputType")
}
}
InputType.ASCIIDOC -> {
when (outputType) {
OutputType.HTML -> converter = AsciidocToHtmlConverter(fromFile, toFile)
OutputType.XHTML -> converter = AsciidocToXhtmlConverter(fromFile, toFile)
OutputType.DOCBOOK -> converter = AsciidocToDocBookConverter(fromFile, toFile)
OutputType.DOCBOOK45 -> converter = AsciidocToDocBook45Converter(fromFile, toFile)
OutputType.MANPAGE -> converter = AsciidocToManPageConverter(fromFile, toFile)
else -> throw Exception("unknown input type $inputType")
}
}
InputType.RST -> {
when (outputType) {
OutputType.HTML -> converter = ReStructuredTextToHtmlConverter(fromFile, toFile)
OutputType.PDF -> converter = ReStructuredTextToPdfConverter(fromFile, toFile)
else -> throw Exception("unknown input type $inputType")
}
}
InputType.RESTRUCTURED_TEXT -> {
when (outputType) {
OutputType.HTML -> converter = ReStructuredTextToHtmlConverter(fromFile, toFile)
OutputType.PDF -> converter = ReStructuredTextToPdfConverter(fromFile, toFile)
else -> throw Exception("unknown input type $inputType")
}
}
InputType.EXCEL -> {
when (outputType) {
OutputType.CSV -> converter = ExcelToCsvConverter(fromFile, toFile)
else -> throw Exception("unknown input type $inputType")
}
}
InputType.RESTRUCTURED_TEXT -> throw Exception("unknown input type $inputType")
InputType.ORG_MODE -> throw Exception("unknown input type $inputType")
InputType.MEDIAWIKI -> throw Exception("unknown input type $inputType")
else -> throw Exception("unknown input type $inputType")
}
converter.convert()
}
}
| mit | 5c3f2fec44227b0f6f09092351e6b35b | 47.569767 | 102 | 0.630596 | 5.087698 | false | false | false | false |
SUPERCILEX/Robot-Scouter | library/core-data/src/main/java/com/supercilex/robotscouter/core/data/model/Scouts.kt | 1 | 6699 | package com.supercilex.robotscouter.core.data.model
import com.firebase.ui.firestore.ObservableSnapshotArray
import com.firebase.ui.firestore.SnapshotParser
import com.google.firebase.Timestamp
import com.google.firebase.firestore.FieldValue
import com.google.firebase.firestore.FirebaseFirestoreException
import com.google.firebase.firestore.Query
import com.google.firebase.firestore.SetOptions
import com.google.firebase.firestore.ktx.firestore
import com.google.firebase.ktx.Firebase
import com.supercilex.robotscouter.common.FIRESTORE_METRICS
import com.supercilex.robotscouter.common.FIRESTORE_NAME
import com.supercilex.robotscouter.common.FIRESTORE_SCOUTS
import com.supercilex.robotscouter.common.FIRESTORE_TEMPLATE_ID
import com.supercilex.robotscouter.common.FIRESTORE_TIMESTAMP
import com.supercilex.robotscouter.core.InvocationMarker
import com.supercilex.robotscouter.core.data.QueuedDeletion
import com.supercilex.robotscouter.core.data.R
import com.supercilex.robotscouter.core.data.defaultTemplatesRef
import com.supercilex.robotscouter.core.data.firestoreBatch
import com.supercilex.robotscouter.core.data.logAddScout
import com.supercilex.robotscouter.core.data.logFailures
import com.supercilex.robotscouter.core.data.waitForChange
import com.supercilex.robotscouter.core.logBreadcrumb
import com.supercilex.robotscouter.core.longToast
import com.supercilex.robotscouter.core.model.Scout
import com.supercilex.robotscouter.core.model.Team
import com.supercilex.robotscouter.core.model.TemplateType
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import kotlinx.coroutines.invoke
import kotlinx.coroutines.launch
import kotlinx.coroutines.tasks.await
import java.util.Date
import kotlin.math.abs
val scoutParser = SnapshotParser { snapshot ->
Scout(snapshot.id,
checkNotNull(snapshot.getString(FIRESTORE_TEMPLATE_ID)),
snapshot.getString(FIRESTORE_NAME),
checkNotNull(snapshot.getTimestamp(FIRESTORE_TIMESTAMP)),
@Suppress("UNCHECKED_CAST") // Our data is stored as a map of metrics
(snapshot[FIRESTORE_METRICS] as Map<String, Any?>? ?: emptyMap()).map {
parseMetric(it.value as Map<String, Any?>, Firebase.firestore.document(
"${snapshot.reference.path}/$FIRESTORE_METRICS/${it.key}"))
})
}
val Team.scoutsRef get() = ref.collection(FIRESTORE_SCOUTS)
fun Team.getScoutsQuery(direction: Query.Direction = Query.Direction.ASCENDING): Query =
FIRESTORE_TIMESTAMP.let {
scoutsRef.whereGreaterThanOrEqualTo(it, Timestamp(0, 0)).orderBy(it, direction)
}
fun Team.getScoutMetricsRef(id: String) = scoutsRef.document(id).collection(FIRESTORE_METRICS)
fun Team.addScout(overrideId: String?, existingScouts: ObservableSnapshotArray<Scout>): String {
val templateId = overrideId ?: templateId
val scoutRef = scoutsRef.document()
logAddScout(id, templateId)
Scout(scoutRef.id, templateId).let {
scoutRef.set(it).logFailures("addScout:set", scoutRef, it)
}
GlobalScope.launch {
val templateName = try {
val metricsRef = getScoutMetricsRef(scoutRef.id)
TemplateType.coerce(templateId)?.let { type ->
val scout = scoutParser.parseSnapshot(
defaultTemplatesRef.document(type.id.toString()).get().await())
val metrics = scout.metrics.associateBy {
metricsRef.document(it.ref.id)
}
firestoreBatch {
for ((metricRef, metric) in metrics) set(metricRef, metric)
}.logFailures(
"addScout:setMetrics",
metrics.map { it.key },
metrics.map { it.value }
)
scout.name
} ?: run {
val deferredName = async {
scoutParser.parseSnapshot(
getTemplateRef(templateId).get()
.logFailures("addScout:getTemplate", templateId)
.await()
).name
}
val snapshot = getTemplateRef(templateId)
.collection(FIRESTORE_METRICS).get()
.logFailures("addScout:getTemplateMetrics", templateId)
.await()
val metrics = snapshot.documents.associate { it.id to checkNotNull(it.data) }
firestoreBatch {
for ((id, data) in metrics) {
set(metricsRef.document(id), data)
}
}.logFailures("addScout:setCustomMetrics", scoutRef, metrics)
try {
deferredName.await()
} catch (e: FirebaseFirestoreException) {
null // Don't abort scout addition if name fetch failed
}
}
} catch (e: Exception) {
scoutRef.delete().logFailures("addScout:abort", scoutRef)
Dispatchers.Main { longToast(R.string.scout_add_template_not_cached_error) }
throw InvocationMarker(e)
} ?: return@launch
val nExistingTemplates = existingScouts.waitForChange().map {
it.templateId
}.groupBy { it }[templateId]?.size ?: return@launch
scoutRef.update(FIRESTORE_NAME, "$templateName $nExistingTemplates")
.logFailures("addScout:updateName", scoutRef)
}
return scoutRef.id
}
fun Team.trashScout(id: String) = updateScoutDate(id) { -abs(it) }
fun Team.untrashScout(id: String) = updateScoutDate(id) { abs(it) }
private fun Team.updateScoutDate(id: String, update: (Long) -> Long) {
GlobalScope.launch {
val ref = scoutsRef.document(id)
val snapshot = try {
ref.get().await()
} catch (e: Exception) {
logBreadcrumb("updateScoutDate:get: ${ref.path}")
throw InvocationMarker(e)
}
if (!snapshot.exists()) return@launch
val oppositeDate = Date(update(checkNotNull(snapshot.getDate(FIRESTORE_TIMESTAMP)).time))
firestoreBatch {
this.update(ref, FIRESTORE_TIMESTAMP, oppositeDate)
if (oppositeDate.time > 0) {
this.update(userDeletionQueue, id, FieldValue.delete())
} else {
set(userDeletionQueue,
QueuedDeletion.Scout(id, [email protected]).data,
SetOptions.merge())
}
}.logFailures("updateScoutDate:set", ref, this@updateScoutDate)
}
}
| gpl-3.0 | 65c2aa6a8eee529e66eccc05562b88b6 | 41.398734 | 97 | 0.649052 | 4.566462 | false | false | false | false |
lgou2w/MoonLakeLauncher | src/main/kotlin/com/minecraft/moonlake/launcher/control/MuiRippler.kt | 1 | 20972 | /*
* Copyright (C) 2017 The MoonLake Authors
*
* 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.minecraft.moonlake.launcher.control
import com.minecraft.moonlake.launcher.animation.MuiCachedAnimation
import com.minecraft.moonlake.launcher.animation.MuiCachedTransition
import com.minecraft.moonlake.launcher.layout.MuiStackPane
import javafx.animation.Interpolator
import javafx.animation.KeyFrame
import javafx.animation.KeyValue
import javafx.animation.Timeline
import javafx.beans.DefaultProperty
import javafx.beans.property.BooleanProperty
import javafx.beans.property.ObjectProperty
import javafx.beans.property.SimpleBooleanProperty
import javafx.beans.property.SimpleObjectProperty
import javafx.event.Event
import javafx.geometry.Insets
import javafx.scene.CacheHint
import javafx.scene.Group
import javafx.scene.Node
import javafx.scene.layout.Background
import javafx.scene.layout.BackgroundFill
import javafx.scene.layout.CornerRadii
import javafx.scene.layout.Region
import javafx.scene.paint.Color
import javafx.scene.paint.Paint
import javafx.scene.shape.Circle
import javafx.scene.shape.Rectangle
import javafx.scene.shape.Shape
import javafx.util.Duration
import java.util.concurrent.atomic.AtomicBoolean
@DefaultProperty(value = "node")
open class MuiRippler: MuiStackPane {
/**************************************************************************
*
* Enum Class
*
**************************************************************************/
enum class RipplerMask {
CIRCLE, RECT
}
enum class RipplerPosition {
FRONT, BACK
}
/**************************************************************************
*
* Protected Member
*
**************************************************************************/
protected var ripplerPane: MuiStackPane
protected var node: Node? = null
/**************************************************************************
*
* Private Member
*
**************************************************************************/
private var enable: Boolean = true
private var rippler: RippleGenerator
private var rippleInterpolator: Interpolator = Interpolator.SPLINE(.0825, .3025, .0875, .9975)
/**************************************************************************
*
* Static Block
*
**************************************************************************/
companion object {
/**
* Rippler Max Radius = 300
*/
private val MAX_RADIUS = 300.0
}
/**************************************************************************
*
* Constructor
*
**************************************************************************/
constructor(): this(null)
constructor(node: Node? = null, maskType: RipplerMask = MuiRippler.RipplerMask.RECT, position: RipplerPosition = MuiRippler.RipplerPosition.FRONT): super() {
styleClass.add("mui-rippler")
this.maskType.set(maskType)
this.position.set(position)
rippler = RippleGenerator()
ripplerPane = MuiStackPane()
ripplerPane.children.add(rippler)
setControl(node)
isCache = true
cacheHint = CacheHint.SPEED
isCacheShape = true
isSnapToPixel = false
}
/**************************************************************************
*
* Public API
*
**************************************************************************/
fun setControl(node: Node?) {
if(node != null) {
this.node = node
if(this.position.get() == RipplerPosition.BACK)
ripplerPane.children.add(this.node)
else
children.add(this.node)
this.position.addListener { _, _, _ -> run {
if(this.position.get() == RipplerPosition.BACK)
ripplerPane.children.add(this.node)
else
children.add(this.node)
}}
children.add(ripplerPane)
initListeners()
this.node!!.layoutBoundsProperty().addListener { _, _, _ -> run {
resetOverlay()
resetClip()
}}
this.node!!.boundsInParentProperty().addListener { _, _, _ -> run {
resetOverlay()
resetClip()
}}
}
}
fun getControl(): Node?
= node
fun setEnable(enable: Boolean) {
this.enable = enable
}
fun createManualRipple(): Runnable {
rippler.setGeneratorCenterX(node!!.layoutBounds.width / 2)
rippler.setGeneratorCenterY(node!!.layoutBounds.height / 2)
return rippler.createManualRipple()
}
open protected fun getMask(): Node {
val bounds = node!!.boundsInParent
val width = node!!.layoutBounds.width
val height = node!!.layoutBounds.height
val borderWidth = if(ripplerPane.border != null) ripplerPane.border.insets.top else .0
val diffMinX = Math.abs(node!!.boundsInLocal.minX - node!!.layoutBounds.minX)
val diffMinY = Math.abs(node!!.boundsInLocal.minY - node!!.layoutBounds.minY)
val diffMaxX = Math.abs(node!!.boundsInLocal.maxX - node!!.layoutBounds.maxX)
val diffMaxY = Math.abs(node!!.boundsInLocal.maxY - node!!.layoutBounds.maxY)
var mask: Node
when(getMaskType()) {
RipplerMask.RECT -> {
mask = Rectangle(bounds.minX + diffMinX, bounds.minY + diffMinY, width - .1 - 2 * borderWidth, height - .1 - 2 * borderWidth)
}
RipplerMask.CIRCLE -> {
val radius = Math.min(width / 2 - .1 - 2 * borderWidth, height / 2 - .1 - 2 * borderWidth)
mask = Circle((bounds.minX + diffMinX + bounds.maxX - diffMaxX) / 2, (bounds.minY + diffMinY + bounds.maxY - diffMaxY) / 2, radius, Color.BLUE)
}
}
if(node is Shape || (node is Region && (node as Region).shape != null)) {
mask = MuiStackPane()
mask.shape = if(node is Shape) node as Shape else (node as Region).shape
mask.background = Background(BackgroundFill(Color.WHITE, CornerRadii.EMPTY, Insets.EMPTY))
mask.resize(width, height)
mask.relocate(bounds.minX + diffMinX, bounds.minY + diffMinY)
}
return mask
}
open protected fun initListeners() {
ripplerPane.setOnMousePressed { event -> run {
createRipple(event.x, event.y)
if(position.get() == RipplerPosition.FRONT)
node!!.fireEvent(event)
}}
ripplerPane.setOnMouseReleased { event -> run {
if(position.get() == RipplerPosition.FRONT)
node!!.fireEvent(event)
}}
ripplerPane.setOnMouseClicked { event -> run {
if(position.get() == RipplerPosition.FRONT)
node!!.fireEvent(event)
}}
}
open protected fun createRipple(x: Double, y: Double) {
rippler.setGeneratorCenterX(x)
rippler.setGeneratorCenterY(y)
rippler.createMouseRipple(x, y)
}
open protected fun computeRippleRadius(): Double {
val width = node!!.layoutBounds.width * node!!.layoutBounds.width
val height = node!!.layoutBounds.height * node!!.layoutBounds.height
return Math.min(Math.sqrt(width + height), MAX_RADIUS) * 1.1 + 5
}
fun fireEventProgrammatically(event: Event) {
if(!event.isConsumed)
ripplerPane.fireEvent(event)
}
fun showOverlay() {
rippler.showOverlay()
}
fun hideOverlay() {
rippler.hideOverlay()
}
fun resetOverlay() {
rippler.resetOverlay()
}
fun resetClip() {
rippler.resetClip()
}
/**************************************************************************
*
* Properties
*
**************************************************************************/
private var ripplerRecenter: BooleanProperty
= SimpleBooleanProperty(false)
fun ripplerRecenterProperty(): BooleanProperty
= ripplerRecenter
fun isRipplerRecenter(): Boolean
= if(ripplerRecenter is BooleanProperty) ripplerRecenter.get() else false
fun setripplerRecenter(ripplerRecenter: Boolean)
= this.ripplerRecenter.set(ripplerRecenter)
private var ripplerFill: ObjectProperty<Paint>
= SimpleObjectProperty(Color.rgb(0, 0, 0, .1))
fun ripplerFillProperty(): ObjectProperty<Paint>
= ripplerFill
fun getRipplerFill(): Paint
= if(ripplerFill is ObjectProperty) ripplerFill.get() else Color.rgb(0, 0, 0, .1)
fun setRipplerFill(ripplerFill: Paint)
= this.ripplerFill.set(ripplerFill)
private var ripplerRadius: ObjectProperty<Number>
= SimpleObjectProperty(Region.USE_COMPUTED_SIZE)
fun ripplerRadiusProperty(): ObjectProperty<Number>
= ripplerRadius
fun getRipplerRadius(): Number
= if(ripplerRadius is ObjectProperty) ripplerRadius.get() else Region.USE_COMPUTED_SIZE
fun setRipplerRadius(ripplerRadius: Number)
= this.ripplerRadius.set(ripplerRadius)
private var maskType: ObjectProperty<RipplerMask>
= SimpleObjectProperty(RipplerMask.RECT)
fun maskTypeProperty(): ObjectProperty<RipplerMask>
= maskType
fun getMaskType(): RipplerMask
= if(maskType is ObjectProperty) maskType.get() else RipplerMask.RECT
fun setMaskType(maskType: RipplerMask)
= this.maskType.set(maskType)
private var position: ObjectProperty<RipplerPosition>
= SimpleObjectProperty(RipplerPosition.FRONT)
fun positionProperty(): ObjectProperty<RipplerPosition>
= position
fun getPosition(): RipplerPosition
= if(position is ObjectProperty) position.get() else RipplerPosition.FRONT
fun setPosition(position: RipplerPosition)
= this.position.set(position)
/**************************************************************************
*
* Inner Class
*
**************************************************************************/
internal inner class RippleGenerator internal constructor(): Group() {
private var generatorCenterX = .0
private var generatorCenterY = .0
private var overlayRect: OverlayRipple? = null
private var generating = AtomicBoolean(false)
private var cacheRipplerClip = false
private var resetClip = false
init {
isManaged = false
}
fun createMouseRipple(mouseX: Double, mouseY: Double) {
if(enable && !generating.getAndSet(true)) {
createOverlay()
if(clip == null || (children.size == 1 && !cacheRipplerClip) || resetClip)
clip = getMask()
resetClip = false
val ripple = Ripple(generatorCenterX, generatorCenterY)
children.add(ripple)
overlayRect!!.outAnimation.stop()
overlayRect!!.inAnimation.play()
ripple.inAnimation!!.getAnimation().play()
ripplerPane.setOnMouseReleased { _ -> run {
if(generating.getAndSet(false)) {
if(overlayRect != null)
overlayRect!!.inAnimation.stop()
ripple.inAnimation!!.getAnimation().stop()
ripple.outAnimation = MuiCachedAnimation(Timeline(KeyFrame(duration(scaleX, mouseX, mouseY), *ripple.outKeyValues)), this)
ripple.outAnimation!!.getAnimation().setOnFinished { _ -> children.remove(ripple) }
ripple.outAnimation!!.getAnimation().play()
if(overlayRect != null)
overlayRect!!.outAnimation.play()
}
}}
}
}
fun createManualRipple(): Runnable {
if(enable && !generating.getAndSet(true)) {
createOverlay()
if(clip == null || (children.size == 1 && !cacheRipplerClip) || resetClip)
clip = getMask()
resetClip = false
val ripple = Ripple(generatorCenterX, generatorCenterY)
children.add(ripple)
overlayRect!!.outAnimation.stop()
overlayRect!!.inAnimation.play()
ripple.inAnimation!!.getAnimation().play()
return Runnable {
if(generating.getAndSet(false)) {
if(overlayRect != null)
overlayRect!!.inAnimation.stop()
ripple.inAnimation!!.getAnimation().stop()
ripple.outAnimation = MuiCachedAnimation(Timeline(KeyFrame(duration(scaleX), *ripple.outKeyValues)), this)
ripple.outAnimation!!.getAnimation().setOnFinished { _ -> children.remove(ripple) }
ripple.outAnimation!!.getAnimation().play()
if(overlayRect != null)
overlayRect!!.outAnimation.play()
}
}
}
return Runnable { }
}
private fun duration(scaleX: Double, mouseX: Double = -1.0, mouseY: Double = -1.0): Duration {
if(mouseX < .0 || mouseY < .0) // not is mouse clicked
return Duration(Math.min(1000.0, .9 * 1000 / scaleX))
return Duration(Math.min(1000.0, .9 * 1000 / scaleX)) // mouse Clicked
}
fun showOverlay() {
if(rippler.overlayRect != null)
rippler.overlayRect!!.outAnimation.stop()
rippler.createOverlay()
rippler.overlayRect!!.inAnimation.play()
}
fun hideOverlay() {
if(rippler.overlayRect != null)
rippler.overlayRect!!.inAnimation.stop()
if(rippler.overlayRect != null)
rippler.overlayRect!!.outAnimation.play()
}
fun resetOverlay() {
if(rippler.overlayRect != null) {
val oldOverlay = rippler.overlayRect!!
rippler.overlayRect!!.inAnimation.stop()
rippler.overlayRect!!.outAnimation.setOnFinished { _ -> rippler.children.remove(oldOverlay) }
rippler.overlayRect!!.outAnimation.play()
rippler.overlayRect = null
}
}
fun resetClip() {
rippler.resetClip = true
}
fun cacheRippleClip(cached: Boolean) {
cacheRipplerClip = cached
}
fun createOverlay() {
if(overlayRect == null) {
val fill = ripplerFill.get() as Color
overlayRect = OverlayRipple()
overlayRect!!.clip = getMask()
overlayRect!!.fill = Color(fill.red, fill.green, fill.blue, .2)
children.add(0, overlayRect)
}
}
fun setGeneratorCenterX(generatorCenterX: Double) {
this.generatorCenterX = generatorCenterX
}
fun setGeneratorCenterY(generatorCenterY: Double) {
this.generatorCenterY = generatorCenterY
}
fun clear() {
children.clear()
generating.set(false)
}
/**************************************************************************
*
* Private Inner Class
*
**************************************************************************/
private inner class OverlayRipple internal constructor(): Rectangle(node!!.layoutBounds.width - .1, node!!.layoutBounds.height - .1) {
internal var inAnimation: MuiCachedTransition = object: MuiCachedTransition(this, Timeline(KeyFrame(Duration(1300.0), KeyValue(opacityProperty(), 1, Interpolator.EASE_IN)))) {
init {
cycleDuration = Duration(3000.0)
delay = Duration(.0)
}
}
internal var outAnimation: MuiCachedTransition = object: MuiCachedTransition(this, Timeline(KeyFrame(Duration(1300.0), KeyValue(opacityProperty(), 0, Interpolator.EASE_OUT)))) {
init {
cycleDuration = Duration(0300.0)
delay = Duration(.0)
}
}
init {
val diffMinX = Math.abs(node!!.boundsInLocal.minX - node!!.layoutBounds.minX)
val diffMinY = Math.abs(node!!.boundsInLocal.minY - node!!.layoutBounds.minY)
val bounds = node!!.boundsInParent
x = bounds.minX + diffMinX
y = bounds.minY + diffMinY
opacity = .0
isCache = true
cacheHint = CacheHint.SPEED
isCacheShape = true
isSnapToPixel = false
outAnimation.setOnFinished { _ -> resetOverlay() }
}
}
private fun radiusRippler(): Double {
if(ripplerRadius.get().toDouble() == Region.USE_COMPUTED_SIZE)
return computeRippleRadius()
else
return ripplerRadius.get().toDouble()
}
private inner class Ripple internal constructor(centerX: Double, centerY: Double) : Circle(centerX, centerY, radiusRippler()) {
internal var outKeyValues: Array<KeyValue?>
internal var outAnimation: MuiCachedAnimation? = null
internal var inAnimation: MuiCachedAnimation? = null
init {
val isRipplerInterpolator = isRipplerRecenter()
val inKeyValues = arrayOfNulls<KeyValue>(if(isRipplerInterpolator) 4 else 2)
outKeyValues = arrayOfNulls<KeyValue>(if(isRipplerInterpolator) 5 else 3)
inKeyValues[0] = KeyValue(scaleXProperty(), .9, rippleInterpolator)
inKeyValues[1] = KeyValue(scaleYProperty(), .9, rippleInterpolator)
outKeyValues[0] = KeyValue(scaleXProperty(), 1.0, rippleInterpolator)
outKeyValues[1] = KeyValue(scaleYProperty(), 1.0, rippleInterpolator)
outKeyValues[2] = KeyValue(opacityProperty(), .1, rippleInterpolator)
if(isRipplerInterpolator) {
val dx = (node!!.layoutBounds.width / 2 - centerX) / 1.55
val dy = (node!!.layoutBounds.height / 2 - centerY) / 1.55
outKeyValues[3] = KeyValue(translateXProperty(), Math.signum(dx) * Math.min(Math.abs(dx), radius / 2), rippleInterpolator)
outKeyValues[4] = KeyValue(translateYProperty(), Math.signum(dy) * Math.min(Math.abs(dy), radius / 2), rippleInterpolator)
inKeyValues[2] = outKeyValues[3]
inKeyValues[3] = outKeyValues[4]
}
inAnimation = MuiCachedAnimation(Timeline(
KeyFrame(Duration.ZERO,
KeyValue(scaleXProperty(), .0, rippleInterpolator),
KeyValue(scaleYProperty(), .0, rippleInterpolator),
KeyValue(translateXProperty(), .0, rippleInterpolator),
KeyValue(translateYProperty(), .0, rippleInterpolator),
KeyValue(opacityProperty(), 1, rippleInterpolator)),
KeyFrame(Duration(900.0), *inKeyValues)), this)
isCache = true
cacheHint = CacheHint.SPEED
isCacheShape = true
isSnapToPixel = false
scaleX = .0
scaleY = .0
if(ripplerFill.get() is Color) {
val ripplerFill = ripplerFill.get() as Color
val circleColor = Color(ripplerFill.red, ripplerFill.green, ripplerFill.blue, .2)
stroke = circleColor
fill = circleColor
} else {
stroke = ripplerFill.get()
fill = ripplerFill.get()
}
}
}
}
}
| gpl-3.0 | e36d7a6755819740780c14df74fe93c0 | 38.126866 | 189 | 0.546061 | 4.9 | false | false | false | false |
kotlin-everywhere/keuix-browser | src/test/kotlin/com/minek/kotlin/everywhere/testProgram.kt | 1 | 3581 | package com.minek.kotlin.everywhere
import com.minek.kotlin.everywhere.keduct.bluebird.Bluebird
import com.minek.kotlin.everywhere.keduct.qunit.asyncTest
import com.minek.kotlin.everywhere.keduct.qunit.fixture
import com.minek.kotlin.everywhere.keuix.browser.*
import com.minek.kotlin.everywhere.keuix.browser.html.Html
import com.minek.kotlin.everywhere.keuix.browser.html.onClick
import kotlin.test.Test
import org.w3c.dom.Element
import kotlin.browser.window
import kotlin.test.assertEquals
private data class Model(val count: Int = 0)
private sealed class Msg
private val init = Model()
private val update: Update<Model, Msg> = { _, model ->
model to null
}
private val view: (Model) -> Html<Msg> = { (count) ->
Html.text("count = $count")
}
@JsModule("jquery")
external val q: dynamic
class TestProgram {
@Test
fun testProgram() {
val fixture = q(fixture())
val container = q("<div>").appendTo(fixture)[0] as Element
asyncTest { resolve, _ ->
runProgram(container, init, update, view) {
assertEquals("count = 0", fixture.text())
resolve(Unit)
}
}
}
@Test
fun testProgramInitialCmd() {
asyncSerialTest(
0,
{ _: Unit, model: Int -> (model + 1) to null },
{ Html.div(text = "$it") },
Cmd.value(Unit),
{
assertEquals("0", it().text())
},
{
assertEquals("1", it().text())
}
)
}
@Test
fun testBeginnerProgram() {
val fixture = q(fixture())
val container = q("<div>").appendTo(fixture)[0] as Element
val update: (Msg, Model) -> Model = { _, model ->
model
}
asyncTest { resolve, _ ->
runBeginnerProgram(container, init, update, view) {
assertEquals("count = 0", fixture.text())
resolve(Unit)
}
}
}
@Test
fun testBeginnerViewProgram() {
val fixture = q(fixture())
val container = q("<div>").appendTo(fixture)[0] as Element
asyncTest { resolve, _ ->
runBeginnerProgram(container, Html.text("beginnerViewProgram")) {
assertEquals("beginnerViewProgram", fixture.text())
resolve(Unit)
}
}
}
@Test
fun testProgramRenderTiming() {
val update: Update<Int, Unit> = { _, model ->
model + 1 to null
}
val view: View<Int, Unit> = {
Html.button(onClick(Unit), text = "$it")
}
asyncSerialTest(
0, update, view,
{
assertEquals("0", it().text())
window.setTimeout({ it().find("button").click() }, 1)
window.setTimeout({ it().find("button").click() }, 2)
},
{
assertEquals("2", it().text())
}
)
}
@Test
fun testUnmount() {
val update = { _: Unit, model: Int -> model to null }
val view: (Int) -> Html<Unit> = { model: Int -> Html.text("$model") }
val tests = Bluebird.resolve(Unit)
.andThen { serialTest(0, update, view, null, { assertEquals("0", it().text()) }) }
.then { assertEquals("", q(fixture()).html()) }
.andThen { serialTest(1, update, view, null, { assertEquals("1", it().text()) }) }
asyncTest(tests)
}
} | mit | 54e343cf626f5de506328d7bf93a3e9a | 28.603306 | 98 | 0.521363 | 4.116092 | false | true | false | false |
valich/intellij-markdown | src/commonMain/kotlin/org/intellij/markdown/parser/sequentialparsers/impl/LinkParserUtil.kt | 1 | 5127 | package org.intellij.markdown.parser.sequentialparsers.impl
import org.intellij.markdown.IElementType
import org.intellij.markdown.MarkdownElementTypes
import org.intellij.markdown.MarkdownTokenTypes
import org.intellij.markdown.parser.sequentialparsers.*
class LinkParserUtil {
companion object {
fun parseLinkDestination(iterator: TokensCache.Iterator): LocalParsingResult? {
var it = iterator
if (it.type == MarkdownTokenTypes.EOL || it.type == MarkdownTokenTypes.RPAREN) {
return null
}
val startIndex = it.index
val withBraces = it.type == MarkdownTokenTypes.LT
if (withBraces) {
it = it.advance()
}
var hasOpenedParentheses = false
while (it.type != null) {
if (withBraces && it.type == MarkdownTokenTypes.GT) {
break
} else if (!withBraces) {
if (it.type == MarkdownTokenTypes.LPAREN) {
if (hasOpenedParentheses) {
break
}
hasOpenedParentheses = true
}
val next = it.rawLookup(1)
if (SequentialParserUtil.isWhitespace(it, 1) || next == null) {
break
} else if (next == MarkdownTokenTypes.RPAREN) {
if (!hasOpenedParentheses) {
break
}
hasOpenedParentheses = false
}
}
it = it.advance()
}
if (it.type != null && !hasOpenedParentheses) {
return LocalParsingResult(it,
listOf(SequentialParser.Node(startIndex..it.index + 1, MarkdownElementTypes.LINK_DESTINATION)))
}
return null
}
fun parseLinkLabel(iterator: TokensCache.Iterator): LocalParsingResult? {
var it = iterator
if (it.type != MarkdownTokenTypes.LBRACKET) {
return null
}
val startIndex = it.index
val delegate = RangesListBuilder()
it = it.advance()
while (it.type != MarkdownTokenTypes.RBRACKET && it.type != null) {
delegate.put(it.index)
if (it.type == MarkdownTokenTypes.LBRACKET) {
break
}
it = it.advance()
}
if (it.type == MarkdownTokenTypes.RBRACKET) {
val endIndex = it.index
if (endIndex == startIndex + 1) {
return null
}
return LocalParsingResult(it,
listOf(SequentialParser.Node(startIndex..endIndex + 1, MarkdownElementTypes.LINK_LABEL)),
delegate.get())
}
return null
}
fun parseLinkText(iterator: TokensCache.Iterator): LocalParsingResult? {
var it = iterator
if (it.type != MarkdownTokenTypes.LBRACKET) {
return null
}
val startIndex = it.index
val delegate = RangesListBuilder()
var bracketDepth = 1
it = it.advance()
while (it.type != null) {
if (it.type == MarkdownTokenTypes.RBRACKET) {
if (--bracketDepth == 0) {
break
}
}
delegate.put(it.index)
if (it.type == MarkdownTokenTypes.LBRACKET) {
bracketDepth++
}
it = it.advance()
}
if (it.type == MarkdownTokenTypes.RBRACKET) {
return LocalParsingResult(it,
listOf(SequentialParser.Node(startIndex..it.index + 1, MarkdownElementTypes.LINK_TEXT)),
delegate.get())
}
return null
}
fun parseLinkTitle(iterator: TokensCache.Iterator): LocalParsingResult? {
var it = iterator
if (it.type == MarkdownTokenTypes.EOL) {
return null
}
val startIndex = it.index
val closingType: IElementType?
if (it.type == MarkdownTokenTypes.SINGLE_QUOTE || it.type == MarkdownTokenTypes.DOUBLE_QUOTE) {
closingType = it.type
} else if (it.type == MarkdownTokenTypes.LPAREN) {
closingType = MarkdownTokenTypes.RPAREN
} else {
return null
}
it = it.advance()
while (it.type != null && it.type != closingType) {
it = it.advance()
}
if (it.type != null) {
return LocalParsingResult(it,
listOf(SequentialParser.Node(startIndex..it.index + 1, MarkdownElementTypes.LINK_TITLE)))
}
return null
}
}
}
| apache-2.0 | 282ee3e07125b8de17b02234d450dbf4 | 32.730263 | 119 | 0.484884 | 5.652701 | false | false | false | false |
icanit/mangafeed | app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/pager/PagerReaderAdapter.kt | 1 | 2226 | package eu.kanade.tachiyomi.ui.reader.viewer.pager
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentStatePagerAdapter
import android.support.v4.view.PagerAdapter
import android.view.ViewGroup
import eu.kanade.tachiyomi.data.source.model.Page
/**
* Adapter of pages for a ViewPager.
*
* @param fm the fragment manager.
*/
class PagerReaderAdapter(fm: FragmentManager) : FragmentStatePagerAdapter(fm) {
/**
* Pages stored in the adapter.
*/
var pages: List<Page>? = null
set(value) {
field = value
notifyDataSetChanged()
}
/**
* Returns the number of pages.
*
* @return the number of pages or 0 if the list is null.
*/
override fun getCount(): Int {
return pages?.size ?: 0
}
/**
* Creates a new fragment for the given position when it's called.
*
* @param position the position to instantiate.
* @return a fragment for the given position.
*/
override fun getItem(position: Int): Fragment {
return PagerReaderFragment.newInstance()
}
/**
* Instantiates a fragment in the given position.
*
* @param container the parent view.
* @param position the position to instantiate.
* @return an instance of a fragment for the given position.
*/
override fun instantiateItem(container: ViewGroup, position: Int): Any {
val f = super.instantiateItem(container, position) as PagerReaderFragment
f.page = pages!![position]
f.position = position
return f
}
/**
* Returns the position of a given item.
*
* @param obj the item to find its position.
* @return the position for the item.
*/
override fun getItemPosition(obj: Any): Int {
val f = obj as PagerReaderFragment
val position = f.position
if (position >= 0 && position < count) {
if (pages!![position] === f.page) {
return PagerAdapter.POSITION_UNCHANGED
} else {
return PagerAdapter.POSITION_NONE
}
}
return super.getItemPosition(obj)
}
}
| apache-2.0 | 0a292f6ab1551d7f246f40187df0cee7 | 27.538462 | 81 | 0.625786 | 4.452 | false | false | false | false |
ntemplon/ygo-combo-calculator | src/com/croffgrin/ygocalc/ui/Gui.kt | 1 | 2688 | package com.croffgrin.ygocalc.ui
import java.util.*
import javax.swing.JComponent
import javax.swing.JScrollPane
import javax.swing.UIManager
/*
* Copyright (c) 2016 Nathan S. Templon
*
* 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.
*/
object Gui {
fun configureGuiSettings() {
// Enable hardware acceleration
System.setProperty("sun.java2d.opengl", "true")
// Set look and feel
if (LAF_NAME != null) {
try {
UIManager.setLookAndFeel(Gui.LAF_NAME)
} catch (ex: Exception) {
}
}
}
private val NIMBUS: String? = UIManager.getInstalledLookAndFeels().firstOrNull { info -> info.name == "Nimbus" }?.className
private val METAL: String? = UIManager.getInstalledLookAndFeels().firstOrNull { info -> info.name == "Metal" }?.className
private val MOTIF: String? = UIManager.getInstalledLookAndFeels().firstOrNull { info -> info.name == "Motif" }?.className
private val NATIVE: String? = UIManager.getSystemLookAndFeelClassName()
private val PREFERENCE_ORDER: List<String?> by lazy {
val os = System.getProperty("os.name").toLowerCase(Locale.US)
when {
os.contains("win") -> listOf(NATIVE, METAL, NIMBUS, MOTIF) // Windows
os.contains("mac") -> listOf(NATIVE, NIMBUS, METAL, MOTIF) // Mac OS X
os.contains("nix") || os.contains("nux") || os.contains("aix") || os.contains("sunos") -> listOf(METAL, NATIVE, NIMBUS, MOTIF) // Unix, Linux, or Solaris
else -> listOf(METAL, NIMBUS, MOTIF, NATIVE)
}
}
val LAF_NAME: String? = PREFERENCE_ORDER.first { it != null }
} | mit | 5bbcc44b6302e7d45758c3268c72fc20 | 44.576271 | 165 | 0.68564 | 4.135385 | false | false | false | false |
tkiapril/Weisseliste | tests/kotlin/sql/tests/h2/Assert.kt | 1 | 1584 | package kotlin.sql.tests.h2
import org.joda.time.DateTime
import kotlin.test.assertEquals
private fun<T> assertEqualCollectionsImpl(collection : Collection<T>, expected : Collection<T>) {
assertEquals (expected.size, collection.size, "Count mismatch")
for (p in collection) {
assert(expected.any {p == it}) { "Unexpected element in collection pair $p" }
}
}
fun<T> assertEqualCollections (collection : Collection<T>, expected : Collection<T>) {
assertEqualCollectionsImpl(collection, expected)
}
fun<T> assertEqualCollections (collection : Collection<T>, vararg expected : T) {
assertEqualCollectionsImpl(collection, expected.toList())
}
fun<T> assertEqualCollections (collection : Iterable<T>, vararg expected : T) {
assertEqualCollectionsImpl(collection.toList(), expected.toList())
}
fun<T> assertEqualCollections (collection : Iterable<T>, expected : Collection<T>) {
assertEqualCollectionsImpl(collection.toList(), expected)
}
fun<T> assertEqualLists (l1: List<T>, l2: List<T>) {
assertEquals(l1.size, l2.size, "Count mismatch")
for (i in 0..l1.size -1)
assertEquals(l1[i], l2[i], "Error at pos $i:")
}
fun<T> assertEqualLists (l1: List<T>, vararg expected : T) {
assertEqualLists(l1, expected.toList())
}
fun assertEqualDateTime (d1: DateTime?, d2: DateTime?) {
if (d1 == null) {
if (d2 != null)
error("d1 is null while d2 is not")
return
} else {
if (d2 == null)
error ("d1 is not null while d2 is null")
assertEquals(d1.millis, d2.millis)
}
}
| agpl-3.0 | b0cd89ccbd665c5abfbe3702513ee7f5 | 31.326531 | 97 | 0.676768 | 3.58371 | false | false | false | false |
infinum/android_dbinspector | dbinspector/src/main/kotlin/com/infinum/dbinspector/ui/databases/DatabasesAdapter.kt | 1 | 1536 | package com.infinum.dbinspector.ui.databases
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.ListAdapter
import com.infinum.dbinspector.databinding.DbinspectorItemDatabaseBinding
import com.infinum.dbinspector.domain.database.models.DatabaseDescriptor
internal class DatabasesAdapter(
private val onClick: (DatabaseDescriptor) -> Unit,
private val interactions: DatabaseInteractions,
private val onEmpty: (Boolean) -> Unit
) : ListAdapter<DatabaseDescriptor, DatabaseViewHolder>(DatabaseDiffUtil()) {
init {
stateRestorationPolicy = StateRestorationPolicy.PREVENT_WHEN_EMPTY
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DatabaseViewHolder =
DatabaseViewHolder(
DbinspectorItemDatabaseBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
)
override fun onBindViewHolder(holder: DatabaseViewHolder, position: Int) =
holder.bind(
item = getItem(position),
onClick = onClick,
interactions = interactions
)
override fun onViewRecycled(holder: DatabaseViewHolder) =
with(holder) {
unbind()
super.onViewRecycled(this)
}
override fun onCurrentListChanged(
previousList: MutableList<DatabaseDescriptor>,
currentList: MutableList<DatabaseDescriptor>
) {
onEmpty(currentList.isEmpty())
}
}
| apache-2.0 | e7dd8e3f8b104d4437d97e7f5513bf79 | 31.680851 | 91 | 0.690755 | 5.446809 | false | false | false | false |
jeffgbutler/mybatis-qbe | src/test/kotlin/examples/kotlin/mybatis3/canonical/AddressDynamicSqlSupport.kt | 1 | 1672 | /*
* Copyright 2016-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package examples.kotlin.mybatis3.canonical
import org.mybatis.dynamic.sql.SqlTable
import org.mybatis.dynamic.sql.util.kotlin.elements.column
import java.sql.JDBCType
object AddressDynamicSqlSupport {
val address = Address()
val id = address.id
val streetAddress = address.streetAddress
val city = address.city
val state = address.state
val addressType = address.addressType
class Address : SqlTable("Address") {
val id = column<Int>(name = "address_id", jdbcType = JDBCType.INTEGER)
val streetAddress = column<String>(name = "street_address", jdbcType = JDBCType.VARCHAR)
val city = column<String>(name = "city", jdbcType = JDBCType.VARCHAR)
val state = column<String>(name = "state", jdbcType = JDBCType.VARCHAR)
val addressType = column(
name = "address_type",
jdbcType = JDBCType.INTEGER,
javaType = AddressType::class,
typeHandler = "org.apache.ibatis.type.EnumOrdinalTypeHandler"
)
}
}
| apache-2.0 | 5f1f4fc8ed1333cbc4a347c22696ae53 | 38.809524 | 96 | 0.687799 | 4.222222 | false | false | false | false |
FHannes/intellij-community | plugins/settings-repository/src/git/pull.kt | 16 | 15537 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.settingsRepository.git
import com.intellij.openapi.diagnostic.debug
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.SmartList
import com.intellij.util.containers.hash.LinkedHashMap
import org.eclipse.jgit.api.MergeCommand.FastForwardMode
import org.eclipse.jgit.api.MergeResult
import org.eclipse.jgit.api.MergeResult.MergeStatus
import org.eclipse.jgit.api.errors.CheckoutConflictException
import org.eclipse.jgit.api.errors.ConcurrentRefUpdateException
import org.eclipse.jgit.api.errors.JGitInternalException
import org.eclipse.jgit.api.errors.NoHeadException
import org.eclipse.jgit.diff.RawText
import org.eclipse.jgit.diff.Sequence
import org.eclipse.jgit.dircache.DirCacheCheckout
import org.eclipse.jgit.internal.JGitText
import org.eclipse.jgit.lib.*
import org.eclipse.jgit.merge.MergeMessageFormatter
import org.eclipse.jgit.merge.MergeStrategy
import org.eclipse.jgit.merge.ResolveMerger
import org.eclipse.jgit.merge.SquashMessageFormatter
import org.eclipse.jgit.revwalk.RevWalk
import org.eclipse.jgit.revwalk.RevWalkUtils
import org.eclipse.jgit.transport.CredentialsProvider
import org.eclipse.jgit.transport.RemoteConfig
import org.eclipse.jgit.transport.TrackingRefUpdate
import org.eclipse.jgit.treewalk.FileTreeIterator
import org.jetbrains.settingsRepository.*
import java.io.IOException
import java.text.MessageFormat
interface GitRepositoryClient {
val repository: Repository
val credentialsProvider: CredentialsProvider
}
class GitRepositoryClientImpl(override val repository: Repository, private val credentialsStore: Lazy<IcsCredentialsStore>) : GitRepositoryClient {
override val credentialsProvider: CredentialsProvider by lazy {
JGitCredentialsProvider(credentialsStore, repository)
}
}
open internal class Pull(val manager: GitRepositoryClient, val indicator: ProgressIndicator?, val commitMessageFormatter: CommitMessageFormatter = IdeaCommitMessageFormatter()) {
val repository = manager.repository
// we must use the same StoredConfig instance during the operation
val config = repository.config!!
val remoteConfig = RemoteConfig(config, Constants.DEFAULT_REMOTE_NAME)
fun pull(mergeStrategy: MergeStrategy = MergeStrategy.RECURSIVE, commitMessage: String? = null, prefetchedRefToMerge: Ref? = null): UpdateResult? {
indicator?.checkCanceled()
LOG.debug("Pull")
val state = repository.fixAndGetState()
if (!state.canCheckout()) {
LOG.error("Cannot pull, repository in state ${state.description}")
return null
}
val refToMerge = prefetchedRefToMerge ?: fetch() ?: return null
val mergeResult = merge(refToMerge, mergeStrategy, commitMessage = commitMessage)
val mergeStatus = mergeResult.status
LOG.debug { mergeStatus.toString() }
return when {
mergeStatus == MergeStatus.CONFLICTING -> resolveConflicts(mergeResult, repository)
!mergeStatus.isSuccessful -> throw IllegalStateException(mergeResult.toString())
else -> mergeResult.result
}
}
fun fetch(prevRefUpdateResult: RefUpdate.Result? = null, refUpdateProcessor: ((TrackingRefUpdate) -> Unit)? = null): Ref? {
indicator?.checkCanceled()
val fetchResult = repository.fetch(remoteConfig, manager.credentialsProvider, indicator.asProgressMonitor()) ?: return null
if (LOG.isDebugEnabled) {
printMessages(fetchResult)
for (refUpdate in fetchResult.trackingRefUpdates) {
LOG.debug(refUpdate.toString())
}
}
indicator?.checkCanceled()
var hasChanges = false
for (fetchRefSpec in remoteConfig.fetchRefSpecs) {
val refUpdate = fetchResult.getTrackingRefUpdate(fetchRefSpec.destination)
if (refUpdate == null) {
LOG.debug("No ref update for $fetchRefSpec")
continue
}
val refUpdateResult = refUpdate.result
// we can have more than one fetch ref spec, but currently we don't worry about it
if (refUpdateResult == RefUpdate.Result.LOCK_FAILURE || refUpdateResult == RefUpdate.Result.IO_FAILURE) {
if (prevRefUpdateResult == refUpdateResult) {
throw IOException("Ref update result ${refUpdateResult.name}, we have already tried to fetch again, but no luck")
}
LOG.warn("Ref update result ${refUpdateResult.name}, trying again after 500 ms")
Thread.sleep(500)
return fetch(refUpdateResult)
}
if (!(refUpdateResult == RefUpdate.Result.FAST_FORWARD || refUpdateResult == RefUpdate.Result.NEW || refUpdateResult == RefUpdate.Result.FORCED)) {
throw UnsupportedOperationException("Unsupported ref update result")
}
if (!hasChanges) {
hasChanges = refUpdateResult != RefUpdate.Result.NO_CHANGE
}
refUpdateProcessor?.invoke(refUpdate)
}
if (!hasChanges) {
LOG.debug("No remote changes")
return null
}
return fetchResult.getAdvertisedRef(config.getRemoteBranchFullName()) ?: throw IllegalStateException("Could not get advertised ref")
}
fun merge(unpeeledRef: Ref,
mergeStrategy: MergeStrategy = MergeStrategy.RECURSIVE,
commit: Boolean = true,
fastForwardMode: FastForwardMode = FastForwardMode.FF,
squash: Boolean = false,
forceMerge: Boolean = false,
commitMessage: String? = null): MergeResultEx {
indicator?.checkCanceled()
val head = repository.findRef(Constants.HEAD) ?: throw NoHeadException(JGitText.get().commitOnRepoWithoutHEADCurrentlyNotSupported)
// handle annotated tags
val ref = repository.peel(unpeeledRef)
val objectId = ref.peeledObjectId ?: ref.objectId
// Check for FAST_FORWARD, ALREADY_UP_TO_DATE
val revWalk = RevWalk(repository)
var dirCacheCheckout: DirCacheCheckout? = null
try {
val srcCommit = revWalk.lookupCommit(objectId)
val headId = head.objectId
if (headId == null) {
revWalk.parseHeaders(srcCommit)
dirCacheCheckout = DirCacheCheckout(repository, repository.lockDirCache(), srcCommit.tree)
dirCacheCheckout.setFailOnConflict(false)
dirCacheCheckout.checkout()
val refUpdate = repository.updateRef(head.target.name)
refUpdate.setNewObjectId(objectId)
refUpdate.setExpectedOldObjectId(null)
refUpdate.setRefLogMessage("initial pull", false)
if (refUpdate.update() != RefUpdate.Result.NEW) {
throw NoHeadException(JGitText.get().commitOnRepoWithoutHEADCurrentlyNotSupported)
}
return MergeResultEx(MergeStatus.FAST_FORWARD, arrayOf(null, srcCommit), ImmutableUpdateResult(dirCacheCheckout.updated.keys, dirCacheCheckout.removed))
}
val refLogMessage = StringBuilder("merge ")
refLogMessage.append(ref.name)
val headCommit = revWalk.lookupCommit(headId)
if (!forceMerge && revWalk.isMergedInto(srcCommit, headCommit)) {
return MergeResultEx(MergeStatus.ALREADY_UP_TO_DATE, arrayOf<ObjectId?>(headCommit, srcCommit), EMPTY_UPDATE_RESULT)
}
else if (!forceMerge && fastForwardMode != FastForwardMode.NO_FF && revWalk.isMergedInto(headCommit, srcCommit)) {
// FAST_FORWARD detected: skip doing a real merge but only update HEAD
refLogMessage.append(": ").append(MergeStatus.FAST_FORWARD)
dirCacheCheckout = DirCacheCheckout(repository, headCommit.tree, repository.lockDirCache(), srcCommit.tree)
dirCacheCheckout.setFailOnConflict(false)
dirCacheCheckout.checkout()
val mergeStatus: MergeStatus
if (squash) {
mergeStatus = MergeStatus.FAST_FORWARD_SQUASHED
val squashedCommits = RevWalkUtils.find(revWalk, srcCommit, headCommit)
repository.writeSquashCommitMsg(SquashMessageFormatter().format(squashedCommits, head))
}
else {
updateHead(refLogMessage, srcCommit, headId, repository)
mergeStatus = MergeStatus.FAST_FORWARD
}
return MergeResultEx(mergeStatus, arrayOf<ObjectId?>(headCommit, srcCommit), ImmutableUpdateResult(dirCacheCheckout.updated.keys, dirCacheCheckout.removed))
}
else {
if (fastForwardMode == FastForwardMode.FF_ONLY) {
return MergeResultEx(MergeStatus.ABORTED, arrayOf<ObjectId?>(headCommit, srcCommit), EMPTY_UPDATE_RESULT)
}
val mergeMessage: String
if (squash) {
mergeMessage = ""
repository.writeSquashCommitMsg(SquashMessageFormatter().format(RevWalkUtils.find(revWalk, srcCommit, headCommit), head))
}
else {
mergeMessage = commitMessageFormatter.mergeMessage(listOf(ref), head)
repository.writeMergeCommitMsg(mergeMessage)
repository.writeMergeHeads(listOf(ref.objectId))
}
val merger = mergeStrategy.newMerger(repository)
val noProblems: Boolean
var lowLevelResults: Map<String, org.eclipse.jgit.merge.MergeResult<out Sequence>>? = null
var failingPaths: Map<String, ResolveMerger.MergeFailureReason>? = null
var unmergedPaths: List<String>? = null
if (merger is ResolveMerger) {
merger.commitNames = arrayOf("BASE", "HEAD", ref.name)
merger.setWorkingTreeIterator(FileTreeIterator(repository))
noProblems = merger.merge(headCommit, srcCommit)
lowLevelResults = merger.mergeResults
failingPaths = merger.failingPaths
unmergedPaths = merger.unmergedPaths
}
else {
noProblems = merger.merge(headCommit, srcCommit)
}
refLogMessage.append(": Merge made by ")
refLogMessage.append(if (revWalk.isMergedInto(headCommit, srcCommit)) "recursive" else mergeStrategy.name)
refLogMessage.append('.')
var result = if (merger is ResolveMerger) ImmutableUpdateResult(merger.toBeCheckedOut.keys, merger.toBeDeleted) else null
if (noProblems) {
// ResolveMerger does checkout
if (merger !is ResolveMerger) {
dirCacheCheckout = DirCacheCheckout(repository, headCommit.tree, repository.lockDirCache(), merger.resultTreeId)
dirCacheCheckout.setFailOnConflict(false)
dirCacheCheckout.checkout()
result = ImmutableUpdateResult(dirCacheCheckout.updated.keys, dirCacheCheckout.removed)
}
var mergeStatus: MergeResult.MergeStatus? = null
if (!commit && squash) {
mergeStatus = MergeResult.MergeStatus.MERGED_SQUASHED_NOT_COMMITTED
}
if (!commit && !squash) {
mergeStatus = MergeResult.MergeStatus.MERGED_NOT_COMMITTED
}
if (commit && !squash) {
repository.commit(commitMessage, refLogMessage.toString()).id
mergeStatus = MergeResult.MergeStatus.MERGED
}
if (commit && squash) {
mergeStatus = MergeResult.MergeStatus.MERGED_SQUASHED
}
return MergeResultEx(mergeStatus!!, arrayOf(headCommit.id, srcCommit.id), result!!)
}
else if (failingPaths == null) {
repository.writeMergeCommitMsg(MergeMessageFormatter().formatWithConflicts(mergeMessage, unmergedPaths))
return MergeResultEx(MergeResult.MergeStatus.CONFLICTING, arrayOf(headCommit.id, srcCommit.id), result!!, lowLevelResults)
}
else {
repository.writeMergeCommitMsg(null)
repository.writeMergeHeads(null)
return MergeResultEx(MergeResult.MergeStatus.FAILED, arrayOf(headCommit.id, srcCommit.id), result!!, lowLevelResults)
}
}
}
catch (e: org.eclipse.jgit.errors.CheckoutConflictException) {
throw CheckoutConflictException(dirCacheCheckout?.conflicts ?: listOf(), e)
}
finally {
revWalk.close()
}
}
}
class MergeResultEx(val status: MergeStatus, val mergedCommits: Array<ObjectId?>, val result: ImmutableUpdateResult, val conflicts: Map<String, org.eclipse.jgit.merge.MergeResult<out Sequence>>? = null)
private fun updateHead(refLogMessage: StringBuilder, newHeadId: ObjectId, oldHeadID: ObjectId, repository: Repository) {
val refUpdate = repository.updateRef(Constants.HEAD)
refUpdate.setNewObjectId(newHeadId)
refUpdate.setRefLogMessage(refLogMessage.toString(), false)
refUpdate.setExpectedOldObjectId(oldHeadID)
val rc = refUpdate.update()
when (rc) {
RefUpdate.Result.NEW, RefUpdate.Result.FAST_FORWARD -> return
RefUpdate.Result.REJECTED, RefUpdate.Result.LOCK_FAILURE -> throw ConcurrentRefUpdateException(JGitText.get().couldNotLockHEAD, refUpdate.ref, rc)
else -> throw JGitInternalException(MessageFormat.format(JGitText.get().updatingRefFailed, Constants.HEAD, newHeadId.toString(), rc))
}
}
private fun resolveConflicts(mergeResult: MergeResultEx, repository: Repository): MutableUpdateResult {
assert(mergeResult.mergedCommits.size == 2)
val conflicts = mergeResult.conflicts!!
val mergeProvider = JGitMergeProvider(repository, conflicts, { path, index ->
val rawText = get(path)!!.sequences.get(index) as RawText
// RawText.EMPTY_TEXT if content is null - deleted
if (rawText == RawText.EMPTY_TEXT) null else rawText.content
})
val mergedFiles = resolveConflicts(mergeProvider, conflictsToVirtualFiles(conflicts), repository)
return mergeResult.result.toMutable().addChanged(mergedFiles)
}
private fun resolveConflicts(mergeProvider: JGitMergeProvider<out Any>, unresolvedFiles: MutableList<VirtualFile>, repository: Repository): List<String> {
val mergedFiles = SmartList<String>()
while (true) {
val resolvedFiles = resolveConflicts(unresolvedFiles, mergeProvider)
for (file in resolvedFiles) {
mergedFiles.add(file.path)
}
if (resolvedFiles.size == unresolvedFiles.size) {
break
}
else {
unresolvedFiles.removeAll { it.path in mergedFiles }
}
}
// merge commit template will be used, so, we don't have to specify commit message explicitly
repository.commit()
return mergedFiles
}
internal fun Repository.fixAndGetState(): RepositoryState {
var state = repositoryState
if (state == RepositoryState.MERGING) {
resolveUnmergedConflicts(this)
// compute new state
state = repositoryState
}
return state
}
internal fun resolveUnmergedConflicts(repository: Repository) {
val conflicts = LinkedHashMap<String, Array<ByteArray?>>()
repository.newObjectReader().use { reader ->
val dirCache = repository.readDirCache()
for (i in 0..(dirCache.entryCount - 1)) {
val entry = dirCache.getEntry(i)
if (!entry.isMerged) {
conflicts.getOrPut(entry.pathString, { arrayOfNulls<ByteArray>(3) })[entry.stage - 1] = reader.open(entry.objectId, Constants.OBJ_BLOB).cachedBytes
}
}
}
resolveConflicts(JGitMergeProvider(repository, conflicts, { path, index -> get(path)!!.get(index) }), conflictsToVirtualFiles(conflicts), repository)
} | apache-2.0 | af5c79869d66909fd06d72b22388c025 | 42.402235 | 202 | 0.722018 | 4.708182 | false | false | false | false |
AcapellaSoft/Aconite | aconite-client/src/io/aconite/client/KotlinProxyFactory.kt | 1 | 1669 | package io.aconite.client
import io.aconite.utils.allOrNull
import java.lang.reflect.Constructor
import java.lang.reflect.InvocationHandler
import java.lang.reflect.Method
import java.lang.reflect.Proxy
import java.util.concurrent.ConcurrentHashMap
import kotlin.reflect.KClass
import kotlin.reflect.KFunction
import kotlin.reflect.full.functions
import kotlin.reflect.jvm.javaMethod
typealias KotlinInvocationHandler = (KFunction<*>, Array<Any?>) -> Any?
internal object KotlinProxyFactory {
private val map = ConcurrentHashMap<Class<*>, ProxyInfo>()
private data class ProxyInfo(
val ctor: Constructor<*>,
val methodMap: Map<Method, KFunction<*>>
)
private class ModuleProxyHandler(proxyInfo: ProxyInfo, val handler: KotlinInvocationHandler): InvocationHandler {
val methodMap = proxyInfo.methodMap
override fun invoke(proxy: Any, method: Method, args: Array<Any?>): Any? {
val fn = methodMap[method]!!
return handler(fn, args)
}
}
@Suppress("UNCHECKED_CAST")
fun <T: Any> create(iface: KClass<T>, handler: KotlinInvocationHandler): T {
val cls = iface.java
val info = map.computeIfAbsent(cls) {
val proxyCls = Proxy.getProxyClass(cls.classLoader, cls)
ProxyInfo(
ctor = proxyCls.getConstructor(InvocationHandler::class.java),
methodMap = iface.functions
.mapNotNull { Pair(it.javaMethod, it).allOrNull() }
.toMap()
)
}
return info.ctor.newInstance(ModuleProxyHandler(info, handler)) as T
}
} | mit | 0497dbba3da9931b24f6104c9133bf06 | 34.531915 | 117 | 0.659676 | 4.623269 | false | false | false | false |
DSolyom/ViolinDS | ViolinDS/app/src/main/java/ds/violin/v1/model/modeling/Model.kt | 1 | 5728 | /*
Copyright 2016 Dániel Sólyom
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 ds.violin.v1.model.modeling
import android.database.Cursor
import ds.violin.v1.datasource.sqlite.*
import ds.violin.v1.model.entity.HasSerializableData
import ds.violin.v1.util.common.JSONObjectWrapper
import org.json.simple.JSONObject
import org.json.simple.JSONValue
import java.io.Serializable
import java.util.*
interface GetSetModeling<VALUE> {
fun has(key: String): Boolean
operator fun get(key: String): VALUE?
operator fun set(key: String, value: VALUE?)
fun remove(key: String) : VALUE?
}
interface Modeling<T, VALUE> : GetSetModeling<VALUE> {
var values: T?
}
interface IterableModeling<T, VALUE> : Modeling<T, VALUE>, Iterable<Any?> {
}
interface MapModeling<VALUE> : IterableModeling<MutableMap<String, VALUE>, VALUE> {
override fun get(key: String): VALUE? {
return values!![key]
}
override fun set(key: String, value: VALUE?) {
if (value == null) {
values!!.remove(key)
} else {
values!![key] = value
}
}
override fun has(key: String): Boolean {
return values?.containsKey(key) ?: false
}
override fun remove(key: String) : VALUE? {
return values?.remove(key)
}
fun clear() {
values!!.clear()
}
override operator fun iterator(): Iterator<Any?> {
return values!!.keys.iterator()
}
}
interface JSONModeling : IterableModeling<JSONObject, Any>, HasSerializableData, Serializable {
override fun get(key: String): Any? {
return values!![key]
}
override fun set(key: String, value: Any?) {
values!!.put(key, value)
}
override fun has(key: String): Boolean {
return values?.contains(key) ?: false
}
override fun remove(key: String) : Any? {
return values?.remove(key)
}
fun clear() {
values = JSONObject()
}
override operator fun iterator(): Iterator<Any?> {
return values!!.keys.iterator()
}
override fun dataToSerializable(): Serializable {
return JSONObjectWrapper(values)
}
override fun createDataFrom(serializedData: Serializable) {
values = (serializedData as JSONObjectWrapper).values!!
}
}
/**
* !note: unsafe - only hold in local scope - cursorPosition may change
*/
interface CursorModeling : Modeling<Cursor, Any> {
var _cursorPosition: Int
override fun get(key: String): Any? {
/** make sure cursor is in [_cursorPosition] at this point */
val columnIndex = values!!.getColumnIndex(key)
return when (values!!.getType(columnIndex)) {
Cursor.FIELD_TYPE_INTEGER -> values!!.getInt(columnIndex)
Cursor.FIELD_TYPE_STRING -> values!!.getString(columnIndex)
Cursor.FIELD_TYPE_FLOAT -> {
try {
values!!.getDouble(columnIndex)
} catch(e: Throwable) {
values!!.getFloat(columnIndex)
}
}
else -> null
}
}
override fun has(key: String): Boolean {
return (values?.getColumnIndex(key) ?: -1) != -1
}
override fun set(key: String, value: Any?) {
throw UnsupportedOperationException()
}
override fun remove(key: String) {
throw UnsupportedOperationException()
}
}
/**
* [JSONModeling] used in JSONEntity and [JSONArrayListModeling]
*/
open class JSONModel(values: JSONObject = JSONObject()) : JSONModeling {
override var values: JSONObject? = values
}
/**
* [MapModeling] for MapEntity
*/
open class MapModel(values: MutableMap<String, Any> = HashMap()) : MapModeling<Any> {
override var values: MutableMap<String, Any>? = values
}
/**
* a [MapModeling] which is [Serializable] and [HasSerializableData] for SerializableMapEntity and
* as such can only use [Serializable] data
*/
open class SerializableMapModel(values: MutableMap<String, Serializable> = HashMap()) :
MapModeling<Serializable>, Serializable, HasSerializableData {
override var values: MutableMap<String, Serializable>? = values
set(value) {
if (value !is Serializable) {
throw IllegalArgumentException()
}
field = value
}
override fun dataToSerializable(): Serializable {
return values as HashMap
}
override fun createDataFrom(serializedData: Serializable) {
values = serializedData as MutableMap<String, Serializable>
}
}
/**
* [CursorModeling] used in [CursorEntity]
*/
open class CursorModel(values: Cursor? = null, cursorPosition: Int = 0) : CursorModeling {
override var values: Cursor? = values
set(value) {
if (field != null && field != value && !field!!.isClosed) {
field!!.close()
}
value?.moveToPosition(_cursorPosition)
field = value
}
override var _cursorPosition: Int = cursorPosition
set(value) {
values?.moveToPosition(value)
field = value
}
init {
values?.moveToPosition(_cursorPosition)
}
} | apache-2.0 | dcae1ad96f1329bb0befef24389b8483 | 25.761682 | 98 | 0.633776 | 4.305263 | false | false | false | false |
milos85vasic/Pussycat | Android/src/main/kotlin/net/milosvasic/pussycat/android/data/parser/DefaultLogCatMessageHeaderMessageObtain.kt | 1 | 1410 | package net.milosvasic.pussycat.android.data.parser
import com.android.ddmlib.Log
import com.android.ddmlib.logcat.LogCatHeader
import com.android.ddmlib.logcat.LogCatMessage
import com.android.ddmlib.logcat.LogCatTimestamp
import net.milosvasic.pussycat.android.data.AndroidLogCatMessage
import java.util.regex.Matcher
class DefaultLogCatMessageHeaderMessageObtain : LogCatMessageObtain {
var lastHeader: LogCatHeader? = null
override fun getMessage(matcher: Matcher): AndroidLogCatMessage {
var pid = -1
try {
pid = Integer.parseInt(matcher.group(2))
} catch (ignored: NumberFormatException) {
}
var tid = -1
try {
tid = Integer.decode(matcher.group(3))!!
} catch (ignored: NumberFormatException) {
}
var logLevel: Log.LogLevel? = Log.LogLevel.getByLetterString(matcher.group(4))
if (logLevel == null && matcher.group(4) == "F") {
logLevel = Log.LogLevel.ASSERT
}
if (logLevel == null) {
logLevel = Log.LogLevel.WARN
}
lastHeader = LogCatHeader(
logLevel,
pid,
tid,
matcher.group(5),
matcher.group(5),
LogCatTimestamp.fromString(matcher.group(1))
)
return AndroidLogCatMessage.getFrom(LogCatMessage(lastHeader, ""))
}
} | apache-2.0 | ed78fbf0420f9fd5eaa28840dffe0f74 | 31.813953 | 86 | 0.624113 | 4.285714 | false | false | false | false |
graphql-java/graphql-java-tools | src/main/kotlin/graphql/kickstart/tools/resolver/MethodFieldResolver.kt | 1 | 11594 | package graphql.kickstart.tools.resolver
import com.fasterxml.jackson.core.type.TypeReference
import graphql.GraphQLContext
import graphql.TrivialDataFetcher
import graphql.kickstart.tools.*
import graphql.kickstart.tools.SchemaParserOptions.GenericWrapper
import graphql.kickstart.tools.util.JavaType
import graphql.kickstart.tools.util.coroutineScope
import graphql.kickstart.tools.util.isTrivialDataFetcher
import graphql.kickstart.tools.util.unwrap
import graphql.language.*
import graphql.schema.DataFetcher
import graphql.schema.DataFetchingEnvironment
import graphql.schema.GraphQLTypeUtil.isScalar
import kotlinx.coroutines.future.future
import org.slf4j.LoggerFactory
import java.lang.reflect.Method
import java.util.*
import kotlin.coroutines.intrinsics.suspendCoroutineUninterceptedOrReturn
import kotlin.reflect.full.valueParameters
import kotlin.reflect.jvm.javaType
import kotlin.reflect.jvm.kotlinFunction
/**
* @author Andrew Potter
*/
internal class MethodFieldResolver(
field: FieldDefinition,
search: FieldResolverScanner.Search,
options: SchemaParserOptions,
val method: Method
) : FieldResolver(field, search, options, search.type) {
private val log = LoggerFactory.getLogger(javaClass)
private val additionalLastArgument =
try {
(method.kotlinFunction?.valueParameters?.size
?: method.parameterCount) == (field.inputValueDefinitions.size + getIndexOffset() + 1)
} catch (e: InternalError) {
method.parameterCount == (field.inputValueDefinitions.size + getIndexOffset() + 1)
}
override fun createDataFetcher(): DataFetcher<*> {
val args = mutableListOf<ArgumentPlaceholder>()
val mapper = options.objectMapperProvider.provide(field)
// Add source argument if this is a resolver (but not a root resolver)
if (this.search.requiredFirstParameterType != null) {
val expectedType = this.search.requiredFirstParameterType
args.add { environment ->
val source = environment.getSource<Any>()
if (!expectedType.isAssignableFrom(source.javaClass)) {
throw ResolverError("Source type (${source.javaClass.name}) is not expected type (${expectedType.name})!")
}
source
}
}
// Add an argument for each argument defined in the GraphQL schema
this.field.inputValueDefinitions.forEachIndexed { index, definition ->
val parameterType = this.getMethodParameterType(index)
?.apply { genericType.getRawClass(this) }
?: throw ResolverError("Missing method type at position ${this.getJavaMethodParameterIndex(index)}, this is most likely a bug with graphql-java-tools")
val isNonNull = definition.type is NonNullType
val isOptional = this.genericType.getRawClass(parameterType) == Optional::class.java
args.add { environment ->
val argumentPresent = environment.arguments.containsKey(definition.name)
if (!argumentPresent && isNonNull) {
throw ResolverError("Missing required argument with name '${definition.name}', this is most likely a bug with graphql-java-tools")
}
val value = environment.arguments[definition.name]
if (value == null && isOptional) {
if (options.inputArgumentOptionalDetectOmission && !environment.containsArgument(definition.name)) {
return@add null
}
return@add Optional.empty<Any>()
}
if (value == null || shouldValueBeConverted(value, definition, parameterType, environment)) {
return@add mapper.convertValue(value, object : TypeReference<Any>() {
override fun getType() = parameterType
})
}
return@add value
}
}
// Add DataFetchingEnvironment/Context argument
if (this.additionalLastArgument) {
when (this.method.parameterTypes.last()) {
null -> throw ResolverError("Expected at least one argument but got none, this is most likely a bug with graphql-java-tools")
options.contextClass -> args.add { environment ->
val context: Any? = environment.graphQlContext[options.contextClass]
if (context != null) {
context
} else {
log.warn(
"Generic context class has been deprecated by graphql-java. " +
"To continue using a custom context class as the last parameter in resolver methods " +
"please insert it into the GraphQLContext map when building the ExecutionInput. " +
"This warning will become an error in the future."
)
environment.getContext() // TODO: remove deprecated use in next major release
}
}
GraphQLContext::class.java -> args.add { environment -> environment.graphQlContext }
else -> args.add { environment -> environment }
}
}
return if (args.isEmpty() && isTrivialDataFetcher(this.method)) {
TrivialMethodFieldResolverDataFetcher(getSourceResolver(), this.method, args, options)
} else {
MethodFieldResolverDataFetcher(getSourceResolver(), this.method, args, options)
}
}
private fun shouldValueBeConverted(value: Any, definition: InputValueDefinition, parameterType: JavaType, environment: DataFetchingEnvironment): Boolean {
return !parameterType.unwrap().isAssignableFrom(value.javaClass) || !isConcreteScalarType(environment, definition.type, parameterType)
}
/**
* A concrete scalar type is a scalar type where values always coerce to the same Java type. The ID scalar type is not concrete
* because values can be coerced to multiple different Java types (eg. String, Long, UUID). All values of a non-concrete scalar
* type must be converted to the target method parameter type.
*/
private fun isConcreteScalarType(environment: DataFetchingEnvironment, type: Type<*>, genericParameterType: JavaType): Boolean {
return when (type) {
is ListType -> List::class.java.isAssignableFrom(this.genericType.getRawClass(genericParameterType))
&& isConcreteScalarType(environment, type.type, this.genericType.unwrapGenericType(genericParameterType))
is TypeName -> environment.graphQLSchema?.getType(type.name)?.let { isScalar(it) && type.name != "ID" }
?: false
is NonNullType -> isConcreteScalarType(environment, type.type, genericParameterType)
else -> false
}
}
override fun scanForMatches(): List<TypeClassMatcher.PotentialMatch> {
val unwrappedGenericType = genericType.unwrapGenericType(try {
method.kotlinFunction?.returnType?.javaType ?: method.genericReturnType
} catch (e: InternalError) {
method.genericReturnType
})
val returnValueMatch = TypeClassMatcher.PotentialMatch.returnValue(field.type, unwrappedGenericType, genericType, SchemaClassScanner.ReturnValueReference(method))
return field.inputValueDefinitions.mapIndexed { i, inputDefinition ->
TypeClassMatcher.PotentialMatch.parameterType(inputDefinition.type, getMethodParameterType(i)!!, genericType, SchemaClassScanner.MethodParameterReference(method, i))
} + listOf(returnValueMatch)
}
private fun getIndexOffset(): Int {
return if (resolverInfo is DataClassTypeResolverInfo && !method.declaringClass.isAssignableFrom(resolverInfo.dataClassType)) {
1
} else {
0
}
}
private fun getJavaMethodParameterIndex(index: Int) = index + getIndexOffset()
private fun getMethodParameterType(index: Int): JavaType? {
val methodIndex = getJavaMethodParameterIndex(index)
val parameters = method.parameterTypes
return if (parameters.size > methodIndex) {
method.genericParameterTypes[methodIndex]
} else {
null
}
}
override fun toString() = "MethodFieldResolver{method=$method}"
}
internal open class MethodFieldResolverDataFetcher(
private val sourceResolver: SourceResolver,
method: Method,
private val args: List<ArgumentPlaceholder>,
private val options: SchemaParserOptions
) : DataFetcher<Any> {
private val resolverMethod = method
private val isSuspendFunction = try {
method.kotlinFunction?.isSuspend == true
} catch (e: InternalError) {
false
}
private class CompareGenericWrappers {
companion object : Comparator<GenericWrapper> {
override fun compare(w1: GenericWrapper, w2: GenericWrapper): Int = when {
w1.type.isAssignableFrom(w2.type) -> 1
else -> -1
}
}
}
override fun get(environment: DataFetchingEnvironment): Any? {
val source = sourceResolver(environment)
val args = this.args.map { it(environment) }.toTypedArray()
return if (isSuspendFunction) {
environment.coroutineScope().future(options.coroutineContextProvider.provide()) {
invokeSuspend(source, resolverMethod, args)?.transformWithGenericWrapper(environment)
}
} else {
invoke(resolverMethod, source, args)?.transformWithGenericWrapper(environment)
}
}
private fun Any.transformWithGenericWrapper(environment: DataFetchingEnvironment): Any? {
return options.genericWrappers
.asSequence()
.filter { it.type.isInstance(this) }
.sortedWith(CompareGenericWrappers)
.firstOrNull()
?.transformer?.invoke(this, environment) ?: this
}
/**
* Function that returns the object used to fetch the data.
* It can be a DataFetcher or an entity.
*/
@Suppress("unused")
open fun getWrappedFetchingObject(environment: DataFetchingEnvironment): Any {
return sourceResolver(environment)
}
}
internal class TrivialMethodFieldResolverDataFetcher(
sourceResolver: SourceResolver,
method: Method,
args: List<ArgumentPlaceholder>,
options: SchemaParserOptions
) : MethodFieldResolverDataFetcher(sourceResolver, method, args, options),
TrivialDataFetcher<Any> // just to mark it for tracing and optimizations
private suspend inline fun invokeSuspend(target: Any, resolverMethod: Method, args: Array<Any?>): Any? {
return suspendCoroutineUninterceptedOrReturn { continuation ->
invoke(resolverMethod, target, args + continuation)
}
}
@Suppress("NOTHING_TO_INLINE")
private inline fun invoke(method: Method, instance: Any, args: Array<Any?>): Any? {
try {
return method.invoke(instance, *args)
} catch (invocationException: java.lang.reflect.InvocationTargetException) {
val e = invocationException.cause
if (e is RuntimeException) {
throw e
}
if (e is Error) {
throw e
}
throw java.lang.reflect.UndeclaredThrowableException(e)
}
}
internal typealias ArgumentPlaceholder = (DataFetchingEnvironment) -> Any?
| mit | 348f090ec3690005c660496508ab95f5 | 41.782288 | 177 | 0.659134 | 5.194444 | false | false | false | false |
tasks/tasks | app/src/main/java/org/tasks/preferences/fragments/DashClock.kt | 1 | 1899 | package org.tasks.preferences.fragments
import android.os.Bundle
import androidx.lifecycle.lifecycleScope
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import org.tasks.LocalBroadcastManager
import org.tasks.R
import org.tasks.dialogs.FilterPicker.Companion.newFilterPicker
import org.tasks.dialogs.FilterPicker.Companion.setFilterPickerResultListener
import org.tasks.injection.InjectingPreferenceFragment
import org.tasks.preferences.DefaultFilterProvider
import javax.inject.Inject
@AndroidEntryPoint
class DashClock : InjectingPreferenceFragment() {
@Inject lateinit var defaultFilterProvider: DefaultFilterProvider
@Inject lateinit var localBroadcastManager: LocalBroadcastManager
override fun getPreferenceXml() = R.xml.preferences_dashclock
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
childFragmentManager.setFilterPickerResultListener(this) {
defaultFilterProvider.dashclockFilter = it
lifecycleScope.launch {
refreshPreferences()
}
localBroadcastManager.broadcastRefresh()
}
}
override suspend fun setupPreferences(savedInstanceState: Bundle?) {
findPreference(R.string.p_dashclock_filter)
.setOnPreferenceClickListener {
newFilterPicker(defaultFilterProvider.dashclockFilter)
.show(childFragmentManager, FRAG_TAG_SELECT_PICKER)
false
}
refreshPreferences()
}
private suspend fun refreshPreferences() {
val filter = defaultFilterProvider.getFilterFromPreference(R.string.p_dashclock_filter)
findPreference(R.string.p_dashclock_filter).summary = filter.listingTitle
}
companion object {
private const val FRAG_TAG_SELECT_PICKER = "frag_tag_select_picker"
}
} | gpl-3.0 | 764f5b4dbcd3763e34a66611f0479af2 | 34.849057 | 95 | 0.740916 | 5.275 | false | false | false | false |
pavelaizen/SoundZones | app/src/main/java/com/gm/soundzones/manager/RemoteMusicPlayer.kt | 1 | 1811 | package com.gm.soundzones.manager
import java.io.File
class RemoteMusicPlayer(baselineVolume: Int) : AudioPlayer(baselineVolume) {
val IP_ADDRESS:String = UserDataManager.getIpAddress()
private var track1CommWorker:CommunicationWorker?=null
private var track2CommWorker:CommunicationWorker?=null
private var noiseCommWorker:CommunicationWorker?=null
suspend override fun setVolumeMaster(volume: Int) =
CommunicationWorker(StringJob(IP_ADDRESS, UserDataManager.getVolumePort().toInt(),"m=$volume")).start().await()
suspend override fun setVolumeSecondary(volume: Int) =
CommunicationWorker(StringJob(IP_ADDRESS, UserDataManager.getVolumePort().toInt(),"s=$volume")).start().await()
suspend override fun playTrack1(audioFile: String):Result{
track1CommWorker?.waitTillComplete()
return CommunicationWorker(FileJob(IP_ADDRESS, UserDataManager.getMasterPort().toInt(), File(audioFile))).also { track1CommWorker=it }.start().await()
}
suspend override fun playTrack2(audioFile: String):Result{
track2CommWorker?.waitTillComplete()
return CommunicationWorker(FileJob(IP_ADDRESS, UserDataManager.getSecondaryPort().toInt(),File(audioFile))).also { track2CommWorker=it }.start().await()
}
suspend override fun playNoise(noiseFile: String):Result{
noiseCommWorker?.waitTillComplete()
return CommunicationWorker(FileJob(IP_ADDRESS, UserDataManager.getNoisePort().toInt(),File(noiseFile))).also { noiseCommWorker=it }.start().await()
}
private suspend fun CommunicationWorker.waitTillComplete(){
this.defer?.takeIf { !it.isCompleted }?.await()
}
override fun stop() {
track1CommWorker?.stop()
track2CommWorker?.stop()
noiseCommWorker?.stop()
}
} | apache-2.0 | c5db4cfa6701a62e498ffb6c9be23fe1 | 43.195122 | 160 | 0.728327 | 4.332536 | false | false | false | false |
goodwinnk/intellij-community | plugins/github/src/org/jetbrains/plugins/github/pullrequest/data/GithubPullRequestsChangesLoader.kt | 1 | 2591 | // 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.github.pullrequest.data
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.runInEdt
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.vcs.changes.Change
import com.intellij.openapi.vcs.changes.committed.CommittedChangesTreeBrowser
import com.intellij.util.EventDispatcher
import git4idea.history.GitLogUtil
import git4idea.repo.GitRepository
import org.jetbrains.annotations.CalledInAwt
import org.jetbrains.plugins.github.api.data.GithubSearchedIssue
import org.jetbrains.plugins.github.pullrequest.ui.GithubPullRequestsListComponent
import java.util.*
class GithubPullRequestsChangesLoader(private val project: Project,
progressManager: ProgressManager,
private val informationLoader: GithubPullRequestsDetailsLoader,
private val repository: GitRepository)
: SingleWorkerProcessExecutor(progressManager, "GitHub PR changes loading breaker"),
GithubPullRequestsListComponent.PullRequestSelectionListener {
private val stateEventDispatcher = EventDispatcher.create(ChangesLoadingListener::class.java)
override fun selectionChanged(selection: GithubSearchedIssue?) {
showChanges()
}
@CalledInAwt
fun showChanges() {
cancelCurrentTasks()
submit { indicator ->
try {
val pullRequest = informationLoader.detailsFuture?.get() ?: return@submit
val details = GitLogUtil.collectFullDetails(project, repository.root, "${pullRequest.base.sha}..${pullRequest.head.sha}")
val changes = CommittedChangesTreeBrowser.zipChanges(details.reversed().flatMap { it.changes })
runInEdt { if (!indicator.isCanceled) stateEventDispatcher.multicaster.changesLoaded(changes) }
}
catch (pce: ProcessCanceledException) {
// ignore
}
catch (e: Exception) {
runInEdt { if (!indicator.isCanceled) stateEventDispatcher.multicaster.errorOccurred(e) }
}
}
}
fun addLoadingListener(listener: ChangesLoadingListener, disposable: Disposable) = stateEventDispatcher.addListener(listener, disposable)
interface ChangesLoadingListener : EventListener {
fun changesLoaded(changes: List<Change>) {}
fun errorOccurred(error: Throwable) {}
}
} | apache-2.0 | 2c022136b9ed506b33d5724be7689be4 | 42.932203 | 140 | 0.753763 | 5.130693 | false | false | false | false |
nextcloud/android | app/src/main/java/com/nextcloud/client/logger/LoggerImpl.kt | 1 | 5792 | /*
* Nextcloud Android client application
*
* @author Chris Narkiewicz
* Copyright (C) 2019 Chris Narkiewicz <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.nextcloud.client.logger
import android.os.Handler
import android.util.Log
import com.nextcloud.client.core.Clock
import java.util.Date
import java.util.concurrent.BlockingQueue
import java.util.concurrent.LinkedBlockingQueue
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicLong
@Suppress("TooManyFunctions")
internal class LoggerImpl(
private val clock: Clock,
private val handler: FileLogHandler,
private val mainThreadHandler: Handler,
queueCapacity: Int
) : Logger, LogsRepository {
data class Load(val onResult: (List<LogEntry>, Long) -> Unit)
class Delete
private val looper = ThreadLoop()
private val eventQueue: BlockingQueue<Any> = LinkedBlockingQueue(queueCapacity)
private val processedEvents = mutableListOf<Any>()
private val otherEvents = mutableListOf<Any>()
private val missedLogs = AtomicBoolean()
private val missedLogsCount = AtomicLong()
override val lostEntries: Boolean
get() {
return missedLogs.get()
}
fun start() {
looper.start(this::eventLoop)
}
override fun v(tag: String, message: String) {
Log.v(tag, message)
enqueue(Level.VERBOSE, tag, message)
}
override fun d(tag: String, message: String) {
Log.d(tag, message)
enqueue(Level.DEBUG, tag, message)
}
override fun d(tag: String, message: String, t: Throwable) {
Log.d(tag, message, t)
enqueue(Level.DEBUG, tag, message)
}
override fun i(tag: String, message: String) {
Log.i(tag, message)
enqueue(Level.INFO, tag, message)
}
override fun w(tag: String, message: String) {
Log.w(tag, message)
enqueue(Level.WARNING, tag, message)
}
override fun e(tag: String, message: String) {
Log.e(tag, message)
enqueue(Level.ERROR, tag, message)
}
override fun e(tag: String, message: String, t: Throwable) {
Log.e(tag, message, t)
enqueue(Level.ERROR, tag, message)
}
override fun load(onLoaded: (entries: List<LogEntry>, totalLogSize: Long) -> Unit) {
eventQueue.put(Load(onLoaded))
}
override fun deleteAll() {
eventQueue.put(Delete())
}
private fun enqueue(level: Level, tag: String, message: String) {
try {
val entry = LogEntry(timestamp = clock.currentDate, level = level, tag = tag, message = message)
val enqueued = eventQueue.offer(entry, 1, TimeUnit.SECONDS)
if (!enqueued) {
missedLogs.set(true)
missedLogsCount.incrementAndGet()
}
} catch (ex: InterruptedException) {
// since interrupted flag is consumed now, we need to re-set the flag so
// the caller can continue handling the thread interruption in it's own way
Thread.currentThread().interrupt()
}
}
private fun eventLoop() {
try {
processedEvents.clear()
otherEvents.clear()
processedEvents.add(eventQueue.take())
eventQueue.drainTo(processedEvents)
// process all writes in bulk - this is most frequest use case and we can
// assume handler must be opened 99.999% of time; anything that is not a log
// write should be deferred
handler.open()
for (event in processedEvents) {
if (event is LogEntry) {
handler.write(event.toString() + "\n")
} else {
otherEvents.add(event)
}
}
handler.close()
// Those events are very sporadic and we don't have to be clever here
for (event in otherEvents) {
when (event) {
is Load -> {
val loaded = handler.loadLogFiles()
val entries = loaded.lines.mapNotNull { LogEntry.parse(it) }
mainThreadHandler.post {
event.onResult(entries, loaded.logSize)
}
}
is Delete -> handler.deleteAll()
}
}
checkAndLogLostMessages()
} catch (ex: InterruptedException) {
handler.close()
throw ex
}
}
private fun checkAndLogLostMessages() {
val lastMissedLogsCount = missedLogsCount.getAndSet(0)
if (lastMissedLogsCount > 0) {
handler.open()
val warning = LogEntry(
timestamp = Date(),
level = Level.WARNING,
tag = "Logger",
message = "Logger queue overflow. Approx $lastMissedLogsCount entries lost. You write too much."
).toString()
handler.write(warning)
handler.close()
}
}
}
| gpl-2.0 | 86f705d10b0c4fe666af14e42130d65c | 32.287356 | 112 | 0.60549 | 4.582278 | false | false | false | false |
soywiz/korge | korge-dragonbones/src/commonMain/kotlin/com/dragonbones/util/ArrayListExt.kt | 1 | 1170 | package com.dragonbones.util
import com.soywiz.kds.*
internal var IntArrayList.lengthSet: Int
get() = size
set(value) = run { size = value }
internal var DoubleArrayList.lengthSet: Int
get() = size
set(value) = run { size = value }
internal var IntArrayList.length: Int
get() = size
set(value) = run { size = value }
internal var DoubleArrayList.length: Int
get() = size
set(value) = run { size = value }
internal var <T> FastArrayList<T>.lengthSet
get() = size
set(value) = if (value == 0) clear() else {
while (size > value) this.removeAt(size - 1)
@Suppress("UNCHECKED_CAST")
while (size < value) (this as FastArrayList<T?>).add(null)
}
internal var <T> FastArrayList<T>.length; get() = size; set(value) = run { lengthSet = value }
internal fun DoubleArrayList.push(value: Double) = this.add(value)
internal fun IntArrayList.push(value: Int) = this.add(value)
internal fun <T> MutableList<T>.splice(removeOffset: Int, removeCount: Int, vararg itemsToAdd: T) {
// @TODO: Improve performance
for (n in 0 until removeCount) this.removeAt(removeOffset)
for (n in 0 until itemsToAdd.size) {
this.add(removeOffset + n, itemsToAdd[n])
}
}
| apache-2.0 | cb4a7d1ef492e8e269e67d694529dcf1 | 26.209302 | 99 | 0.698291 | 3.145161 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.