content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package opengles.templates
import org.lwjgl.generator.*
import opengles.*
val EXT_texture_mirror_clamp_to_edge = "EXTTextureMirrorClampToEdge".nativeClassGLES("EXT_texture_mirror_clamp_to_edge", postfix = EXT) {
documentation =
"""
Native bindings to the $registryLink extension.
{@code EXT_texture_mirror_clamp_to_edge} extends the set of texture wrap modes to include an additional mode (#MIRROR_CLAMP_TO_EDGE_EXT) that
effectively uses a texture map twice as large as the original image in which the additional half of the new image is a mirror image of the original
image.
This new mode relaxes the need to generate images whose opposite edges match by using the original image to generate a matching "mirror image". This
mode allows the texture to be mirrored only once in the negative s, t, and r directions.
"""
IntConstant(
"""
Accepted by the {@code param} parameter of TexParameter{if}, SamplerParameter{if} and SamplerParameter{if}v, and by the {@code params} parameter of
TexParameter{if}v, TexParameterI{i ui}v and SamplerParameterI{i ui}v when their {@code pname} parameter is #TEXTURE_WRAP_S, #TEXTURE_WRAP_T, or
#TEXTURE_WRAP_R.
""",
"MIRROR_CLAMP_TO_EDGE_EXT"..0x8743
)
} | modules/lwjgl/opengles/src/templates/kotlin/opengles/templates/EXT_texture_mirror_clamp_to_edge.kt | 3750420018 |
package de.flocksserver.data.service
import java.security.SecureRandom
import java.util.*
import javax.inject.Inject
/**
* Created by marcel on 8/30/17.
*/
class TextService @Inject constructor(){
private val LENGTH = 21
private val UPPER = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
private val LOWER = UPPER.toLowerCase(Locale.ROOT)
private val DIGITS = "0123456789"
private val alphanum = UPPER + LOWER + DIGITS
private var random: Random = SecureRandom()
private var symbols: CharArray = alphanum.toCharArray()
private var buf: CharArray = CharArray(LENGTH)
fun generateText(): String{
for (idx in 0 until buf.size){
buf[idx] = symbols[random.nextInt(symbols.size)]
}
return String(buf)
}
} | data/src/main/java/de/flocksserver/data/service/TextService.kt | 592467949 |
/*
* Copyright (C) 2014 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp3
import java.io.IOException
import java.util.concurrent.TimeUnit
/**
* Observes, modifies, and potentially short-circuits requests going out and the corresponding
* responses coming back in. Typically interceptors add, remove, or transform headers on the request
* or response.
*
* Implementations of this interface throw [IOException] to signal connectivity failures. This
* includes both natural exceptions such as unreachable servers, as well as synthetic exceptions
* when responses are of an unexpected type or cannot be decoded.
*
* Other exception types cancel the current call:
*
* * For synchronous calls made with [Call.execute], the exception is propagated to the caller.
*
* * For asynchronous calls made with [Call.enqueue], an [IOException] is propagated to the caller
* indicating that the call was canceled. The interceptor's exception is delivered to the current
* thread's [uncaught exception handler][Thread.UncaughtExceptionHandler]. By default this
* crashes the application on Android and prints a stacktrace on the JVM. (Crash reporting
* libraries may customize this behavior.)
*
* A good way to signal a failure is with a synthetic HTTP response:
*
* ```kotlin
* @Throws(IOException::class)
* override fun intercept(chain: Interceptor.Chain): Response {
* if (myConfig.isInvalid()) {
* return Response.Builder()
* .request(chain.request())
* .protocol(Protocol.HTTP_1_1)
* .code(400)
* .message("client config invalid")
* .body("client config invalid".toResponseBody(null))
* .build()
* }
*
* return chain.proceed(chain.request())
* }
* ```
*/
fun interface Interceptor {
@Throws(IOException::class)
fun intercept(chain: Chain): Response
companion object {
/**
* Constructs an interceptor for a lambda. This compact syntax is most useful for inline
* interceptors.
*
* ```kotlin
* val interceptor = Interceptor { chain: Interceptor.Chain ->
* chain.proceed(chain.request())
* }
* ```
*/
inline operator fun invoke(crossinline block: (chain: Chain) -> Response): Interceptor =
Interceptor { block(it) }
}
interface Chain {
fun request(): Request
@Throws(IOException::class)
fun proceed(request: Request): Response
/**
* Returns the connection the request will be executed on. This is only available in the chains
* of network interceptors; for application interceptors this is always null.
*/
fun connection(): Connection?
fun call(): Call
fun connectTimeoutMillis(): Int
fun withConnectTimeout(timeout: Int, unit: TimeUnit): Chain
fun readTimeoutMillis(): Int
fun withReadTimeout(timeout: Int, unit: TimeUnit): Chain
fun writeTimeoutMillis(): Int
fun withWriteTimeout(timeout: Int, unit: TimeUnit): Chain
}
}
| okhttp/src/main/kotlin/okhttp3/Interceptor.kt | 2669043809 |
package libsys
import org.junit.*
/**
* Test Book related operations
*/
class BookTest
{
private var book1: Book? = null
private var book2: Book? = null
/**
* Set up before testing
*/
@Before fun prepareTest()
{
book1 = Book("Book1", 10, "AVAILABLE")
book2 = Book("Book2", 12, "NOT AVAILABLE")
}
init
{
}
/**
* Test Book related operations
*/
@Test fun bookTest()
{
Assert.assertEquals("Title is \"Book1\"", book1!!.title, "Book1")
Assert.assertEquals("Status is \"AVAILABLE\"", book1!!.status, "AVAILABLE")
Assert.assertEquals("Book id is 10", book1!!.id, 10)
Assert.assertEquals("Title is \"Book2\"", book2!!.title, "Book2")
Assert.assertEquals("Status is \"NOT AVAILABLE\"", book2!!.status, "NOT AVAILABLE")
Assert.assertEquals("Book id is 12", book2!!.id, 12)
val date = intArrayOf(2018, 10, 5)
Assert.assertTrue("Rent should be successful", book1!!.rent(date))
Assert.assertEquals("Book status is \"RENTED\"", book1!!.status, "RENTED")
Assert.assertEquals("Book due date is 2018/10/5", book1!!.dueDate, date)
Assert.assertFalse("Book2 is not rent-able", book2!!.rent(date))
book1!!.returned()
Assert.assertTrue("Book1 is \"AVAILABLE\"", book1!!.status == "AVAILABLE")
val newBook1Title = "New Book 1"
book1!!.title = newBook1Title
Assert.assertEquals("Title is \"New Book 1\"", book1!!.title, newBook1Title)
val newBook2Title = "New Book 2"
book2!!.title = newBook2Title
Assert.assertEquals("Title is \"New Book 2\"", book2!!.title, newBook2Title)
val testBook1 = Book(10)
val testBook2 = Book("Test Title", 20, "RESERVED")
val testBook3 = Book(15, "Test Title 2", "RENTED", intArrayOf(2019, 3, 23))
Assert.assertEquals("Book name is \"UNDEFINED\"", testBook1.title, "UNDEFINED")
Assert.assertEquals("Book1 id is 10", testBook1.id, 10)
Assert.assertEquals("Book1 status is \"NOT AVAILABLE\"", testBook1.status, "NOT AVAILABLE")
Assert.assertEquals("Book2 title is \"Test Title\"", testBook2.title, "Test Title")
Assert.assertEquals("Book2 id is 20", testBook2.id, 20)
Assert.assertEquals("Book2 status is \"RESERVED\"", testBook2.status, "RESERVED")
Assert.assertEquals("Book3 title is \"Test Title 2\"", testBook3.title, "Test Title 2")
Assert.assertEquals("Book3 id is 15", testBook3.id, 15)
Assert.assertEquals("Book3 status is \"RENTED\"", testBook3.status, "RENTED")
val dueDate = testBook3.dueDate
Assert.assertEquals("Book3 due date year is 2019", dueDate[0], 2019)
Assert.assertEquals("Book3 due date month is 3", dueDate[1], 3)
Assert.assertEquals("Book3 due date day is 23", dueDate[2], 23)
}
}
| src/test/kotlin/libsys/BookTest.kt | 2586523396 |
package rynkbit.tk.coffeelist.ui.item
import androidx.lifecycle.ViewModelProviders
import android.os.Bundle
import android.renderscript.RSInvalidStateException
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.lifecycle.LiveData
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.Navigation
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import io.reactivex.Single
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.item_fragment.*
import rynkbit.tk.coffeelist.R
import rynkbit.tk.coffeelist.contract.entity.Customer
import rynkbit.tk.coffeelist.contract.entity.InvoiceState
import rynkbit.tk.coffeelist.contract.entity.Item
import rynkbit.tk.coffeelist.db.facade.InvoiceFacade
import rynkbit.tk.coffeelist.db.facade.ItemFacade
import rynkbit.tk.coffeelist.ui.MainActivity
import rynkbit.tk.coffeelist.ui.MainViewModel
import rynkbit.tk.coffeelist.ui.ResponsiveStaggeredGridLayoutManager
import rynkbit.tk.coffeelist.ui.entity.UIInvoice
import rynkbit.tk.coffeelist.ui.entity.UIItem
import java.lang.IllegalStateException
import java.util.*
class ItemFragment : Fragment() {
private lateinit var viewModel: ItemViewModel
private lateinit var itemAdapter: ItemAdapter
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.item_fragment, container, false)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
val activityViewModel = ViewModelProvider(activity!!)[MainViewModel::class.java]
viewModel = ViewModelProvider(this).get(ItemViewModel::class.java)
itemAdapter = ItemAdapter()
itemAdapter.onClickListener = { item ->
if (item.stock > 0) {
showConfirmationDialog(item, activityViewModel.customer)
} else {
showItemNotInStockMessage(item)
}
}
listItem.layoutManager = ResponsiveStaggeredGridLayoutManager(
context!!, StaggeredGridLayoutManager.VERTICAL
)
listItem.adapter = itemAdapter
}
private fun showItemNotInStockMessage(item: Item){
Toast
.makeText(context!!,
getString(R.string.item_outOfStock, item.name),
Toast.LENGTH_SHORT)
.show()
}
private fun showConfirmationDialog(item: Item, customer: Customer?){
BuyItemDialog(item) {
it.dismiss()
buyItemForCustomer(item, customer)
.observe(this, Observer {
activity?.runOnUiThread {
decreaseItemStock(item).observe(this, Observer {
Navigation
.findNavController(activity!!, R.id.nav_host)
.popBackStack()
})
}
})
}.show(fragmentManager!!, ItemFragment::class.java.simpleName)
}
private fun buyItemForCustomer(item: Item, customer: Customer?): LiveData<Long> {
return InvoiceFacade()
.createInvoiceForCustomerAndItem(item, customer ?:
throw IllegalStateException("Customer must not be null"))
}
private fun decreaseItemStock(item: Item): LiveData<Int> {
return ItemFacade()
.decreaseItemStock(item)
}
override fun onResume() {
super.onResume()
ItemFacade().findAll()
.observe(this,
Observer {
itemAdapter.updateItems(it)
})
}
}
| app/src/main/java/rynkbit/tk/coffeelist/ui/item/ItemFragment.kt | 3263366950 |
/*
* Copyright (C) 2016-Present The MoonLake ([email protected])
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.mcmoonlake.api.packet
import com.mcmoonlake.api.isCombatOrLaterVer
class PacketOutNamedSoundLegacyAdapter
: PacketLegacyAdapterCustom<PacketOutNamedSound, PacketOutNamedSoundLegacy>() {
override val packet: Class<PacketOutNamedSound>
get() = PacketOutNamedSound::class.java
override val packetName: String
get() = "PacketPlayOutCustomSoundEffect" // 1.9+
override val packetLegacy: Class<PacketOutNamedSoundLegacy>
get() = PacketOutNamedSoundLegacy::class.java
override val packetLegacyName: String
get() = "PacketPlayOutNamedSoundEffect" // 1.8.x
override val isLegacy: Boolean
get() = !isCombatOrLaterVer
}
| API/src/main/kotlin/com/mcmoonlake/api/packet/PacketOutNamedSoundLegacyAdapter.kt | 398928735 |
package org.moire.ultrasonic.api.subsonic
import okhttp3.mockwebserver.MockResponse
import org.amshove.kluent.`should be equal to`
import org.amshove.kluent.`should be`
import org.amshove.kluent.`should equal`
import org.amshove.kluent.`should not be`
import org.junit.Test
/**
* Integration test for [SubsonicAPIClient] for [SubsonicAPIDefinition.getCoverArt] call.
*/
class SubsonicApiGetCoverArtTest : SubsonicAPIClientTest() {
@Test
fun `Should handle api error response`() {
mockWebServerRule.enqueueResponse("request_data_not_found_error_response.json")
val response = client.getCoverArt("some-id")
with(response) {
stream `should be` null
responseHttpCode `should be equal to` 200
apiError `should equal` SubsonicError.RequestedDataWasNotFound
}
}
@Test
fun `Should handle server error`() {
val httpErrorCode = 404
mockWebServerRule.mockWebServer.enqueue(MockResponse().setResponseCode(httpErrorCode))
val response = client.getCoverArt("some-id")
with(response) {
stream `should be` null
responseHttpCode `should equal` 404
apiError `should be` null
}
}
@Test
fun `Should return successful call stream`() {
mockWebServerRule.mockWebServer.enqueue(
MockResponse()
.setBody(mockWebServerRule.loadJsonResponse("ping_ok.json"))
)
val response = client.getCoverArt("some-id")
with(response) {
responseHttpCode `should be equal to` 200
apiError `should be` null
stream `should not be` null
val expectedContent = mockWebServerRule.loadJsonResponse("ping_ok.json")
stream!!.bufferedReader().readText() `should be equal to` expectedContent
}
}
@Test
fun `Should pass id as parameter`() {
val id = "ca123994"
mockWebServerRule.assertRequestParam("ping_ok.json", id) {
client.api.getCoverArt(id).execute()
}
}
@Test
fun `Should pass size as a parameter`() {
val size = 45600L
mockWebServerRule.assertRequestParam("ping_ok.json", size.toString()) {
client.api.getCoverArt("some-id", size).execute()
}
}
}
| core/subsonic-api/src/integrationTest/kotlin/org/moire/ultrasonic/api/subsonic/SubsonicApiGetCoverArtTest.kt | 3044485485 |
package com.tinmegali.myweather.web
import android.arch.lifecycle.LiveData
import com.tinmegali.myweather.R
import com.tinmegali.myweather.models.ApiResponse
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type
import retrofit2.CallAdapter
import retrofit2.Retrofit
class LiveDataCallAdapterFactory : CallAdapter.Factory() {
override fun get(returnType: Type, annotations: Array<Annotation>, retrofit: Retrofit): CallAdapter<Any, Any>? {
if (CallAdapter.Factory.getRawType(returnType) != LiveData::class.java) {
return null
}
val observableType = CallAdapter.Factory.getParameterUpperBound(0, returnType as ParameterizedType)
val rawObservableType = CallAdapter.Factory.getRawType(observableType)
if (rawObservableType != ApiResponse::class.java) {
throw IllegalArgumentException("type must be a resource")
}
if (observableType !is ParameterizedType) {
throw IllegalArgumentException("resource must be parameterized")
}
val bodyType = CallAdapter.Factory.getParameterUpperBound(0, observableType)
return LiveDataCallAdapter<Any>(bodyType) as CallAdapter<Any, Any>
}
}
| app/src/main/java/com/tinmegali/myweather/web/LiveDataCallAdapterFactory.kt | 674671443 |
// 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.jetbrains.python.target
import com.intellij.execution.target.LanguageRuntimeConfiguration
import com.intellij.openapi.components.BaseState
import com.intellij.openapi.components.PersistentStateComponent
/**
* This is the intended misuse of [LanguageRuntimeConfiguration] concept. This class is for passing the target introspection results to the
* panels that configure different Python virtual envs.
*/
class PythonLanguageRuntimeConfiguration : LanguageRuntimeConfiguration(PythonLanguageRuntimeType.TYPE_ID),
PersistentStateComponent<PythonLanguageRuntimeConfiguration.State> {
var pythonInterpreterPath: String = ""
var userHome: String = ""
class State : BaseState() {
var pythonInterpreterPath by string()
var userHome by string()
}
override fun getState(): State = State().also {
it.pythonInterpreterPath = pythonInterpreterPath
it.userHome = userHome
}
override fun loadState(state: State) {
pythonInterpreterPath = state.pythonInterpreterPath.orEmpty()
userHome = state.userHome.orEmpty()
}
} | python/src/com/jetbrains/python/target/PythonLanguageRuntimeConfiguration.kt | 1403714790 |
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.diff.contents
import com.intellij.diff.HeavyDiffTestCase
import com.intellij.diff.actions.DocumentFragmentContent
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.command.CommandProcessor
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.EditorFactory
import com.intellij.openapi.util.TextRange
class FragmentContentTest : HeavyDiffTestCase() {
private lateinit var document: Document
private lateinit var fragment: Document
private lateinit var documentContent: DocumentContent
private lateinit var fragmentContent: DocumentFragmentContent
override fun setUp() {
super.setUp()
document = EditorFactory.getInstance().createDocument("0123456789")
documentContent = DocumentContentImpl(document)
fragmentContent = DocumentFragmentContent(null, documentContent, TextRange(3, 7))
fragment = fragmentContent.document
fragmentContent.onAssigned(true)
}
override fun tearDown() {
try {
fragmentContent.onAssigned(false)
}
finally {
super.tearDown()
}
}
fun testSynchronization() {
assertEquals("3456", fragment.text)
replaceString(fragment, 1, 3, "xy")
assertEquals("0123xy6789", document.text)
replaceString(document, 4, 6, "45")
assertEquals("0123456789", document.text)
assertEquals("3456", fragment.text)
replaceString(document, 0, 1, "xyz")
assertEquals("3456", fragment.text)
replaceString(fragment, 1, 3, "xy")
assertEquals("xyz123xy6789", document.text)
}
fun testEditReadonlyDocument() {
documentContent.onAssigned(false)
document.setReadOnly(true)
documentContent.onAssigned(true)
assertFalse(fragment.isWritable)
}
fun testOriginalBecomesReadOnly() {
assertTrue(fragment.isWritable)
document.setReadOnly(true)
assertFalse(fragment.isWritable)
document.setReadOnly(false)
assertTrue(fragment.isWritable)
}
fun testRemoveOriginalFragment() {
assertTrue(fragment.isWritable)
replaceString(document, 2, 8, "")
assertEquals("0189", document.text)
assertEquals("Invalid selection range", fragment.text)
assertFalse(fragment.isWritable)
}
fun testRemoveListeners() {
replaceString(fragment, 0, 1, "x")
assertEquals("012x456789", document.text)
fragmentContent.onAssigned(false)
replaceString(fragment, 0, 1, "3")
assertEquals("012x456789", document.text)
replaceString(document, 3, 4, "y")
assertEquals("012y456789", document.text)
assertEquals("3456", fragment.text)
fragmentContent.onAssigned(true)
}
private fun replaceString(document: Document, startOffset: Int, endOffset: Int, string: String) {
ApplicationManager.getApplication().runWriteAction {
CommandProcessor.getInstance().executeCommand(null, {
document.replaceString(startOffset, endOffset, string)
}, null, null)
}
}
}
| platform/diff-impl/tests/testSrc/com/intellij/diff/contents/FragmentContentTest.kt | 2729611549 |
package one.two
fun write() {
with(KotlinObject) {
42.staticExtensionVariable = 3
}
} | plugins/kotlin/refIndex/tests/testData/compilerIndex/properties/fromObject/staticExtensionVariable/Write.kt | 2202803090 |
/*
* Copyright (c) 2019 VenomVendor. All rights reserved.
* Created by VenomVendor on 18-Feb-2019.
*/
package com.venomvendor.tigerspike.core
import android.app.Application
/**
* Application class for core functionality.
*/
class TigerApplication : Application()
// TODO: For future usage.
| demo/src/main/java/com/venomvendor/tigerspike/core/TigerApplication.kt | 1062164244 |
/**
* Copyright (C) 2017 Cesar Valiente & Corey Shaw
*
* https://github.com/CesarValiente
* https://github.com/coshaw
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.cesarvaliente.kunidirectional.itemslist.recyclerview
import android.support.v7.util.DiffUtil
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.ViewGroup
import com.cesarvaliente.kunidirectional.R
import com.cesarvaliente.kunidirectional.getStableId
import com.cesarvaliente.kunidirectional.store.Item
import java.util.Collections
internal interface ItemTouchHelperAdapter {
fun onItemMove(fromPosition: Int, toPosition: Int)
fun onItemDeleted(position: Int)
}
class ItemsAdapter(
private var items: List<Item>,
private val itemClick: (Item) -> Unit,
private val setFavorite: (Item) -> Unit,
private val updateItemsPositions: (List<Item>) -> Unit,
private val deleteItem: (Item) -> Unit)
: RecyclerView.Adapter<ItemViewHolder>(), ItemTouchHelperAdapter {
init {
setHasStableIds(true)
}
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ItemViewHolder {
val view = LayoutInflater.from(parent?.context).inflate(R.layout.item_layout, parent, false)
return ItemViewHolder(view, itemClick, setFavorite, this::updateItemsPositions)
}
override fun onBindViewHolder(itemViewHolder: ItemViewHolder, position: Int) {
itemViewHolder.bindItem(items[position])
}
override fun getItemCount(): Int = items.size
fun getItem(position: Int): Item = items[position]
override fun getItemId(position: Int): Long =
getItem(position).getStableId()
fun removeAt(position: Int) {
items = items.minus(items[position])
notifyItemRemoved(position)
}
fun updateItems(newItems: List<Item>) {
val oldItems = items
items = newItems
applyDiff(oldItems, items)
}
private fun applyDiff(oldItems: List<Item>, newItems: List<Item>) {
val diffResult = DiffUtil.calculateDiff(ItemsDiffCallback(oldItems, newItems))
diffResult.dispatchUpdatesTo(this)
}
private fun updateItemsPositions() {
updateItemsPositions(items)
}
override fun onItemDeleted(position: Int) {
deleteItem(items[position])
removeAt(position)
}
override fun onItemMove(fromPosition: Int, toPosition: Int) {
swapItems(fromPosition, toPosition)
notifyItemMoved(fromPosition, toPosition)
}
fun swapItems(fromPosition: Int, toPosition: Int) = if (fromPosition < toPosition) {
(fromPosition .. toPosition - 1).forEach { i ->
swapPositions(i, i + 1)
Collections.swap(items, i, i + 1)
}
} else {
(fromPosition downTo toPosition + 1).forEach { i ->
swapPositions(i, i - 1)
Collections.swap(items, i, i - 1)
}
}
fun swapPositions(position1: Int, position2: Int) {
val item1 = items[position1]
val item2 = items[position2]
items = items.map {
if (it.localId == item1.localId) it.copy(position = item2.position)
else if (it.localId == item2.localId) it.copy(position = item1.position)
else it
}
}
} | app/src/main/kotlin/com/cesarvaliente/kunidirectional/itemslist/recyclerview/ItemsAdapter.kt | 1052611423 |
package evoasm
inline fun measureTimeSeconds(block: () -> Unit): Double {
val start = System.nanoTime()
block()
return (System.nanoTime() - start).toDouble() / 1e9
}
| src/evoasm/Ext.kt | 1788596164 |
/*
* Copyright 2014 Cazcade Limited (http://cazcade.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @todo document.
* @author <a href="http://uk.linkedin.com/in/neilellis">Neil Ellis</a>
*/
import org.junit.Test as test
import org.junit.Before as before
import org.junit.After as after
import kontrol.sensor.SSHLoadSensor
import kontrol.mock.MockMachine
import kontrol.common.DefaultSensorArray
import kontrol.mock.MockDoubleSensor
public class TestSensors {
test fun testLoad(): Unit {
val sensor = SSHLoadSensor()
sensor.start();
println(sensor.value(MockMachine("teamcity.cazcade.com")));
sensor.stop();
}
test fun testArray(): Unit {
val sensors = listOf(MockDoubleSensor(50..100))
val array = DefaultSensorArray(sensors)
val machines = listOf(MockMachine("1.2.3.4"), MockMachine("1.2.3.5"))
//
// println(array.avg(machines, "mock"));
// println(array.sum(machines, "mock"));
// println(array.max(machines, "mock"));
// println(array.min(machines, "mock"));
//
// assert(array.avg(machines, "mock")!! > 50);
// assert(array.sum(machines, "mock")!! > 100);
// assert(array.max(machines, "mock")!! > 50);
// assert(array.min(machines, "mock")!! > 50);
//
// assert(array.avg(machines, "mock")!! < 100);
// assert(array.sum(machines, "mock")!! < 200);
// assert(array.max(machines, "mock")!! < 100);
// assert(array.min(machines, "mock")!! < 100);
}
}
| sensors/src/test/kotlin/TestSensors.kt | 547971298 |
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.stats.completion
import com.intellij.stats.completion.events.LogEvent
interface CompletionEventLogger {
fun log(event: LogEvent)
} | plugins/stats-collector/src/com/intellij/stats/completion/CompletionEventLogger.kt | 3245877842 |
package variances
data class Producer<out T : Beverage>(
val beverage: T
) {
fun produce(): T = beverage
}
class Consumer<in T : Beverage> {
fun consume(t: T) = println("Thanks for the drink $t!")
}
interface Beverage
object Coffee : Beverage
object Whisky : Beverage
fun main(args: Array<String>) {
val colombia: Producer<Coffee> = Producer(Coffee)
val scottland: Producer<Whisky> = Producer(Whisky)
// val noCoffeeThere : Coffee = scottland.produce() // error
val beverages: List<Beverage> = listOf(colombia, scottland).map { it.produce() }
val starbucks = Consumer<Coffee>()
starbucks.consume(colombia.produce())
// starbucks.consume(scottland.produce()) // error
val pub = Consumer<Whisky>()
pub.consume(scottland.produce())
// pub.consume(colombia.produce()) // error
}
| test/kotlin/variances.kt | 180229002 |
// 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.actions
import com.intellij.configurationStore.StoreUtil
import com.intellij.openapi.actionSystem.Presentation
import com.intellij.openapi.actionSystem.UpdateInBackground
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.vcs.FilePath
import com.intellij.openapi.vcs.ProjectLevelVcsManager
import com.intellij.openapi.vcs.VcsBundle.message
import com.intellij.openapi.vcs.changes.*
import com.intellij.openapi.vcs.changes.ui.CommitChangeListDialog
import com.intellij.util.containers.ContainerUtil.concat
import com.intellij.util.ui.UIUtil.removeMnemonic
private val LOG = logger<AbstractCommonCheckinAction>()
private fun getChangesIn(project: Project, roots: Array<FilePath>): Set<Change> {
val manager = ChangeListManager.getInstance(project)
return roots.flatMap { manager.getChangesIn(it) }.toSet()
}
abstract class AbstractCommonCheckinAction : AbstractVcsAction(), UpdateInBackground {
override fun update(vcsContext: VcsContext, presentation: Presentation) {
val project = vcsContext.project
if (project == null || !ProjectLevelVcsManager.getInstance(project).hasActiveVcss()) {
presentation.isEnabledAndVisible = false
}
else if (!approximatelyHasRoots(vcsContext)) {
presentation.isEnabled = false
}
else {
getActionName(vcsContext)?.let { presentation.text = "$it..." }
presentation.isEnabled = !ProjectLevelVcsManager.getInstance(project).isBackgroundVcsOperationRunning
presentation.isVisible = true
}
}
protected abstract fun approximatelyHasRoots(dataContext: VcsContext): Boolean
protected open fun getActionName(dataContext: VcsContext): String? = null
public override fun actionPerformed(context: VcsContext) {
LOG.debug("actionPerformed. ")
val project = context.project!!
val actionName = getActionName(context)?.let { removeMnemonic(it) } ?: templatePresentation.text
val isFreezedDialogTitle = actionName?.let { "Can not $it now" }
if (ChangeListManager.getInstance(project).isFreezedWithNotification(isFreezedDialogTitle)) {
LOG.debug("ChangeListManager is freezed. returning.")
}
else if (ProjectLevelVcsManager.getInstance(project).isBackgroundVcsOperationRunning) {
LOG.debug("Background operation is running. returning.")
}
else {
val roots = prepareRootsForCommit(getRoots(context), project)
ChangeListManager.getInstance(project).invokeAfterUpdate(
{ performCheckIn(context, project, roots) }, InvokeAfterUpdateMode.SYNCHRONOUS_CANCELLABLE,
message("waiting.changelists.update.for.show.commit.dialog.message"), ModalityState.current())
}
}
@Deprecated("getActionName() will be used instead")
protected open fun getMnemonicsFreeActionName(context: VcsContext): String? = null
protected abstract fun getRoots(dataContext: VcsContext): Array<FilePath>
protected open fun prepareRootsForCommit(roots: Array<FilePath>, project: Project): Array<FilePath> {
StoreUtil.saveDocumentsAndProjectSettings(project)
return DescindingFilesFilter.filterDescindingFiles(roots, project)
}
protected open fun performCheckIn(context: VcsContext, project: Project, roots: Array<FilePath>) {
LOG.debug("invoking commit dialog after update")
val selectedChanges = context.selectedChanges
val selectedUnversioned = context.selectedUnversionedFiles
val changesToCommit: Collection<Change>
val included: Collection<*>
if (selectedChanges.isNullOrEmpty() && selectedUnversioned.isEmpty()) {
changesToCommit = getChangesIn(project, roots)
included = changesToCommit
}
else {
changesToCommit = selectedChanges.orEmpty().toList()
included = concat(changesToCommit, selectedUnversioned)
}
val initialChangeList = getInitiallySelectedChangeList(context, project)
CommitChangeListDialog.commitChanges(project, changesToCommit, included, initialChangeList, getExecutor(project), null)
}
protected open fun getInitiallySelectedChangeList(context: VcsContext, project: Project): LocalChangeList? {
val manager = ChangeListManager.getInstance(project)
context.selectedChangeLists?.firstOrNull()?.let { return manager.findChangeList(it.name) }
context.selectedChanges?.firstOrNull()?.let { return manager.getChangeList(it) }
return manager.defaultChangeList
}
protected open fun getExecutor(project: Project): CommitExecutor? = null
}
| platform/vcs-impl/src/com/intellij/openapi/vcs/actions/AbstractCommonCheckinAction.kt | 4208430837 |
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.debugger
import com.intellij.openapi.util.text.StringUtil
import com.intellij.util.SmartList
import com.intellij.xdebugger.frame.XCompositeNode
import com.intellij.xdebugger.frame.XValueChildrenList
import org.jetbrains.concurrency.Obsolescent
import org.jetbrains.concurrency.ObsolescentFunction
import org.jetbrains.concurrency.Promise
import org.jetbrains.debugger.values.ValueType
import java.util.*
import java.util.regex.Pattern
private val UNNAMED_FUNCTION_PATTERN = Pattern.compile("^function[\\t ]*\\(")
private val NATURAL_NAME_COMPARATOR = object : Comparator<Variable> {
override fun compare(o1: Variable, o2: Variable) = naturalCompare(o1.name, o2.name)
}
// start properties loading to achieve, possibly, parallel execution (properties loading & member filter computation)
fun processVariables(context: VariableContext,
variables: Promise<List<Variable>>,
obsolescent: Obsolescent,
consumer: (memberFilter: MemberFilter, variables: List<Variable>) -> Unit) = context.memberFilter
.then(object : ValueNodeAsyncFunction<MemberFilter, Any?>(obsolescent) {
override fun `fun`(memberFilter: MemberFilter): Promise<Any?> {
return variables.then(object : ObsolescentFunction<List<Variable>, Any?> {
override fun isObsolete() = obsolescent.isObsolete
override fun `fun`(variables: List<Variable>): Void? {
consumer(memberFilter, variables)
return null
}
})
}
})
fun processScopeVariables(scope: Scope,
node: XCompositeNode,
context: VariableContext,
isLast: Boolean) = processVariables(context, scope.variablesHost.get(), node, { memberFilter, variables ->
val additionalVariables = memberFilter.additionalVariables
val properties = ArrayList<Variable>(variables.size + additionalVariables.size)
val functions = SmartList<Variable>()
for (variable in variables) {
if (memberFilter.isMemberVisible(variable)) {
val value = variable.value
if (value != null && value.type == ValueType.FUNCTION && value.valueString != null && !UNNAMED_FUNCTION_PATTERN.matcher(value.valueString).lookingAt()) {
functions.add(variable)
}
else {
properties.add(variable)
}
}
}
val comparator = if (memberFilter.hasNameMappings()) comparator { o1, o2 -> naturalCompare(memberFilter.rawNameToSource(o1), memberFilter.rawNameToSource(o2)) } else NATURAL_NAME_COMPARATOR
Collections.sort(properties, comparator)
Collections.sort(functions, comparator)
addAditionalVariables(variables, additionalVariables, properties, memberFilter)
if (!properties.isEmpty()) {
node.addChildren(createVariablesList(properties, context, memberFilter), functions.isEmpty() && isLast)
}
if (!functions.isEmpty()) {
node.addChildren(XValueChildrenList.bottomGroup(VariablesGroup("Functions", functions, context)), isLast)
}
else if (isLast && properties.isEmpty()) {
node.addChildren(XValueChildrenList.EMPTY, true)
}
})
fun processNamedObjectProperties(variables: List<Variable>,
node: XCompositeNode,
context: VariableContext,
memberFilter: MemberFilter,
maxChildrenToAdd: Int,
defaultIsLast: Boolean): List<Variable>? {
val list = filterAndSort(variables, memberFilter)
if (list.isEmpty()) {
if (defaultIsLast) {
node.addChildren(XValueChildrenList.EMPTY, true)
}
return null
}
val to = Math.min(maxChildrenToAdd, list.size)
val isLast = to == list.size
node.addChildren(createVariablesList(list, 0, to, context, memberFilter), defaultIsLast && isLast)
if (isLast) {
return null
}
else {
node.tooManyChildren(list.size - to)
return list
}
}
fun filterAndSort(variables: List<Variable>, memberFilter: MemberFilter): List<Variable> {
if (variables.isEmpty()) {
return emptyList()
}
val additionalVariables = memberFilter.additionalVariables
val result = ArrayList<Variable>(variables.size + additionalVariables.size)
for (variable in variables) {
if (memberFilter.isMemberVisible(variable)) {
result.add(variable)
}
}
Collections.sort(result, NATURAL_NAME_COMPARATOR)
addAditionalVariables(variables, additionalVariables, result, memberFilter)
return result
}
private fun addAditionalVariables(variables: List<Variable>,
additionalVariables: Collection<Variable>,
result: MutableList<Variable>,
memberFilter: MemberFilter) {
ol@ for (variable in additionalVariables) {
for (frameVariable in variables) {
if (memberFilter.rawNameToSource(frameVariable) == memberFilter.rawNameToSource(variable)) {
continue@ol
}
}
result.add(variable)
}
}
// prefixed '_' must be last, fixed case sensitive natural compare
private fun naturalCompare(string1: String?, string2: String?): Int {
//noinspection StringEquality
if (string1 === string2) {
return 0
}
if (string1 == null) {
return -1
}
if (string2 == null) {
return 1
}
val string1Length = string1.length
val string2Length = string2.length
var i = 0
var j = 0
while (i < string1Length && j < string2Length) {
var ch1 = string1[i]
var ch2 = string2[j]
if ((StringUtil.isDecimalDigit(ch1) || ch1 == ' ') && (StringUtil.isDecimalDigit(ch2) || ch2 == ' ')) {
var startNum1 = i
while (ch1 == ' ' || ch1 == '0') {
// skip leading spaces and zeros
startNum1++
if (startNum1 >= string1Length) {
break
}
ch1 = string1[startNum1]
}
var startNum2 = j
while (ch2 == ' ' || ch2 == '0') {
// skip leading spaces and zeros
startNum2++
if (startNum2 >= string2Length) {
break
}
ch2 = string2[startNum2]
}
i = startNum1
j = startNum2
// find end index of number
while (i < string1Length && StringUtil.isDecimalDigit(string1[i])) {
i++
}
while (j < string2Length && StringUtil.isDecimalDigit(string2[j])) {
j++
}
val lengthDiff = (i - startNum1) - (j - startNum2)
if (lengthDiff != 0) {
// numbers with more digits are always greater than shorter numbers
return lengthDiff
}
while (startNum1 < i) {
// compare numbers with equal digit count
val diff = string1[startNum1] - string2[startNum2]
if (diff != 0) {
return diff
}
startNum1++
startNum2++
}
i--
j--
}
else if (ch1 != ch2) {
if (ch1 == '_') {
return 1
}
else if (ch2 == '_') {
return -1
}
else {
return ch1 - ch2
}
}
i++
j++
}
// After the loop the end of one of the strings might not have been reached, if the other
// string ends with a number and the strings are equal until the end of that number. When
// there are more characters in the string, then it is greater.
if (i < string1Length) {
return 1
}
else if (j < string2Length) {
return -1
}
return string1Length - string2Length
}
@JvmOverloads fun createVariablesList(variables: List<Variable>, variableContext: VariableContext, memberFilter: MemberFilter? = null): XValueChildrenList {
return createVariablesList(variables, 0, variables.size, variableContext, memberFilter)
}
fun createVariablesList(variables: List<Variable>, from: Int, to: Int, variableContext: VariableContext, memberFilter: MemberFilter?): XValueChildrenList {
val list = XValueChildrenList(to - from)
var getterOrSetterContext: VariableContext? = null
for (i in from..to - 1) {
val variable = variables[i]
val normalizedName = if (memberFilter == null) variable.name else memberFilter.rawNameToSource(variable)
list.add(VariableView(normalizedName, variable, variableContext))
if (variable is ObjectProperty) {
if (variable.getter != null) {
if (getterOrSetterContext == null) {
getterOrSetterContext = NonWatchableVariableContext(variableContext)
}
list.add(VariableView(VariableImpl("get $normalizedName", variable.getter!!), getterOrSetterContext))
}
if (variable.setter != null) {
if (getterOrSetterContext == null) {
getterOrSetterContext = NonWatchableVariableContext(variableContext)
}
list.add(VariableView(VariableImpl("set $normalizedName", variable.setter!!), getterOrSetterContext))
}
}
}
return list
}
private class NonWatchableVariableContext(variableContext: VariableContext) : VariableContextWrapper(variableContext, null) {
override fun watchableAsEvaluationExpression() = false
} | platform/script-debugger/debugger-ui/src/org/jetbrains/debugger/Variables.kt | 990710264 |
package org.jetbrains.yesod.hamlet.highlight
/**
* @author Leyla H
*/
import com.intellij.openapi.editor.colors.TextAttributesKey
interface HamletColors {
companion object {
val OPERATOR: TextAttributesKey = TextAttributesKey.createTextAttributesKey("HAMLET_OPERATOR")
val COMMENT: TextAttributesKey = TextAttributesKey.createTextAttributesKey("HAMLET_COMMENT")
val ATTRIBUTE: TextAttributesKey = TextAttributesKey.createTextAttributesKey("HAMLET_ATTRIBUTE")
val ATTRIBUTE_VALUE: TextAttributesKey = TextAttributesKey.createTextAttributesKey("HAMLET_ATTRIBUTE_VALUE")
val STRING: TextAttributesKey = TextAttributesKey.createTextAttributesKey("HAMLET_STRING")
val IDENTIFIER: TextAttributesKey = TextAttributesKey.createTextAttributesKey("HAMLET_IDENTIFIER")
}
}
| plugin/src/org/jetbrains/yesod/hamlet/highlight/HamletColors.kt | 2767022081 |
package org.jetbrains.completion.full.line.local.suggest.collector
import org.jetbrains.completion.full.line.local.ModelsFiles
import org.jetbrains.completion.full.line.local.generation.generation.FullLineGenerationConfig
import org.jetbrains.completion.full.line.local.generation.model.GPT2ModelWrapper
import org.jetbrains.completion.full.line.local.tokenizer.FullLineTokenizer
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Disabled
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.Arguments
import org.junit.jupiter.params.provider.MethodSource
import org.mockito.Mockito
import java.io.File
import java.util.stream.Stream
internal class ServerInputComparisonTest {
@Disabled("new tokens or test override must be provided")
@ParameterizedTest
@MethodSource("preprocessingTests")
fun `context match test`(context: String, serverPrefix: String, serverModelInput: List<Int>) {
val (filename, newContext) = context.split("\n", limit = 2)
val generationConfig = FullLineGenerationConfig(filename = filename)
val (contextIds, _) = mockedCompletionsGenerator.makeCompletionInput(newContext, generationConfig)
assertEquals(serverModelInput, contextIds.toList())
}
@ParameterizedTest
@MethodSource("preprocessingTests")
fun `prefix match test`(context: String, serverPrefix: String, serverModelInput: List<Int>) {
val (filename, newContext) = context.split("\n", limit = 2)
val generationConfig = FullLineGenerationConfig(filename = filename)
val (_, prefix) = mockedCompletionsGenerator.makeCompletionInput(newContext, generationConfig)
assertEquals(serverPrefix, prefix)
}
@Disabled("new tokens or test override must be provided")
@ParameterizedTest
@MethodSource("preprocessingTests")
fun `decoded input match`(context: String, serverPrefix: String, serverModelInput: List<Int>) {
val (filename, newContext) = context.split("\n", limit = 2)
val generationConfig = FullLineGenerationConfig(filename = filename)
val (contextIds, _) = mockedCompletionsGenerator.makeCompletionInput(newContext, generationConfig)
assertEquals(tokenizer.decode(serverModelInput), tokenizer.decode(contextIds))
}
companion object {
private val tokenizer = FullLineTokenizer(ModelsFiles.gpt2_py_4L_512_83_q_local.tokenizer, nThreads = 2)
private val mockModel = Mockito.mock(GPT2ModelWrapper::class.java)
private val mockedCompletionsGenerator: FullLineCompletionsGenerator
init {
Mockito.`when`(mockModel.maxSeqLen).thenReturn(384)
mockedCompletionsGenerator = FullLineCompletionsGenerator(mockModel, tokenizer)
}
@JvmStatic
fun preprocessingTests(): Stream<Arguments> {
val resourceDirName = "flcc/preprocessing"
fun getResourceFile(name: String): File {
return File(this::class.java.classLoader.getResource(name)?.file ?: error("Can't find resource: $name"))
}
return getResourceFile(resourceDirName).list()!!.map {
Arguments.of(
getResourceFile("$resourceDirName/${it}/context.txt").readText(),
getResourceFile("$resourceDirName/${it}/prefix.txt").readText(),
getResourceFile("$resourceDirName/${it}/input.txt").readText().split(",").map(String::toInt)
)
}.stream()
}
}
}
| plugins/full-line/local/test/org/jetbrains/completion/full/line/local/suggest/collector/ServerInputComparisonTest.kt | 2780833782 |
package com.nibado.projects.advent.y2019
import com.nibado.projects.advent.Day
import com.nibado.projects.advent.resourceString
object Day02 : Day {
private val program = resourceString(2019, 2).split(",").map { it.toLong() }
override fun part1() = run(12,2)
override fun part2() = (0..99).flatMap { noun -> (0..99).map { verb -> noun to verb } }
.first { (noun, verb) -> run(noun, verb) == 19690720 }.let { (noun, verb) -> 100 * noun + verb }
private fun run(noun: Int, verb: Int) : Int =
IntCode(program).also { it.memory.set(1, noun.toLong());it.memory.set(2, verb);it.run() }.memory.get(0).toInt()
} | src/main/kotlin/com/nibado/projects/advent/y2019/Day02.kt | 2561044523 |
// 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.scratch.actions
import com.intellij.execution.lineMarker.RunLineMarkerContributor
import com.intellij.openapi.editor.EditorFactory
import com.intellij.openapi.fileEditor.TextEditor
import com.intellij.openapi.fileEditor.impl.text.TextEditorProvider
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiWhiteSpace
import com.intellij.psi.impl.source.tree.LeafPsiElement
import com.intellij.psi.util.PsiTreeUtil
import org.jetbrains.kotlin.idea.base.psi.getLineCount
import org.jetbrains.kotlin.idea.base.psi.getLineNumber
import org.jetbrains.kotlin.idea.scratch.ScratchExpression
import org.jetbrains.kotlin.idea.scratch.getScratchFile
import org.jetbrains.kotlin.idea.scratch.isKotlinScratch
import org.jetbrains.kotlin.idea.scratch.isKotlinWorksheet
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.findDescendantOfType
import org.jetbrains.kotlin.psi.psiUtil.getParentOfType
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
class ScratchRunLineMarkerContributor : RunLineMarkerContributor() {
override fun getInfo(element: PsiElement): Info? {
element.containingFile.safeAs<KtFile>()?.takeIf {
val file = it.virtualFile
file.isKotlinWorksheet || file.isKotlinScratch || it.isScript()
} ?: return null
val declaration = element.getStrictParentOfType<KtNamedDeclaration>()
if (declaration != null && declaration !is KtParameter && declaration.nameIdentifier == element) {
return isLastExecutedExpression(element)
}
element.getParentOfType<KtScriptInitializer>(true)?.body?.let { scriptInitializer ->
return if (scriptInitializer.findDescendantOfType<LeafPsiElement>() == element) {
isLastExecutedExpression(element)
} else null
}
// Show arrow for last added empty line
if (declaration is KtScript && element is PsiWhiteSpace) {
getLastExecutedExpression(element)?.let { _ ->
if (element.getLineNumber() == element.containingFile.getLineCount() ||
element.getLineNumber(false) == element.containingFile.getLineCount()
) return Info(RunScratchFromHereAction())
}
}
return null
}
private fun isLastExecutedExpression(element: PsiElement): Info? {
val expression = getLastExecutedExpression(element) ?: return null
if (element.getLineNumber(true) != expression.lineStart) {
return null
}
return if (PsiTreeUtil.isAncestor(expression.element, element, false)) {
Info(RunScratchFromHereAction())
} else null
}
private fun getLastExecutedExpression(element: PsiElement): ScratchExpression? {
val scratchFile = getSingleOpenedTextEditor(element.containingFile)?.getScratchFile() ?: return null
if (!scratchFile.options.isRepl) return null
val replExecutor = scratchFile.replScratchExecutor ?: return null
return replExecutor.getFirstNewExpression()
}
/**
* This method returns single editor in which passed [psiFile] opened.
* If there is no such editor or there is more than one editor, it returns `null`.
*
* We use [PsiDocumentManager.getCachedDocument] instead of [PsiDocumentManager.getDocument]
* so this would not require read action.
*/
private fun getSingleOpenedTextEditor(psiFile: PsiFile): TextEditor? {
val document = PsiDocumentManager.getInstance(psiFile.project).getCachedDocument(psiFile) ?: return null
val singleOpenedEditor = EditorFactory.getInstance().getEditors(document, psiFile.project).singleOrNull() ?: return null
return TextEditorProvider.getInstance().getTextEditor(singleOpenedEditor)
}
}
| plugins/kotlin/jvm/src/org/jetbrains/kotlin/idea/scratch/actions/ScratchRunLineMarkerContributor.kt | 3277538508 |
/*
* Copyright 2021 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.j2cl.transpiler.backend.kotlin
import com.google.j2cl.transpiler.ast.HasName
/** Code generation environment. */
data class Environment(
/** Name to identifier mapping. */
private val nameToIdentifierMap: Map<HasName, String> = emptyMap(),
/** A set of used identifiers, which potentially shadow imports. */
private val identifierSet: Set<String> = emptySet(),
/** Mutable map from simple name to qualified name of types to be imported. */
val importedSimpleNameToQualifiedNameMap: MutableMap<String, String> = mutableMapOf()
) {
/** Returns identifier for the given name */
fun identifier(hasName: HasName): String =
nameToIdentifierMap[hasName] ?: error("No such identifier: $hasName")
/** Returns whether the given identifier is used. */
fun containsIdentifier(identifier: String): Boolean = identifierSet.contains(identifier)
}
| transpiler/java/com/google/j2cl/transpiler/backend/kotlin/Environment.kt | 145675987 |
/*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.iosched.shared.fcm
import com.google.firebase.firestore.FieldValue
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.firestore.SetOptions
import com.google.firebase.iid.FirebaseInstanceId
import com.google.samples.apps.iosched.shared.data.document2020
import com.google.samples.apps.iosched.shared.di.ApplicationScope
import com.google.samples.apps.iosched.shared.di.MainDispatcher
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import javax.inject.Inject
import timber.log.Timber
/**
* Saves the FCM ID tokens in Firestore.
*/
class FcmTokenUpdater @Inject constructor(
@ApplicationScope private val externalScope: CoroutineScope,
@MainDispatcher private val mainDispatcher: CoroutineDispatcher,
val firestore: FirebaseFirestore
) {
fun updateTokenForUser(userId: String) {
FirebaseInstanceId.getInstance().instanceId.addOnSuccessListener { instanceIdResult ->
val token = instanceIdResult.token
// Write token to /users/<userId>/fcmTokens/<token[0..TOKEN_ID_LENGTH]/
val tokenInfo = mapOf(
LAST_VISIT_KEY to FieldValue.serverTimestamp(),
TOKEN_ID_KEY to token
)
// All Firestore operations start from the main thread to avoid concurrency issues.
externalScope.launch(mainDispatcher) {
firestore
.document2020()
.collection(USERS_COLLECTION)
.document(userId)
.collection(FCM_IDS_COLLECTION)
.document(token.take(TOKEN_ID_LENGTH))
.set(tokenInfo, SetOptions.merge()).addOnCompleteListener {
if (it.isSuccessful) {
Timber.d("FCM ID token successfully uploaded for user $userId\"")
} else {
Timber.e("FCM ID token: Error uploading for user $userId")
}
}
}
}
}
companion object {
private const val USERS_COLLECTION = "users"
private const val LAST_VISIT_KEY = "lastVisit"
private const val TOKEN_ID_KEY = "tokenId"
private const val FCM_IDS_COLLECTION = "fcmTokens"
private const val TOKEN_ID_LENGTH = 25
}
}
| shared/src/main/java/com/google/samples/apps/iosched/shared/fcm/FcmTokenUpdater.kt | 18841042 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.refactoring.cutPaste
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.RangeMarker
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.util.TextRange
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiManager
import com.intellij.refactoring.RefactoringBundle
import com.intellij.refactoring.suggested.range
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor
import org.jetbrains.kotlin.idea.codeInsight.shorten.runRefactoringAndKeepDelayedRequests
import org.jetbrains.kotlin.idea.core.util.runSynchronouslyWithProgress
import org.jetbrains.kotlin.idea.refactoring.cutPaste.MoveDeclarationsTransferableData.Companion.STUB_RENDERER
import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.*
import org.jetbrains.kotlin.idea.util.application.executeWriteCommand
import org.jetbrains.kotlin.idea.util.getSourceRoot
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.findDescendantOfType
import org.jetbrains.kotlin.psi.psiUtil.startOffset
class MoveDeclarationsProcessor(
val project: Project,
private val sourceContainer: KtDeclarationContainer,
private val targetPsiFile: KtFile,
val pastedDeclarations: List<KtNamedDeclaration>,
private val imports: List<String>,
private val sourceDeclarationsText: List<String>
) {
companion object {
fun build(editor: Editor, cookie: MoveDeclarationsEditorCookie): MoveDeclarationsProcessor? {
val data = cookie.data
val project = editor.project ?: return null
val range = cookie.bounds.range ?: return null
val sourceFileUrl = data.sourceFileUrl
val sourceFile = VirtualFileManager.getInstance().findFileByUrl(sourceFileUrl) ?: return null
if (sourceFile.getSourceRoot(project) == null) return null
val psiDocumentManager = PsiDocumentManager.getInstance(project)
psiDocumentManager.commitAllDocuments()
val targetPsiFile = psiDocumentManager.getPsiFile(editor.document) as? KtFile ?: return null
if (targetPsiFile.virtualFile.getSourceRoot(project) == null) return null
val sourcePsiFile = PsiManager.getInstance(project).findFile(sourceFile) as? KtFile ?: return null
val sourceObject = data.sourceObjectFqName?.let { fqName ->
sourcePsiFile.findDescendantOfType<KtObjectDeclaration> { it.fqName?.asString() == fqName } ?: return null
}
val sourceContainer: KtDeclarationContainer = sourceObject ?: sourcePsiFile
if (targetPsiFile == sourceContainer) return null
val declarations = MoveDeclarationsCopyPasteProcessor.rangeToDeclarations(targetPsiFile, range)
if (declarations.isEmpty() || declarations.any { it.parent !is KtFile }) return null
if (sourceContainer == sourcePsiFile && sourcePsiFile.packageFqName == targetPsiFile.packageFqName) return null
// check that declarations were cut (not copied)
if (sourceContainer.declarations.any { declaration -> declaration.text in data.declarationTexts }) {
return null
}
return MoveDeclarationsProcessor(
project,
sourceContainer,
targetPsiFile,
declarations,
data.imports,
data.declarationTexts
)
}
}
private val sourcePsiFile = (sourceContainer as KtElement).containingKtFile
private val psiDocumentManager = PsiDocumentManager.getInstance(project)
private val sourceDocument = psiDocumentManager.getDocument(sourcePsiFile)!!
fun performRefactoring() {
psiDocumentManager.commitAllDocuments()
val commandName = KotlinBundle.message("action.usage.update.command")
val commandGroupId = Any() // we need to group both commands for undo
// temporary revert imports to the state before they have been changed
val importsSubstitution = if (sourcePsiFile.importDirectives.size != imports.size) {
val startOffset = sourcePsiFile.importDirectives.minOfOrNull { it.startOffset } ?: 0
val endOffset = sourcePsiFile.importDirectives.minOfOrNull { it.endOffset } ?: 0
val importsDeclarationsText = sourceDocument.getText(TextRange(startOffset, endOffset))
val tempImportsText = imports.joinToString(separator = "\n")
project.executeWriteCommand(commandName, commandGroupId) {
sourceDocument.deleteString(startOffset, endOffset)
sourceDocument.insertString(startOffset, tempImportsText)
}
psiDocumentManager.commitDocument(sourceDocument)
ImportsSubstitution(importsDeclarationsText, tempImportsText, startOffset)
} else {
null
}
val tmpRangeAndDeclarations = insertStubDeclarations(commandName, commandGroupId, sourceDeclarationsText)
assert(tmpRangeAndDeclarations.second.size == pastedDeclarations.size)
val stubTexts = tmpRangeAndDeclarations.second.map { STUB_RENDERER.render(it.unsafeResolveToDescriptor()) }
project.executeWriteCommand(commandName, commandGroupId) {
sourceDocument.deleteString(tmpRangeAndDeclarations.first.startOffset, tmpRangeAndDeclarations.first.endOffset)
}
psiDocumentManager.commitDocument(sourceDocument)
val stubRangeAndDeclarations = insertStubDeclarations(commandName, commandGroupId, stubTexts)
val stubDeclarations = stubRangeAndDeclarations.second
assert(stubDeclarations.size == pastedDeclarations.size)
importsSubstitution?.let {
project.executeWriteCommand(commandName, commandGroupId) {
sourceDocument.deleteString(it.startOffset, it.startOffset + it.tempImportsText.length)
sourceDocument.insertString(it.startOffset, it.originalImportsText)
}
psiDocumentManager.commitDocument(sourceDocument)
}
val mover = object : Mover {
override fun invoke(declaration: KtNamedDeclaration, targetContainer: KtElement): KtNamedDeclaration {
val index = stubDeclarations.indexOf(declaration)
assert(index >= 0)
declaration.delete()
return pastedDeclarations[index]
}
}
val declarationProcessor = MoveKotlinDeclarationsProcessor(
MoveDeclarationsDescriptor(
moveSource = MoveSource(stubDeclarations),
moveTarget = KotlinMoveTargetForExistingElement(targetPsiFile),
delegate = MoveDeclarationsDelegate.TopLevel,
project = project
),
mover
)
val declarationUsages = project.runSynchronouslyWithProgress(RefactoringBundle.message("progress.text"), true) {
runReadAction {
declarationProcessor.findUsages().toList()
}
} ?: return
project.executeWriteCommand(commandName, commandGroupId) {
project.runRefactoringAndKeepDelayedRequests { declarationProcessor.execute(declarationUsages) }
psiDocumentManager.doPostponedOperationsAndUnblockDocument(sourceDocument)
val insertedStubRange = stubRangeAndDeclarations.first
assert(insertedStubRange.isValid)
sourceDocument.deleteString(insertedStubRange.startOffset, insertedStubRange.endOffset)
}
}
private data class ImportsSubstitution(val originalImportsText: String, val tempImportsText: String, val startOffset: Int)
private fun insertStubDeclarations(
@NlsContexts.Command commandName: String,
commandGroupId: Any?,
values: List<String>
): Pair<RangeMarker, List<KtNamedDeclaration>> {
val insertedRange = project.executeWriteCommand(commandName, commandGroupId) {
val insertionOffset = sourceContainer.declarations.firstOrNull()?.startOffset
?: when (sourceContainer) {
is KtFile -> sourceContainer.textLength
is KtObjectDeclaration -> sourceContainer.getBody()?.rBrace?.startOffset ?: sourceContainer.endOffset
else -> error("Unknown sourceContainer: $sourceContainer")
}
val textToInsert = "\n//start\n\n${values.joinToString(separator = "\n")}\n//end\n"
sourceDocument.insertString(insertionOffset, textToInsert)
sourceDocument.createRangeMarker(TextRange(insertionOffset, insertionOffset + textToInsert.length))
}
psiDocumentManager.commitDocument(sourceDocument)
val declarations =
MoveDeclarationsCopyPasteProcessor.rangeToDeclarations(
sourcePsiFile,
insertedRange.textRange)
return Pair(insertedRange, declarations)
}
} | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/cutPaste/MoveDeclarationsProcessor.kt | 1870993978 |
package org.stepik.android.view.base.ui.widget
import android.content.Context
import android.util.AttributeSet
import android.view.KeyEvent
import androidx.appcompat.widget.AppCompatEditText
/**
* Clears focus from edit text when back button is pressed, but does not call onBackPressed
*/
class StoriesClearFocusEditText
@JvmOverloads
constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : AppCompatEditText(context, attrs, defStyleAttr) {
override fun onKeyPreIme(keyCode: Int, event: KeyEvent?): Boolean {
if (keyCode == KeyEvent.KEYCODE_BACK) {
clearFocus()
return true
}
return super.onKeyPreIme(keyCode, event)
}
} | app/src/main/java/org/stepik/android/view/base/ui/widget/StoriesClearFocusEditText.kt | 2383156130 |
package com.nononsenseapps.feeder.model
import androidx.room.ColumnInfo
import androidx.room.Ignore
import com.nononsenseapps.feeder.db.COL_CURRENTLY_SYNCING
import com.nononsenseapps.feeder.db.room.ID_ALL_FEEDS
import com.nononsenseapps.feeder.db.room.ID_UNSET
import com.nononsenseapps.feeder.util.sloppyLinkToStrictURLNoThrows
import java.net.URL
data class FeedUnreadCount @Ignore constructor(
var id: Long = ID_UNSET,
var title: String = "",
var url: URL = sloppyLinkToStrictURLNoThrows(""),
var tag: String = "",
@ColumnInfo(name = "custom_title") var customTitle: String = "",
var notify: Boolean = false,
@ColumnInfo(name = COL_CURRENTLY_SYNCING) var currentlySyncing: Boolean = false,
@ColumnInfo(name = "image_url") var imageUrl: URL? = null,
@ColumnInfo(name = "unread_count") var unreadCount: Int = 0
) : Comparable<FeedUnreadCount> {
constructor() : this(id = ID_UNSET)
val displayTitle: String
get() = customTitle.ifBlank { title }
val isTop: Boolean
get() = id == ID_ALL_FEEDS
val isTag: Boolean
get() = id < 1 && tag.isNotEmpty()
override operator fun compareTo(other: FeedUnreadCount): Int {
return when {
// Top tag is always at the top (implies empty tags)
isTop -> -1
other.isTop -> 1
// Feeds with no tags are always last
isTag && !other.isTag && other.tag.isEmpty() -> -1
!isTag && other.isTag && tag.isEmpty() -> 1
!isTag && !other.isTag && tag.isNotEmpty() && other.tag.isEmpty() -> -1
!isTag && !other.isTag && tag.isEmpty() && other.tag.isNotEmpty() -> 1
// Feeds with identical tags compare by title
tag == other.tag -> displayTitle.compareTo(other.displayTitle, ignoreCase = true)
// In other cases it's just a matter of comparing tags
else -> tag.compareTo(other.tag, ignoreCase = true)
}
}
override fun equals(other: Any?): Boolean {
return when (other) {
null -> false
is FeedUnreadCount -> {
// val f = other as FeedWrapper?
if (isTag && other.isTag) {
// Compare tags
tag == other.tag
} else {
// Compare items
!isTag && !other.isTag && id == other.id
}
}
else -> false
}
}
override fun hashCode(): Int {
return if (isTag) {
// Tag
tag.hashCode()
} else {
// Item
id.hashCode()
}
}
}
| app/src/main/java/com/nononsenseapps/feeder/model/FeedUnreadCount.kt | 4184269459 |
package course.examples.ui.alertdialog
import android.app.AlertDialog
import android.app.Dialog
import android.os.Bundle
import android.support.v4.app.DialogFragment
// Class that creates the AlertDialog
class AlertDialogFragment : DialogFragment() {
companion object {
fun newInstance(): AlertDialogFragment {
return AlertDialogFragment()
}
}
// Build AlertDialog using AlertDialog.Builder
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
return AlertDialog.Builder(activity)
.setMessage("Do you really want to exit?")
// User cannot dismiss dialog by hitting back button
.setCancelable(false)
// Set up No Button
.setNegativeButton(
"No"
) { _, _ ->
(activity as AlertDialogActivity)
.continueShutdown(false)
}
// Set up Yes Button
.setPositiveButton(
"Yes"
) { _, _ ->
(activity as AlertDialogActivity)
.continueShutdown(true)
}.create()
}
}
| ExamplesKotlin/UIAlertDialog/app/src/main/java/course/examples/ui/alertdialog/AlertDialogFragment.kt | 573882440 |
package viper.sample.ui.presenters
import android.os.Bundle
import viper.sample.model.entities.Branch
import viper.sample.model.entities.Repo
import viper.sample.model.interactors.SampleInteractors
import viper.sample.ui.router.SampleFlow
/**
* Presents a list of GitHub repositories.
* Created by Nick Cipollo on 12/19/16.
*/
class BranchesPresenter
: GitPresenter<BranchListItem, SampleInteractors>() {
val user: String
get() = args.getString(SampleFlow.ARGS_USER)
val repo: Repo
get() = args.getParcelable(SampleFlow.ARGS_REPO)
override fun onRefresh() {
interactors.gitInteractor.fetchBranches(user,repo)
.map { BranchListItem(it) }
.toList()
.subscribe({
itemList.clear()
itemList.addAll(it)
notifyCollectionUpdated()
finishRefresh()
}, {
showError(it)
})
}
override fun onItemAction(actionId: Int, itemIndex: Int) {
val args = Bundle()
args.putParcelable(SampleFlow.ARGS_BRANCH,itemList[itemIndex].branch)
moveBack(args)
}
}
data class BranchListItem(val branch: Branch,
val title: String = branch.name)
| sample/src/main/kotlin/viper/sample/ui/presenters/BranchesPresenter.kt | 1147186160 |
/*
* Copyright 2019 New Vector Ltd
*
* 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.matrix.androidsdk.crypto.verification
import androidx.annotation.StringRes
import org.matrix.androidsdk.crypto.R
object VerificationEmoji {
data class EmojiRepresentation(val emoji: String,
@StringRes val nameResId: Int)
fun getEmojiForCode(code: Int): EmojiRepresentation {
return when (code % 64) {
0 -> EmojiRepresentation("🐶", R.string.verification_emoji_dog)
1 -> EmojiRepresentation("🐱", R.string.verification_emoji_cat)
2 -> EmojiRepresentation("🦁", R.string.verification_emoji_lion)
3 -> EmojiRepresentation("🐎", R.string.verification_emoji_horse)
4 -> EmojiRepresentation("🦄", R.string.verification_emoji_unicorn)
5 -> EmojiRepresentation("🐷", R.string.verification_emoji_pig)
6 -> EmojiRepresentation("🐘", R.string.verification_emoji_elephant)
7 -> EmojiRepresentation("🐰", R.string.verification_emoji_rabbit)
8 -> EmojiRepresentation("🐼", R.string.verification_emoji_panda)
9 -> EmojiRepresentation("🐓", R.string.verification_emoji_rooster)
10 -> EmojiRepresentation("🐧", R.string.verification_emoji_penguin)
11 -> EmojiRepresentation("🐢", R.string.verification_emoji_turtle)
12 -> EmojiRepresentation("🐟", R.string.verification_emoji_fish)
13 -> EmojiRepresentation("🐙", R.string.verification_emoji_octopus)
14 -> EmojiRepresentation("🦋", R.string.verification_emoji_butterfly)
15 -> EmojiRepresentation("🌷", R.string.verification_emoji_flower)
16 -> EmojiRepresentation("🌳", R.string.verification_emoji_tree)
17 -> EmojiRepresentation("🌵", R.string.verification_emoji_cactus)
18 -> EmojiRepresentation("🍄", R.string.verification_emoji_mushroom)
19 -> EmojiRepresentation("🌏", R.string.verification_emoji_globe)
20 -> EmojiRepresentation("🌙", R.string.verification_emoji_moon)
21 -> EmojiRepresentation("☁️", R.string.verification_emoji_cloud)
22 -> EmojiRepresentation("🔥", R.string.verification_emoji_fire)
23 -> EmojiRepresentation("🍌", R.string.verification_emoji_banana)
24 -> EmojiRepresentation("🍎", R.string.verification_emoji_apple)
25 -> EmojiRepresentation("🍓", R.string.verification_emoji_strawberry)
26 -> EmojiRepresentation("🌽", R.string.verification_emoji_corn)
27 -> EmojiRepresentation("🍕", R.string.verification_emoji_pizza)
28 -> EmojiRepresentation("🎂", R.string.verification_emoji_cake)
29 -> EmojiRepresentation("❤️", R.string.verification_emoji_heart)
30 -> EmojiRepresentation("😀", R.string.verification_emoji_smiley)
31 -> EmojiRepresentation("🤖", R.string.verification_emoji_robot)
32 -> EmojiRepresentation("🎩", R.string.verification_emoji_hat)
33 -> EmojiRepresentation("👓", R.string.verification_emoji_glasses)
34 -> EmojiRepresentation("🔧", R.string.verification_emoji_wrench)
35 -> EmojiRepresentation("🎅", R.string.verification_emoji_santa)
36 -> EmojiRepresentation("👍", R.string.verification_emoji_thumbsup)
37 -> EmojiRepresentation("☂️", R.string.verification_emoji_umbrella)
38 -> EmojiRepresentation("⌛", R.string.verification_emoji_hourglass)
39 -> EmojiRepresentation("⏰", R.string.verification_emoji_clock)
40 -> EmojiRepresentation("🎁", R.string.verification_emoji_gift)
41 -> EmojiRepresentation("💡", R.string.verification_emoji_lightbulb)
42 -> EmojiRepresentation("📕", R.string.verification_emoji_book)
43 -> EmojiRepresentation("✏️", R.string.verification_emoji_pencil)
44 -> EmojiRepresentation("📎", R.string.verification_emoji_paperclip)
45 -> EmojiRepresentation("✂️", R.string.verification_emoji_scissors)
46 -> EmojiRepresentation("🔒", R.string.verification_emoji_lock)
47 -> EmojiRepresentation("🔑", R.string.verification_emoji_key)
48 -> EmojiRepresentation("🔨", R.string.verification_emoji_hammer)
49 -> EmojiRepresentation("☎️", R.string.verification_emoji_telephone)
50 -> EmojiRepresentation("🏁", R.string.verification_emoji_flag)
51 -> EmojiRepresentation("🚂", R.string.verification_emoji_train)
52 -> EmojiRepresentation("🚲", R.string.verification_emoji_bicycle)
53 -> EmojiRepresentation("✈️", R.string.verification_emoji_airplane)
54 -> EmojiRepresentation("🚀", R.string.verification_emoji_rocket)
55 -> EmojiRepresentation("🏆", R.string.verification_emoji_trophy)
56 -> EmojiRepresentation("⚽", R.string.verification_emoji_ball)
57 -> EmojiRepresentation("🎸", R.string.verification_emoji_guitar)
58 -> EmojiRepresentation("🎺", R.string.verification_emoji_trumpet)
59 -> EmojiRepresentation("🔔", R.string.verification_emoji_bell)
60 -> EmojiRepresentation("⚓", R.string.verification_emoji_anchor)
61 -> EmojiRepresentation("🎧", R.string.verification_emoji_headphone)
62 -> EmojiRepresentation("📁", R.string.verification_emoji_folder)
/* 63 */ else -> EmojiRepresentation("📌", R.string.verification_emoji_pin)
}
}
} | matrix-sdk-crypto/src/main/java/org/matrix/androidsdk/crypto/verification/VerificationEmoji.kt | 880284023 |
package jp.cordea.mackerelclient.activity
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import dagger.android.AndroidInjection
import dagger.android.AndroidInjector
import dagger.android.DispatchingAndroidInjector
import dagger.android.support.HasSupportFragmentInjector
import jp.cordea.mackerelclient.ListItemDecoration
import jp.cordea.mackerelclient.R
import jp.cordea.mackerelclient.adapter.DetailCommonAdapter
import jp.cordea.mackerelclient.databinding.ActivityDetailCommonBinding
import jp.cordea.mackerelclient.fragment.HostRetireDialogFragment
import jp.cordea.mackerelclient.model.DisplayableHost
import jp.cordea.mackerelclient.utils.DateUtils
import jp.cordea.mackerelclient.utils.StatusUtils
import javax.inject.Inject
class HostDetailActivity : AppCompatActivity(), HasSupportFragmentInjector {
@Inject
lateinit var dispatchingAndroidInjector: DispatchingAndroidInjector<Fragment>
private lateinit var host: DisplayableHost
override fun onCreate(savedInstanceState: Bundle?) {
AndroidInjection.inject(this)
super.onCreate(savedInstanceState)
val binding = DataBindingUtil
.setContentView<ActivityDetailCommonBinding>(this, R.layout.activity_detail_common)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
host = intent.getParcelableExtra(HOST_KEY)
binding.recyclerView.let {
it.layoutManager = LinearLayoutManager(this)
it.adapter = DetailCommonAdapter(this, createData(host))
it.addItemDecoration(ListItemDecoration(this))
}
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.host_detail, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> finish()
R.id.action_retire -> {
HostRetireDialogFragment
.newInstance(host)
.apply {
onSuccess = {
setResult(Activity.RESULT_OK)
finish()
}
}
.show(supportFragmentManager, "")
}
}
return super.onOptionsItemSelected(item)
}
override fun supportFragmentInjector(): AndroidInjector<Fragment> = dispatchingAndroidInjector
private fun createData(host: DisplayableHost): List<List<Pair<String, Int>>> {
val list: MutableList<MutableList<Pair<String, Int>>> = arrayListOf()
var inner: MutableList<Pair<String, Int>> = arrayListOf()
inner.add(StatusUtils.requestNameToString(host.status) to R.string.host_detail_status)
inner.add(host.memo to R.string.host_detail_memo)
list.add(inner)
inner = arrayListOf()
inner.add(
host.numberOfRoles.let {
when {
it <= 1 -> resources.getString(R.string.format_role).format(it)
it > 99 -> resources.getString(R.string.format_roles_ex)
else -> resources.getString(R.string.format_roles).format(it)
}
} to R.string.host_detail_roles
)
inner.add(
DateUtils.stringDateFromEpoch(host.createdAt) to R.string.host_detail_created_at
)
list.add(inner)
return list
}
companion object {
const val REQUEST_CODE = 0
private const val HOST_KEY = "HostKey"
fun createIntent(context: Context, host: DisplayableHost): Intent =
Intent(context, HostDetailActivity::class.java).apply {
putExtra(HOST_KEY, host)
}
}
}
| app/src/main/java/jp/cordea/mackerelclient/activity/HostDetailActivity.kt | 312328417 |
/*
* Copyright 2002-2022 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
*
* 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 org.springframework.transaction.annotation
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.toList
import kotlinx.coroutines.runBlocking
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.fail
import org.junit.jupiter.api.Test
import org.springframework.aop.framework.ProxyFactory
import org.springframework.transaction.interceptor.TransactionInterceptor
import org.springframework.transaction.testfixture.ReactiveCallCountingTransactionManager
/**
* @author Sebastien Deleuze
*/
class CoroutinesAnnotationTransactionInterceptorTests {
private val rtm = ReactiveCallCountingTransactionManager()
private val source = AnnotationTransactionAttributeSource()
@Test
fun suspendingNoValueSuccess() {
val proxyFactory = ProxyFactory()
proxyFactory.setTarget(TestWithCoroutines())
proxyFactory.addAdvice(TransactionInterceptor(rtm, source))
val proxy = proxyFactory.proxy as TestWithCoroutines
runBlocking {
proxy.suspendingNoValueSuccess()
}
assertReactiveGetTransactionAndCommitCount(1)
}
@Test
fun suspendingNoValueFailure() {
val proxyFactory = ProxyFactory()
proxyFactory.setTarget(TestWithCoroutines())
proxyFactory.addAdvice(TransactionInterceptor(rtm, source))
val proxy = proxyFactory.proxy as TestWithCoroutines
runBlocking {
try {
proxy.suspendingNoValueFailure()
}
catch (ex: IllegalStateException) {
}
}
assertReactiveGetTransactionAndRollbackCount(1)
}
@Test
fun suspendingValueSuccess() {
val proxyFactory = ProxyFactory()
proxyFactory.setTarget(TestWithCoroutines())
proxyFactory.addAdvice(TransactionInterceptor(rtm, source))
val proxy = proxyFactory.proxy as TestWithCoroutines
runBlocking {
assertThat(proxy.suspendingValueSuccess()).isEqualTo("foo")
}
assertReactiveGetTransactionAndCommitCount(1)
}
@Test
fun suspendingValueFailure() {
val proxyFactory = ProxyFactory()
proxyFactory.setTarget(TestWithCoroutines())
proxyFactory.addAdvice(TransactionInterceptor(rtm, source))
val proxy = proxyFactory.proxy as TestWithCoroutines
runBlocking {
try {
proxy.suspendingValueFailure()
fail("No exception thrown as expected")
}
catch (ex: IllegalStateException) {
}
}
assertReactiveGetTransactionAndRollbackCount(1)
}
@Test
fun suspendingFlowSuccess() {
val proxyFactory = ProxyFactory()
proxyFactory.setTarget(TestWithCoroutines())
proxyFactory.addAdvice(TransactionInterceptor(rtm, source))
val proxy = proxyFactory.proxy as TestWithCoroutines
runBlocking {
assertThat(proxy.suspendingFlowSuccess().toList()).containsExactly("foo", "foo")
}
assertReactiveGetTransactionAndCommitCount(1)
}
@Test
fun flowSuccess() {
val proxyFactory = ProxyFactory()
proxyFactory.setTarget(TestWithCoroutines())
proxyFactory.addAdvice(TransactionInterceptor(rtm, source))
val proxy = proxyFactory.proxy as TestWithCoroutines
runBlocking {
assertThat(proxy.flowSuccess().toList()).containsExactly("foo", "foo")
}
assertReactiveGetTransactionAndCommitCount(1)
}
private fun assertReactiveGetTransactionAndCommitCount(expectedCount: Int) {
assertThat(rtm.begun).isEqualTo(expectedCount)
assertThat(rtm.commits).isEqualTo(expectedCount)
}
private fun assertReactiveGetTransactionAndRollbackCount(expectedCount: Int) {
assertThat(rtm.begun).isEqualTo(expectedCount)
assertThat(rtm.rollbacks).isEqualTo(expectedCount)
}
@Transactional
open class TestWithCoroutines {
open suspend fun suspendingNoValueSuccess() {
delay(10)
}
open suspend fun suspendingNoValueFailure() {
delay(10)
throw IllegalStateException()
}
open suspend fun suspendingValueSuccess(): String {
delay(10)
return "foo"
}
open suspend fun suspendingValueFailure(): String {
delay(10)
throw IllegalStateException()
}
open fun flowSuccess(): Flow<String> {
return flow {
emit("foo")
delay(10)
emit("foo")
}
}
open suspend fun suspendingFlowSuccess(): Flow<String> {
delay(10)
return flow {
emit("foo")
delay(10)
emit("foo")
}
}
}
}
| spring-tx/src/test/kotlin/org/springframework/transaction/annotation/CoroutinesAnnotationTransactionInterceptorTests.kt | 1394682027 |
/*
* Copyright (C) 2012-2018 ZXing authors, Journey Mobile
* Copyright (C) 2021 Veli Tasalı
*
* 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.monora.android.codescanner
import android.graphics.Bitmap
import com.google.zxing.BarcodeFormat
import com.google.zxing.EncodeHintType
import com.google.zxing.MultiFormatWriter
import com.google.zxing.WriterException
import com.google.zxing.common.BitMatrix
class BarcodeEncoder {
fun createBitmap(matrix: BitMatrix): Bitmap {
val width = matrix.width
val height = matrix.height
val pixels = IntArray(width * height)
for (y in 0 until height) {
val offset = y * width
for (x in 0 until width) {
pixels[offset + x] = if (matrix[x, y]) BLACK else WHITE
}
}
val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
bitmap.setPixels(pixels, 0, width, 0, 0, width, height)
return bitmap
}
@Throws(WriterException::class)
fun encode(contents: String?, format: BarcodeFormat?, width: Int, height: Int): BitMatrix {
return try {
MultiFormatWriter().encode(contents, format, width, height)
} catch (e: WriterException) {
throw e
} catch (e: Exception) {
throw WriterException(e)
}
}
@Throws(WriterException::class)
fun encode(
contents: String?,
format: BarcodeFormat?,
width: Int,
height: Int,
hints: Map<EncodeHintType?, *>?
): BitMatrix {
return try {
MultiFormatWriter().encode(contents, format, width, height, hints)
} catch (e: WriterException) {
throw e
} catch (e: Exception) {
throw WriterException(e)
}
}
@Throws(WriterException::class)
fun encodeBitmap(contents: String?, format: BarcodeFormat?, width: Int, height: Int): Bitmap {
return createBitmap(encode(contents, format, width, height))
}
@Throws(WriterException::class)
fun encodeBitmap(
contents: String?,
format: BarcodeFormat?,
width: Int,
height: Int,
hints: Map<EncodeHintType?, *>?
): Bitmap {
return createBitmap(encode(contents, format, width, height, hints))
}
companion object {
private const val WHITE = -0x1
private const val BLACK = -0x1000000
}
} | zxing/src/main/java/org/monora/android/codescanner/BarcodeEncoder.kt | 3063820940 |
package main.tut03
import buffer.destroy
import com.jogamp.newt.event.KeyEvent
import com.jogamp.opengl.GL.*
import com.jogamp.opengl.GL2ES3.GL_COLOR
import com.jogamp.opengl.GL3
import com.jogamp.opengl.util.glsl.ShaderProgram
import extensions.intBufferBig
import extensions.toFloatBuffer
import glsl.programOf
import glsl.shaderCodeOf
import main.L
import main.SIZE
import main.f
import main.framework.Framework
import main.framework.Semantic
import main.glm
import vec._2.Vec2
import vec._4.Vec4
/**
* Created by elect on 21/02/17.
*/
fun main(args: Array<String>) {
VertPositionOffset_()
}
class VertPositionOffset_ : Framework("Tutorial 03 - Shader Position Offset") {
var theProgram = 0
var offsetLocation = 0
val positionBufferObject = intBufferBig(1)
val vao = intBufferBig(1)
val vertexPositions = floatArrayOf(
+0.25f, +0.25f, 0.0f, 1.0f,
+0.25f, -0.25f, 0.0f, 1.0f,
-0.25f, -0.25f, 0.0f, 1.0f)
var startingTime = 0L
override fun init(gl: GL3) = with(gl) {
initializeProgram(gl)
initializeVertexBuffer(gl)
glGenVertexArrays(1, vao)
glBindVertexArray(vao[0])
startingTime = System.currentTimeMillis()
}
fun initializeProgram(gl: GL3) {
theProgram = programOf(gl, this::class.java, "tut03", "position-offset.vert", "standard.frag")
offsetLocation = gl.glGetUniformLocation(theProgram, "offset")
}
fun initializeVertexBuffer(gl: GL3) = with(gl){
val vertexBuffer = vertexPositions.toFloatBuffer()
glGenBuffers(1, positionBufferObject)
glBindBuffer(GL_ARRAY_BUFFER, positionBufferObject[0])
glBufferData(GL_ARRAY_BUFFER, vertexBuffer.SIZE.L, vertexBuffer, GL_STATIC_DRAW)
glBindBuffer(GL_ARRAY_BUFFER, 0)
vertexBuffer.destroy()
}
override fun display(gl: GL3) = with(gl){
val offset = Vec2(0f)
computePositionOffsets(offset)
glClearBufferfv(GL_COLOR, 0, clearColor.put(0, 0f).put(1, 0f).put(2, 0f).put(3, 1f))
glUseProgram(theProgram)
glUniform2f(offsetLocation, offset.x, offset.y)
glBindBuffer(GL_ARRAY_BUFFER, positionBufferObject[0])
glEnableVertexAttribArray(Semantic.Attr.POSITION)
glVertexAttribPointer(Semantic.Attr.POSITION, 4, GL_FLOAT, false, Vec4.SIZE, 0)
glDrawArrays(GL_TRIANGLES, 0, 3)
glDisableVertexAttribArray(Semantic.Attr.POSITION)
glUseProgram(0)
}
fun computePositionOffsets(offset: Vec2) {
val loopDuration = 5.0f
val scale = Math.PI.f * 2f / loopDuration // todo glm
val elapsedTime = (System.currentTimeMillis() - startingTime) / 1_000f
val currTimeThroughLoop = elapsedTime % loopDuration
offset.x = glm.cos(currTimeThroughLoop * scale) * .5f
offset.y = glm.sin(currTimeThroughLoop * scale) * .5f
}
override fun reshape(gl: GL3, w: Int, h: Int) {
gl.glViewport(0, 0, w, h)
}
override fun end(gl: GL3) = with(gl) {
glDeleteProgram(theProgram)
glDeleteBuffers(1, positionBufferObject)
glDeleteVertexArrays(1, vao)
positionBufferObject.destroy()
vao.destroy()
}
override fun keyPressed(keyEvent: KeyEvent) {
when (keyEvent.keyCode) {
KeyEvent.VK_ESCAPE -> {
animator.remove(window)
window.destroy()
}
}
}
} | src/main/kotlin/main/tut03/vertPositionOffset.kt | 4001966509 |
package jetbrains.buildServer.agent.runner
import jetbrains.buildServer.agent.*
import jetbrains.buildServer.rx.distinct
import jetbrains.buildServer.rx.filter
import jetbrains.buildServer.rx.map
import jetbrains.buildServer.rx.use
class BasePathResolverWorkflowFactory(
private val _pathsService: PathsService,
private val _virtualContext: VirtualContext)
: PathResolverWorkflowFactory {
override fun create(context: WorkflowContext, state: PathResolverState) = Workflow (
sequence {
context
.toOutput()
.distinct()
.filter { it.endsWith(state.pathToResolve.path) }
.map { Path(it) }
.subscribe(state.virtualPathObserver)
.use {
yield(CommandLine(
null,
TargetType.SystemDiagnostics,
state.commandToResolve,
Path(_pathsService.getPath(PathType.WorkingDirectory).path),
listOf(CommandLineArgument(state.pathToResolve.path, CommandLineArgumentType.Target)),
emptyList(),
"get ${state.pathToResolve.path}"))
}
}
)
} | plugin-dotnet-agent/src/main/kotlin/jetbrains/buildServer/agent/runner/BasePathResolverWorkflowFactory.kt | 3404556382 |
/**
<slate_header>
author: Kishore Reddy
url: www.github.com/code-helix/slatekit
copyright: 2015 Kishore Reddy
license: www.github.com/code-helix/slatekit/blob/master/LICENSE.md
desc: A tool-kit, utility library and server-backend
usage: Please refer to license on github for more info.
</slate_header>
*/
package slatekit.examples
//<doc:import_required>
import slatekit.common.auth.AuthConsole
import slatekit.common.auth.User
//</doc:import_required>
//<doc:import_examples>
import slatekit.results.Try
import slatekit.results.Success
//</doc:import_examples>
class Example_Auth : Command("auth") {
override fun execute(request: CommandRequest) : Try<Any>
{
//<doc:setup>
// Setup: Setup the Auth wrapper with the user to inspect info about the user
// NOTES:
// * 1. This component does NOT handle any actual login/logout/authorization features.
// * 2. This set of classes are only used to inspect information about a user.
// * 3. Since authorization is a fairly complex feature with implementations such as
// * OAuth, Social Auth, Slate Kit has purposely left out the Authentication to more reliable
// * libraries and frameworks.
// * 4. The SlateKit.Api component, while supporting basic api "Keys" based authentication,
// * and a roles based authentication, it leaves the login/logout and actual generating
// * of tokens to libraries such as OAuth.
val user2 = User( "2", "johndoe","john doe", "john doe", "john","doe", "[email protected]", "123-456-7890", "us", false, false, true)
val auth = AuthConsole(isAuthenticated = true, user = user2, roles = "admin")
//</doc:setup>
//<doc:examples>
// CASE 1: Use the auth to check user info
println ("Checking auth info in desktop/local mode" )
println ( "user info : " + auth.user )
println ( "user id : " + auth.userId )
println ( "is authenticated : " + auth.isAuthenticated )
println ( "is email verified : " + auth.isEmailVerified )
println ( "is phone verified : " + auth.isPhoneVerified )
println ( "is a moderator : " + auth.isInRole( "moderator") )
println ( "is an admin : " + auth.isInRole( "admin" ) )
//</doc:examples>
return Success("")
}
}
| src/apps/kotlin/slatekit-examples/src/main/kotlin/slatekit/examples/Example_Auth.kt | 3102900220 |
// 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.configurationStore
import com.intellij.AbstractBundle
import com.intellij.DynamicBundle
import com.intellij.configurationStore.schemeManager.ROOT_CONFIG
import com.intellij.configurationStore.schemeManager.SchemeManagerFactoryBase
import com.intellij.ide.IdeBundle
import com.intellij.ide.actions.ImportSettingsFilenameFilter
import com.intellij.ide.actions.RevealFileAction
import com.intellij.ide.plugins.PluginManager
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.components.*
import com.intellij.openapi.extensions.PluginDescriptor
import com.intellij.openapi.options.OptionsBundle
import com.intellij.openapi.options.SchemeManagerFactory
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.ui.showOkCancelDialog
import com.intellij.openapi.util.io.FileUtil
import com.intellij.serviceContainer.PlatformComponentManagerImpl
import com.intellij.serviceContainer.processAllImplementationClasses
import com.intellij.util.ArrayUtil
import com.intellij.util.ReflectionUtil
import com.intellij.util.containers.putValue
import com.intellij.util.io.*
import gnu.trove.THashMap
import gnu.trove.THashSet
import java.io.IOException
import java.io.OutputStream
import java.io.StringWriter
import java.nio.file.Path
import java.nio.file.Paths
import java.util.*
internal fun isImportExportActionApplicable(): Boolean {
val app = ApplicationManager.getApplication()
val storageManager = app.stateStore.storageManager as? StateStorageManagerImpl ?: return true
return !storageManager.isStreamProviderPreventExportAction
}
// for Rider purpose
open class ExportSettingsAction : AnAction(), DumbAware {
protected open fun getExportableComponents(): Map<Path, List<ExportableItem>> = getExportableComponentsMap(true, true)
protected open fun exportSettings(saveFile: Path, markedComponents: Set<ExportableItem>) {
val exportFiles = markedComponents.mapTo(THashSet()) { it.file }
saveFile.outputStream().use {
exportSettings(exportFiles, it, FileUtil.toSystemIndependentName(PathManager.getConfigPath()))
}
}
override fun update(e: AnActionEvent) {
e.presentation.isEnabled = isImportExportActionApplicable()
}
override fun actionPerformed(e: AnActionEvent) {
ApplicationManager.getApplication().saveSettings()
val dialog = ChooseComponentsToExportDialog(getExportableComponents(), true,
IdeBundle.message("title.select.components.to.export"),
IdeBundle.message("prompt.please.check.all.components.to.export"))
if (!dialog.showAndGet()) {
return
}
val markedComponents = dialog.exportableComponents
if (markedComponents.isEmpty()) {
return
}
val saveFile = dialog.exportFile
try {
if (saveFile.exists() && showOkCancelDialog(
title = IdeBundle.message("title.file.already.exists"),
message = IdeBundle.message("prompt.overwrite.settings.file", saveFile.toString()),
okText = IdeBundle.message("action.overwrite"),
icon = Messages.getWarningIcon()) != Messages.OK) {
return
}
exportSettings(saveFile, markedComponents)
RevealFileAction.showDialog(getEventProject(e), IdeBundle.message("message.settings.exported.successfully"),
IdeBundle.message("title.export.successful"), saveFile.toFile(), null)
}
catch (e: IOException) {
Messages.showErrorDialog(IdeBundle.message("error.writing.settings", e.toString()), IdeBundle.message("title.error.writing.file"))
}
}
}
fun exportSettings(exportFiles: Set<Path>, out: OutputStream, configPath: String) {
val filter = THashSet<String>()
Compressor.Zip(out).filter { entryName, _ -> filter.add(entryName) }.use { zip ->
for (file in exportFiles) {
val fileInfo = file.basicAttributesIfExists() ?: continue
val relativePath = FileUtil.getRelativePath(configPath, file.toAbsolutePath().systemIndependentPath, '/')!!
if (fileInfo.isDirectory) {
zip.addDirectory(relativePath, file.toFile())
}
else {
zip.addFile(relativePath, file.inputStream())
}
}
exportInstalledPlugins(zip)
zip.addFile(ImportSettingsFilenameFilter.SETTINGS_JAR_MARKER, ArrayUtil.EMPTY_BYTE_ARRAY)
}
}
data class ExportableItem(val file: Path, val presentableName: String, val roamingType: RoamingType = RoamingType.DEFAULT)
fun exportInstalledPlugins(zip: Compressor) {
val plugins = PluginManagerCore.getPlugins().asSequence().filter { !it.isBundled && it.isEnabled }.map { it.pluginId }.toList()
if (plugins.isNotEmpty()) {
val buffer = StringWriter()
PluginManagerCore.writePluginsList(plugins, buffer)
zip.addFile(PluginManager.INSTALLED_TXT, buffer.toString().toByteArray())
}
}
// onlyPaths - include only specified paths (relative to config dir, ends with "/" if directory)
fun getExportableComponentsMap(isOnlyExisting: Boolean,
isComputePresentableNames: Boolean,
storageManager: StateStorageManager = ApplicationManager.getApplication().stateStore.storageManager,
onlyPaths: Set<String>? = null): Map<Path, List<ExportableItem>> {
val result = LinkedHashMap<Path, MutableList<ExportableItem>>()
@Suppress("DEPRECATION")
val processor = { component: ExportableComponent ->
for (file in component.exportFiles) {
val item = ExportableItem(file.toPath(), component.presentableName, RoamingType.DEFAULT)
result.putValue(item.file, item)
}
}
val app = ApplicationManager.getApplication() as PlatformComponentManagerImpl
@Suppress("DEPRECATION")
app.getComponentInstancesOfType(ExportableApplicationComponent::class.java).forEach(processor)
@Suppress("DEPRECATION")
ServiceBean.loadServicesFromBeans(ExportableComponent.EXTENSION_POINT, ExportableComponent::class.java).forEach(processor)
val configPath = storageManager.expandMacros(ROOT_CONFIG)
fun isSkipFile(file: Path): Boolean {
if (onlyPaths != null) {
var relativePath = FileUtil.getRelativePath(configPath, file.systemIndependentPath, '/')!!
if (!file.fileName.toString().contains('.') && !file.isFile()) {
relativePath += '/'
}
if (!onlyPaths.contains(relativePath)) {
return true
}
}
return isOnlyExisting && !file.exists()
}
if (isOnlyExisting || onlyPaths != null) {
result.keys.removeAll(::isSkipFile)
}
val fileToContent = THashMap<Path, String>()
processAllImplementationClasses(app.picoContainer) { aClass, pluginDescriptor ->
val stateAnnotation = getStateSpec(aClass)
@Suppress("DEPRECATION")
if (stateAnnotation == null || stateAnnotation.name.isEmpty() || ExportableComponent::class.java.isAssignableFrom(aClass)) {
return@processAllImplementationClasses true
}
val storage = stateAnnotation.storages.sortByDeprecated().firstOrNull() ?: return@processAllImplementationClasses true
val isRoamable = getEffectiveRoamingType(storage.roamingType, storage.path) != RoamingType.DISABLED
if (!isStorageExportable(storage, isRoamable)) {
return@processAllImplementationClasses true
}
val additionalExportFile: Path?
val file: Path
try {
additionalExportFile = getAdditionalExportFile(stateAnnotation, storageManager, ::isSkipFile)
file = Paths.get(storageManager.expandMacros(storage.path))
}
catch (e: UnknownMacroException) {
LOG.error("Cannot expand macro for component \"${stateAnnotation.name}\"", e)
return@processAllImplementationClasses true
}
val isFileIncluded = !isSkipFile(file)
if (isFileIncluded || additionalExportFile != null) {
if (isComputePresentableNames && isOnlyExisting && additionalExportFile == null && file.fileName.toString().endsWith(".xml")) {
val content = fileToContent.getOrPut(file) { file.readText() }
if (!content.contains("""<component name="${stateAnnotation.name}"""")) {
return@processAllImplementationClasses true
}
}
val presentableName = if (isComputePresentableNames) getComponentPresentableName(stateAnnotation, aClass, pluginDescriptor) else ""
if (isFileIncluded) {
result.putValue(file, ExportableItem(file, presentableName, storage.roamingType))
}
if (additionalExportFile != null) {
result.putValue(additionalExportFile, ExportableItem(additionalExportFile, "$presentableName (schemes)", RoamingType.DEFAULT))
}
}
true
}
// must be in the end - because most of SchemeManager clients specify additionalExportFile in the State spec
(SchemeManagerFactory.getInstance() as SchemeManagerFactoryBase).process {
if (it.roamingType != RoamingType.DISABLED && it.fileSpec.getOrNull(0) != '$') {
val file = Paths.get(storageManager.expandMacros(ROOT_CONFIG), it.fileSpec)
if (!result.containsKey(file) && !isSkipFile(file)) {
result.putValue(file, ExportableItem(file, it.presentableName ?: "", it.roamingType))
}
}
}
return result
}
private inline fun getAdditionalExportFile(stateAnnotation: State, storageManager: StateStorageManager, isSkipFile: (file: Path) -> Boolean): Path? {
val additionalExportPath = stateAnnotation.additionalExportFile
if (additionalExportPath.isEmpty()) {
return null
}
val additionalExportFile: Path?
// backward compatibility - path can contain macro
if (additionalExportPath[0] == '$') {
additionalExportFile = Paths.get(storageManager.expandMacros(additionalExportPath))
}
else {
additionalExportFile = Paths.get(storageManager.expandMacros(ROOT_CONFIG), additionalExportPath)
}
return if (isSkipFile(additionalExportFile)) null else additionalExportFile
}
private fun isStorageExportable(storage: Storage, isRoamable: Boolean): Boolean =
storage.exportable || isRoamable && storage.storageClass == StateStorage::class && storage.path.isNotEmpty()
private fun getComponentPresentableName(state: State, aClass: Class<*>, pluginDescriptor: PluginDescriptor?): String {
val presentableName = state.presentableName.java
if (presentableName != State.NameGetter::class.java) {
try {
return ReflectionUtil.newInstance(presentableName).get()
}
catch (e: Exception) {
LOG.error(e)
}
}
val defaultName = state.name
fun trimDefaultName(): String {
// Vcs.Log.App.Settings
return defaultName
.removeSuffix(".Settings")
.removeSuffix(".Settings")
}
var resourceBundleName: String?
if (pluginDescriptor != null && PluginManagerCore.CORE_ID != pluginDescriptor.pluginId) {
resourceBundleName = pluginDescriptor.resourceBundleBaseName
if (resourceBundleName == null) {
if (pluginDescriptor.vendor == "JetBrains") {
resourceBundleName = OptionsBundle.BUNDLE
}
else {
return trimDefaultName()
}
}
}
else {
resourceBundleName = OptionsBundle.BUNDLE
}
val classLoader = pluginDescriptor?.pluginClassLoader ?: aClass.classLoader
if (classLoader != null) {
val message = messageOrDefault(classLoader, resourceBundleName, defaultName)
if (message !== defaultName) {
return message
}
}
return trimDefaultName()
}
private fun messageOrDefault(classLoader: ClassLoader, bundleName: String, defaultName: String): String {
try {
return AbstractBundle.messageOrDefault(
DynamicBundle.INSTANCE.getResourceBundle(bundleName, classLoader), "exportable.$defaultName.presentable.name", defaultName)
}
catch (e: MissingResourceException) {
LOG.warn("Missing bundle ${bundleName} at ${classLoader}: ${e.message}")
return defaultName
}
} | platform/configuration-store-impl/src/ExportSettingsAction.kt | 1887269649 |
package slatekit.providers.aws
import com.amazonaws.auth.AWSCredentials
import com.amazonaws.auth.AWSStaticCredentialsProvider
import slatekit.core.docs.CloudDocs
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder
import com.amazonaws.services.dynamodbv2.document.DynamoDB
import com.amazonaws.services.dynamodbv2.document.Item
import com.amazonaws.services.dynamodbv2.document.spec.GetItemSpec
import slatekit.results.Outcome
import slatekit.results.builders.Outcomes
import com.amazonaws.services.dynamodbv2.document.PrimaryKey
import com.amazonaws.services.dynamodbv2.document.spec.DeleteItemSpec
/**
* Conversion to/from no sql
* @tparam TPartition
* @tparam TCluster
*/
interface AwsDocMapper<TEntity, TPartition, TCluster> {
fun keys(entity:TEntity):Pair<TPartition, TCluster>
fun toDoc(entity:TEntity):Item
fun ofDoc(doc:Item, partition:TPartition, cluster:TCluster):TEntity
}
class AwsCloudDocs<TEntity, TPartition, TCluster>(
val region:String,
val tableName: String,
val partitionName:String,
val clusterName:String,
val mapper:AwsDocMapper<TEntity, TPartition, TCluster>,
creds: AWSCredentials) : CloudDocs<TEntity, TPartition, TCluster>{
private val client = AmazonDynamoDBClientBuilder.standard().withCredentials(AWSStaticCredentialsProvider(creds)).build()
private val dynamoDB = DynamoDB(client)
private val table = dynamoDB.getTable(tableName)
override fun create(entity:TEntity): Outcome<TEntity> {
return Outcomes.of {
val item = mapper.toDoc(entity)
val result = table.putItem(item)
entity
}
}
override fun update(entity:TEntity): Outcome<TEntity> {
return Outcomes.errored(Exception("DynamoDB.update : Not implemented"))
}
override fun delete(entity:TEntity): Outcome<TEntity> {
return Outcomes.of {
val keys = mapper.keys(entity)
val spec = DeleteItemSpec().withPrimaryKey(PrimaryKey(partitionName, keys.first, clusterName, keys.second))
val item = table.deleteItem(spec)
entity
}
}
override fun get(partition: TPartition): Outcome<TEntity> {
return Outcomes.invalid()
}
override fun get(partition: TPartition, cluster: TCluster): Outcome<TEntity> {
return Outcomes.of {
val spec = GetItemSpec().withPrimaryKey(partitionName, partition, clusterName, cluster)
val item = table.getItem(spec)
val entity = mapper.ofDoc(item, partition, cluster)
entity
}
}
}
/*
open class AwsCloudDoc<TPartition, TCluster>(override val partition:TPartition,
override val cluster:TCluster,
override val fields:Map<String, Any?>,
override val source:Any
) : CloudDoc<TPartition, TCluster> {
constructor(partition:TPartition,
cluster:TCluster,
fields:Map<String, Any?>): this(partition, cluster, fields, fields)
}
*/ | src/ext/kotlin/slatekit-providers-aws/src/main/kotlin/slatekit/providers/aws/AwsCloudDocs.kt | 3659580343 |
package com.scliang.kquick.demo
import android.app.Activity
import android.os.Bundle
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import com.scliang.kquick.FullScreenActivity
import com.scliang.kquick.NUtils
import java.util.*
import android.graphics.BitmapFactory
import android.graphics.Bitmap
import android.os.Environment
import android.widget.Button
import android.content.Intent
import android.graphics.Canvas
import android.graphics.Paint
import android.util.Log
import java.io.ByteArrayInputStream
import java.io.File
import java.io.PrintStream
import java.net.ConnectException
import java.net.Socket
import java.net.SocketException
import java.net.SocketTimeoutException
import java.nio.ByteBuffer
/**
* Created by scliang on 2017/6/12.
* KQuick Library Demo
*/
class DemoActivity : FullScreenActivity<IData>() {
private val sCaptureTmpFile = Environment.getExternalStorageDirectory().absolutePath + "/tmp.jpg"
var videoRecvable = false
// var client: Socket? = null
var ori: ImageView? = null
// override fun giveWindowColor(): Long {
// return 0xffff4444
// }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_demo)
val tv: TextView = findViewById(R.id.version_text)
val parent = tv.parent as ViewGroup
parent.setPadding(0, getStatusBarHeight(), 0, 0)
tv.text = String.format(Locale.CHINESE, "v%s", NUtils.getNativeVersion())
// val bmp = BitmapFactory.decodeResource(resources, R.mipmap.walle)
ori = findViewById(R.id.imageView)
// ori.setImageBitmap(bmp)
// val w = bmp.width
// val h = bmp.height
//
// val src = IntArray(w * h)
// bmp.getPixels(src, 0, w, 0, 0, w, h)
// val dst = IntArray(w * h)
// val rect = NUtils.findObject(src, dst, w, h, 0x1982f8)
// println("Find Object: ${rect[0]}:${rect[1]}:${rect[2]}:${rect[3]} @ ${rect[4]}:${rect[5]}")
// val resultImg = Bitmap.createBitmap(dst, w, h, Bitmap.Config.ARGB_8888)
// val gray = findViewById(R.id.imageView_gray) as ImageView
// gray.setImageBitmap(resultImg)
val camera: Button = findViewById(R.id.camera)
camera.setOnClickListener {
// if (PackageManager.PERMISSION_GRANTED ==
// ContextCompat.checkSelfPermission(container!!.context,
// Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
// val file = File(sCaptureTmpFile)
// if (file.exists()) {
// file.delete()
// }
// val uri = Uri.fromFile(file)
// val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
// intent.putExtra(MediaStore.EXTRA_OUTPUT, uri)
// startActivityForResult(intent, 100)
// } else {
// ActivityCompat.requestPermissions(container!!.context as Activity,
// Array(1, {Manifest.permission.WRITE_EXTERNAL_STORAGE}),
// 200)
// Toast.makeText(container!!.context, "没有权限", Toast.LENGTH_SHORT).show()
// }
startFragment(DemoFragment().javaClass)
}
startRecvWalleVideo()
}
override fun onDestroy() {
stopRecvWalleVideo()
super.onDestroy()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == 100 && resultCode == Activity.RESULT_OK) {
val file = File(sCaptureTmpFile)
if (file.exists()) {
val op = BitmapFactory.Options()
op.inSampleSize = 3
val bmp = BitmapFactory.decodeFile(file.absolutePath, op)
if (bmp != null) {
val w = bmp.width
val h = bmp.height
val src = IntArray(w * h)
bmp.getPixels(src, 0, w, 0, 0, w, h)
val dst = IntArray(w * h)
val rect = NUtils.findObject(src, dst, w, h, 0x1982f8)
println("Find Object: ${rect[0]}:${rect[1]}:${rect[2]}:${rect[3]} @ ${rect[4]}:${rect[5]}")
val tmp = Bitmap.createBitmap(src, w, h, Bitmap.Config.ARGB_8888)
val resultImg = tmp.copy(Bitmap.Config.ARGB_8888, true)
tmp.recycle()
val canvas = Canvas(resultImg)
val r = Math.sqrt(Math.pow((rect[2] - rect[0]).toDouble(), 2.0) +
Math.pow((rect[3] - rect[1]).toDouble(), 2.0)) / 2
val paint = Paint()
paint.isAntiAlias = true
paint.style = Paint.Style.STROKE
paint.color = 0xffff4444.toInt()
paint.strokeWidth = 2f
canvas.drawCircle(rect[4].toFloat(), rect[5].toFloat(), r.toFloat(), paint)
val ori: ImageView = findViewById(R.id.imageView)
ori.setImageBitmap(resultImg)
}
}
}
}
fun startRecvWalleVideo() {
if (!videoRecvable) {
videoRecvable = true
// Thread(Runnable {
// try {
// client = Socket("192.168.2.26", 8869)
// client!!.soTimeout = 1000
// val out = PrintStream(client!!.getOutputStream())
// val reader = client!!.getInputStream()
// val buffer = ByteArray(10240, { 0 })
//// val bf = ByteArray(buffer.size, {0})
// val byteBuffer = ByteArray(320 * 240, {0})
// val resultImg = Bitmap.createBitmap(320, 240, Bitmap.Config.ARGB_8888)
// while (videoRecvable) {
// out.write("once".toByteArray())
// out.flush()
// var countSum = 0
// val start = System.currentTimeMillis()
// while (videoRecvable) {
// try {
// val count = reader.read(buffer)
// if (count != -1) {
// System.arraycopy(buffer, 0, byteBuffer, countSum, buffer.size)
// countSum += count
// Log.d("WalleVideo", "read count $count, Sum: $countSum")
// } else {
// break
// }
// } catch (e: SocketException) {
// e.printStackTrace()
// break
// } catch (e: SocketTimeoutException) {
// e.printStackTrace()
// break
// }
// }
//// Log.d("kQuick", "read sum: $countSum")
//// for (d in byteBuffer) {
//// Log.d("kQuick", "dstArray: $d")
//// }
// Log.d("kQuick", "duration1: ${System.currentTimeMillis() - start}")
// val targetArray = NUtils.decodeImage(byteBuffer, countSum)
// Log.d("kQuick", "duration2: ${System.currentTimeMillis() - start}")
// if (targetArray != null) {
//// Log.d("kQuick", "read end: $countSum - ${byteBuffer.size} - ${targetArray.size}")
//// val resultImg = Bitmap.createBitmap(targetArray, 640, 240, Bitmap.Config.ARGB_8888)
// resultImg.setPixels(targetArray, 0, 320, 0, 0, 320, 240)
// Log.d("kQuick", "duration3: ${System.currentTimeMillis() - start}")
// if (ori != null) {
// ori!!.post {
// ori!!.setImageBitmap(resultImg)
// }
// }
// }
// }
// out.write("bye".toByteArray())
// out.flush()
// Thread.sleep(1000)
// client!!.close()
// } catch (e: ConnectException) {
// e.printStackTrace()
// }
// }).start()
NUtils.startRecvImage("192.168.88.129", 8869)
if (ori != null) {
val targetArray = IntArray(320 * 240, {0})
val resultImg = Bitmap.createBitmap(320, 240, Bitmap.Config.ARGB_8888)
Thread(Runnable {
while (videoRecvable) {
NUtils.getRecvImage(targetArray)
resultImg.setPixels(targetArray, 0, 320, 0, 0, 320, 240)
ori!!.post {
ori!!.setImageBitmap(resultImg)
}
Thread.sleep(40)
}
}).start()
}
}
}
fun stopRecvWalleVideo() {
// if (client != null) {
// client!!.close()
// }
NUtils.stopRecvImage()
videoRecvable = false
}
}
| demo/src/main/kotlin/DemoActivity.kt | 3056055772 |
/*
* Copyright 2000-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.
*/
package com.intellij.stats.logger
import com.intellij.openapi.application.ApplicationManager
import com.intellij.stats.completion.*
import com.intellij.stats.completion.events.DownPressedEvent
import com.intellij.stats.completion.events.LogEvent
import com.intellij.testFramework.HeavyPlatformTestCase
import junit.framework.TestCase
import java.util.concurrent.LinkedBlockingQueue
/**
* @author Vitaliy.Bibaev
*/
class ValidationOnClientTest : HeavyPlatformTestCase() {
private companion object {
val EMPTY_STATE = LookupState(emptyList(), emptyList(), emptyList(), 1, emptyMap())
const val bucket = "0"
}
fun `test validation before log`() {
val event1 = DownPressedEvent("1", "1", EMPTY_STATE, bucket, System.currentTimeMillis())
val event2 = DownPressedEvent("1", "2", EMPTY_STATE, bucket, System.currentTimeMillis())
TestCase.assertEquals(ValidationStatus.UNKNOWN, event1.validationStatus)
val queue = LinkedBlockingQueue<DeserializedLogEvent>()
val logger = createLogger { queue.add(it) }
logger.log(event1)
logger.log(event2)
val event = queue.take().event!!
TestCase.assertEquals(ValidationStatus.VALID, event.validationStatus)
}
fun `test log after session finished`() {
val event1 = DownPressedEvent("1", "1", EMPTY_STATE, bucket, System.currentTimeMillis())
val event2 = DownPressedEvent("1", "1", EMPTY_STATE.withSelected(2), bucket, System.currentTimeMillis())
val event3 = DownPressedEvent("1", "2", EMPTY_STATE, bucket, System.currentTimeMillis())
val queue = LinkedBlockingQueue<DeserializedLogEvent>()
val logger = createLogger { queue.put(it) }
logger.log(event1)
TestCase.assertTrue(queue.isEmpty())
logger.log(event2)
TestCase.assertTrue(queue.isEmpty())
logger.log(event3)
val e1 = queue.take().event!!
TestCase.assertEquals(event1.sessionUid, e1.sessionUid)
val e2 = queue.take().event!!
TestCase.assertEquals(event2.sessionUid, e2.sessionUid)
TestCase.assertTrue(queue.isEmpty())
}
fun `test log executed on pooled thread`() {
val event1 = DownPressedEvent("1", "1", EMPTY_STATE, bucket, System.currentTimeMillis())
val event2 = DownPressedEvent("1", "2", EMPTY_STATE, bucket, System.currentTimeMillis())
val queue = LinkedBlockingQueue<Boolean>()
val logger = createLogger { queue.add(ApplicationManager.getApplication().isDispatchThread) }
logger.log(event1)
logger.log(event2)
TestCase.assertFalse(queue.take())
}
private class DefaultValidator : SessionValidator {
override fun validate(session: List<LogEvent>) {
session.forEach { it.validationStatus = ValidationStatus.VALID }
}
}
private fun createLogger(onLogCallback: (DeserializedLogEvent) -> Unit): EventLoggerWithValidation {
return EventLoggerWithValidation(object : FileLogger {
override fun println(message: String) {
onLogCallback(LogEventSerializer.fromString(message))
}
override fun flush() {
}
}, DefaultValidator())
}
} | plugins/stats-collector/test/com/intellij/stats/logger/ValidationOnClientTest.kt | 1810742367 |
// TODO: muted automatically, investigate should it be ran for JS or not
// IGNORE_BACKEND: JS
// WITH_RUNTIME
fun fn0() {}
fun fn1(x: Any) {}
inline fun <reified T> assertReifiedIs(x: Any, type: String) {
val answer: Boolean
try {
answer = x is T
}
catch (e: Throwable) {
throw AssertionError("$x is $type: should not throw exceptions, got $e")
}
assert(answer) { "$x is $type: failed" }
}
inline fun <reified T> assertReifiedIsNot(x: Any, type: String) {
val answer: Boolean
try {
answer = x !is T
}
catch (e: Throwable) {
throw AssertionError("$x !is $type: should not throw exceptions, got $e")
}
assert(answer) { "$x !is $type: failed" }
}
fun box(): String {
val f0 = ::fn0 as Any
val f1 = ::fn1 as Any
assertReifiedIs<Function0<*>>(f0, "Function0<*>")
assertReifiedIs<Function1<*, *>>(f1, "Function1<*, *>")
assertReifiedIsNot<Function0<*>>(f1, "Function0<*>")
assertReifiedIsNot<Function1<*, *>>(f0, "Function1<*, *>")
return "OK"
}
| backend.native/tests/external/codegen/box/casts/functions/reifiedIsFunKSmall.kt | 3809830652 |
package net.modcrafters.mclib.features.implementations
import net.minecraft.nbt.NBTTagCompound
import net.modcrafters.mclib.features.IFeature
import net.modcrafters.mclib.features.IFeaturesHolder
object DummyFeature: IFeature {
override val key get() = "DUMMY"
override fun canBeAddedTo(machine: IFeaturesHolder) = true
override fun added(holder: IFeaturesHolder) { }
override fun removed(holder: IFeaturesHolder) { }
override fun deserializeNBT(nbt: NBTTagCompound) { }
override fun serializeNBT() = null
}
| src/main/kotlin/net/modcrafters/mclib/features/implementations/DummyFeature.kt | 3825590777 |
package com.github.triplet.gradle.play.tasks
import com.github.triplet.gradle.androidpublisher.CommitResponse
import com.github.triplet.gradle.androidpublisher.FakePlayPublisher
import com.github.triplet.gradle.androidpublisher.newSuccessCommitResponse
import com.github.triplet.gradle.common.utils.marked
import com.github.triplet.gradle.common.utils.safeCreateNewFile
import com.github.triplet.gradle.play.helpers.IntegrationTestBase
import com.github.triplet.gradle.play.helpers.SharedIntegrationTest
import com.google.common.truth.Truth.assertThat
import org.gradle.testkit.runner.TaskOutcome.SKIPPED
import org.gradle.testkit.runner.TaskOutcome.SUCCESS
import org.junit.jupiter.api.Test
import java.io.File
class CommitEditIntegrationTest : IntegrationTestBase(), SharedIntegrationTest {
override fun taskName(taskVariant: String) = ":commitEditForComDotExampleDotPublisher"
@Test
fun `Commit is not applied by default`() {
val editFile = File(appDir, "build/gpp/com.example.publisher.txt")
editFile.safeCreateNewFile().writeText("foobar")
val result = execute("", ":commitEditForComDotExampleDotPublisher")
result.requireTask(outcome = SUCCESS)
assertThat(result.output).doesNotContain("commitEdit(")
}
@Test
fun `Commit is not applied if skip requested`() {
val editFile = File(appDir, "build/gpp/com.example.publisher.txt")
editFile.safeCreateNewFile().writeText("foobar")
editFile.marked("skipped").safeCreateNewFile()
val result = execute("", ":commitEditForComDotExampleDotPublisher")
result.requireTask(outcome = SUCCESS)
assertThat(result.output).doesNotContain("commitEdit(")
assertThat(result.output).contains("validateEdit(")
}
@Test
fun `Commit is applied if requested`() {
val editFile = File(appDir, "build/gpp/com.example.publisher.txt")
editFile.safeCreateNewFile().writeText("foobar")
editFile.marked("commit").safeCreateNewFile()
val result = execute("", "commitEditForComDotExampleDotPublisher")
result.requireTask(outcome = SUCCESS)
assertThat(result.output).contains("commitEdit(foobar")
}
@Test
fun `Commit task is not run if build failed`() {
val editFile = File(appDir, "build/gpp/com.example.publisher.txt")
editFile.safeCreateNewFile().writeText("foobar")
editFile.marked("commit").safeCreateNewFile()
// language=gradle
val config = """
afterEvaluate {
tasks.named("promoteReleaseArtifact").configure {
doFirst {
throw new IllegalStateException("Dang :(")
}
}
}
"""
val result = executeExpectingFailure(config, "promoteReleaseArtifact")
result.requireTask(outcome = SKIPPED)
assertThat(result.output).doesNotContain("commitEdit(")
assertThat(editFile.exists()).isFalse()
assertThat(editFile.marked("commit").exists()).isFalse()
}
companion object {
@JvmStatic
fun installFactories() {
val publisher = object : FakePlayPublisher() {
override fun commitEdit(id: String, sendChangesForReview: Boolean): CommitResponse {
println("commitEdit($id, $sendChangesForReview)")
return newSuccessCommitResponse()
}
override fun validateEdit(id: String) {
println("validateEdit($id)")
}
}
publisher.install()
}
}
}
| play/plugin/src/test/kotlin/com/github/triplet/gradle/play/tasks/CommitEditIntegrationTest.kt | 1656657491 |
@file:Suppress("BlockingMethodInNonBlockingContext")
package com.sksamuel.scrimage.core
import com.sksamuel.scrimage.ImmutableImage
import io.kotest.core.spec.style.WordSpec
import io.kotest.matchers.shouldBe
import java.awt.image.BufferedImage
import java.io.ByteArrayOutputStream
import javax.imageio.ImageIO
class Issue125Test : WordSpec({
val jpeg: BufferedImage = ImageIO.read(javaClass.getResourceAsStream("/issue125.jpg"))
"Image written with ImageIO" should {
"not swap color channels" {
val out1 = ByteArrayOutputStream()
ImageIO.write(jpeg, "jpg", out1)
val converted = ImmutableImage.fromAwt(jpeg).awt()
val out2 = ByteArrayOutputStream()
ImageIO.write(converted, "jpg", out2)
out1.toByteArray() shouldBe out2.toByteArray()
}
}
})
| scrimage-tests/src/test/kotlin/com/sksamuel/scrimage/core/Issue125Test.kt | 2017787403 |
// WITH_STDLIB
// INTENTION_TEXT: "Replace with 'firstOrNull{}'"
// IS_APPLICABLE_2: false
fun foo(list: List<String>): Int {
<caret>for (s in list) {
if (s.isNotEmpty()) {
return s.length
}
}
return -1
} | plugins/kotlin/idea/tests/testData/intentions/loopToCallChain/firstOrNull/returnExpressionOrNotNull.kt | 2515671176 |
// PROBLEM: none
var a = 5
fun foo() = <caret>if (true) {
a = 6
} else {
a = 8
} | plugins/kotlin/idea/tests/testData/inspectionsLocal/liftOut/ifToAssignment/usedAsExpression.kt | 2281554333 |
// 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.collaboration.ui
import com.intellij.util.EventDispatcher
import com.intellij.util.concurrency.annotations.RequiresEdt
class SingleValueModel<T>(initialValue: T) {
private val changeEventDispatcher = EventDispatcher.create(SimpleEventListener::class.java)
var value: T = initialValue
set(value) {
field = value
changeEventDispatcher.multicaster.eventOccurred()
}
@RequiresEdt
fun addAndInvokeListener(listener: (newValue: T) -> Unit) {
addListener(listener)
listener(value)
}
@RequiresEdt
fun addListener(listener: (newValue: T) -> Unit) {
SimpleEventListener.addListener(changeEventDispatcher) {
listener(value)
}
}
fun <R> map(mapper: (T) -> R): SingleValueModel<R> {
val mappedModel = SingleValueModel(value.let(mapper))
this.addListener {
mappedModel.value = value.let(mapper)
}
return mappedModel
}
} | platform/collaboration-tools/src/com/intellij/collaboration/ui/SingleValueModel.kt | 599724612 |
// 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.vcs.log.data.util
import com.intellij.openapi.Disposable
import com.intellij.util.concurrency.annotations.RequiresEdt
import com.intellij.vcs.log.CommitId
interface VcsCommitsDataLoader<T> : Disposable {
@RequiresEdt
fun loadData(commits: List<CommitId>, onChange: (Map<CommitId, T>) -> Unit)
} | platform/vcs-log/impl/src/com/intellij/vcs/log/data/util/VcsCommitsDataLoader.kt | 302679119 |
package usages
import target.foo
import target.Foo
fun test() {
Foo()
foo()
} | plugins/kotlin/idea/tests/testData/multiFileLocalInspections/reconcilePackageWithDirectory/changeToNonDefaultPackageFromRoot/after/usages/usagesWithFqNames.kt | 2717524220 |
package com.github.wreulicke.flexypool.demo
import com.vladmihalcea.flexypool.FlexyPoolDataSource
import com.vladmihalcea.flexypool.adaptor.TomcatCPPoolAdapter
import com.vladmihalcea.flexypool.metric.AbstractMetrics
import com.vladmihalcea.flexypool.metric.micrometer.MicrometerHistogram
import com.vladmihalcea.flexypool.metric.micrometer.MicrometerTimer
import com.vladmihalcea.flexypool.strategy.IncrementPoolOnTimeoutConnectionAcquiringStrategy
import io.micrometer.core.instrument.Metrics
import org.apache.tomcat.jdbc.pool.DataSource
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties
import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.boot.context.properties.EnableConfigurationProperties
import org.springframework.boot.jdbc.DatabaseDriver
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.Primary
@Configuration
@EnableConfigurationProperties(DataSourceProperties::class)
class FlexyPoolConfig(val properties: DataSourceProperties) {
@Bean
@ConfigurationProperties(prefix = "spring.datasource.tomcat")
fun dataSource(): DataSource {
val dataSource: DataSource = properties.initializeDataSourceBuilder()
.type(DataSource::class.java)
.build() as DataSource
val databaseDriver = DatabaseDriver
.fromJdbcUrl(properties.determineUrl())
val validationQuery = databaseDriver.validationQuery
if (validationQuery != null) {
dataSource.setTestOnBorrow(true)
dataSource.setValidationQuery(validationQuery)
}
return dataSource
}
@Bean
fun configuration(): com.vladmihalcea.flexypool.config.Configuration<DataSource>? {
return com.vladmihalcea.flexypool.config.Configuration.Builder<DataSource>(
"test", dataSource(), TomcatCPPoolAdapter.FACTORY)
.build()
}
@Bean(initMethod = "start", destroyMethod = "stop")
@Primary
fun pool(): FlexyPoolDataSource<DataSource> = FlexyPoolDataSource(configuration(),
IncrementPoolOnTimeoutConnectionAcquiringStrategy.Factory(5)
)
}
// for test
class EnhancedMicrometerMetrics(configurationProperties: com.vladmihalcea.flexypool.common.ConfigurationProperties<*, *, *>?, private val database: String)
: AbstractMetrics(configurationProperties) {
override fun stop() {
}
override fun timer(name: String): MicrometerTimer = MicrometerTimer(Metrics.globalRegistry.timer(name, "database", database))
override fun start() {
}
override fun histogram(name: String) = MicrometerHistogram(Metrics.globalRegistry.summary(name, "database", database))
}
| flexy-pool/src/main/kotlin/com/github/wreulicke/flexypool/demo/FlexyPoolConfig.kt | 2714046275 |
package main.another.one.two
import one.two.MainJava
import one.two.SubMainJavaClass
open class KotlinMain : MainJava() {
open class NestedKotlinMain : MainJava()
open class NestedKotlinNestedMain : MainJava.NestedJava()
open class NestedKotlinSubMain : SubMainJavaClass()
}
object ObjectKotlin : SubMainJavaClass.SubNestedJava() {
object NestedObjectKotlin {
open class NestedNestedKotlin : SubMainJavaClass.SubNestedJava()
}
}
open class K : MainJava.Wrapper.NestedWrapper()
typealias AliasToK = K
class KotlinFromAlias : AliasToK() | plugins/kotlin/refIndex/tests/testData/customCompilerIndexData/testMixedSubtypes/one/two/KotlinSubMain.kt | 457811792 |
// a.A
package a
class A {
@Deprecated("f", level = DeprecationLevel.HIDDEN)
fun f() {
}
}
// LAZINESS:NoLaziness
// FIR_COMPARISON | plugins/kotlin/idea/tests/testData/compiler/asJava/lightClasses/HiddenDeprecatedInClass.kt | 1909897440 |
// 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.util.io
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.util.io.ByteArraySequence
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.text.StringUtil
import com.intellij.util.CompressionUtil
import com.intellij.util.ConcurrencyUtil
import com.intellij.util.indexing.impl.IndexStorageUtil
import it.unimi.dsi.fastutil.ints.IntLinkedOpenHashSet
import it.unimi.dsi.fastutil.ints.IntSet
import java.io.*
import java.nio.file.FileAlreadyExistsException
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.StandardOpenOption
import java.util.concurrent.ExecutorService
import java.util.function.Function
import java.util.zip.CRC32
import java.util.zip.CheckedInputStream
import java.util.zip.CheckedOutputStream
import java.util.zip.Checksum
private const val VERSION = 0
internal enum class WalOpCode(internal val code: Int) {
PUT(0),
REMOVE(1),
APPEND(2);
companion object {
val size = values().size
}
}
private val checksumGen = { CRC32() }
@Volatile
var debugWalRecords = false
private val log = logger<WalRecord>()
private class CorruptionException(val reason: String): IOException(reason)
private class EndOfLog: IOException()
internal class PersistentEnumeratorWal<Data> @Throws(IOException::class) @JvmOverloads constructor(dataDescriptor: KeyDescriptor<Data>,
useCompression: Boolean,
file: Path,
walIoExecutor: ExecutorService,
compact: Boolean = false) : Closeable {
private val underlying = PersistentMapWal(dataDescriptor, integerExternalizer, useCompression, file, walIoExecutor, compact)
fun enumerate(data: Data, id: Int) = underlying.put(data, id)
fun flush() = underlying.flush()
override fun close() = underlying.close()
}
internal class PersistentMapWal<K, V> @Throws(IOException::class) @JvmOverloads constructor(private val keyDescriptor: KeyDescriptor<K>,
private val valueExternalizer: DataExternalizer<V>,
private val useCompression: Boolean,
private val file: Path,
private val walIoExecutor: ExecutorService /*todo ensure sequential*/,
compact: Boolean = false) : Closeable {
private val out: DataOutputStream
val version: Int = VERSION
init {
if (compact) {
tryCompact(file, keyDescriptor, valueExternalizer)?.let { compactedWal ->
FileUtil.deleteWithRenaming(file)
FileUtil.rename(compactedWal.toFile(), file.toFile())
}
}
ensureCompatible(version, useCompression, file)
out = DataOutputStream(Files.newOutputStream(file, StandardOpenOption.WRITE, StandardOpenOption.APPEND).buffered())
}
@Throws(IOException::class)
private fun ensureCompatible(expectedVersion: Int, useCompression: Boolean, file: Path) {
if (!Files.exists(file)) {
Files.createDirectories(file.parent)
DataOutputStream(Files.newOutputStream(file, StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE)).use {
DataInputOutputUtil.writeINT(it, expectedVersion)
it.writeBoolean(useCompression)
}
return
}
val (actualVersion, actualUsesCompression) = DataInputStream(Files.newInputStream(file, StandardOpenOption.READ)).use {
DataInputOutputUtil.readINT(it) to it.readBoolean()
}
if (actualVersion != expectedVersion) {
throw VersionUpdatedException(file, expectedVersion, actualVersion)
}
if (actualUsesCompression != useCompression) {
throw VersionUpdatedException(file, useCompression, actualUsesCompression)
}
}
private fun ByteArray.write(outputStream: DataOutputStream) {
if (useCompression) {
CompressionUtil.writeCompressed(outputStream, this, 0, size)
}
else {
outputStream.writeInt(size)
outputStream.write(this)
}
}
private fun AppendablePersistentMap.ValueDataAppender.writeToByteArray(): ByteArray {
val baos = UnsyncByteArrayOutputStream()
append(DataOutputStream(baos))
return baos.toByteArray()
}
private fun appendRecord(key: K, appender: AppendablePersistentMap.ValueDataAppender) = WalRecord.writeRecord(WalOpCode.APPEND) {
keyDescriptor.save(it, key)
appender.writeToByteArray().write(it)
}
private fun putRecord(key: K, value: V) = WalRecord.writeRecord(WalOpCode.PUT) {
keyDescriptor.save(it, key)
writeData(value, valueExternalizer).write(it)
}
private fun removeRecord(key: K) = WalRecord.writeRecord(WalOpCode.REMOVE) {
keyDescriptor.save(it, key)
}
private fun WalRecord.submitWrite() {
walIoExecutor.submit {
if (debugWalRecords) {
println("write: $this")
}
this.write(out)
}
}
@Throws(IOException::class)
fun appendData(key: K, appender: AppendablePersistentMap.ValueDataAppender) {
appendRecord(key, appender).submitWrite()
}
@Throws(IOException::class)
fun put(key: K, value: V) {
putRecord(key, value).submitWrite()
}
@Throws(IOException::class)
fun remove(key: K) {
removeRecord(key).submitWrite()
}
@Throws(IOException::class) // todo rethrow io exception
fun flush() {
walIoExecutor.submit {
out.flush()
}.get()
}
// todo rethrow io exception
@Throws(IOException::class)
override fun close() {
walIoExecutor.submit {
out.close()
}.get()
}
@Throws(IOException::class)
fun closeAndDelete() {
close()
FileUtil.deleteWithRenaming(file)
}
}
private val integerExternalizer: EnumeratorIntegerDescriptor
get() = EnumeratorIntegerDescriptor.INSTANCE
sealed class WalEvent<K, V> {
abstract val key: K
data class PutEvent<K, V>(override val key: K, val value: V): WalEvent<K, V>()
data class RemoveEvent<K, V>(override val key: K): WalEvent<K, V>()
data class AppendEvent<K, V>(override val key: K, val data: ByteArray): WalEvent<K, V>() {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as AppendEvent<*, *>
if (key != other.key) return false
if (!data.contentEquals(other.data)) return false
return true
}
override fun hashCode(): Int {
var result = key?.hashCode() ?: 0
result = 31 * result + data.contentHashCode()
return result
}
}
object CorruptionEvent: WalEvent<Nothing, Nothing>() {
override val key: Nothing
get() = throw UnsupportedOperationException()
}
}
@Throws(IOException::class)
fun <Data> restoreMemoryEnumeratorFromWal(walFile: Path,
dataDescriptor: KeyDescriptor<Data>): List<Data> {
return restoreFromWal(walFile, dataDescriptor, integerExternalizer, object : Accumulator<Data, Int, List<Data>> {
val result = arrayListOf<Data>()
override fun get(key: Data): Int = error("get not supported")
override fun remove(key: Data) = error("remove not supported")
override fun put(key: Data, value: Int) {
assert(result.size == value)
result.add(key)
}
override fun result(): List<Data> = result
}).toList()
}
@Throws(IOException::class)
fun <Data> restorePersistentEnumeratorFromWal(walFile: Path,
outputMapFile: Path,
dataDescriptor: KeyDescriptor<Data>): PersistentEnumerator<Data> {
if (Files.exists(outputMapFile)) {
throw FileAlreadyExistsException(outputMapFile.toString())
}
return restoreFromWal(walFile, dataDescriptor, integerExternalizer, object : Accumulator<Data, Int, PersistentEnumerator<Data>> {
val result = PersistentEnumerator(outputMapFile, dataDescriptor, 1024)
override fun get(key: Data): Int = error("get not supported")
override fun remove(key: Data) = error("remove not supported")
override fun put(key: Data, value: Int) = assert(result.enumerate(key) == value)
override fun result(): PersistentEnumerator<Data> = result
})
}
@Throws(IOException::class)
fun <K, V> restorePersistentMapFromWal(walFile: Path,
outputMapFile: Path,
keyDescriptor: KeyDescriptor<K>,
valueExternalizer: DataExternalizer<V>): PersistentMap<K, V> {
if (Files.exists(outputMapFile)) {
throw FileAlreadyExistsException(outputMapFile.toString())
}
return restoreFromWal(walFile, keyDescriptor, valueExternalizer, object : Accumulator<K, V, PersistentMap<K, V>> {
val result = PersistentHashMap(outputMapFile, keyDescriptor, valueExternalizer)
override fun get(key: K): V? = result.get(key)
override fun remove(key: K) = result.remove(key)
override fun put(key: K, value: V) = result.put(key, value)
override fun result(): PersistentMap<K, V> = result
})
}
@Throws(IOException::class)
fun <K, V> restoreHashMapFromWal(walFile: Path,
keyDescriptor: KeyDescriptor<K>,
valueExternalizer: DataExternalizer<V>): Map<K, V> {
return restoreFromWal(walFile, keyDescriptor, valueExternalizer, object : Accumulator<K, V, Map<K, V>> {
private val map = linkedMapOf<K, V>()
override fun get(key: K): V? = map.get(key)
override fun remove(key: K) {
map.remove(key)
}
override fun put(key: K, value: V) {
map.put(key, value)
}
override fun result(): Map<K, V> = map
})
}
private fun <K, V> tryCompact(walFile: Path,
keyDescriptor: KeyDescriptor<K>,
valueExternalizer: DataExternalizer<V>): Path? {
if (!Files.exists(walFile)) {
return null
}
val keyToLastEvent = IndexStorageUtil.createKeyDescriptorHashedMap<K, IntSet>(keyDescriptor)
val shouldCompact = PersistentMapWalPlayer(keyDescriptor, valueExternalizer, walFile).use {
var eventCount = 0
for (walEvent in it.readWal()) {
when (walEvent) {
is WalEvent.AppendEvent -> keyToLastEvent.computeIfAbsent(walEvent.key, Function { IntLinkedOpenHashSet() }).add(eventCount)
is WalEvent.PutEvent -> keyToLastEvent.put(walEvent.key, IntLinkedOpenHashSet().also{ set -> set.add(eventCount) })
is WalEvent.RemoveEvent -> keyToLastEvent.put(walEvent.key, IntLinkedOpenHashSet())
is WalEvent.CorruptionEvent -> throw CorruptionException("wal has been corrupted")
}
keyToLastEvent.computeIfAbsent(walEvent.key, Function { IntLinkedOpenHashSet() }).add(eventCount)
eventCount++
}
keyToLastEvent.size * 2 < eventCount
}
if (!shouldCompact) return null
val compactedWalFile = walFile.resolveSibling("${walFile.fileName}_compacted")
PersistentMapWalPlayer(keyDescriptor, valueExternalizer, walFile).use { walPlayer ->
PersistentMapWal(keyDescriptor, valueExternalizer, walPlayer.useCompression, compactedWalFile, ConcurrencyUtil.newSameThreadExecutorService()).use { compactedWal ->
walPlayer.readWal().forEachIndexed{index, walEvent ->
val key = walEvent.key
val events = keyToLastEvent.get(key) ?: throw IOException("No events found for key = $key")
if (events.contains(index)) {
when (walEvent) {
is WalEvent.AppendEvent -> compactedWal.appendData(key, AppendablePersistentMap.ValueDataAppender { out -> out.write(walEvent.data) })
is WalEvent.PutEvent -> compactedWal.put(key, walEvent.value)
is WalEvent.RemoveEvent -> {/*do nothing*/}
is WalEvent.CorruptionEvent -> throw CorruptionException("wal has been corrupted")
}
}
}
}
}
return compactedWalFile
}
private class ChecksumOutputStream(delegate: OutputStream, checksumGen: () -> Checksum): CheckedOutputStream(delegate, checksumGen()) {
fun checksum() = checksum.value
}
private class ChecksumInputStream(delegate: InputStream, checksumGen: () -> Checksum): CheckedInputStream(delegate, checksumGen()) {
fun checksum() = checksum.value
}
/**
* +-------------+---------------+---------------------+---------+
* | OpCode (1b) | Checksum (8b) | Payload Length (4b) | Payload |
* +-------------+---------------+---------------------+---------+
*
* TODO it makes sense to add header for each record
*/
private class WalRecord(val opCode: WalOpCode,
private val checksum: Long,
val payload: ByteArraySequence) {
override fun toString(): String {
return "record($opCode, checksum = $checksum, len = ${payload.length()}, payload = ${StringUtil.toHexString(payload.toBytes())})"
}
@Throws(IOException::class)
fun write(target: DataOutputStream) {
target.writeByte(opCode.code)
DataInputOutputUtil.writeLONG(target, checksum)
DataInputOutputUtil.writeINT(target, payload.length)
target.write(payload.internalBuffer, payload.offset, payload.length)
}
companion object {
@Throws(IOException::class)
fun writeRecord(opCode: WalOpCode, writer: (DataOutputStream) -> Unit): WalRecord {
val baos = UnsyncByteArrayOutputStream()
val cos = ChecksumOutputStream(baos, checksumGen)
DataOutputStream(cos).use { writer(it) }
return WalRecord(opCode, cos.checksum(), baos.toByteArraySequence())
}
@Throws(IOException::class)
fun read(input: DataInputStream): WalRecord {
val code: Int
try {
code = input.readByte().toInt()
}
catch (e: EOFException) {
throw EndOfLog()
}
if (code >= WalOpCode.size) {
throw CorruptionException("no opcode present for code $code")
}
val checksum = DataInputOutputUtil.readLONG(input)
val payloadLength = DataInputOutputUtil.readINT(input)
val cis = ChecksumInputStream(input, checksumGen)
val data = cis.readNBytes(payloadLength)
val actualChecksum = cis.checksum()
if (actualChecksum != checksum) {
throw CorruptionException("checksum is wrong for log record: expected = $checksum but actual = $actualChecksum")
}
return WalRecord(WalOpCode.values()[code], checksum, ByteArraySequence(data))
}
}
}
private fun <V> readData(array: ByteArray, valueExternalizer: DataExternalizer<V>): V {
return valueExternalizer.read(DataInputStream(ByteArrayInputStream(array)))
}
private fun <V> writeData(value: V, valueExternalizer: DataExternalizer<V>): ByteArray {
val baos = UnsyncByteArrayOutputStream()
valueExternalizer.save(DataOutputStream(baos), value)
return baos.toByteArray()
}
private interface Accumulator<K, V, R> {
fun get(key: K): V?
fun remove(key: K)
fun put(key: K, value: V)
fun result(): R
}
private fun <K, V, R> restoreFromWal(walFile: Path,
keyDescriptor: KeyDescriptor<K>,
valueExternalizer: DataExternalizer<V>,
accumulator: Accumulator<K, V, R>): R {
return PersistentMapWalPlayer(keyDescriptor, valueExternalizer, walFile).use {
for (walEvent in it.readWal()) {
when (walEvent) {
is WalEvent.AppendEvent -> {
val previous = accumulator.get(walEvent.key)
val currentData = if (previous == null) walEvent.data else writeData(previous, valueExternalizer) + walEvent.data
accumulator.put(walEvent.key, readData(currentData, valueExternalizer))
}
is WalEvent.PutEvent -> accumulator.put(walEvent.key, walEvent.value)
is WalEvent.RemoveEvent -> accumulator.remove(walEvent.key)
is WalEvent.CorruptionEvent -> throw CorruptionException("wal has been corrupted")
}
}
accumulator.result()
}
}
class PersistentMapWalPlayer<K, V> @Throws(IOException::class) constructor(private val keyDescriptor: KeyDescriptor<K>,
private val valueExternalizer: DataExternalizer<V>,
file: Path) : Closeable {
private val input: DataInputStream
internal val useCompression: Boolean
val version: Int = VERSION
init {
if (!Files.exists(file)) {
throw FileNotFoundException(file.toString())
}
input = DataInputStream(Files.newInputStream(file).buffered())
ensureCompatible(version, input, file)
useCompression = input.readBoolean()
}
@Throws(IOException::class)
private fun ensureCompatible(expectedVersion: Int, input: DataInputStream, file: Path) {
val actualVersion = DataInputOutputUtil.readINT(input)
if (actualVersion != expectedVersion) {
throw VersionUpdatedException(file, expectedVersion, actualVersion)
}
}
fun readWal(): Sequence<WalEvent<K, V>> = generateSequence {
readNextEvent()
}
@Throws(IOException::class)
override fun close() = input.close()
@Throws(IOException::class)
private fun readNextEvent(): WalEvent<K, V>? {
val record: WalRecord
try {
record = WalRecord.read(input)
}
catch (e: EndOfLog) {
return null
}
catch (e: IOException) {
return WalEvent.CorruptionEvent as WalEvent<K, V>
}
if (debugWalRecords) {
println("read: $record")
}
val recordStream = record.payload.toInputStream()
return when (record.opCode) {
WalOpCode.PUT -> WalEvent.PutEvent(keyDescriptor.read(recordStream), readData(readByteArray(recordStream), valueExternalizer))
WalOpCode.REMOVE -> WalEvent.RemoveEvent(keyDescriptor.read(recordStream))
WalOpCode.APPEND -> WalEvent.AppendEvent(keyDescriptor.read(recordStream), readByteArray(recordStream))
}
}
private fun readByteArray(inputStream: DataInputStream): ByteArray {
if (useCompression) {
return CompressionUtil.readCompressed(inputStream)
}
else {
return ByteArray(inputStream.readInt()).also { inputStream.readFully(it) }
}
}
} | platform/util/src/com/intellij/util/io/writeAheadLog.kt | 3296202258 |
// WITH_STDLIB
// WITHOUT_CUSTOM_LINE_INDENT_PROVIDER
fun foo() {
run {<caret> | plugins/kotlin/idea/tests/testData/editor/enterHandler/afterUnmatchedBrace/UnfinishedLambdaIsLastElement.kt | 2278178152 |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.firebase.encoders.proto.codegen
import com.google.firebase.encoders.proto.CodeGenConfig
import com.google.firebase.encoders.proto.codegen.UserDefined.Message
import com.google.firebase.encoders.proto.codegen.UserDefined.ProtoEnum
import com.google.protobuf.compiler.PluginProtos.CodeGeneratorResponse
import com.squareup.javapoet.AnnotationSpec
import com.squareup.javapoet.ArrayTypeName
import com.squareup.javapoet.ClassName
import com.squareup.javapoet.FieldSpec
import com.squareup.javapoet.JavaFile
import com.squareup.javapoet.MethodSpec
import com.squareup.javapoet.ParameterizedTypeName
import com.squareup.javapoet.TypeName
import com.squareup.javapoet.TypeSpec
import java.io.IOException
import java.io.OutputStream
import javax.inject.Inject
import javax.lang.model.element.Modifier
private val ENCODER_CLASS = ClassName.get("com.google.firebase.encoders.proto", "ProtobufEncoder")
private val ENCODABLE_ANNOTATION =
ClassName.get("com.google.firebase.encoders.annotations", "Encodable")
private val PROTOBUF_ANNOTATION = ClassName.get("com.google.firebase.encoders.proto", "Protobuf")
private val FIELD_ANNOTATION = ENCODABLE_ANNOTATION.nestedClass("Field")
private val IGNORE_ANNOTATION = ENCODABLE_ANNOTATION.nestedClass("Ignore")
internal class Gen(
private val messages: Collection<UserDefined>,
private val vendorPackage: String
) {
private val rootEncoder = ClassName.get(vendorPackage, "ProtoEncoderDoNotUse")
private val index = mutableMapOf<UserDefined, TypeSpec.Builder>()
val rootClasses = mutableMapOf<UserDefined, TypeSpec.Builder>()
fun generate() {
if (messages.isEmpty()) {
return
}
rootClasses[
Message(
owner = Owner.Package(vendorPackage, vendorPackage, "unknown"),
name = "ProtoEncoderDoNotUse",
fields = listOf()
)] = protoEncoder()
for (message in messages) {
generate(message)
}
// Messages generated above are "shallow". Meaning that they don't include their nested
// message types. Below we are addressing that by nesting messages within their respective
// containing classes.
for (type in index.keys) {
(type.owner as? Owner.MsgRef)?.let { index[it.message]!!.addType(index[type]!!.build()) }
}
}
/**
* Generates the "root" `@Encodable` class.
*
* This class is the only `@Encodable`-annotated class in the codegen. This ensures that we
* generate an encoder exactly once per message and there is no code duplication.
*
* All "included" messages(as per plugin config) delegate to this class to implement encoding.
*/
private fun protoEncoder(): TypeSpec.Builder {
return TypeSpec.classBuilder(rootEncoder)
.addAnnotation(ENCODABLE_ANNOTATION)
.addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT)
.addMethod(MethodSpec.constructorBuilder().addModifiers(Modifier.PRIVATE).build())
.addField(
FieldSpec.builder(
ENCODER_CLASS,
"ENCODER",
Modifier.PRIVATE,
Modifier.STATIC,
Modifier.FINAL
)
.initializer(
"\$T.builder().configureWith(AutoProtoEncoderDoNotUseEncoder.CONFIG).build()",
ENCODER_CLASS
)
.build()
)
.addMethod(
MethodSpec.methodBuilder("encode")
.addModifiers(Modifier.PUBLIC, Modifier.STATIC)
.returns(ArrayTypeName.of(TypeName.BYTE))
.addParameter(Any::class.java, "value")
.addCode("return ENCODER.encode(value);\n")
.build()
)
.addMethod(
MethodSpec.methodBuilder("encode")
.addModifiers(Modifier.PUBLIC, Modifier.STATIC)
.addException(IOException::class.java)
.addParameter(Any::class.java, "value")
.addParameter(OutputStream::class.java, "output")
.addCode("ENCODER.encode(value, output);\n")
.build()
)
.apply {
for (message in messages) {
addMethod(
MethodSpec.methodBuilder("get${message.name.capitalize()}")
.returns(message.toTypeName())
.addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT)
.build()
)
}
}
}
private fun generate(type: UserDefined) {
if (type in index) return
index[type] = TypeSpec.classBuilder("Dummy")
val builder =
when (type) {
is ProtoEnum -> generateEnum(type)
is Message -> {
val classBuilder = generateClass(type)
classBuilder.addType(generateBuilder(type))
for (field in type.fields) {
(field.type as? UserDefined)?.let { generate(it) }
}
classBuilder
}
}
if (type.owner is Owner.Package) {
rootClasses[type] = builder
}
index[type] = builder
}
/**
* Generates an enum.
*
* Example generated enum:
*
* ```java
* import com.google.firebase.encoders.proto.ProtoEnum;
*
* public enum Foo implements ProtoEnum {
* DEFAULT(0),
* EXAMPLE(1);
*
* private final int number_;
* Foo(int number_) {
* this.number_ = number_;
* }
*
* @Override
* public int getNumber() {
* return number_;
* }
* }
* ```
*/
private fun generateEnum(type: ProtoEnum): TypeSpec.Builder {
val builder =
TypeSpec.enumBuilder(type.name).apply {
addModifiers(Modifier.PUBLIC)
this.addSuperinterface(ClassName.get("com.google.firebase.encoders.proto", "ProtoEnum"))
for (value in type.values) {
addEnumConstant("${value.name}(${value.value})")
}
}
builder.addField(
FieldSpec.builder(TypeName.INT, "number_", Modifier.PRIVATE, Modifier.FINAL).build()
)
builder.addMethod(
MethodSpec.constructorBuilder()
.addModifiers(Modifier.PRIVATE)
.addParameter(TypeName.INT, "number_")
.addCode("this.number_ = number_;\n")
.build()
)
builder.addMethod(
MethodSpec.methodBuilder("getNumber")
.addModifiers(Modifier.PUBLIC)
.addAnnotation(Override::class.java)
.returns(TypeName.INT)
.addCode("return number_;\n")
.build()
)
return builder
}
/**
* Generates a class that corresponds to a proto message.
*
* Example class:
* ```java
* public final class Foo {
* private final int field_;
* private final List<String> str_;
* private Foo(int field_, List<String> str_) {
* this.field_ = field_;
* this.str_ = str_;
* }
*
* @Protobuf(tag = 1)
* public int getField() { return field_; }
*
* @Protobuf(tag = 2)
* @Field(name = "str")
* public List<String> getStrList() { return field_; }
*
* // see generateBuilder() below
* public static class Builder {}
* public static Builder newBuilder() ;
*
* public static Foo getDefaultInstance();
*
* // these are generated only for types explicitly specified in the plugin config.
* public void writeTo(OutputStream output) throws IOException;
* public byte[] toByteArray();
*
* }
* ```
*/
// TODO(vkryachko): generate equals() and hashCode()
private fun generateClass(type: Message): TypeSpec.Builder {
val messageClass =
if (type.owner is Owner.Package) {
TypeSpec.classBuilder(type.name).addModifiers(Modifier.PUBLIC, Modifier.FINAL)
} else {
TypeSpec.classBuilder(type.name)
.addModifiers(Modifier.PUBLIC, Modifier.FINAL, Modifier.STATIC)
}
if (type in messages) {
messageClass
.addMethod(
MethodSpec.methodBuilder("toByteArray")
.addModifiers(Modifier.PUBLIC)
.returns(ArrayTypeName.of(TypeName.BYTE))
.addCode("return \$T.encode(this);\n", rootEncoder)
.build()
)
.addMethod(
MethodSpec.methodBuilder("writeTo")
.addModifiers(Modifier.PUBLIC)
.addException(IOException::class.java)
.addParameter(OutputStream::class.java, "output")
.addCode("\$T.encode(this, output);\n", rootEncoder)
.build()
)
}
val messageTypeName = ClassName.bestGuess(type.name)
val constructor = MethodSpec.constructorBuilder()
messageClass.addMethod(
MethodSpec.methodBuilder("newBuilder")
.addModifiers(Modifier.PUBLIC, Modifier.STATIC)
.returns(ClassName.bestGuess("Builder"))
.addCode("return new Builder();\n")
.build()
)
for (field in type.fields) {
messageClass.addField(
FieldSpec.builder(field.typeName, "${field.name}_", Modifier.PRIVATE, Modifier.FINAL)
.build()
)
constructor.addParameter(field.typeName, "${field.name}_")
constructor.addCode("this.${field.name}_ = ${field.name}_;\n")
if (field.repeated || field.type !is Message) {
messageClass.addMethod(
MethodSpec.methodBuilder("get${field.camelCaseName}${if (field.repeated) "List" else ""}")
.addModifiers(Modifier.PUBLIC)
.addAnnotation(
AnnotationSpec.builder(PROTOBUF_ANNOTATION)
.addMember("tag", "${field.number}")
.apply { field.type.intEncoding?.let { addMember("intEncoding", it) } }
.build()
)
.apply {
if (field.repeated) {
addAnnotation(
AnnotationSpec.builder(FIELD_ANNOTATION)
.addMember("name", "\$S", field.lowerCamelCaseName)
.build()
)
}
}
.returns(field.typeName)
.addCode("return ${field.name}_;\n")
.build()
)
} else {
// this method is for use as public API, it never returns null and falls back to
// returning default instances.
messageClass.addMethod(
MethodSpec.methodBuilder("get${field.camelCaseName}")
.addModifiers(Modifier.PUBLIC)
.addAnnotation(AnnotationSpec.builder(IGNORE_ANNOTATION).build())
.returns(field.typeName)
.addCode(
"return ${field.name}_ == null ? \$T.getDefaultInstance() : ${field.name}_;\n",
field.typeName
)
.build()
)
// this method can return null and is needed by the encoder to make sure we don't
// try to encode default instances, which is:
// 1. inefficient
// 2. can lead to infinite recursion in case of self-referential types.
messageClass.addMethod(
MethodSpec.methodBuilder("get${field.camelCaseName}Internal")
.addModifiers(Modifier.PUBLIC)
.addAnnotation(
AnnotationSpec.builder(PROTOBUF_ANNOTATION)
.addMember("tag", "${field.number}")
.build()
)
.addAnnotation(
AnnotationSpec.builder(FIELD_ANNOTATION)
.addMember("name", "\$S", field.lowerCamelCaseName)
.build()
)
.returns(field.typeName)
.addCode("return ${field.name}_;\n")
.build()
)
}
}
messageClass.addMethod(constructor.build())
messageClass.addField(
FieldSpec.builder(
messageTypeName,
"DEFAULT_INSTANCE",
Modifier.PRIVATE,
Modifier.STATIC,
Modifier.FINAL
)
.initializer("new Builder().build()", messageTypeName)
.build()
)
messageClass.addMethod(
MethodSpec.methodBuilder("getDefaultInstance")
.addModifiers(Modifier.PUBLIC, Modifier.STATIC)
.returns(messageTypeName)
.addCode("return DEFAULT_INSTANCE;\n")
.build()
)
return messageClass
}
/**
* Generates a builder for a proto message.
*
* Example builder:
* ```java
* public static final class Builder {
* public Foo build();
* public Builder setField(int value);
* public Builder setStrList(List<String> value);
* public Builder addStr(String value);
* }
* ```
*/
// TODO(vkryachko): oneof setters should clear other oneof cases.
private fun generateBuilder(type: Message): TypeSpec {
val messageTypeName = ClassName.bestGuess(type.name)
val builder =
TypeSpec.classBuilder("Builder")
.addModifiers(Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL)
val buildMethodArgs =
type.fields.joinToString(", ") {
if (it.repeated) "java.util.Collections.unmodifiableList(${it.name}_)" else "${it.name}_"
}
builder.addMethod(
MethodSpec.methodBuilder("build")
.addModifiers(Modifier.PUBLIC)
.returns(messageTypeName)
.addCode("return new \$T(\$L);\n", messageTypeName, buildMethodArgs)
.build()
)
val builderConstructor = MethodSpec.constructorBuilder()
for (field in type.fields) {
builder.addField(
FieldSpec.builder(field.typeName, "${field.name}_", Modifier.PRIVATE).build()
)
builderConstructor
.addCode("this.${field.name}_ = ")
.apply {
field.type.let { t ->
when (t) {
is Message ->
when {
field.repeated -> addCode("new \$T<>()", ClassName.get(ArrayList::class.java))
else -> addCode("null")
}
is Primitive ->
if (field.repeated) addCode("new \$T<>()", ClassName.get(ArrayList::class.java))
else addCode(t.defaultValue)
is ProtoEnum ->
if (field.repeated) addCode("new \$T<>()", ClassName.get(ArrayList::class.java))
else addCode(t.defaultValue.replace("$", "."))
is Unresolved -> TODO()
}
}
}
.addCode(";\n")
if (field.repeated) {
builder.addMethod(
MethodSpec.methodBuilder("add${field.camelCaseName}")
.addModifiers(Modifier.PUBLIC)
.returns(ClassName.bestGuess("Builder"))
.addParameter(field.type.toTypeName(), "${field.name}_")
.addCode("this.${field.name}_.add(${field.name}_);\n")
.addCode("return this;\n")
.build()
)
}
builder.addMethod(
MethodSpec.methodBuilder("set${field.camelCaseName}${if (field.repeated) "List" else ""}")
.addModifiers(Modifier.PUBLIC)
.returns(ClassName.bestGuess("Builder"))
.addParameter(field.typeName, "${field.name}_")
.addCode("this.${field.name}_ = ${field.name}_;\n")
.addCode("return this;\n")
.build()
)
}
builder.addMethod(builderConstructor.build())
return builder.build()
}
}
private fun ProtobufType.toTypeName(): TypeName {
return when (this) {
Primitive.INT32 -> TypeName.INT
Primitive.SINT32 -> TypeName.INT
Primitive.FIXED32 -> TypeName.INT
Primitive.SFIXED32 -> TypeName.INT
Primitive.FLOAT -> TypeName.FLOAT
Primitive.INT64 -> TypeName.LONG
Primitive.SINT64 -> TypeName.LONG
Primitive.FIXED64 -> TypeName.LONG
Primitive.SFIXED64 -> TypeName.LONG
Primitive.DOUBLE -> TypeName.DOUBLE
Primitive.BOOLEAN -> TypeName.BOOLEAN
Primitive.STRING -> ClassName.get(String::class.java)
Primitive.BYTES -> ArrayTypeName.of(TypeName.BYTE)
is Message -> {
return when (owner) {
is Owner.Package -> ClassName.get(owner.javaName, name)
is Owner.MsgRef -> (owner.message.toTypeName() as ClassName).nestedClass(name)
}
}
is ProtoEnum -> {
return when (owner) {
is Owner.Package -> ClassName.get(owner.javaName, name)
is Owner.MsgRef -> (owner.message.toTypeName() as ClassName).nestedClass(name)
}
}
is Unresolved -> throw AssertionError("Impossible!")
}
}
val ProtoField.typeName: TypeName
get() {
if (!repeated) {
return type.toTypeName()
}
return ParameterizedTypeName.get(ClassName.get(List::class.java), type.boxed)
}
private val ProtobufType.boxed: TypeName
get() {
return when (this) {
Primitive.INT32,
Primitive.SINT32,
Primitive.FIXED32,
Primitive.SFIXED32 -> ClassName.get("java.lang", "Integer")
Primitive.INT64,
Primitive.SINT64,
Primitive.FIXED64,
Primitive.SFIXED64 -> ClassName.get("java.lang", "Long")
Primitive.FLOAT -> ClassName.get("java.lang", "Float")
Primitive.DOUBLE -> ClassName.get("java.lang", "Double")
Primitive.BOOLEAN -> ClassName.get("java.lang", "Boolean")
Primitive.STRING -> ClassName.get("java.lang", "String")
Primitive.BYTES -> ArrayTypeName.of(TypeName.BYTE)
else -> toTypeName()
}
}
val ProtobufType.intEncoding: String?
get() {
return when (this) {
is Primitive.SINT32,
Primitive.SINT64 -> "com.google.firebase.encoders.proto.Protobuf.IntEncoding.SIGNED"
is Primitive.FIXED32,
Primitive.FIXED64,
Primitive.SFIXED32,
Primitive.SFIXED64 -> "com.google.firebase.encoders.proto.Protobuf.IntEncoding.FIXED"
else -> null
}
}
val ProtoEnum.defaultValue: String
get() = "$javaName.${values.find { it.value == 0 }?.name}"
class CodeGenerator @Inject constructor(private val config: CodeGenConfig) {
fun generate(messages: Collection<UserDefined>): CodeGeneratorResponse {
val gen = Gen(messages, config.vendorPackage)
gen.generate()
val responseBuilder = CodeGeneratorResponse.newBuilder()
for ((type, typeBuilder) in gen.rootClasses.entries) {
val typeSpec = typeBuilder.build()
val packageName = type.owner.javaName
val out = StringBuilder()
val file = JavaFile.builder(packageName, typeSpec).build()
file.writeTo(out)
val qualifiedName =
if (packageName.isEmpty()) typeSpec.name else "$packageName.${typeSpec.name}"
val fileName = "${qualifiedName.replace('.', '/')}.java"
responseBuilder.addFile(
CodeGeneratorResponse.File.newBuilder().setContent(out.toString()).setName(fileName)
)
}
return responseBuilder.build()
}
}
| encoders/protoc-gen-firebase-encoders/src/main/kotlin/com/google/firebase/encoders/proto/codegen/CodeGenerator.kt | 4264471017 |
/**
* Designed and developed by Aidan Follestad (@afollestad)
*
* 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.afollestad.assent.rationale
import android.app.Activity
import android.content.pm.PackageManager.PERMISSION_GRANTED
import androidx.annotation.CheckResult
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.afollestad.assent.Permission
import com.afollestad.assent.Prefs
interface ShouldShowRationale {
fun check(permission: Permission): Boolean
@CheckResult fun isPermanentlyDenied(permission: Permission): Boolean
}
internal class RealShouldShowRationale(
private val activity: Activity,
private val prefs: Prefs
) : ShouldShowRationale {
override fun check(permission: Permission): Boolean {
return ActivityCompat.shouldShowRequestPermissionRationale(activity, permission.value)
.also { shouldShow ->
if (shouldShow) {
prefs.set(permission.key(), shouldShow)
}
}
}
/**
* Android provides a utility method, `shouldShowRequestPermissionRationale()`, that returns:
* - `true` if the user has previously denied the request...
* - `false` if a user has denied a permission and selected the "Don't ask again" option in
* the permission request dialog...
* - `false` if a device policy prohibits the permission.
*/
override fun isPermanentlyDenied(permission: Permission): Boolean {
val showRationaleWasTrue: Boolean = prefs[permission.key()] ?: false
// Using point 2 in the kdoc here...
return showRationaleWasTrue && !permission.isGranted() && !check(permission)
}
/**
* Provides a sanity check to avoid falsely returning true in [isPermanentlyDenied]. See
* [https://github.com/afollestad/assent/issues/16].
*/
private fun Permission.isGranted(): Boolean =
ContextCompat.checkSelfPermission(activity, value) == PERMISSION_GRANTED
private fun Permission.key() = "${KEY_SHOULD_SHOW_RATIONALE}_$value"
}
private const val KEY_SHOULD_SHOW_RATIONALE = "show_rationale_"
| core/src/main/java/com/afollestad/assent/rationale/ShouldShowRationale.kt | 1388053454 |
package com.kickstarter.services.apirequests
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
@Parcelize
class MessageBody private constructor(
private val body: String?
) : Parcelable {
fun body() = this.body
@Parcelize
data class Builder(
private var body: String? = null
) : Parcelable {
fun body(body: String?) = apply { this.body = body }
fun build() = MessageBody(
body = body
)
}
fun toBuilder() = Builder(
body = body
)
override fun equals(obj: Any?): Boolean {
var equals = super.equals(obj)
if (obj is MessageBody) {
equals = body() == obj.body()
}
return equals
}
companion object {
@JvmStatic
fun builder() = Builder()
}
}
| app/src/main/java/com/kickstarter/services/apirequests/MessageBody.kt | 3396179322 |
package de.fabmax.kool.modules.audio.synth
/**
* @author fabmax
*/
class Pad : SampleNode() {
private val lfo1 = Oscillator(Wave.SINE, 2f).apply { gain = 0.2f }
private val lfo2 = Oscillator(Wave.SINE, 2f).apply { gain = 150f }
private val osc1 = Oscillator(Wave.SAW).apply { gain = 5.1f }
private val osc2 = Oscillator(Wave.SAW).apply { gain = 3.9f }
private val osc3 = Oscillator(Wave.SAW).apply { gain = 4.0f }
private val osc4 = Oscillator(Wave.SQUARE).apply { gain = 3.0f }
private val highPass = HighPassFilter(0.5f, this)
private val moodFilter = MoodFilter(this)
private val chords = arrayOf(
intArrayOf( 7, 12, 17, 10),
intArrayOf(10, 15, 19, 24)
)
override fun generate(dt: Float): Float {
val n = chords[(t / 4).toInt() % chords.size]
val osc = osc1.next(dt, note(n[0], 1)) + osc2.next(dt, note(n[1], 2)) +
osc3.next(dt, note(n[2], 1)) + osc4.next(dt, note(n[3], 0)) + noise(0.7f)
val s = moodFilter.filter(lfo2.next(dt) + 1100, 0.05f, osc / 33f, dt)
return ((lfo1.next(dt) + 0.5f) * highPass.filter(s)) * 0.15f
}
}
| kool-core/src/commonMain/kotlin/de/fabmax/kool/modules/audio/synth/Pad.kt | 20299667 |
/*
* Copyright 2018 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.room
import android.content.BroadcastReceiver
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageManager
import android.content.pm.ProviderInfo
import com.google.android.apps.muzei.api.provider.MuzeiArtProvider
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.callbackFlow
fun ProviderInfo.getComponentName() = ComponentName(packageName, name)
private fun getProviders(context: Context, packageName: String? = null): List<ProviderInfo> {
val queryIntent = Intent(MuzeiArtProvider.ACTION_MUZEI_ART_PROVIDER)
if (packageName != null) {
queryIntent.`package` = packageName
}
val pm = context.packageManager
@Suppress("DEPRECATION")
return pm.queryIntentContentProviders(queryIntent, PackageManager.GET_META_DATA).filterNotNull().map {
it.providerInfo
}.filter {
it.enabled
}
}
/**
* Get a [Flow] for the list of currently installed [MuzeiArtProvider] instances.
*/
fun getInstalledProviders(context: Context): Flow<List<ProviderInfo>> = callbackFlow {
val currentProviders = HashMap<ComponentName, ProviderInfo>()
val packageChangeReceiver : BroadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent?) {
if (intent?.data == null) {
return
}
val packageName = intent.data?.schemeSpecificPart
when (intent.action) {
Intent.ACTION_PACKAGE_ADDED -> {
getProviders(context, packageName).forEach { providerInfo ->
currentProviders[providerInfo.getComponentName()] = providerInfo
}
}
Intent.ACTION_PACKAGE_CHANGED, Intent.ACTION_PACKAGE_REPLACED -> {
currentProviders.entries.removeAll { it.key.packageName == packageName }
getProviders(context, packageName).forEach { providerInfo ->
currentProviders[providerInfo.getComponentName()] = providerInfo
}
}
Intent.ACTION_PACKAGE_REMOVED -> {
currentProviders.entries.removeAll { it.key.packageName == packageName }
}
}
trySend(currentProviders.values.toList())
}
}
val packageChangeFilter = IntentFilter().apply {
addDataScheme("package")
addAction(Intent.ACTION_PACKAGE_ADDED)
addAction(Intent.ACTION_PACKAGE_CHANGED)
addAction(Intent.ACTION_PACKAGE_REPLACED)
addAction(Intent.ACTION_PACKAGE_REMOVED)
}
context.registerReceiver(packageChangeReceiver, packageChangeFilter)
// Populate the initial set of providers
getProviders(context).forEach { providerInfo ->
currentProviders[providerInfo.getComponentName()] = providerInfo
}
send(currentProviders.values.toList())
awaitClose {
context.unregisterReceiver(packageChangeReceiver)
}
} | android-client-common/src/main/java/com/google/android/apps/muzei/room/InstalledProviders.kt | 751970516 |
// 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.
@file:JvmName("GroovyUnresolvedAccessChecker")
package org.jetbrains.plugins.groovy.codeInspection.untypedUnresolvedAccess
import com.intellij.codeInsight.daemon.HighlightDisplayKey
import com.intellij.codeInsight.daemon.QuickFixActionRegistrar
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.codeInsight.intention.QuickFixFactory
import com.intellij.codeInsight.quickfix.UnresolvedReferenceQuickFixProvider
import com.intellij.codeInspection.ProblemHighlightType.LIKE_UNKNOWN_SYMBOL
import com.intellij.openapi.util.TextRange
import org.jetbrains.plugins.groovy.GroovyBundle.message
import org.jetbrains.plugins.groovy.codeInspection.GroovyQuickFixFactory
import org.jetbrains.plugins.groovy.highlighting.HighlightSink
import org.jetbrains.plugins.groovy.lang.psi.api.GroovyReference
import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrMethodCall
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression
import org.jetbrains.plugins.groovy.lang.resolve.ResolveUtil
fun checkUnresolvedReference(
expression: GrReferenceExpression,
highlightIfGroovyObjectOverridden: Boolean,
highlightIfMissingMethodsDeclared: Boolean,
highlightSink: HighlightSink
) {
val referenceNameElement = expression.referenceNameElement ?: return
val referenceName = expression.referenceName ?: return
val parent = expression.parent
val results: Collection<GroovyResolveResult> = getBestResolveResults(expression)
if (results.isNotEmpty()) {
val staticsOk = results.all(GrUnresolvedAccessChecker::isStaticOk)
if (!staticsOk) {
highlightSink.registerProblem(referenceNameElement, LIKE_UNKNOWN_SYMBOL, message("cannot.reference.non.static", referenceName))
}
return
}
if (ResolveUtil.isKeyOfMap(expression) || ResolveUtil.isClassReference(expression)) {
return
}
if (!highlightIfGroovyObjectOverridden && GrUnresolvedAccessChecker.areGroovyObjectMethodsOverridden(expression)) return
if (!highlightIfMissingMethodsDeclared && GrUnresolvedAccessChecker.areMissingMethodsDeclared(expression)) return
val actions = ArrayList<IntentionAction>()
if (parent is GrMethodCall) {
actions += GroovyQuickFixFactory.getInstance().createGroovyStaticImportMethodFix(parent)
}
else {
actions += generateCreateClassActions(expression)
actions += generateAddImportActions(expression)
}
actions += generateReferenceExpressionFixes(expression)
val registrar = object : QuickFixActionRegistrar {
override fun register(action: IntentionAction) {
actions += action
}
override fun register(fixRange: TextRange, action: IntentionAction, key: HighlightDisplayKey?) {
actions += action
}
}
UnresolvedReferenceQuickFixProvider.registerReferenceFixes(expression, registrar)
QuickFixFactory.getInstance().registerOrderEntryFixes(registrar, expression)
highlightSink.registerProblem(referenceNameElement, LIKE_UNKNOWN_SYMBOL, message("cannot.resolve", referenceName), actions)
}
private fun getBestResolveResults(ref: GroovyReference): Collection<GroovyResolveResult> = getBestResolveResults(ref.resolve(false))
private fun getBestResolveResults(results: Collection<GroovyResolveResult>): Collection<GroovyResolveResult> {
val staticsOk: Collection<GroovyResolveResult> = results.filter(GroovyResolveResult::isStaticsOK)
if (staticsOk.isEmpty()) {
return results
}
val accessibleStaticsOk: Collection<GroovyResolveResult> = staticsOk.filter(GroovyResolveResult::isAccessible)
if (accessibleStaticsOk.isEmpty()) {
return staticsOk
}
return accessibleStaticsOk
}
| plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/codeInspection/untypedUnresolvedAccess/impl.kt | 3498151814 |
interface T
interface B: T
interface C: T
object A {
fun Any.fooForAny() {}
fun T.fooForT() {}
fun B.fooForB() {}
fun C.fooForC() {}
fun <TT> TT.fooForAnyGeneric() {}
fun <TT: T> TT.fooForTGeneric() {}
fun <TT: B> TT.fooForBGeneric() {}
fun <TT: C> TT.fooForCGeneric() {}
fun fooNoReceiver() {}
}
fun B.usage() {
foo<caret>
}
// EXIST: { lookupString: "fooForAny", itemText: "fooForAny" }
// EXIST: { lookupString: "fooForT", itemText: "fooForT" }
// EXIST: { lookupString: "fooForB", itemText: "fooForB" }
// EXIST: { lookupString: "fooForTGeneric", itemText: "fooForTGeneric" }
// EXIST: { lookupString: "fooForBGeneric", itemText: "fooForBGeneric" }
// ABSENT: fooNoReceiver
// ABSENT: fooForC
// ABSENT: fooForCGeneric
| plugins/kotlin/completion/tests/testData/basic/common/extensionMethodInObject/CorrectTypeImplicitReceiver.kt | 3590339801 |
// 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.uast.java.generate
import com.intellij.codeInsight.BlockUtils
import com.intellij.lang.Language
import com.intellij.lang.java.JavaLanguage
import com.intellij.lang.jvm.JvmModifier
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.*
import com.intellij.psi.codeStyle.JavaCodeStyleManager
import com.intellij.psi.codeStyle.VariableKind
import com.intellij.psi.impl.PsiDiamondTypeUtil
import com.intellij.psi.impl.source.tree.CompositeElement
import com.intellij.psi.impl.source.tree.java.PsiLiteralExpressionImpl
import com.intellij.psi.util.PsiTypesUtil
import com.intellij.psi.util.PsiUtil
import com.intellij.util.castSafelyTo
import com.siyeh.ig.psiutils.ParenthesesUtils
import org.jetbrains.uast.*
import org.jetbrains.uast.generate.UParameterInfo
import org.jetbrains.uast.generate.UastCodeGenerationPlugin
import org.jetbrains.uast.generate.UastElementFactory
import org.jetbrains.uast.java.*
internal class JavaUastCodeGenerationPlugin : UastCodeGenerationPlugin {
override fun getElementFactory(project: Project): UastElementFactory = JavaUastElementFactory(project)
override val language: Language
get() = JavaLanguage.INSTANCE
private fun cleanupMethodCall(methodCall: PsiMethodCallExpression): PsiMethodCallExpression {
if (methodCall.typeArguments.isNotEmpty()) {
val resolved = methodCall.resolveMethod() ?: return methodCall
if (methodCall.typeArguments.size == resolved.typeParameters.size &&
PsiDiamondTypeUtil.areTypeArgumentsRedundant(
methodCall.typeArguments,
methodCall,
false,
resolved,
resolved.typeParameters
)
) {
val emptyTypeArgumentsMethodCall = JavaPsiFacade.getElementFactory(methodCall.project)
.createExpressionFromText("foo()", null) as PsiMethodCallExpression
methodCall.typeArgumentList.replace(emptyTypeArgumentsMethodCall.typeArgumentList)
}
}
return JavaCodeStyleManager.getInstance(methodCall.project).shortenClassReferences(methodCall) as PsiMethodCallExpression
}
private fun adjustChainStyleToMethodCalls(oldPsi: PsiElement, newPsi: PsiElement) {
if (oldPsi is PsiMethodCallExpression && newPsi is PsiMethodCallExpression &&
oldPsi.methodExpression.qualifierExpression != null && newPsi.methodExpression.qualifier != null) {
if (oldPsi.methodExpression.children.getOrNull(1) is PsiWhiteSpace &&
newPsi.methodExpression.children.getOrNull(1) !is PsiWhiteSpace
) {
newPsi.methodExpression.addAfter(oldPsi.methodExpression.children[1], newPsi.methodExpression.children[0])
}
}
}
override fun <T : UElement> replace(oldElement: UElement, newElement: T, elementType: Class<T>): T? {
val oldPsi = oldElement.sourcePsi ?: return null
val newPsi = newElement.sourcePsi ?: return null
adjustChainStyleToMethodCalls(oldPsi, newPsi)
val factory = JavaPsiFacade.getElementFactory(oldPsi.project)
val updOldPsi = when {
(newPsi is PsiBlockStatement || newPsi is PsiCodeBlock) && oldPsi.parent is PsiExpressionStatement -> oldPsi.parent
else -> oldPsi
}
val updNewPsi = when {
updOldPsi is PsiStatement && newPsi is PsiExpression -> factory.createExpresionStatement(newPsi) ?: return null
updOldPsi is PsiCodeBlock && newPsi is PsiBlockStatement -> newPsi.codeBlock
else -> newPsi
}
return when (val replaced = updOldPsi.replace(updNewPsi)) {
is PsiExpressionStatement -> replaced.expression.toUElementOfExpectedTypes(elementType)
is PsiMethodCallExpression -> cleanupMethodCall(replaced).toUElementOfExpectedTypes(elementType)
else -> replaced.toUElementOfExpectedTypes(elementType)
}
}
}
private fun PsiElementFactory.createExpresionStatement(expression: PsiExpression): PsiStatement? {
val statement = createStatementFromText("x;", null) as? PsiExpressionStatement ?: return null
statement.expression.replace(expression)
return statement
}
class JavaUastElementFactory(private val project: Project) : UastElementFactory {
private val psiFactory: PsiElementFactory = JavaPsiFacade.getElementFactory(project)
override fun createQualifiedReference(qualifiedName: String, context: UElement?): UQualifiedReferenceExpression? =
createQualifiedReference(qualifiedName, context?.sourcePsi)
override fun createQualifiedReference(qualifiedName: String, context: PsiElement?): UQualifiedReferenceExpression? {
return psiFactory.createExpressionFromText(qualifiedName, context)
.castSafelyTo<PsiReferenceExpression>()
?.let { JavaUQualifiedReferenceExpression(it, null) }
}
override fun createIfExpression(condition: UExpression,
thenBranch: UExpression,
elseBranch: UExpression?,
context: PsiElement?): UIfExpression? {
val conditionPsi = condition.sourcePsi ?: return null
val thenBranchPsi = thenBranch.sourcePsi ?: return null
val ifStatement = psiFactory.createStatementFromText("if (a) b else c", null) as? PsiIfStatement ?: return null
ifStatement.condition?.replace(conditionPsi)
ifStatement.thenBranch?.replace(thenBranchPsi.branchStatement ?: return null)
elseBranch?.sourcePsi?.branchStatement?.let { ifStatement.elseBranch?.replace(it) } ?: ifStatement.elseBranch?.delete()
return JavaUIfExpression(ifStatement, null)
}
override fun createCallExpression(receiver: UExpression?,
methodName: String,
parameters: List<UExpression>,
expectedReturnType: PsiType?,
kind: UastCallKind,
context: PsiElement?): UCallExpression? {
if (kind != UastCallKind.METHOD_CALL) return null
val methodCall = psiFactory.createExpressionFromText(
if (receiver != null) "a.b()" else "a()", context
) as? PsiMethodCallExpression ?: return null
val methodIdentifier = psiFactory.createIdentifier(methodName)
if (receiver != null) {
methodCall.methodExpression.qualifierExpression?.replace(receiver.sourcePsi!!)
}
methodCall.methodExpression.referenceNameElement?.replace(methodIdentifier)
for (parameter in parameters) {
methodCall.argumentList.add(parameter.sourcePsi!!)
}
return if (expectedReturnType == null)
methodCall.toUElementOfType<UCallExpression>()
else
MethodCallUpgradeHelper(project, methodCall, expectedReturnType).tryUpgradeToExpectedType()
?.let { JavaUCallExpression(it, null) }
}
override fun createStringLiteralExpression(text: String, context: PsiElement?): ULiteralExpression? {
val literalExpr = psiFactory.createExpressionFromText(StringUtil.wrapWithDoubleQuote(text), context)
if (literalExpr !is PsiLiteralExpressionImpl) return null
return JavaULiteralExpression(literalExpr, null)
}
override fun createNullLiteral(context: PsiElement?): ULiteralExpression? {
val literalExpr = psiFactory.createExpressionFromText("null", context)
if (literalExpr !is PsiLiteralExpressionImpl) return null
return JavaULiteralExpression(literalExpr, null)
}
private class MethodCallUpgradeHelper(val project: Project, val methodCall: PsiMethodCallExpression, val expectedReturnType: PsiType) {
lateinit var resultType: PsiType
fun tryUpgradeToExpectedType(): PsiMethodCallExpression? {
resultType = methodCall.type ?: return null
if (expectedReturnType.isAssignableFrom(resultType)) return methodCall
if (!(resultType eqResolved expectedReturnType))
return null
return methodCall.methodExpression.qualifierExpression?.let { tryPickUpTypeParameters() }
}
private fun tryPickUpTypeParameters(): PsiMethodCallExpression? {
val expectedTypeTypeParameters = expectedReturnType.castSafelyTo<PsiClassType>()?.parameters ?: return null
val resultTypeTypeParameters = resultType.castSafelyTo<PsiClassType>()?.parameters ?: return null
val notEqualTypeParametersIndices = expectedTypeTypeParameters
.zip(resultTypeTypeParameters)
.withIndex()
.filterNot { (_, pair) -> PsiTypesUtil.compareTypes(pair.first, pair.second, false) }
.map { (i, _) -> i }
val resolvedMethod = methodCall.resolveMethod() ?: return null
val methodReturnTypeTypeParameters = (resolvedMethod.returnType.castSafelyTo<PsiClassType>())?.parameters ?: return null
val methodDefinitionTypeParameters = resolvedMethod.typeParameters
val methodDefinitionToReturnTypeParametersMapping = methodDefinitionTypeParameters.map {
it to methodReturnTypeTypeParameters.indexOfFirst { param -> it.name == param.canonicalText }
}
.filter { it.second != -1 }
.toMap()
val notMatchedTypesParametersNames = notEqualTypeParametersIndices
.map { methodReturnTypeTypeParameters[it].canonicalText }
.toSet()
val callTypeParametersSubstitutor = methodCall.resolveMethodGenerics().substitutor
val newParametersList = mutableListOf<PsiType>()
for (parameter in methodDefinitionTypeParameters) {
if (parameter.name in notMatchedTypesParametersNames) {
newParametersList += expectedTypeTypeParameters[methodDefinitionToReturnTypeParametersMapping[parameter] ?: return null]
}
else {
newParametersList += callTypeParametersSubstitutor.substitute(parameter) ?: return null
}
}
return buildMethodCallFromNewTypeParameters(newParametersList)
}
private fun buildMethodCallFromNewTypeParameters(newParametersList: List<PsiType>): PsiMethodCallExpression? {
val factory = JavaPsiFacade.getElementFactory(project)
val expr = factory.createExpressionFromText(buildString {
append("a.<")
newParametersList.joinTo(this) { "T" }
append(">b()")
}, null) as? PsiMethodCallExpression ?: return null
for ((i, param) in newParametersList.withIndex()) {
val typeElement = factory.createTypeElement(param)
expr.typeArgumentList.typeParameterElements[i].replace(typeElement)
}
methodCall.typeArgumentList.replace(expr.typeArgumentList)
if (methodCall.type?.let { expectedReturnType.isAssignableFrom(it) } != true)
return null
return methodCall
}
infix fun PsiType.eqResolved(other: PsiType): Boolean {
val resolvedThis = this.castSafelyTo<PsiClassType>()?.resolve() ?: return false
val resolvedOther = other.castSafelyTo<PsiClassType>()?.resolve() ?: return false
return PsiManager.getInstance(project).areElementsEquivalent(resolvedThis, resolvedOther)
}
}
override fun createDeclarationExpression(declarations: List<UDeclaration>, context: PsiElement?): UDeclarationsExpression? {
return JavaUDeclarationsExpression(null, declarations)
}
override fun createReturnExpresion(expression: UExpression?,
inLambda: Boolean,
context: PsiElement?): UReturnExpression? {
val returnStatement = psiFactory.createStatementFromText("return ;", null) as? PsiReturnStatement ?: return null
expression?.sourcePsi?.node?.let { (returnStatement as CompositeElement).addChild(it, returnStatement.lastChild.node) }
return JavaUReturnExpression(returnStatement, null)
}
private fun PsiVariable.setMutability(immutable: Boolean) {
if (immutable && !this.hasModifier(JvmModifier.FINAL)) {
PsiUtil.setModifierProperty(this, PsiModifier.FINAL, true)
}
if (!immutable && this.hasModifier(JvmModifier.FINAL)) {
PsiUtil.setModifierProperty(this, PsiModifier.FINAL, false)
}
}
override fun createLocalVariable(suggestedName: String?,
type: PsiType?,
initializer: UExpression,
immutable: Boolean,
context: PsiElement?): ULocalVariable? {
val initializerPsi = initializer.sourcePsi as? PsiExpression ?: return null
val name = createNameFromSuggested(
suggestedName,
VariableKind.LOCAL_VARIABLE,
type,
initializer = initializerPsi,
context = initializerPsi
) ?: return null
val variable = (type ?: initializer.getExpressionType())?.let { variableType ->
psiFactory.createVariableDeclarationStatement(name, variableType, initializerPsi,
initializerPsi.context).declaredElements.firstOrNull() as? PsiLocalVariable
} ?: return null
variable.setMutability(immutable)
return JavaULocalVariable(variable, null)
}
override fun createBlockExpression(expressions: List<UExpression>, context: PsiElement?): UBlockExpression? {
val blockStatement = BlockUtils.createBlockStatement(project)
for (expression in expressions) {
if (expression is JavaUDeclarationsExpression) {
for (declaration in expression.declarations) {
if (declaration.sourcePsi is PsiLocalVariable) {
blockStatement.codeBlock.add(declaration.sourcePsi?.parent as? PsiDeclarationStatement ?: return null)
}
}
continue
}
expression.sourcePsi?.let { psi ->
psi as? PsiStatement ?: (psi as? PsiExpression)?.let { psiFactory.createExpresionStatement(it) }
}?.let { blockStatement.codeBlock.add(it) } ?: return null
}
return JavaUBlockExpression(blockStatement, null)
}
override fun createLambdaExpression(parameters: List<UParameterInfo>, body: UExpression, context: PsiElement?): ULambdaExpression? {
//TODO: smart handling cases, when parameters types should exist in code
val lambda = psiFactory.createExpressionFromText(
buildString {
parameters.joinTo(this, separator = ",", prefix = "(", postfix = ")") { "x x" }
append("->{}")
},
null
) as? PsiLambdaExpression ?: return null
val needsType = parameters.all { it.type != null }
lambda.parameterList.parameters.forEachIndexed { i, parameter ->
parameters[i].also { parameterInfo ->
val name = createNameFromSuggested(
parameterInfo.suggestedName,
VariableKind.PARAMETER,
parameterInfo.type,
context = body.sourcePsi
) ?: return null
parameter.nameIdentifier?.replace(psiFactory.createIdentifier(name))
if (needsType) {
parameter.typeElement?.replace(psiFactory.createTypeElement(parameterInfo.type!!))
}
else {
parameter.removeTypeElement()
}
}
}
if (lambda.parameterList.parametersCount == 1) {
lambda.parameterList.parameters[0].removeTypeElement()
lambda.parameterList.firstChild.delete()
lambda.parameterList.lastChild.delete()
}
val normalizedBody = when (val bodyPsi = body.sourcePsi) {
is PsiExpression -> bodyPsi
is PsiCodeBlock -> normalizeBlockForLambda(bodyPsi)
is PsiBlockStatement -> normalizeBlockForLambda(bodyPsi.codeBlock)
else -> return null
}
lambda.body?.replace(normalizedBody) ?: return null
return JavaULambdaExpression(lambda, null)
}
private fun normalizeBlockForLambda(block: PsiCodeBlock): PsiElement =
block
.takeIf { block.statementCount == 1 }
?.let { block.statements[0] as? PsiReturnStatement }
?.returnValue
?: block
override fun createParenthesizedExpression(expression: UExpression, context: PsiElement?): UParenthesizedExpression? {
val parenthesizedExpression = psiFactory.createExpressionFromText("()", null) as? PsiParenthesizedExpression ?: return null
parenthesizedExpression.children.getOrNull(1)?.replace(expression.sourcePsi ?: return null) ?: return null
return JavaUParenthesizedExpression(parenthesizedExpression, null)
}
override fun createSimpleReference(name: String, context: PsiElement?): USimpleNameReferenceExpression? {
val reference = psiFactory.createExpressionFromText(name, null)
return JavaUSimpleNameReferenceExpression(reference, name, null)
}
override fun createSimpleReference(variable: UVariable, context: PsiElement?): USimpleNameReferenceExpression? {
return createSimpleReference(variable.name ?: return null, context)
}
override fun createBinaryExpression(leftOperand: UExpression,
rightOperand: UExpression,
operator: UastBinaryOperator,
context: PsiElement?): UBinaryExpression? {
val leftPsi = leftOperand.sourcePsi ?: return null
val rightPsi = rightOperand.sourcePsi ?: return null
val operatorSymbol = when (operator) {
UastBinaryOperator.LOGICAL_AND -> "&&"
UastBinaryOperator.PLUS -> "+"
else -> return null
}
val psiBinaryExpression = psiFactory.createExpressionFromText("a $operatorSymbol b", null) as? PsiBinaryExpression
?: return null
psiBinaryExpression.lOperand.replace(leftPsi)
psiBinaryExpression.rOperand?.replace(rightPsi)
return JavaUBinaryExpression(psiBinaryExpression, null)
}
override fun createFlatBinaryExpression(leftOperand: UExpression,
rightOperand: UExpression,
operator: UastBinaryOperator,
context: PsiElement?): UPolyadicExpression? {
val binaryExpression = createBinaryExpression(leftOperand, rightOperand, operator, context) ?: return null
val binarySourcePsi = binaryExpression.sourcePsi as? PsiBinaryExpression ?: return null
val dummyParent = psiFactory.createStatementFromText("a;", null)
dummyParent.firstChild.replace(binarySourcePsi)
ParenthesesUtils.removeParentheses(dummyParent.firstChild as PsiExpression, false)
return when (val result = dummyParent.firstChild) {
is PsiBinaryExpression -> JavaUBinaryExpression(result, null)
is PsiPolyadicExpression -> JavaUPolyadicExpression(result, null)
else -> error("Unexpected type " + result.javaClass)
}
}
private val PsiElement.branchStatement: PsiStatement?
get() = when (this) {
is PsiExpression -> JavaPsiFacade.getElementFactory(project).createExpresionStatement(this)
is PsiCodeBlock -> BlockUtils.createBlockStatement(project).also { it.codeBlock.replace(this) }
is PsiStatement -> this
else -> null
}
private fun PsiVariable.removeTypeElement() {
this.typeElement?.delete()
if (this.children.getOrNull(1) !is PsiIdentifier) {
this.children.getOrNull(1)?.delete()
}
}
private fun createNameFromSuggested(suggestedName: String?,
variableKind: VariableKind,
type: PsiType? = null,
initializer: PsiExpression? = null,
context: PsiElement? = null): String? {
val codeStyleManager = JavaCodeStyleManager.getInstance(project)
val name = suggestedName ?: codeStyleManager.generateVariableName(type, initializer, variableKind) ?: return null
return codeStyleManager.suggestUniqueVariableName(name, context, false)
}
private fun JavaCodeStyleManager.generateVariableName(type: PsiType?, initializer: PsiExpression?, kind: VariableKind) =
suggestVariableName(kind, null, initializer, type).names.firstOrNull()
} | uast/uast-java/src/org/jetbrains/uast/java/generate/JavaUastCodeGenerationPlugin.kt | 3842378647 |
fun main() {
val y = 20
val ex = 5 <=<caret> y
} | plugins/kotlin/idea/tests/testData/intentions/swapBinaryExpression/lessThanEquals.kt | 119580319 |
// WITH_RUNTIME
fun Int.foo(): Int {
return <caret>let { it.hashCode() }
} | plugins/kotlin/idea/tests/testData/inspectionsLocal/simpleRedundantLet/thisShort.kt | 2187254553 |
// SET_FALSE: CALL_PARAMETERS_LPAREN_ON_NEXT_LINE
// SET_TRUE: CALL_PARAMETERS_RPAREN_ON_NEXT_LINE
fun f() {
foo(<caret>1, "a", 2)
}
fun foo(p1: Int, p2: String, p3: Int){} | plugins/kotlin/idea/tests/testData/intentions/chop/argumentList/leftParOnSameLine.kt | 1462280329 |
// "Import" "true"
// WITH_RUNTIME
// ERROR: Expression 'topVal' of type 'SomeType' cannot be invoked as a function. The function 'invoke()' is not found
package mig
import another.topVal
fun use() {
topVal<caret>()
} | plugins/kotlin/idea/tests/testData/quickfix/autoImports/ImportOperatorInvokeWithConvention.before.Main.kt | 1789762420 |
package ppp
class C {
fun xxx(p: Int) = ""
fun foo() {
xx<caret>
}
}
fun C.xxx(p: Int) = 1
fun Any.xxx(c: Char) = 1
fun C.xxx(c: Char) = 1
// EXIST: { lookupString: "xxx", itemText: "xxx", tailText: "(p: Int)", typeText: "String" }
// EXIST: { lookupString: "xxx", itemText: "xxx", tailText: "(c: Char) for C in ppp", typeText: "Int" }
// NOTHING_ELSE
| plugins/kotlin/completion/tests/testData/basic/common/shadowing/Overloads.kt | 2694180841 |
package com.zeke.localserverdemo
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.zeke.localserverdemo", appContext.packageName)
}
}
| app-hlsCacheDemo/src/androidTest/java/com/zeke/localserverdemo/ExampleInstrumentedTest.kt | 3677850674 |
// 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.github.api.data
import com.intellij.collaboration.api.dto.GraphQLFragment
import java.util.*
@GraphQLFragment("/graphql/fragment/comment.graphql")
open class GHComment(id: String,
val author: GHActor?,
val bodyHTML: String,
val createdAt: Date)
: GHNode(id) | plugins/github/src/org/jetbrains/plugins/github/api/data/GHComment.kt | 2535477178 |
// WITH_RUNTIME
fun foo() {
Integer.<caret>toString(5)
}
| plugins/kotlin/idea/tests/testData/inspectionsLocal/replaceJavaStaticMethodWithKotlinAnalog/toString/replaceIntToString.kt | 193083797 |
// "Create property 'foo'" "false"
// ACTION: Do not show return expression hints
// ERROR: Unresolved reference: @foo
fun refer() {
val v = this@<caret>foo
} | plugins/kotlin/idea/tests/testData/quickfix/createFromUsage/createVariable/property/inLabelRef.kt | 1068833311 |
package com.github.kerubistan.kerub.data.ispn
import com.github.kerubistan.kerub.data.ControllerDao
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.whenever
import org.infinispan.manager.EmbeddedCacheManager
import org.infinispan.remoting.transport.Address
import org.junit.Before
import org.junit.Test
import kotlin.test.assertEquals
class ControllerDaoImplTest {
private var dao : ControllerDao? = null
private val cacheManager : EmbeddedCacheManager = mock()
private val address1 : Address = mock()
private val address2 : Address = mock()
@Before fun setup() {
whenever(cacheManager.members).thenReturn( listOf(address1, address1) )
whenever(address1.toString()).thenReturn("TEST-1")
whenever(address2.toString()).thenReturn("TEST-2")
dao = ControllerDaoImpl(cacheManager)
}
@Test
fun get() {
assertEquals("TEST-1", dao!!.get("TEST-1") )
}
@Test fun list() {
assertEquals(2, dao!!.list().size)
}
} | src/test/kotlin/com/github/kerubistan/kerub/data/ispn/ControllerDaoImplTest.kt | 2962944825 |
/*
* Copyright 2010-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.kotlin.js.inline.util
import org.jetbrains.kotlin.js.backend.ast.*
import org.jetbrains.kotlin.js.backend.ast.metadata.staticRef
import org.jetbrains.kotlin.js.inline.util.collectors.InstanceCollector
import org.jetbrains.kotlin.js.translate.expression.InlineMetadata
import org.jetbrains.kotlin.js.translate.utils.JsAstUtils
fun collectFunctionReferencesInside(scope: JsNode): List<JsName> =
collectReferencedNames(scope).filter { it.staticRef is JsFunction }
fun collectReferencedTemporaryNames(scope: JsNode): Set<JsName> {
val references = mutableSetOf<JsName>()
object : RecursiveJsVisitor() {
override fun visitElement(node: JsNode) {
if (node is HasName) {
node.name?.let { references += it }
}
super.visitElement(node)
}
}.accept(scope)
return references
}
private fun collectReferencedNames(scope: JsNode): Set<JsName> {
val references = mutableSetOf<JsName>()
object : RecursiveJsVisitor() {
override fun visitBreak(x: JsBreak) { }
override fun visitContinue(x: JsContinue) { }
override fun visit(x: JsVars.JsVar) {
val initializer = x.initExpression
if (initializer != null) {
accept(initializer)
}
}
override fun visitNameRef(nameRef: JsNameRef) {
super.visitNameRef(nameRef)
val name = nameRef.name
if (name != null) {
references += name
}
}
}.accept(scope)
return references
}
fun collectUsedNames(scope: JsNode): Set<JsName> {
val references = mutableSetOf<JsName>()
object : RecursiveJsVisitor() {
override fun visitBreak(x: JsBreak) { }
override fun visitContinue(x: JsContinue) { }
override fun visit(x: JsVars.JsVar) {
val initializer = x.initExpression
if (initializer != null) {
accept(initializer)
}
}
override fun visitNameRef(nameRef: JsNameRef) {
super.visitNameRef(nameRef)
val name = nameRef.name
if (name != null && nameRef.qualifier == null) {
references.add(name)
}
}
override fun visitFunction(x: JsFunction) {
references += x.collectFreeVariables()
}
}.accept(scope)
return references
}
fun collectDefinedNames(scope: JsNode): Set<JsName> {
val names = mutableSetOf<JsName>()
object : RecursiveJsVisitor() {
override fun visit(x: JsVars.JsVar) {
val initializer = x.initExpression
if (initializer != null) {
accept(initializer)
}
names += x.name
}
override fun visitExpressionStatement(x: JsExpressionStatement) {
val expression = x.expression
if (expression is JsFunction) {
val name = expression.name
if (name != null) {
names += name
}
}
super.visitExpressionStatement(x)
}
// Skip function expression, since it does not introduce name in scope of containing function.
// The only exception is function statement, that is handled with the code above.
override fun visitFunction(x: JsFunction) { }
}.accept(scope)
return names
}
fun JsFunction.collectFreeVariables() = collectUsedNames(body) - collectDefinedNames(body) - parameters.map { it.name }
fun JsFunction.collectLocalVariables() = collectDefinedNames(body) + parameters.map { it.name }
fun collectNamedFunctions(scope: JsNode) = collectNamedFunctionsAndMetadata(scope).mapValues { it.value.first }
fun collectNamedFunctionsOrMetadata(scope: JsNode) = collectNamedFunctionsAndMetadata(scope).mapValues { it.value.second }
fun collectNamedFunctionsAndMetadata(scope: JsNode): Map<JsName, Pair<JsFunction, JsExpression>> {
val namedFunctions = mutableMapOf<JsName, Pair<JsFunction, JsExpression>>()
scope.accept(object : RecursiveJsVisitor() {
override fun visitBinaryExpression(x: JsBinaryOperation) {
val assignment = JsAstUtils.decomposeAssignment(x)
if (assignment != null) {
val (left, right) = assignment
if (left is JsNameRef) {
val name = left.name
val function = extractFunction(right)
if (function != null && name != null) {
namedFunctions[name] = Pair(function, right)
}
}
}
super.visitBinaryExpression(x)
}
override fun visit(x: JsVars.JsVar) {
val initializer = x.initExpression
val name = x.name
if (initializer != null && name != null) {
val function = extractFunction(initializer)
if (function != null) {
namedFunctions[name] = Pair(function, initializer)
}
}
super.visit(x)
}
override fun visitFunction(x: JsFunction) {
val name = x.name
if (name != null) {
namedFunctions[name] = Pair(x, x)
}
super.visitFunction(x)
}
private fun extractFunction(expression: JsExpression) = when (expression) {
is JsFunction -> expression
else -> InlineMetadata.decompose(expression)?.function
}
})
return namedFunctions
}
fun collectAccessors(scope: JsNode): Map<String, JsFunction> {
val accessors = hashMapOf<String, JsFunction>()
scope.accept(object : RecursiveJsVisitor() {
override fun visitInvocation(invocation: JsInvocation) {
InlineMetadata.decompose(invocation)?.let {
accessors[it.tag.value] = it.function
}
super.visitInvocation(invocation)
}
})
return accessors
}
fun <T : JsNode> collectInstances(klass: Class<T>, scope: JsNode): List<T> {
return with(InstanceCollector(klass, visitNestedDeclarations = false)) {
accept(scope)
collected
}
}
fun JsNode.collectBreakContinueTargets(): Map<JsContinue, JsStatement> {
val targets = mutableMapOf<JsContinue, JsStatement>()
accept(object : RecursiveJsVisitor() {
var defaultBreakTarget: JsStatement? = null
var breakTargets = mutableMapOf<JsName, JsStatement?>()
var defaultContinueTarget: JsStatement? = null
var continueTargets = mutableMapOf<JsName, JsStatement?>()
override fun visitLabel(x: JsLabel) {
val inner = x.statement
when (inner) {
is JsDoWhile -> handleLoop(inner, inner.body, x.name)
is JsWhile -> handleLoop(inner, inner.body, x.name)
is JsFor -> handleLoop(inner, inner.body, x.name)
is JsSwitch -> handleSwitch(inner, x.name)
else -> {
withBreakAndContinue(x.name, x.statement, null) {
accept(inner)
}
}
}
}
override fun visitWhile(x: JsWhile) = handleLoop(x, x.body, null)
override fun visitDoWhile(x: JsDoWhile) = handleLoop(x, x.body, null)
override fun visitFor(x: JsFor) = handleLoop(x, x.body, null)
override fun visit(x: JsSwitch) = handleSwitch(x, null)
private fun handleSwitch(statement: JsSwitch, label: JsName?) {
withBreakAndContinue(label, statement) {
statement.cases.forEach { accept(it) }
}
}
private fun handleLoop(loop: JsStatement, body: JsStatement, label: JsName?) {
withBreakAndContinue(label, loop, loop) {
body.accept(this)
}
}
override fun visitBreak(x: JsBreak) {
val targetLabel = x.label?.name
targets[x] = if (targetLabel == null) {
defaultBreakTarget!!
}
else {
breakTargets[targetLabel]!!
}
}
override fun visitContinue(x: JsContinue) {
val targetLabel = x.label?.name
targets[x] = if (targetLabel == null) {
defaultContinueTarget!!
}
else {
continueTargets[targetLabel]!!
}
}
private fun withBreakAndContinue(
label: JsName?,
breakTargetStatement: JsStatement,
continueTargetStatement: JsStatement? = null,
action: () -> Unit
) {
val oldDefaultBreakTarget = defaultBreakTarget
val oldDefaultContinueTarget = defaultContinueTarget
val (oldBreakTarget, oldContinueTarget) = if (label != null) {
Pair(breakTargets[label], continueTargets[label])
}
else {
Pair(null, null)
}
defaultBreakTarget = breakTargetStatement
if (label != null) {
breakTargets[label] = breakTargetStatement
continueTargets[label] = continueTargetStatement
}
if (continueTargetStatement != null) {
defaultContinueTarget = continueTargetStatement
}
action()
defaultBreakTarget = oldDefaultBreakTarget
defaultContinueTarget = oldDefaultContinueTarget
if (label != null) {
breakTargets[label] = oldBreakTarget
continueTargets[label] = oldContinueTarget
}
}
})
return targets
} | phizdets/phizdetsc/src/org/jetbrains/kotlin/js/inline/util/collectUtils.kt | 1057131273 |
package com.homemods.relay.pin
/**
* @author sergeys
*/
interface OutputPin {
fun set(state: PinState)
fun get(): PinState
fun on() = set(PinState.ON)
fun off() = set(PinState.OFF)
fun toggle() = set(if (get() == PinState.ON) {
PinState.OFF
} else {
PinState.ON
})
fun pulse(millis: Int)
fun setShutdownState(state: PinState)
} | core/src/com/homemods/relay/pin/OutputPin.kt | 2981021935 |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.platform
import com.intellij.CommonBundle
import com.intellij.configurationStore.StoreUtil
import com.intellij.featureStatistics.fusCollectors.LifecycleUsageTriggerCollector
import com.intellij.ide.impl.OpenProjectTask
import com.intellij.lang.LangBundle
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.module.PrimaryModuleManager
import com.intellij.openapi.module.impl.ModuleManagerEx
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ex.ProjectManagerEx
import com.intellij.openapi.project.modifyModules
import com.intellij.openapi.roots.ModuleRootModificationUtil
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.NlsSafe
import com.intellij.platform.ModuleAttachProcessor.Companion.getPrimaryModule
import com.intellij.projectImport.ProjectAttachProcessor
import com.intellij.projectImport.ProjectOpenedCallback
import com.intellij.util.io.directoryStreamIfExists
import com.intellij.util.io.exists
import com.intellij.util.io.systemIndependentPath
import java.nio.file.Path
private val LOG = logger<ModuleAttachProcessor>()
class ModuleAttachProcessor : ProjectAttachProcessor() {
companion object {
@JvmStatic
fun getPrimaryModule(project: Project) = if (canAttachToProject()) PrimaryModuleManager.findPrimaryModule(project) else null
@JvmStatic
fun getSortedModules(project: Project): List<Module> {
val primaryModule = getPrimaryModule(project)
val result = ArrayList<Module>()
ModuleManager.getInstance(project).modules.filterTo(result) { it !== primaryModule}
result.sortBy(Module::getName)
primaryModule?.let {
result.add(0, it)
}
return result
}
/**
* @param project the project
* @return `null` if either multi-projects are not enabled or the project has only one module
*/
@JvmStatic
@NlsSafe
fun getMultiProjectDisplayName(project: Project): String? {
if (!canAttachToProject()) {
return null
}
val modules = ModuleManager.getInstance(project).modules
if (modules.size <= 1) {
return null
}
val primaryModule = getPrimaryModule(project) ?: modules.first()
val result = StringBuilder(primaryModule.name)
.append(", ")
.append(modules.asSequence().filter { it !== primaryModule }.first().name)
if (modules.size > 2) {
result.append("...")
}
return result.toString()
}
}
override fun attachToProject(project: Project, projectDir: Path, callback: ProjectOpenedCallback?): Boolean {
LOG.info(String.format("Attaching directory: \"%s\"", projectDir))
val dotIdeaDir = projectDir.resolve(Project.DIRECTORY_STORE_FOLDER)
if (!dotIdeaDir.exists()) {
val options = OpenProjectTask(useDefaultProjectAsTemplate = true, isNewProject = true)
val newProject = ProjectManagerEx.getInstanceEx().newProject(projectDir, options) ?: return false
PlatformProjectOpenProcessor.runDirectoryProjectConfigurators(projectDir, newProject, true)
StoreUtil.saveSettings(newProject)
runWriteAction { Disposer.dispose(newProject) }
}
val newModule = try {
findMainModule(project, dotIdeaDir) ?: findMainModule(project, projectDir)
}
catch (e: Exception) {
LOG.info(e)
Messages.showErrorDialog(project,
LangBundle.message("module.attach.dialog.message.cannot.attach.project", e.message),
CommonBundle.getErrorTitle())
return false
}
LifecycleUsageTriggerCollector.onProjectModuleAttached(project)
if (newModule != null) {
callback?.projectOpened(project, newModule)
return true
}
return Messages.showYesNoDialog(project,
LangBundle.message("module.attach.dialog.message.project.uses.non.standard.layout", projectDir),
LangBundle.message("module.attach.dialog.title.open.project"),
Messages.getQuestionIcon()) != Messages.YES
}
override fun beforeDetach(module: Module) {
module.project.messageBus.syncPublisher(ModuleAttachListener.TOPIC).beforeDetach(module)
}
}
private fun findMainModule(project: Project, projectDir: Path): Module? {
projectDir.directoryStreamIfExists({ path -> path.fileName.toString().endsWith(ModuleManagerEx.IML_EXTENSION) }) { directoryStream ->
for (file in directoryStream) {
return attachModule(project, file)
}
}
return null
}
private fun attachModule(project: Project, imlFile: Path): Module {
val module = project.modifyModules {
loadModule(imlFile.systemIndependentPath)
}
val newModule = ModuleManager.getInstance(project).findModuleByName(module.name)!!
val primaryModule = addPrimaryModuleDependency(project, newModule)
module.project.messageBus.syncPublisher(ModuleAttachListener.TOPIC).afterAttach(newModule, primaryModule, imlFile)
return newModule
}
private fun addPrimaryModuleDependency(project: Project, newModule: Module): Module? {
val module = getPrimaryModule(project)
if (module != null && module !== newModule) {
ModuleRootModificationUtil.addDependency(module, newModule)
return module
}
return null
}
| platform/lang-impl/src/com/intellij/platform/ModuleAttachProcessor.kt | 2603651282 |
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.tv.material
@RequiresOptIn(
"This tv-material API is experimental and likely to change or be removed in the future."
)
@Retention(AnnotationRetention.BINARY)
annotation class ExperimentalTvMaterialApi | tv/tv-material/src/main/java/androidx/tv/material/ExperimentalTvMaterialApi.kt | 1686614352 |
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.camera.camera2.internal
import android.content.Context
import android.hardware.camera2.CameraCharacteristics
import android.hardware.camera2.CameraMetadata
import android.os.Build
import android.os.Handler
import android.os.Looper
import androidx.camera.core.CameraSelector
import androidx.camera.core.impl.CameraThreadConfig
import androidx.camera.core.impl.utils.executor.CameraXExecutors
import androidx.test.core.app.ApplicationProvider
import com.google.common.truth.Truth.assertThat
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import org.robolectric.annotation.internal.DoNotInstrument
import org.robolectric.shadow.api.Shadow
import org.robolectric.shadows.ShadowCameraCharacteristics
import org.robolectric.shadows.ShadowCameraManager
import org.robolectric.util.ReflectionHelpers
@RunWith(RobolectricTestRunner::class)
@DoNotInstrument
@Config(
minSdk = Build.VERSION_CODES.LOLLIPOP,
instrumentedPackages = ["androidx.camera.camera2.internal"]
)
class Camera2CameraFactoryTest {
@Test
fun filterOutIncompatibleCameras_withoutAvailableCameraSelector() {
// Customizes Build.FINGERPRINT to be not "fingerprint", so that cameras without
// REQUEST_AVAILABLE_CAPABILITIES_BACKWARD_COMPATIBLE will be filtered.
ReflectionHelpers.setStaticField(Build::class.java, "FINGERPRINT", "fake-fingerprint")
setupCameras()
val camera2CameraFactory = Camera2CameraFactory(
ApplicationProvider.getApplicationContext(),
CameraThreadConfig.create(
CameraXExecutors.mainThreadExecutor(),
Handler(Looper.getMainLooper())
),
null)
assertThat(camera2CameraFactory.availableCameraIds).containsExactly("0", "1", "2")
}
@Test
fun filterOutIncompatibleCameras_withAvailableCameraSelector() {
// Customizes Build.FINGERPRINT to be not "fingerprint", so that cameras without
// REQUEST_AVAILABLE_CAPABILITIES_BACKWARD_COMPATIBLE will be filtered.
ReflectionHelpers.setStaticField(Build::class.java, "FINGERPRINT", "fake-fingerprint")
setupCameras()
val camera2CameraFactory = Camera2CameraFactory(
ApplicationProvider.getApplicationContext(),
CameraThreadConfig.create(
CameraXExecutors.mainThreadExecutor(),
Handler(Looper.getMainLooper())
),
CameraSelector.DEFAULT_BACK_CAMERA)
assertThat(camera2CameraFactory.availableCameraIds).containsExactly("0", "2")
}
@Test
fun NotFilterOutIncompatibleCameras_whenBuildFingerprintIsRobolectric() {
setupCameras()
val camera2CameraFactory = Camera2CameraFactory(
ApplicationProvider.getApplicationContext(),
CameraThreadConfig.create(
CameraXExecutors.mainThreadExecutor(),
Handler(Looper.getMainLooper())
),
null)
assertThat(camera2CameraFactory.availableCameraIds).containsExactly("0", "1", "2", "3")
}
private fun setupCameras() {
val capabilities =
intArrayOf(CameraMetadata.REQUEST_AVAILABLE_CAPABILITIES_BACKWARD_COMPATIBLE)
// Camera "0" and "1" won't be filtered out even they don't have
// REQUEST_AVAILABLE_CAPABILITIES_BACKWARD_COMPATIBLE.
initCharacterisic("0", CameraCharacteristics.LENS_FACING_BACK, null)
initCharacterisic("1", CameraCharacteristics.LENS_FACING_FRONT, null)
initCharacterisic("2", CameraCharacteristics.LENS_FACING_BACK, capabilities)
// Do not set REQUEST_AVAILABLE_CAPABILITIES_BACKWARD_COMPATIBLE for the camera, so that
// it will be filtered out if Build.FINGERPRINT is no "robolectric".
// Do not set REQUEST_AVAILABLE_CAPABILITIES_BACKWARD_COMPATIBLE for the camera, so that
// it will be filtered out if Build.FINGERPRINT is no "robolectric".
initCharacterisic("3", CameraCharacteristics.LENS_FACING_BACK, null)
}
private fun initCharacterisic(cameraId: String, lensFacing: Int, capabilities: IntArray?) {
val characteristics = ShadowCameraCharacteristics.newCameraCharacteristics()
val shadowCharacteristics = Shadow.extract<ShadowCameraCharacteristics>(characteristics)
shadowCharacteristics.set(
CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL,
CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_FULL
)
// Add a lens facing to the camera
shadowCharacteristics.set(CameraCharacteristics.LENS_FACING, lensFacing)
capabilities?.let {
shadowCharacteristics.set(
CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES,
capabilities
)
}
// Add the camera to the camera service
(Shadow.extract<Any>(
ApplicationProvider.getApplicationContext<Context>()
.getSystemService(Context.CAMERA_SERVICE)
) as ShadowCameraManager)
.addCamera(cameraId, characteristics)
}
}
| camera/camera-camera2/src/test/java/androidx/camera/camera2/internal/Camera2CameraFactoryTest.kt | 1875727916 |
package de.droidcon.berlin2018.ui.home
import android.support.design.widget.BottomNavigationView
import android.view.ViewGroup
import de.droidcon.berlin2018.R
import de.droidcon.berlin2018.ui.disableShiftMode
import de.droidcon.berlin2018.ui.searchbox.SearchBox
import de.droidcon.berlin2018.ui.viewbinding.LifecycleAwareRef
import de.droidcon.berlin2018.ui.viewbinding.ViewBinding
/**
* Binds the UI to [HomeController]
*
* @author Hannes Dorfmann
*/
class HomeViewBinding : ViewBinding(), HomeView {
private var bottomNavigationView: BottomNavigationView by LifecycleAwareRef(this)
private var searchBox: SearchBox by LifecycleAwareRef(this)
private val navigationListener = BottomNavigationView.OnNavigationItemSelectedListener { item ->
searchBox.slideInIfNeeded()
when (item.itemId) {
R.id.nav_sessions -> {
navigator.showSessions()
true
}
R.id.nav_my_schedule -> {
navigator.showMySchedule()
true
}
R.id.nav_speakers -> {
navigator.showSpeakers()
true
}
R.id.nav_twitter -> {
navigator.showTweets()
true
}
R.id.nav_barcamp -> {
navigator.showBarcamp()
true
}
else -> false
}
}
override fun bindView(rootView: ViewGroup) {
searchBox = rootView.findViewById(R.id.searchBox)
searchBox.showInput = false
searchBox.setOnClickListener { navigator.showSearch() }
searchBox.overflowMenuClickListener = {
when (it) {
0 -> navigator.showSourceCode()
1 -> navigator.showLicences()
}
}
bottomNavigationView = rootView.findViewById(R.id.navigation)
bottomNavigationView.setOnNavigationItemSelectedListener(navigationListener)
bottomNavigationView.disableShiftMode()
bottomNavigationView.setOnNavigationItemReselectedListener { } // Disallow reselect
}
}
| app/src/main/java/de/droidcon/berlin2018/ui/home/HomeViewBinding.kt | 3011636649 |
package com.sotwtm.example
import com.sotwtm.example.contributor.ActivitiesClassMapModule
import com.sotwtm.example.contributor.ActivitiesContributorModule
import com.sotwtm.example.contributor.FragmentsClassMapModule
import com.sotwtm.example.contributor.FragmentsContributorModule
import com.sotwtm.support.scope.AppScope
import dagger.BindsInstance
import dagger.Component
import dagger.android.AndroidInjector
import dagger.android.support.AndroidSupportInjectionModule
/**
* All modules needed by this application are installed here.
* @author sheungon
* */
@AppScope
@Component(
modules = [
AndroidSupportInjectionModule::class,
ApplicationModule::class,
ActivitiesContributorModule::class,
ActivitiesClassMapModule::class,
FragmentsContributorModule::class,
FragmentsClassMapModule::class]
)
interface ExampleApplicationComponent : AndroidInjector<ExampleApplication> {
@Component.Builder
interface Builder {
@BindsInstance
fun application(application: ExampleApplication): Builder
fun build(): ExampleApplicationComponent
}
} | example/src/main/java/com/sotwtm/example/ExampleApplicationComponent.kt | 2038456628 |
package charlie.laplacian.decoder
import charlie.laplacian.output.OutputSettings
import charlie.laplacian.stream.TrackStream
interface DecoderSession {
fun read(buf: ByteArray?): ByteArray?
fun seek(positionMillis: Long)
fun positionMillis(): Long
fun durationMillis(): Long
fun close()
}
interface Decoder {
fun getSession(outputSettings: OutputSettings, stream: TrackStream): DecoderSession
fun getMetadata(): DecoderMetadata
}
interface DecoderMetadata {
fun getName(): String
fun getVersion(): String
fun getVersionID(): Int
} | Laplacian.Framework/src/main/kotlin/charlie/laplacian/decoder/Decoder.kt | 4050045174 |
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.core.splashscreen
import android.R.attr
import android.annotation.SuppressLint
import android.app.Activity
import android.content.res.Resources
import android.graphics.Rect
import android.graphics.drawable.Drawable
import android.os.Build
import android.os.Build.VERSION.SDK_INT
import android.util.TypedValue
import android.view.View
import android.view.View.OnLayoutChangeListener
import android.view.ViewGroup
import android.view.ViewTreeObserver.OnPreDrawListener
import android.view.WindowInsets
import android.view.WindowManager.LayoutParams
import android.widget.ImageView
import android.window.SplashScreenView
import androidx.annotation.MainThread
import androidx.annotation.RequiresApi
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import androidx.core.splashscreen.SplashScreen.KeepOnScreenCondition
/**
* Provides control over the splash screen once the application is started.
*
* On API 31+ (Android 12+) this class calls the platform methods.
*
* Prior API 31, the platform behavior is replicated with the exception of the Animated Vector
* Drawable support on the launch screen.
*
* # Usage of the `core-splashscreen` library:
*
* To replicate the splash screen behavior from Android 12 on older APIs the following steps need to
* be taken:
* 1. Create a new Theme (e.g `Theme.App.Starting`) and set its parent to `Theme.SplashScreen` or
* `Theme.SplashScreen.IconBackground`
*
* 2. In your manifest, set the `theme` attribute of the whole `<application>` or just the
* starting `<activity>` to `Theme.App.Starting`
*
* 3. In the `onCreate` method the starting activity, call [installSplashScreen] just before
* `super.onCreate()`. You also need to make sure that `postSplashScreenTheme` is set
* to the application's theme. Alternatively, this call can be replaced by [Activity#setTheme]
* if a [SplashScreen] instance isn't needed.
*
* ## Themes
*
* The library provides two themes: [R.style.Theme_SplashScreen] and
* [R.style.Theme_SplashScreen_IconBackground]. If you wish to display a background right under
* your icon, the later needs to be used. This ensure that the scale and masking of the icon are
* similar to the Android 12 Splash Screen.
*
* `windowSplashScreenAnimatedIcon`: The splash screen icon. On API 31+ it can be an animated
* vector drawable.
*
* `windowSplashScreenAnimationDuration`: Duration of the Animated Icon Animation. The value
* needs to be > 0 if the icon is animated.
*
* **Note:** This has no impact on the time during which the splash screen is displayed and is
* only used in [SplashScreenViewProvider.iconAnimationDurationMillis]. If you need to display the
* splash screen for a longer time, you can use [SplashScreen.setKeepOnScreenCondition]
*
* `windowSplashScreenIconBackgroundColor`: _To be used in with
* `Theme.SplashScreen.IconBackground`_. Sets a background color under the splash screen icon.
*
* `windowSplashScreenBackground`: Background color of the splash screen. Defaults to the theme's
* `?attr/colorBackground`.
*
* `postSplashScreenTheme`* Theme to apply to the Activity when [installSplashScreen] is called.
*
* **Known incompatibilities:**
* - On API < 31, `windowSplashScreenAnimatedIcon` cannot be animated. If you want to provide an
* animated icon for API 31+ and a still icon for API <31, you can do so by overriding the still
* icon with an animated vector drawable in `res/drawable-v31`.
*
* - On API < 31, if the value of `windowSplashScreenAnimatedIcon` is an
* [adaptive icon](http://developer.android.com/guide/practices/ui_guidelines/icon_design_adaptive)
* , it will be cropped and scaled. The workaround is to respectively assign
* `windowSplashScreenAnimatedIcon` and `windowSplashScreenIconBackgroundColor` to the values of
* the adaptive icon `foreground` and `background`.
*
* - On API 21-22, The icon isn't displayed until the application starts, only the background is
* visible.
*
* # Design
* The splash screen icon uses the same specifications as
* [Adaptive Icons](https://developer.android.com/guide/practices/ui_guidelines/icon_design_adaptive)
* . This means that the icon needs to fit within a circle whose diameter is 2/3 the size of the
* icon. The actual values don't really matter if you use a vector icon.
*
* ## Specs
* - With icon background (`Theme.SplashScreen.IconBackground`)
* + Image Size: 240x240 dp
* + Inner Circle diameter: 160 dp
* - Without icon background (`Theme.SplashScreen`)
* + Image size: 288x288 dp
* + Inner circle diameter: 192 dp
*
* _Example:_ if the full size of the image is 300dp*300dp, the icon needs to fit within a
* circle with a diameter of 200dp. Everything outside the circle will be invisible (masked).
*
*/
@SuppressLint("CustomSplashScreen")
class SplashScreen private constructor(activity: Activity) {
private val impl = when {
SDK_INT >= 31 -> Impl31(activity)
else -> Impl(activity)
}
public companion object {
private const val MASK_FACTOR = 2 / 3f
/**
* Creates a [SplashScreen] instance associated with this [Activity] and handles
* setting the theme to [R.attr.postSplashScreenTheme].
*
* This needs to be called before [Activity.setContentView] or other view operations on
* the root view (e.g setting flags).
*
* Alternatively, if a [SplashScreen] instance is not required, the theme can manually be
* set using [Activity.setTheme].
*/
@JvmStatic
public fun Activity.installSplashScreen(): SplashScreen {
val splashScreen = SplashScreen(this)
splashScreen.install()
return splashScreen
}
}
/**
* Sets the condition to keep the splash screen visible.
*
* The splash will stay visible until the condition isn't met anymore.
* The condition is evaluated before each request to draw the application, so it needs to be
* fast to avoid blocking the UI.
*
* @param condition The condition evaluated to decide whether to keep the splash screen on
* screen
*/
public fun setKeepOnScreenCondition(condition: KeepOnScreenCondition) {
impl.setKeepOnScreenCondition(condition)
}
/**
* Sets a listener that will be called when the splashscreen is ready to be removed.
*
* If a listener is set, the splashscreen won't be automatically removed and the application
* needs to manually call [SplashScreenViewProvider.remove].
*
* IF no listener is set, the splashscreen will be automatically removed once the app is
* ready to draw.
*
* The listener will be called on the ui thread.
*
* @param listener The [OnExitAnimationListener] that will be called when the splash screen
* is ready to be dismissed.
*
* @see setKeepOnScreenCondition
* @see OnExitAnimationListener
* @see SplashScreenViewProvider
*/
@SuppressWarnings("ExecutorRegistration") // Always runs on the MainThread
public fun setOnExitAnimationListener(listener: OnExitAnimationListener) {
impl.setOnExitAnimationListener(listener)
}
private fun install() {
impl.install()
}
/**
* Listener to be passed in [SplashScreen.setOnExitAnimationListener].
*
* The listener will be called once the splash screen is ready to be removed and provides a
* reference to a [SplashScreenViewProvider] that can be used to customize the exit
* animation of the splash screen.
*/
public fun interface OnExitAnimationListener {
/**
* Callback called when the splash screen is ready to be dismissed. The caller is
* responsible for animating and removing splash screen using the provided
* [splashScreenViewProvider].
*
* The caller **must** call [SplashScreenViewProvider.remove] once it's done with the
* splash screen.
*
* @param splashScreenViewProvider An object holding a reference to the displayed splash
* screen.
*/
@MainThread
public fun onSplashScreenExit(splashScreenViewProvider: SplashScreenViewProvider)
}
/**
* Condition evaluated to check if the splash screen should remain on screen
*
* The splash screen will stay visible until the condition isn't met anymore.
* The condition is evaluated before each request to draw the application, so it needs to be
* fast to avoid blocking the UI.
*/
public fun interface KeepOnScreenCondition {
/**
* Callback evaluated before every requests to draw the Activity. If it returns `true`, the
* splash screen will be kept visible to hide the Activity below.
*
* This callback is evaluated in the main thread.
*/
@MainThread
public fun shouldKeepOnScreen(): Boolean
}
private open class Impl(val activity: Activity) {
var finalThemeId: Int = 0
var backgroundResId: Int? = null
var backgroundColor: Int? = null
var icon: Drawable? = null
var hasBackground: Boolean = false
var splashScreenWaitPredicate = KeepOnScreenCondition { false }
private var animationListener: OnExitAnimationListener? = null
private var mSplashScreenViewProvider: SplashScreenViewProvider? = null
open fun install() {
val typedValue = TypedValue()
val currentTheme = activity.theme
if (currentTheme.resolveAttribute(
R.attr.windowSplashScreenBackground,
typedValue,
true
)
) {
backgroundResId = typedValue.resourceId
backgroundColor = typedValue.data
}
if (currentTheme.resolveAttribute(
R.attr.windowSplashScreenAnimatedIcon,
typedValue,
true
)
) {
icon = currentTheme.getDrawable(typedValue.resourceId)
}
if (currentTheme.resolveAttribute(R.attr.splashScreenIconSize, typedValue, true)) {
hasBackground =
typedValue.resourceId == R.dimen.splashscreen_icon_size_with_background
}
setPostSplashScreenTheme(currentTheme, typedValue)
}
protected fun setPostSplashScreenTheme(
currentTheme: Resources.Theme,
typedValue: TypedValue
) {
if (currentTheme.resolveAttribute(R.attr.postSplashScreenTheme, typedValue, true)) {
finalThemeId = typedValue.resourceId
if (finalThemeId != 0) {
activity.setTheme(finalThemeId)
}
}
}
open fun setKeepOnScreenCondition(keepOnScreenCondition: KeepOnScreenCondition) {
splashScreenWaitPredicate = keepOnScreenCondition
val contentView = activity.findViewById<View>(android.R.id.content)
val observer = contentView.viewTreeObserver
observer.addOnPreDrawListener(object : OnPreDrawListener {
override fun onPreDraw(): Boolean {
if (splashScreenWaitPredicate.shouldKeepOnScreen()) {
return false
}
contentView.viewTreeObserver.removeOnPreDrawListener(this)
mSplashScreenViewProvider?.let(::dispatchOnExitAnimation)
return true
}
})
}
open fun setOnExitAnimationListener(exitAnimationListener: OnExitAnimationListener) {
animationListener = exitAnimationListener
val splashScreenViewProvider = SplashScreenViewProvider(activity)
val finalBackgroundResId = backgroundResId
val finalBackgroundColor = backgroundColor
val splashScreenView = splashScreenViewProvider.view
if (finalBackgroundResId != null && finalBackgroundResId != Resources.ID_NULL) {
splashScreenView.setBackgroundResource(finalBackgroundResId)
} else if (finalBackgroundColor != null) {
splashScreenView.setBackgroundColor(finalBackgroundColor)
} else {
splashScreenView.background = activity.window.decorView.background
}
icon?.let { displaySplashScreenIcon(splashScreenView, it) }
splashScreenView.addOnLayoutChangeListener(
object : OnLayoutChangeListener {
override fun onLayoutChange(
view: View,
left: Int,
top: Int,
right: Int,
bottom: Int,
oldLeft: Int,
oldTop: Int,
oldRight: Int,
oldBottom: Int
) {
if (!view.isAttachedToWindow) {
return
}
view.removeOnLayoutChangeListener(this)
if (!splashScreenWaitPredicate.shouldKeepOnScreen()) {
dispatchOnExitAnimation(splashScreenViewProvider)
} else {
mSplashScreenViewProvider = splashScreenViewProvider
}
}
})
}
private fun displaySplashScreenIcon(splashScreenView: View, icon: Drawable) {
val iconView = splashScreenView.findViewById<ImageView>(R.id.splashscreen_icon_view)
iconView.apply {
val maskSize: Float
if (hasBackground) {
// If the splash screen has an icon background we need to mask both the
// background and foreground.
val iconBackgroundDrawable = context.getDrawable(R.drawable.icon_background)
val iconSize =
resources.getDimension(R.dimen.splashscreen_icon_size_with_background)
maskSize = iconSize * MASK_FACTOR
if (iconBackgroundDrawable != null) {
background = MaskedDrawable(iconBackgroundDrawable, maskSize)
}
} else {
val iconSize =
resources.getDimension(R.dimen.splashscreen_icon_size_no_background)
maskSize = iconSize * MASK_FACTOR
}
setImageDrawable(MaskedDrawable(icon, maskSize))
}
}
fun dispatchOnExitAnimation(splashScreenViewProvider: SplashScreenViewProvider) {
val finalListener = animationListener ?: return
animationListener = null
splashScreenViewProvider.view.postOnAnimation {
splashScreenViewProvider.view.bringToFront()
finalListener.onSplashScreenExit(splashScreenViewProvider)
}
}
}
@RequiresApi(Build.VERSION_CODES.S)
private class Impl31(activity: Activity) : Impl(activity) {
var preDrawListener: OnPreDrawListener? = null
var mDecorFitWindowInsets = true
val hierarchyListener = object : ViewGroup.OnHierarchyChangeListener {
override fun onChildViewAdded(parent: View?, child: View?) {
if (child is SplashScreenView) {
/*
* On API 31, the SplashScreenView sets window.setDecorFitsSystemWindows(false)
* when an OnExitAnimationListener is used. This also affects the application
* content that will be pushed up under the status bar even though it didn't
* requested it. And once the SplashScreenView is removed, the whole layout
* jumps back below the status bar. Fortunately, this happens only after the
* view is attached, so we have time to record the value of
* window.setDecorFitsSystemWindows() before the splash screen modifies it and
* reapply the correct value to the window.
*/
mDecorFitWindowInsets = computeDecorFitsWindow(child)
(activity.window.decorView as ViewGroup).setOnHierarchyChangeListener(null)
}
}
override fun onChildViewRemoved(parent: View?, child: View?) {
// no-op
}
}
fun computeDecorFitsWindow(child: SplashScreenView): Boolean {
val inWindowInsets = WindowInsets.Builder().build()
val outLocalInsets = Rect(
Int.MIN_VALUE, Int.MIN_VALUE, Int.MAX_VALUE,
Int.MAX_VALUE
)
// If setDecorFitWindowInsets is set to false, computeSystemWindowInsets
// will return the same instance of WindowInsets passed in its parameter and
// will set outLocalInsets to empty, so we check that both conditions are
// filled to extrapolate the value of setDecorFitWindowInsets
return !(inWindowInsets === child.rootView.computeSystemWindowInsets
(inWindowInsets, outLocalInsets) && outLocalInsets.isEmpty)
}
override fun install() {
setPostSplashScreenTheme(activity.theme, TypedValue())
(activity.window.decorView as ViewGroup).setOnHierarchyChangeListener(
hierarchyListener
)
}
override fun setKeepOnScreenCondition(keepOnScreenCondition: KeepOnScreenCondition) {
splashScreenWaitPredicate = keepOnScreenCondition
val contentView = activity.findViewById<View>(android.R.id.content)
val observer = contentView.viewTreeObserver
if (preDrawListener != null && observer.isAlive) {
observer.removeOnPreDrawListener(preDrawListener)
}
preDrawListener = object : OnPreDrawListener {
override fun onPreDraw(): Boolean {
if (splashScreenWaitPredicate.shouldKeepOnScreen()) {
return false
}
contentView.viewTreeObserver.removeOnPreDrawListener(this)
return true
}
}
observer.addOnPreDrawListener(preDrawListener)
}
override fun setOnExitAnimationListener(
exitAnimationListener: OnExitAnimationListener
) {
activity.splashScreen.setOnExitAnimationListener { splashScreenView ->
applyAppSystemUiTheme()
val splashScreenViewProvider = SplashScreenViewProvider(splashScreenView, activity)
exitAnimationListener.onSplashScreenExit(splashScreenViewProvider)
}
}
/**
* Apply the system ui related theme attribute defined in the application to override the
* ones set on the [SplashScreenView]
*
* On API 31, if an OnExitAnimationListener is set, the Window layout params are only
* applied only when the [SplashScreenView] is removed. This lead to some
* flickers.
*
* To fix this, we apply these attributes as soon as the [SplashScreenView]
* is visible.
*/
private fun applyAppSystemUiTheme() {
val tv = TypedValue()
val theme = activity.theme
val window = activity.window
if (theme.resolveAttribute(attr.statusBarColor, tv, true)) {
window.statusBarColor = tv.data
}
if (theme.resolveAttribute(attr.navigationBarColor, tv, true)) {
window.navigationBarColor = tv.data
}
if (theme.resolveAttribute(attr.windowDrawsSystemBarBackgrounds, tv, true)) {
if (tv.data != 0) {
window.addFlags(LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
} else {
window.clearFlags(LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
}
}
if (theme.resolveAttribute(attr.enforceNavigationBarContrast, tv, true)) {
window.isNavigationBarContrastEnforced = tv.data != 0
}
if (theme.resolveAttribute(attr.enforceStatusBarContrast, tv, true)) {
window.isStatusBarContrastEnforced = tv.data != 0
}
val decorView = window.decorView as ViewGroup
ThemeUtils.Api31.applyThemesSystemBarAppearance(theme, decorView, tv)
// Fix setDecorFitsSystemWindows being overridden by the SplashScreenView
decorView.setOnHierarchyChangeListener(null)
window.setDecorFitsSystemWindows(mDecorFitWindowInsets)
}
}
}
| core/core-splashscreen/src/main/java/androidx/core/splashscreen/SplashScreen.kt | 1909726755 |
// "Add 'CancellationException::class'" "false"
// ERROR: @Throws must have non-empty class list
// ACTION: Make internal
// ACTION: Make private
// ACTION: Remove annotation
// No compilation error => no quickfix.
<caret>@Throws
suspend fun emptyThrows() {}
| plugins/kotlin/idea/tests/testData/multiModuleQuickFix/fixNativeThrowsErrors/addCancellationException4/native/test.kt | 747001572 |
/*
* Copyright (C) 2018 Jhon Kenneth Carino
*
* 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.jkcarino.ankieditor.ui.editor
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import androidx.appcompat.widget.LinearLayoutCompat
import androidx.appcompat.widget.PopupMenu
import com.jkcarino.ankieditor.R
import kotlinx.android.synthetic.main.item_note_type_field.view.*
class NoteTypeFieldsContainer @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : LinearLayoutCompat(context, attrs, defStyleAttr) {
var onFieldOptionsClickListener: OnFieldOptionsClickListener? = null
val fieldsText: Array<String?>
get() {
val totalFields = childCount
val fields = arrayOfNulls<String>(totalFields)
for (i in 0 until totalFields) {
fields[i] = getChildAt(i).note_field_edittext.fieldText
}
return fields
}
fun addFields(fields: Array<String>) {
val inflater = LayoutInflater.from(context)
removeAllViews()
for (field in fields.indices) {
val view = inflater.inflate(R.layout.item_note_type_field, null)
// Set floating label
val fieldHint = view.note_field_til.apply { hint = fields[field] }
val fieldEditText = view.note_field_edittext.apply { tag = field }
view.note_field_options.setOnClickListener {
val index = fieldEditText.tag as Int
val text = fieldEditText.fieldText
PopupMenu(context, it).apply {
menuInflater.inflate(R.menu.menu_field_options, menu)
setOnMenuItemClickListener { item ->
val id = item.itemId
when (id) {
R.id.menu_cloze_deletion -> {
val fieldText = fieldEditText.text.toString()
val selectionStart = fieldEditText.selectionStart
val selectionEnd = fieldEditText.selectionEnd
onFieldOptionsClickListener?.onClozeDeletionClick(
index, fieldText, selectionStart, selectionEnd)
}
R.id.menu_advanced_editor -> {
onFieldOptionsClickListener?.onAdvancedEditorClick(
index, fieldHint.hint.toString(), text
)
}
}
true
}
}.show()
}
addView(view)
}
}
fun setFieldText(index: Int, text: String) {
if (childCount > 0) {
findViewWithTag<NoteTypeFieldEditText>(index).apply {
fieldText = text
requestFocus()
}
}
}
fun clearFields() {
(0 until childCount)
.map { getChildAt(it).note_field_edittext }
.forEach { it.text = null }
// Set the focus to the first field
getChildAt(0).note_field_edittext.requestFocus()
}
interface OnFieldOptionsClickListener {
fun onClozeDeletionClick(index: Int, text: String, selectionStart: Int, selectionEnd: Int)
fun onAdvancedEditorClick(index: Int, fieldName: String, text: String)
}
}
| app/src/main/java/com/jkcarino/ankieditor/ui/editor/NoteTypeFieldsContainer.kt | 3687237514 |
// PROBLEM: none
@Target(AnnotationTarget.TYPE)
annotation class Ann
fun foo() {
val t: @Ann <caret>Boolean = true
}
| plugins/kotlin/idea/tests/testData/inspectionsLocal/redundantExplicitType/annotated.kt | 706128588 |
package test
class Foo
fun test(list: List<Foo>) {
for (<caret>foo in list) {}
}
// TYPE: foo -> <html>Foo</html>
| plugins/kotlin/idea/tests/testData/codeInsight/expressionType/LoopVariableWithoutType.kt | 4123798322 |
// "Convert to 'isArrayOf' call" "true"
// WITH_STDLIB
fun test(a: Array<*>) {
if (a is <caret>Array<String>) {
}
} | plugins/kotlin/idea/tests/testData/quickfix/convertToIsArrayOfCall/arrayLhs.kt | 1710555722 |
// 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.gradle.importing
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.invokeAndWaitIfNeeded
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.externalSystem.action.AttachExternalProjectAction
import com.intellij.openapi.externalSystem.autoimport.AutoImportProjectTracker
import com.intellij.openapi.externalSystem.autoimport.ProjectNotificationAware
import com.intellij.openapi.externalSystem.importing.ExternalSystemSetupProjectTest
import com.intellij.openapi.externalSystem.importing.ExternalSystemSetupProjectTestCase
import com.intellij.openapi.externalSystem.model.ProjectSystemId
import com.intellij.openapi.externalSystem.service.execution.ExternalSystemJdkUtil
import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.ProjectJdkTable
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.vfs.VirtualFile
import org.jetbrains.plugins.gradle.action.ImportProjectFromScriptAction
import org.jetbrains.plugins.gradle.importing.GradleBuildScriptBuilder.Companion.buildscript
import org.jetbrains.plugins.gradle.settings.GradleSettings
import org.jetbrains.plugins.gradle.util.GradleConstants.SYSTEM_ID
import org.jetbrains.plugins.gradle.util.waitForProjectReload
import org.jetbrains.plugins.gradle.util.whenResolveTaskStarted
import org.junit.runners.Parameterized
import java.util.concurrent.atomic.AtomicInteger
class GradleSetupProjectTest : ExternalSystemSetupProjectTest, GradleImportingTestCase() {
private lateinit var testDisposable: Disposable
private lateinit var expectedImportActionsCounter: AtomicInteger
private lateinit var actualImportActionsCounter: AtomicInteger
override fun setUp() {
super.setUp()
testDisposable = Disposer.newDisposable()
expectedImportActionsCounter = AtomicInteger(0)
actualImportActionsCounter = AtomicInteger(0)
whenResolveTaskStarted({ actualImportActionsCounter.incrementAndGet() }, testDisposable)
AutoImportProjectTracker.enableAutoReloadInTests(testDisposable)
}
override fun tearDown() {
Disposer.dispose(testDisposable)
super.tearDown()
}
override fun getSystemId(): ProjectSystemId = SYSTEM_ID
override fun generateProject(id: String): ExternalSystemSetupProjectTestCase.ProjectInfo {
val name = "${System.currentTimeMillis()}-$id"
createProjectSubFile("$name-composite/settings.gradle", "rootProject.name = '$name-composite'")
createProjectSubFile("$name-project/settings.gradle", """
rootProject.name = '$name-project'
include 'module'
includeBuild '../$name-composite'
includeFlat '$name-module'
""".trimIndent())
val buildScript = buildscript { withJavaPlugin() }
createProjectSubFile("$name-composite/build.gradle", buildScript)
createProjectSubFile("$name-module/build.gradle", buildScript)
createProjectSubFile("$name-project/module/build.gradle", buildScript)
val projectFile = createProjectSubFile("$name-project/build.gradle", buildScript)
return ExternalSystemSetupProjectTestCase.ProjectInfo(projectFile,
"$name-project", "$name-project.main", "$name-project.test",
"$name-project.module", "$name-project.module.main", "$name-project.module.test",
"$name-project.$name-module", "$name-project.$name-module.main",
"$name-project.$name-module.test",
"$name-composite", "$name-composite.main", "$name-composite.test")
}
override fun assertDefaultProjectSettings(project: Project) {
val externalProjectPath = project.basePath!!
val settings = ExternalSystemApiUtil.getSettings(project, SYSTEM_ID) as GradleSettings
val projectSettings = settings.getLinkedProjectSettings(externalProjectPath)!!
assertEquals(projectSettings.externalProjectPath, externalProjectPath)
assertEquals(projectSettings.isUseQualifiedModuleNames, true)
assertEquals(settings.storeProjectFilesExternally, true)
}
override fun assertDefaultProjectState(project: Project) {
val notificationAware = ProjectNotificationAware.getInstance(myProject)
invokeAndWaitIfNeeded {
assertEmpty(notificationAware.getProjectsWithNotification())
}
assertEquals(expectedImportActionsCounter.get(), actualImportActionsCounter.get())
}
override fun <R> waitForImport(action: () -> R): R {
expectedImportActionsCounter.incrementAndGet()
return waitForProjectReload(action)
}
override fun attachProject(project: Project, projectFile: VirtualFile) {
AttachExternalProjectAction().perform(project, selectedFile = projectFile)
}
override fun attachProjectFromScript(project: Project, projectFile: VirtualFile) {
ImportProjectFromScriptAction().perform(project, selectedFile = projectFile)
}
override fun cleanupProjectTestResources(project: Project) {
super.cleanupProjectTestResources(project)
removeGradleJvmSdk(project)
}
companion object {
/**
* It's sufficient to run the test against one gradle version
*/
@Parameterized.Parameters(name = "with Gradle-{0}")
@JvmStatic
fun tests(): Collection<Array<out String>> = arrayListOf(arrayOf(BASE_GRADLE_VERSION))
fun removeGradleJvmSdk(project: Project) {
ApplicationManager.getApplication().invokeAndWait {
runWriteAction {
val projectJdkTable = ProjectJdkTable.getInstance()
val settings = GradleSettings.getInstance(project)
for (projectSettings in settings.linkedProjectsSettings) {
val gradleJvm = projectSettings.gradleJvm
val sdk = ExternalSystemJdkUtil.getJdk(project, gradleJvm)
if (sdk != null) projectJdkTable.removeJdk(sdk)
}
}
}
}
}
} | plugins/gradle/java/testSources/importing/GradleSetupProjectTest.kt | 241183228 |
package my.demo
// http://kotlinlang.org/docs/tutorials/command-line.html
fun main(args: Array<String>) {
if (args.size == 0) return
println("First argument: ${args[0]}")
println("Hello, World!")
System.out.println("Java, Hello Wrold!")
println(sum(3,5))
println(sum1(4,5))
printSum(5, 5)
localVariables()
println(max(3, 99))
println(max2(4, 89))
}
fun sum(a: Int, b: Int): Int {
return a + b
}
fun sum1(a: Int, b: Int) = a + b
fun printSum(a: Int, b: Int) {
println(a + b)
}
fun localVariables() {
val a: Int = 1
val b = 1 // `Int` type is inferred
val c: Int // Type required when no initializer is provided
c = 1 // definite assignment
var x = 5 // `Int` type is inferred
x +=1
println(x)
}
fun max(a: Int, b: Int): Int {
if (a > b)
return a
else
return b
}
fun max2(a: Int, b: Int) = if (a > b) a else b
| hello.kt | 3136461298 |
package com.kingz.mobile.libhlscache.bean
/**
* 下载结果回调
*/
interface IDownloadCallBack {
fun onDownloadError(id: String?, e: Exception?)
fun onDownloadFinish(id: String?)
} | library/hlscache/src/main/java/com/kingz/mobile/libhlscache/bean/IDownloadCallBack.kt | 2713504926 |
// FIR_COMPARISON
fun foo(param: Any): String {
val s = "${<caret>}"
}
// ELEMENT: param
| plugins/kotlin/completion/tests/testData/handlers/basic/stringTemplate/4.kt | 4005031161 |
/*
* Copyright 2010-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/LICENSE.txt file.
*/
package org.jetbrains.kotlin
import org.gradle.api.tasks.JavaExec
import org.gradle.api.tasks.TaskAction
import org.gradle.api.tasks.options.Option
import org.gradle.api.tasks.Input
import org.jetbrains.kotlin.benchmark.LogLevel
import org.jetbrains.kotlin.benchmark.Logger
import org.jetbrains.report.json.*
import java.io.ByteArrayOutputStream
import java.io.File
data class ExecParameters(val warmupCount: Int, val repeatCount: Int,
val filterArgs: List<String>, val filterRegexArgs: List<String>,
val verbose: Boolean, val outputFileName: String?)
open class RunJvmTask: JavaExec() {
@Input
@Option(option = "filter", description = "Benchmarks to run (comma-separated)")
var filter: String = ""
@Input
@Option(option = "filterRegex", description = "Benchmarks to run, described by regular expressions (comma-separated)")
var filterRegex: String = ""
@Input
@Option(option = "verbose", description = "Verbose mode of running benchmarks")
var verbose: Boolean = false
@Input
var warmupCount: Int = 0
@Input
var repeatCount: Int = 0
@Input
var repeatingType = BenchmarkRepeatingType.INTERNAL
@Input
var outputFileName: String? = null
private var predefinedArgs: List<String> = emptyList()
private fun executeTask(execParameters: ExecParameters): String {
// Firstly clean arguments.
setArgs(emptyList())
args(predefinedArgs)
args(execParameters.filterArgs)
args(execParameters.filterRegexArgs)
args("-w", execParameters.warmupCount)
args("-r", execParameters.repeatCount)
if (execParameters.verbose) {
args("-v")
}
execParameters.outputFileName?.let { args("-o", outputFileName) }
standardOutput = ByteArrayOutputStream()
super.exec()
return standardOutput.toString()
}
private fun getBenchmarksList(filterArgs: List<String>, filterRegexArgs: List<String>): List<String> {
// Firstly clean arguments.
setArgs(emptyList())
args("list")
standardOutput = ByteArrayOutputStream()
super.exec()
val benchmarks = standardOutput.toString().lines()
val regexes = filterRegexArgs.map { it.toRegex() }
return if (filterArgs.isNotEmpty() || regexes.isNotEmpty()) {
benchmarks.filter { benchmark -> benchmark in filterArgs || regexes.any { it.matches(benchmark) } }
} else benchmarks.filter { !it.isEmpty() }
}
private fun execSeparateBenchmarkRepeatedly(benchmark: String): List<String> {
// Logging with application should be done only in case it controls running benchmarks itself.
// Although it's a responsibility of gradle task.
val logger = if (verbose) Logger(LogLevel.DEBUG) else Logger()
logger.log("Warm up iterations for benchmark $benchmark\n")
for (i in 0.until(warmupCount)) {
executeTask(ExecParameters(0, 1, listOf("-f", benchmark),
emptyList(), false, null))
}
val result = mutableListOf<String>()
logger.log("Running benchmark $benchmark ")
for (i in 0.until(repeatCount)) {
logger.log(".", usePrefix = false)
val benchmarkReport = JsonTreeParser.parse(
executeTask(ExecParameters(0, 1, listOf("-f", benchmark),
emptyList(), false, null)
).removePrefix("[").removeSuffix("]")
).jsonObject
val modifiedBenchmarkReport = JsonObject(HashMap(benchmarkReport.content).apply {
put("repeat", JsonLiteral(i))
put("warmup", JsonLiteral(warmupCount))
})
result.add(modifiedBenchmarkReport.toString())
}
logger.log("\n", usePrefix = false)
return result
}
private fun execBenchmarksRepeatedly(filterArgs: List<String>, filterRegexArgs: List<String>) {
val benchmarksToRun = getBenchmarksList(filterArgs, filterRegexArgs)
val results = benchmarksToRun.flatMap { benchmark ->
execSeparateBenchmarkRepeatedly(benchmark)
}
File(outputFileName).printWriter().use { out ->
out.println("[${results.joinToString(",")}]")
}
}
@TaskAction
override fun exec() {
assert(outputFileName != null) { "Output file name should be always set" }
predefinedArgs = args ?: emptyList()
val filterArgs = filter.splitCommaSeparatedOption("-f")
val filterRegexArgs = filterRegex.splitCommaSeparatedOption("-fr")
when (repeatingType) {
BenchmarkRepeatingType.INTERNAL -> executeTask(
ExecParameters(warmupCount, repeatCount, filterArgs, filterRegexArgs, verbose, outputFileName)
)
BenchmarkRepeatingType.EXTERNAL -> execBenchmarksRepeatedly(filterArgs, filterRegexArgs)
}
}
} | build-tools/src/main/kotlin/org/jetbrains/kotlin/RunJvmTask.kt | 3692812170 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder
import com.intellij.psi.PsiElement
import com.intellij.util.ArrayUtil
import org.jetbrains.kotlin.cfg.containingDeclarationForPseudocode
import org.jetbrains.kotlin.descriptors.ClassDescriptorWithResolutionScopes
import org.jetbrains.kotlin.descriptors.DescriptorVisibility
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.core.KotlinNameSuggester
import org.jetbrains.kotlin.idea.quickfix.createFromUsage.createClass.ClassInfo
import org.jetbrains.kotlin.idea.util.application.withPsiAttachment
import org.jetbrains.kotlin.idea.util.getResolutionScope
import org.jetbrains.kotlin.idea.util.getResolvableApproximations
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.parents
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils
import org.jetbrains.kotlin.resolve.scopes.LexicalScope
import org.jetbrains.kotlin.types.error.ErrorUtils
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.Variance
import org.jetbrains.kotlin.types.typeUtil.makeNotNullable
import org.jetbrains.kotlin.utils.KotlinExceptionWithAttachments
import java.util.*
/**
* Represents a concrete type or a set of types yet to be inferred from an expression.
*/
abstract class TypeInfo(val variance: Variance) {
object Empty : TypeInfo(Variance.INVARIANT) {
override fun getPossibleTypes(builder: CallableBuilder): List<KotlinType> = Collections.emptyList()
}
class ByExpression(val expression: KtExpression, variance: Variance) : TypeInfo(variance) {
override fun getPossibleNamesFromExpression(bindingContext: BindingContext): Array<String> {
return KotlinNameSuggester.suggestNamesByExpressionOnly(expression, bindingContext, { true }).toTypedArray()
}
override fun getPossibleTypes(builder: CallableBuilder): List<KotlinType> = expression.guessTypes(
context = builder.currentFileContext,
module = builder.currentFileModule,
pseudocode = try {
builder.pseudocode
} catch (stackException: EmptyStackException) {
val originalElement = builder.config.originalElement
val containingDeclarationForPseudocode = originalElement.containingDeclarationForPseudocode
// copy-pasted from org.jetbrains.kotlin.cfg.pseudocode.PseudocodeUtilsKt.getContainingPseudocode
val enclosingPseudocodeDeclaration = (containingDeclarationForPseudocode as? KtFunctionLiteral)?.let { functionLiteral ->
functionLiteral.parents.firstOrNull { it is KtDeclaration && it !is KtFunctionLiteral } as? KtDeclaration
} ?: containingDeclarationForPseudocode
throw KotlinExceptionWithAttachments(stackException.message, stackException)
.withPsiAttachment("original_expression.txt", originalElement)
.withPsiAttachment("containing_declaration.txt", containingDeclarationForPseudocode)
.withPsiAttachment("enclosing_declaration.txt", enclosingPseudocodeDeclaration)
}
).flatMap { it.getPossibleSupertypes(variance, builder) }
}
class ByTypeReference(val typeReference: KtTypeReference, variance: Variance) : TypeInfo(variance) {
override fun getPossibleTypes(builder: CallableBuilder): List<KotlinType> =
builder.currentFileContext[BindingContext.TYPE, typeReference].getPossibleSupertypes(variance, builder)
}
class ByType(val theType: KotlinType, variance: Variance) : TypeInfo(variance) {
override fun getPossibleTypes(builder: CallableBuilder): List<KotlinType> =
theType.getPossibleSupertypes(variance, builder)
}
class ByReceiverType(variance: Variance) : TypeInfo(variance) {
override fun getPossibleTypes(builder: CallableBuilder): List<KotlinType> =
(builder.placement as CallablePlacement.WithReceiver).receiverTypeCandidate.theType.getPossibleSupertypes(variance, builder)
}
class ByExplicitCandidateTypes(val types: List<KotlinType>) : TypeInfo(Variance.INVARIANT) {
override fun getPossibleTypes(builder: CallableBuilder) = types
}
abstract class DelegatingTypeInfo(val delegate: TypeInfo) : TypeInfo(delegate.variance) {
override val substitutionsAllowed: Boolean = delegate.substitutionsAllowed
override fun getPossibleNamesFromExpression(bindingContext: BindingContext) =
delegate.getPossibleNamesFromExpression(bindingContext)
override fun getPossibleTypes(builder: CallableBuilder): List<KotlinType> = delegate.getPossibleTypes(builder)
}
class NoSubstitutions(delegate: TypeInfo) : DelegatingTypeInfo(delegate) {
override val substitutionsAllowed: Boolean = false
}
class StaticContextRequired(delegate: TypeInfo) : DelegatingTypeInfo(delegate) {
override val staticContextRequired: Boolean = true
}
class OfThis(delegate: TypeInfo) : DelegatingTypeInfo(delegate)
val isOfThis: Boolean
get() = when (this) {
is OfThis -> true
is DelegatingTypeInfo -> delegate.isOfThis
else -> false
}
open val substitutionsAllowed: Boolean = true
open val staticContextRequired: Boolean = false
open fun getPossibleNamesFromExpression(bindingContext: BindingContext): Array<String> = ArrayUtil.EMPTY_STRING_ARRAY
abstract fun getPossibleTypes(builder: CallableBuilder): List<KotlinType>
private fun getScopeForTypeApproximation(config: CallableBuilderConfiguration, placement: CallablePlacement?): LexicalScope? {
if (placement == null) return config.originalElement.getResolutionScope()
val containingElement = when (placement) {
is CallablePlacement.NoReceiver -> {
placement.containingElement
}
is CallablePlacement.WithReceiver -> {
val receiverClassDescriptor =
placement.receiverTypeCandidate.theType.constructor.declarationDescriptor
val classDeclaration = receiverClassDescriptor?.let { DescriptorToSourceUtils.getSourceFromDescriptor(it) }
if (!config.isExtension && classDeclaration != null) classDeclaration else config.currentFile
}
}
return when (containingElement) {
is KtClassOrObject -> (containingElement.resolveToDescriptorIfAny() as? ClassDescriptorWithResolutionScopes)?.scopeForMemberDeclarationResolution
is KtBlockExpression -> (containingElement.statements.firstOrNull() ?: containingElement).getResolutionScope()
is KtElement -> containingElement.containingKtFile.getResolutionScope()
else -> null
}
}
protected fun KotlinType?.getPossibleSupertypes(variance: Variance, callableBuilder: CallableBuilder): List<KotlinType> {
if (this == null || ErrorUtils.containsErrorType(this)) {
return Collections.singletonList(callableBuilder.currentFileModule.builtIns.anyType)
}
val scope = getScopeForTypeApproximation(callableBuilder.config, callableBuilder.placement)
val approximations = getResolvableApproximations(scope, checkTypeParameters = false, allowIntersections = true)
return when (variance) {
Variance.IN_VARIANCE -> approximations.toList()
else -> listOf(approximations.firstOrNull() ?: this)
}
}
}
fun TypeInfo(expressionOfType: KtExpression, variance: Variance): TypeInfo = TypeInfo.ByExpression(expressionOfType, variance)
fun TypeInfo(typeReference: KtTypeReference, variance: Variance): TypeInfo = TypeInfo.ByTypeReference(typeReference, variance)
fun TypeInfo(theType: KotlinType, variance: Variance): TypeInfo = TypeInfo.ByType(theType, variance)
fun TypeInfo.noSubstitutions(): TypeInfo = (this as? TypeInfo.NoSubstitutions) ?: TypeInfo.NoSubstitutions(this)
fun TypeInfo.forceNotNull(): TypeInfo {
class ForcedNotNull(delegate: TypeInfo) : TypeInfo.DelegatingTypeInfo(delegate) {
override fun getPossibleTypes(builder: CallableBuilder): List<KotlinType> =
super.getPossibleTypes(builder).map { it.makeNotNullable() }
}
return (this as? ForcedNotNull) ?: ForcedNotNull(this)
}
fun TypeInfo.ofThis() = TypeInfo.OfThis(this)
/**
* Encapsulates information about a function parameter that is going to be created.
*/
class ParameterInfo(
val typeInfo: TypeInfo,
val nameSuggestions: List<String>
) {
constructor(typeInfo: TypeInfo, preferredName: String? = null) : this(typeInfo, listOfNotNull(preferredName))
}
enum class CallableKind {
FUNCTION,
CLASS_WITH_PRIMARY_CONSTRUCTOR,
CONSTRUCTOR,
PROPERTY
}
abstract class CallableInfo(
val name: String,
val receiverTypeInfo: TypeInfo,
val returnTypeInfo: TypeInfo,
val possibleContainers: List<KtElement>,
val typeParameterInfos: List<TypeInfo>,
val isForCompanion: Boolean = false,
val modifierList: KtModifierList? = null
) {
abstract val kind: CallableKind
abstract val parameterInfos: List<ParameterInfo>
val isAbstract get() = modifierList?.hasModifier(KtTokens.ABSTRACT_KEYWORD) == true
abstract fun copy(
receiverTypeInfo: TypeInfo = this.receiverTypeInfo,
possibleContainers: List<KtElement> = this.possibleContainers,
modifierList: KtModifierList? = this.modifierList
): CallableInfo
}
class FunctionInfo(
name: String,
receiverTypeInfo: TypeInfo,
returnTypeInfo: TypeInfo,
possibleContainers: List<KtElement> = Collections.emptyList(),
override val parameterInfos: List<ParameterInfo> = Collections.emptyList(),
typeParameterInfos: List<TypeInfo> = Collections.emptyList(),
isForCompanion: Boolean = false,
modifierList: KtModifierList? = null,
val preferEmptyBody: Boolean = false
) : CallableInfo(name, receiverTypeInfo, returnTypeInfo, possibleContainers, typeParameterInfos, isForCompanion, modifierList) {
override val kind: CallableKind get() = CallableKind.FUNCTION
override fun copy(
receiverTypeInfo: TypeInfo,
possibleContainers: List<KtElement>,
modifierList: KtModifierList?
) = FunctionInfo(
name,
receiverTypeInfo,
returnTypeInfo,
possibleContainers,
parameterInfos,
typeParameterInfos,
isForCompanion,
modifierList
)
}
class ClassWithPrimaryConstructorInfo(
val classInfo: ClassInfo,
expectedTypeInfo: TypeInfo,
modifierList: KtModifierList? = null,
val primaryConstructorVisibility: DescriptorVisibility? = null
) : CallableInfo(
classInfo.name,
TypeInfo.Empty,
expectedTypeInfo.forceNotNull(),
Collections.emptyList(),
classInfo.typeArguments,
false,
modifierList = modifierList
) {
override val kind: CallableKind get() = CallableKind.CLASS_WITH_PRIMARY_CONSTRUCTOR
override val parameterInfos: List<ParameterInfo> get() = classInfo.parameterInfos
override fun copy(
receiverTypeInfo: TypeInfo,
possibleContainers: List<KtElement>,
modifierList: KtModifierList?
) = throw UnsupportedOperationException()
}
class ConstructorInfo(
override val parameterInfos: List<ParameterInfo>,
val targetClass: PsiElement,
val isPrimary: Boolean = false,
modifierList: KtModifierList? = null,
val withBody: Boolean = false
) : CallableInfo("", TypeInfo.Empty, TypeInfo.Empty, Collections.emptyList(), Collections.emptyList(), false, modifierList = modifierList) {
override val kind: CallableKind get() = CallableKind.CONSTRUCTOR
override fun copy(
receiverTypeInfo: TypeInfo,
possibleContainers: List<KtElement>,
modifierList: KtModifierList?
) = throw UnsupportedOperationException()
}
class PropertyInfo(
name: String,
receiverTypeInfo: TypeInfo,
returnTypeInfo: TypeInfo,
val writable: Boolean,
possibleContainers: List<KtElement> = Collections.emptyList(),
typeParameterInfos: List<TypeInfo> = Collections.emptyList(),
val isLateinitPreferred: Boolean = false,
val isConst: Boolean = false,
isForCompanion: Boolean = false,
val annotations: List<KtAnnotationEntry> = emptyList(),
modifierList: KtModifierList? = null,
val initializer: KtExpression? = null
) : CallableInfo(name, receiverTypeInfo, returnTypeInfo, possibleContainers, typeParameterInfos, isForCompanion, modifierList) {
override val kind: CallableKind get() = CallableKind.PROPERTY
override val parameterInfos: List<ParameterInfo> get() = Collections.emptyList()
override fun copy(
receiverTypeInfo: TypeInfo,
possibleContainers: List<KtElement>,
modifierList: KtModifierList?
) = copyProperty(receiverTypeInfo, possibleContainers, modifierList)
fun copyProperty(
receiverTypeInfo: TypeInfo = this.receiverTypeInfo,
possibleContainers: List<KtElement> = this.possibleContainers,
modifierList: KtModifierList? = this.modifierList,
isLateinitPreferred: Boolean = this.isLateinitPreferred
) = PropertyInfo(
name,
receiverTypeInfo,
returnTypeInfo,
writable,
possibleContainers,
typeParameterInfos,
isConst,
isLateinitPreferred,
isForCompanion,
annotations,
modifierList,
initializer
)
}
| plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/callableBuilder/CallableInfo.kt | 826305859 |
package streams.sequence.map
fun main(args: Array<String>) {
//Breakpoint!
intArrayOf(1, 2, 3).asSequence().withIndex().forEach {}
} | plugins/kotlin/jvm-debugger/test/testData/sequence/streams/sequence/map/WithIndex.kt | 3629370960 |
/*
* Copyright (c) 2022, Nordic Semiconductor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package no.nordicsemi.android.dfu.storage
import android.app.DownloadManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.Uri
import android.os.Build
import android.os.Environment
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class ExternalFileDataSource @Inject internal constructor(
@ApplicationContext
private val context: Context,
private val parser: FileNameParser
) {
private val _fileResource = MutableStateFlow<FileResource?>(null)
val fileResource = _fileResource.asStateFlow()
private val downloadManger = context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
private var downloadID: Long? = null
private val onDownloadCompleteReceiver: BroadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent) {
val id: Long = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1)
if (downloadID == id) {
_fileResource.value = downloadManger.getUriForDownloadedFile(id)?.let {
FileDownloaded(it)
} ?: FileError
}
}
}
init {
context.registerReceiver(
onDownloadCompleteReceiver,
IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)
)
}
fun download(url: String) {
if (isRunning()) {
return
}
_fileResource.value = LoadingFile
val request: DownloadManager.Request = DownloadManager.Request(Uri.parse(url))
request.setTitle(parser.parseName(url))
request.setDescription(context.getString(R.string.storage_notification_description))
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
@Suppress("DEPRECATION")
request.allowScanningByMediaScanner()
}
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE)
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, parser.parseName(url))
downloadID = downloadManger.enqueue(request)
}
private fun isRunning(): Boolean {
return fileResource.value is LoadingFile
}
}
| lib_storage/src/main/java/no/nordicsemi/android/dfu/storage/ExternalFileDataSource.kt | 2635001223 |
// 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.codeInsight.intention.impl.preview
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.codeInsight.intention.impl.preview.IntentionPreviewComponent.Companion.LOADING_PREVIEW
import com.intellij.codeInsight.intention.impl.preview.IntentionPreviewComponent.Companion.NO_PREVIEW
import com.intellij.codeInsight.intention.preview.IntentionPreviewInfo
import com.intellij.codeInsight.intention.preview.IntentionPreviewInfo.Html
import com.intellij.openapi.actionSystem.IdeActions
import com.intellij.openapi.actionSystem.ShortcutSet
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.application.ReadAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.EditorFactory
import com.intellij.openapi.editor.ex.EditorEx
import com.intellij.openapi.editor.ex.SoftWrapChangeListener
import com.intellij.openapi.editor.impl.EditorImpl
import com.intellij.openapi.keymap.KeymapUtil
import com.intellij.openapi.progress.EmptyProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.popup.JBPopup
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.openapi.util.NlsSafe
import com.intellij.psi.PsiFile
import com.intellij.ui.ScreenUtil
import com.intellij.ui.popup.PopupPositionManager.Position.LEFT
import com.intellij.ui.popup.PopupPositionManager.Position.RIGHT
import com.intellij.ui.popup.PopupPositionManager.PositionAdjuster
import com.intellij.ui.popup.PopupUpdateProcessor
import com.intellij.util.concurrency.AppExecutorUtil
import com.intellij.util.ui.UIUtil
import org.jetbrains.annotations.TestOnly
import java.awt.Dimension
import java.awt.event.ComponentAdapter
import java.awt.event.ComponentEvent
import javax.swing.JWindow
import kotlin.math.max
import kotlin.math.min
class IntentionPreviewPopupUpdateProcessor(private val project: Project,
private val originalFile: PsiFile,
private val originalEditor: Editor) : PopupUpdateProcessor(project) {
private var index: Int = LOADING_PREVIEW
private var show = false
private var originalPopup : JBPopup? = null
private val editorsToRelease = mutableListOf<EditorEx>()
private lateinit var popup: JBPopup
private lateinit var component: IntentionPreviewComponent
private var justActivated: Boolean = false
private val popupWindow: JWindow?
get() = UIUtil.getParentOfType(JWindow::class.java, popup.content)
override fun updatePopup(intentionAction: Any?) {
if (!show) return
if (!::popup.isInitialized || popup.isDisposed) {
val origPopup = originalPopup
if (origPopup == null || origPopup.isDisposed) return
component = IntentionPreviewComponent(origPopup)
component.multiPanel.select(LOADING_PREVIEW, true)
popup = JBPopupFactory.getInstance().createComponentPopupBuilder(component, null)
.setCancelCallback { cancel() }
.setCancelKeyEnabled(false)
.setShowBorder(false)
.addUserData(IntentionPreviewPopupKey())
.createPopup()
component.addComponentListener(object : ComponentAdapter() {
override fun componentResized(e: ComponentEvent?) {
var size = popup.size
val key = component.multiPanel.key
if (key != NO_PREVIEW) {
size = Dimension(size.width.coerceAtLeast(MIN_WIDTH), size.height)
}
popup.content.preferredSize = size
adjustPosition(originalPopup)
popup.size = size
}
})
adjustPosition(originalPopup)
}
val value = component.multiPanel.getValue(index, false)
if (value != null) {
select(index)
return
}
val action = intentionAction as IntentionAction
component.startLoading()
ReadAction.nonBlocking(
IntentionPreviewComputable(project, action, originalFile, originalEditor))
.expireWith(popup)
.coalesceBy(this)
.finishOnUiThread(ModalityState.defaultModalityState()) { renderPreview(it)}
.submit(AppExecutorUtil.getAppExecutorService())
}
private fun adjustPosition(originalPopup: JBPopup?) {
if (originalPopup != null && originalPopup.content.isShowing) {
PositionAdjuster(originalPopup.content).adjust(popup, RIGHT, LEFT)
}
}
private fun renderPreview(result: IntentionPreviewInfo) {
when (result) {
is IntentionPreviewDiffResult -> {
val editors = IntentionPreviewModel.createEditors(project, result)
if (editors.isEmpty()) {
selectNoPreview()
return
}
editorsToRelease.addAll(editors)
select(index, editors)
}
is Html -> {
select(index, html = result)
}
else -> {
selectNoPreview()
}
}
}
private fun selectNoPreview() {
if (justActivated) {
select(NO_PREVIEW)
}
else {
popupWindow?.isVisible = false
}
}
fun setup(popup: JBPopup, parentIndex: Int) {
index = parentIndex
originalPopup = popup
}
fun isShown() = show && popupWindow?.isVisible != false
fun hide() {
if (::popup.isInitialized && !popup.isDisposed) {
popup.cancel()
}
}
fun show() {
show = true
}
private fun cancel(): Boolean {
editorsToRelease.forEach { editor -> EditorFactory.getInstance().releaseEditor(editor) }
editorsToRelease.clear()
component.removeAll()
show = false
return true
}
private fun select(index: Int, editors: List<EditorEx> = emptyList(), @NlsSafe html: Html? = null) {
justActivated = false
popupWindow?.isVisible = true
component.stopLoading()
component.editors = editors
component.html = html
component.multiPanel.select(index, true)
val size = component.preferredSize
val location = popup.locationOnScreen
val screen = ScreenUtil.getScreenRectangle(location)
if (screen != null) {
var delta = screen.width + screen.x - location.x
val content = originalPopup?.content
val origLocation = if (content?.isShowing == true) content.locationOnScreen else null
// On the left side of the original popup: avoid overlap
if (origLocation != null && location.x < origLocation.x) {
delta = delta.coerceAtMost(origLocation.x - screen.x - PositionAdjuster.DEFAULT_GAP)
}
size.width = size.width.coerceAtMost(delta)
}
component.editors.forEach {
it.softWrapModel.addSoftWrapChangeListener(object : SoftWrapChangeListener {
override fun recalculationEnds() {
val height = (it as EditorImpl).offsetToXY(it.document.textLength).y + it.lineHeight + 6
it.component.preferredSize = Dimension(it.component.preferredSize.width, min(height, MAX_HEIGHT))
it.component.parent.invalidate()
popup.pack(true, true)
}
override fun softWrapsChanged() {}
})
it.component.preferredSize = Dimension(max(size.width, MIN_WIDTH), min(it.component.preferredSize.height, MAX_HEIGHT))
}
popup.pack(true, true)
}
/**
* Call when process is just activated via hotkey
*/
fun activate() {
justActivated = true
}
companion object {
internal const val MAX_HEIGHT = 300
internal const val MIN_WIDTH = 300
fun getShortcutText(): String = KeymapUtil.getPreferredShortcutText(getShortcutSet().shortcuts)
fun getShortcutSet(): ShortcutSet = KeymapUtil.getActiveKeymapShortcuts(IdeActions.ACTION_QUICK_JAVADOC)
@TestOnly
@JvmStatic
fun getPreviewText(project: Project,
action: IntentionAction,
originalFile: PsiFile,
originalEditor: Editor): String? {
return (getPreviewInfo(project, action, originalFile, originalEditor) as? IntentionPreviewDiffResult)?.psiFile?.text
}
/**
* Returns content of preview:
* if it's diff then new content is returned
* if it's HTML then text representation is returned
*/
@TestOnly
@JvmStatic
fun getPreviewContent(project: Project,
action: IntentionAction,
originalFile: PsiFile,
originalEditor: Editor): String {
return when(val info = getPreviewInfo(project, action, originalFile, originalEditor)) {
is IntentionPreviewDiffResult -> info.psiFile.text
is Html -> info.content().toString()
else -> ""
}
}
@TestOnly
@JvmStatic
fun getPreviewInfo(project: Project,
action: IntentionAction,
originalFile: PsiFile,
originalEditor: Editor): IntentionPreviewInfo =
ProgressManager.getInstance().runProcess<IntentionPreviewInfo>(
{ IntentionPreviewComputable(project, action, originalFile, originalEditor).generatePreview() },
EmptyProgressIndicator()) ?: IntentionPreviewInfo.EMPTY
}
internal class IntentionPreviewPopupKey
} | platform/lang-impl/src/com/intellij/codeInsight/intention/impl/preview/IntentionPreviewPopupUpdateProcessor.kt | 2691596283 |
// 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.codeMetaInfo
import com.intellij.util.containers.Stack
import org.jetbrains.kotlin.idea.codeMetaInfo.models.CodeMetaInfo
import java.io.File
object CodeMetaInfoRenderer {
fun renderTagsToText(codeMetaInfos: List<CodeMetaInfo>, originalText: String): StringBuilder {
return StringBuilder().apply {
renderTagsToText(this, codeMetaInfos, originalText)
}
}
fun renderTagsToText(builder: StringBuilder, codeMetaInfos: List<CodeMetaInfo>, originalText: String) {
if (codeMetaInfos.isEmpty()) {
builder.append(originalText)
return
}
val sortedMetaInfos = getSortedCodeMetaInfos(codeMetaInfos).groupBy { it.start }
val opened = Stack<CodeMetaInfo>()
for ((i, c) in originalText.withIndex()) {
processMetaInfosStartedAtOffset(i, sortedMetaInfos, opened, builder)
builder.append(c)
}
val lastSymbolIsNewLine = builder.last() == '\n'
if (lastSymbolIsNewLine) {
builder.deleteCharAt(builder.length - 1)
}
processMetaInfosStartedAtOffset(originalText.length, sortedMetaInfos, opened, builder)
if (lastSymbolIsNewLine) {
builder.appendLine()
}
}
private fun processMetaInfosStartedAtOffset(
offset: Int,
sortedMetaInfos: Map<Int, List<CodeMetaInfo>>,
opened: Stack<CodeMetaInfo>,
builder: StringBuilder
) {
checkOpenedAndCloseStringIfNeeded(opened, offset, builder)
val matchedCodeMetaInfos = sortedMetaInfos[offset] ?: emptyList()
if (matchedCodeMetaInfos.isNotEmpty()) {
openStartTag(builder)
val iterator = matchedCodeMetaInfos.listIterator()
var current: CodeMetaInfo? = iterator.next()
while (current != null) {
val next: CodeMetaInfo? = if (iterator.hasNext()) iterator.next() else null
opened.push(current)
builder.append(current.asString())
when {
next == null ->
closeStartTag(builder)
next.end == current.end ->
builder.append(", ")
else ->
closeStartAndOpenNewTag(builder)
}
current = next
}
}
// Here we need to handle meta infos which has start == end and close them immediately
checkOpenedAndCloseStringIfNeeded(opened, offset, builder)
}
private val metaInfoComparator = (compareBy<CodeMetaInfo> { it.start } then compareByDescending { it.end }) then compareBy { it.tag }
private fun getSortedCodeMetaInfos(metaInfos: Collection<CodeMetaInfo>): List<CodeMetaInfo> {
return metaInfos.sortedWith(metaInfoComparator)
}
private fun closeString(result: StringBuilder) = result.append("<!>")
private fun openStartTag(result: StringBuilder) = result.append("<!")
private fun closeStartTag(result: StringBuilder) = result.append("!>")
private fun closeStartAndOpenNewTag(result: StringBuilder) = result.append("!><!")
private fun checkOpenedAndCloseStringIfNeeded(opened: Stack<CodeMetaInfo>, end: Int, result: StringBuilder) {
var prev: CodeMetaInfo? = null
while (!opened.isEmpty() && end == opened.peek().end) {
if (prev == null || prev.start != opened.peek().start)
closeString(result)
prev = opened.pop()
}
}
}
fun clearFileFromDiagnosticMarkup(file: File) {
val text = file.readText()
val cleanText = clearTextFromDiagnosticMarkup(text)
file.writeText(cleanText)
}
fun clearTextFromDiagnosticMarkup(text: String): String = text.replace(CodeMetaInfoParser.openingOrClosingRegex, "") | plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/codeMetaInfo/CodeMetaInfoRenderer.kt | 2013764658 |
internal class C {
private var s: String? = ""
fun foo() {
s = null
}
} | plugins/kotlin/j2k/old/tests/testData/fileOrElement/nullability/FieldAssignedWithNull.kt | 1781794746 |
open class Base internal constructor(x: Int) {
var x = 42
init {
this.x = x
}
}
internal class Derived(b: Base) : Base(b.x)
| plugins/kotlin/j2k/old/tests/testData/fileOrElement/detectProperties/DifferentFieldNameAndSuperClass.kt | 1571855656 |
// 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.configuration
import com.intellij.openapi.module.Module
import com.intellij.openapi.util.Key
import org.jetbrains.kotlin.idea.KotlinVersionVerbose
import org.jetbrains.kotlin.idea.compiler.configuration.KotlinJpsPluginSettings
import org.jetbrains.kotlin.psi.UserDataProperty
var Module.externalCompilerVersion: String? by UserDataProperty(Key.create("EXTERNAL_COMPILER_VERSION"))
fun Module.findExternalKotlinCompilerVersion(): KotlinVersionVerbose? {
val externalCompilerVersion = (if (getBuildSystemType() == BuildSystemType.JPS) {
KotlinJpsPluginSettings.getInstance(project).settings.version
} else {
this.externalCompilerVersion
}) ?: return null
return KotlinVersionVerbose.parse(externalCompilerVersion)
}
| plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/configuration/moduleUtils.kt | 3430403835 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.