repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
didi/DoraemonKit | Android/dokit/src/main/java/com/didichuxing/doraemonkit/kit/core/DoKitKeyEvent.kt | 1 | 351 | package com.didichuxing.doraemonkit.kit.core
/**
* ================================================
* 作 者:jint(金台)
* 版 本:1.0
* 创建日期:2021/8/25-18:47
* 描 述:
* 修订历史:
* ================================================
*/
data class DoKitKeyEvent(
val action: Int,
val keyCode: Int
)
| apache-2.0 | 3d0e8573acd71516714765bcfaebc801 | 19.333333 | 51 | 0.390164 | 3.674699 | false | false | false | false |
d3xter/bo-android | app/src/main/java/org/blitzortung/android/location/provider/ManualLocationProvider.kt | 1 | 2091 | package org.blitzortung.android.location.provider
import android.content.SharedPreferences
import android.location.Location
import android.util.Log
import org.blitzortung.android.app.Main
import org.blitzortung.android.app.view.PreferenceKey
import org.blitzortung.android.app.view.getAndConvert
import org.blitzortung.android.location.LocationHandler
class ManualLocationProvider(locationUpdate: (Location?) -> Unit, private val sharedPreferences: SharedPreferences) : LocationProvider(locationUpdate), SharedPreferences.OnSharedPreferenceChangeListener {
override val isEnabled: Boolean = true
override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) {
onSharedPreferenceChanged(sharedPreferences, PreferenceKey.fromString(key))
}
private fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: PreferenceKey) {
val doubleConverter = fun (x: String): Double? {
try {
return x.toDouble()
} catch (e: NumberFormatException) {
Log.e(Main.LOG_TAG, "bad longitude/latitude number format '$x'")
}
return null
}
when(key) {
PreferenceKey.LOCATION_LONGITUDE, PreferenceKey.LOCATION_LATITUDE -> {
val location = Location("")
location.longitude = sharedPreferences.getAndConvert(PreferenceKey.LOCATION_LONGITUDE, "11.0", doubleConverter) ?: 11.0
location.latitude = sharedPreferences.getAndConvert(PreferenceKey.LOCATION_LATITUDE, "49.0", doubleConverter) ?: 49.0
sendLocationUpdate(location)
}
}
}
override val type = LocationHandler.MANUAL_PROVIDER
override fun start() {
super.start()
sharedPreferences.registerOnSharedPreferenceChangeListener(this)
onSharedPreferenceChanged(sharedPreferences, PreferenceKey.LOCATION_LONGITUDE)
}
override fun shutdown() {
sharedPreferences.unregisterOnSharedPreferenceChangeListener(this)
super.shutdown()
}
} | apache-2.0 | 205ceadca101534309551d73f82809e3 | 36.357143 | 204 | 0.710665 | 5.488189 | false | false | false | false |
nextcloud/android | app/src/main/java/com/nextcloud/client/etm/pages/EtmAccountsFragment.kt | 1 | 2985 | /*
* Nextcloud Android client application
*
* @author Chris Narkiewicz
* Copyright (C) 2019 Chris Narkiewicz <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.nextcloud.client.etm.pages
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import com.nextcloud.client.etm.EtmBaseFragment
import com.owncloud.android.R
import com.owncloud.android.databinding.FragmentEtmAccountsBinding
class EtmAccountsFragment : EtmBaseFragment() {
private var _binding: FragmentEtmAccountsBinding? = null
private val binding get() = _binding!!
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
_binding = FragmentEtmAccountsBinding.inflate(inflater, container, false)
return binding.root
}
override fun onResume() {
super.onResume()
val builder = StringBuilder()
vm.accounts.forEach {
builder.append("Account: ${it.account.name}\n")
it.userData.forEach {
builder.append("\t${it.key}: ${it.value}\n")
}
}
binding.etmAccountsText.text = builder.toString()
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
inflater.inflate(R.menu.fragment_etm_accounts, menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.etm_accounts_share -> {
onClickedShare(); true
}
else -> super.onOptionsItemSelected(item)
}
}
private fun onClickedShare() {
val intent = Intent(Intent.ACTION_SEND)
intent.putExtra(Intent.EXTRA_SUBJECT, "Nextcloud accounts information")
intent.putExtra(Intent.EXTRA_TEXT, binding.etmAccountsText.text)
intent.type = "text/plain"
startActivity(intent)
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
| gpl-2.0 | be04a198b878736105f8cabc6def5039 | 32.920455 | 116 | 0.694807 | 4.522727 | false | false | false | false |
synyx/calenope | modules/core.google.standalone/src/main/kotlin/de/synyx/calenope/core/google/standalone/internal/spi/GoogleStandaloneBoardProvider.kt | 1 | 2093 | package de.synyx.calenope.core.google.standalone.internal.spi
import com.google.api.client.auth.oauth2.Credential
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport
import com.google.api.client.util.store.FileDataStoreFactory
import com.google.api.services.admin.directory.DirectoryScopes.ADMIN_DIRECTORY_RESOURCE_CALENDAR_READONLY
import com.google.api.services.calendar.CalendarScopes.CALENDAR_READONLY
import de.synyx.calenope.core.api.service.Board
import de.synyx.calenope.core.google.GoogleApi
import de.synyx.calenope.core.google.service.GoogleBoard
import de.synyx.calenope.core.spi.BoardProvider
import java.io.File
import java.io.Reader
import java.util.*
/**
* @author clausen - [email protected]
*/
class GoogleStandaloneBoardProvider : BoardProvider {
private val name = "calendar"
private val scopes = Arrays.asList (ADMIN_DIRECTORY_RESOURCE_CALENDAR_READONLY, CALENDAR_READONLY)
private val transport by lazy { GoogleNetHttpTransport.newTrustedTransport () }
override fun create (meta : Map<String, Any>) : Board? {
val value = meta["secret"]
if (value !is Reader) return null
val secret = GoogleClientSecrets.load (GoogleApi.jackson (), value)
val api = GoogleApi (name, transport, credential (secret))
return GoogleBoard (api)
}
private fun credential (secret : GoogleClientSecrets) : Credential {
val flow = GoogleAuthorizationCodeFlow.Builder(transport, GoogleApi.jackson(), secret, scopes)
.setDataStoreFactory (FileDataStoreFactory (File (".", name)))
.setAccessType ("offline")
.build ()
return AuthorizationCodeInstalledApp (flow, LocalServerReceiver ()).authorize ("user")
}
}
| apache-2.0 | 4d20254c89a2ab34c4468c1042ca4fb4 | 39.25 | 105 | 0.757764 | 4.025 | false | false | false | false |
soywiz/korge | korge/src/commonMain/kotlin/com/soywiz/korge3d/Terrain3D.kt | 1 | 6846 | package com.soywiz.korge3d
import com.soywiz.kds.iterators.fastForEachWithIndex
import com.soywiz.kmem.clamp
import com.soywiz.korag.AG
import com.soywiz.korim.bitmap.Bitmap
import com.soywiz.korma.geom.Matrix3D
import com.soywiz.korma.geom.Vector3D
interface HeightMap {
operator fun get(x: Float, z: Float): Float
}
class HeightMapConstant(val height: Float) : HeightMap {
override fun get(x: Float, z: Float): Float = height
}
class HeightMapBitmap(val bitmap:Bitmap) : HeightMap{
override fun get(x: Float, z: Float): Float {
val x1 = when {
x < 0 -> 0.0
x > bitmap.width -> bitmap.width.toDouble()
else -> x.toDouble()
}
val z1 = when {
z < 0 -> 0.0
z > bitmap.height -> bitmap.height.toDouble()
else -> z.toDouble()
}
return bitmap.getRgbaSampled(x1, z1).rgb.toFloat()
}
}
@Korge3DExperimental
fun Container3D.terrain(
centerX: Float = 0f,
centerZ: Float = 0f,
width: Float = 100.0f,
depth: Float = 100.0f,
heightMap: HeightMap = HeightMapConstant(0f),
heightScale:Float = 1f
): Terrain3D {
return Terrain3D(centerX, centerZ, width, depth, heightMap,heightScale).addTo(this)
}
@Korge3DExperimental
class Terrain3D(
val centerX: Float,
val centerZ: Float,
val width: Float,
val depth: Float,
var heightMap: HeightMap,
val heightScale:Float
) : View3D() {
var stepX = 1f
var stepZ = 1f
private val meshBuilder3D = MeshBuilder3D(AG.DrawType.TRIANGLE_STRIP)
private var mesh: Mesh3D = createMesh()
private val uniformValues = AG.UniformValues()
private val rs = AG.RenderState(depthFunc = AG.CompareMode.LESS_EQUAL)
private val tempMat1 = Matrix3D()
private val tempMat2 = Matrix3D()
private val tempMat3 = Matrix3D()
private fun getHeight(x: Float, z: Float) : Float = heightMap[x,z] * heightScale
fun calcNormal(x: Float, z: Float): Vector3D {
val hl = getHeight(x - 1, z)
val hr = getHeight(x + 1, z)
val hf = getHeight(x, z + 1)
val hb = getHeight(x, z - 1)
val v = Vector3D(hl - hr, 2f, hb - hf).normalize()
return v
}
fun createMesh(): Mesh3D {
meshBuilder3D.reset()
val vec = Vector3D()
val tex = Vector3D() //TODO:
var z = 0f
val adjX = (width / 2) + centerX
val adjZ = (depth / 2) + centerZ
// Vertices
while (z < depth) {
var x = 0f
while (x < width) {
val norm = calcNormal(x, z)
vec.setTo(x - adjX, getHeight(x, z), z - adjZ)
meshBuilder3D.addVertex(vec, norm, tex)
x += stepX
}
z += stepZ
}
//Indices
val totalX: Int = (width / stepX).toInt()
val totalZ: Int = (depth / stepZ).toInt()
for (zi in 0 until totalZ - 1) {
for (xi in 0 until totalX - 1) {
val i1 = (zi * totalX) + xi
val i2 = i1 + totalX
meshBuilder3D.addIndices(i1, i2)
}
//add degenerate to indicate end of row
val d1 = (zi * totalX) + totalX
val d2 = ((zi + 1) * totalX) + 1
meshBuilder3D.addIndices(d1, d2)
}
return meshBuilder3D.build()
}
fun AG.UniformValues.setMaterialLight(
ctx: RenderContext3D,
uniform: Shaders3D.MaterialLightUniform,
actual: Material3D.Light
) {
when (actual) {
is Material3D.LightColor -> {
this[uniform.u_color] = actual.colorVec
}
is Material3D.LightTexture -> {
actual.textureUnit.texture =
actual.bitmap?.let { ctx.rctx.agBitmapTextureManager.getTextureBase(it).base }
actual.textureUnit.linear = true
this[uniform.u_texUnit] = actual.textureUnit
}
}
}
override fun render(ctx: RenderContext3D) {
val ag = ctx.ag
val indexBuffer = ag.createIndexBuffer()
ctx.useDynamicVertexData(mesh.vertexBuffers) { vertexData ->
indexBuffer.upload(mesh.indexBuffer)
Shaders3D.apply {
val meshMaterial = mesh.material
ag.drawV2(
vertexData = vertexData,
indices = indexBuffer,
indexType = mesh.indexType,
type = mesh.drawType,
program = mesh.program ?: ctx.shaders.getProgram3D(
ctx.lights.size.clamp(0, 4),
mesh.maxWeights,
meshMaterial,
mesh.hasTexture
),
vertexCount = mesh.vertexCount,
blending = AG.Blending.NONE,
//vertexCount = 6 * 6,
uniforms = uniformValues.apply {
this[u_ProjMat] = ctx.projCameraMat
this[u_ViewMat] = transform.globalMatrix
this[u_ModMat] = modelMat
//this[u_NormMat] = tempMat3.multiply(tempMat2, localTransform.matrix).invert().transpose()
this[u_NormMat] = tempMat3.multiply(tempMat2, transform.globalMatrix)//.invert()
this[u_Shininess] = meshMaterial?.shininess ?: 0.5f
this[u_IndexOfRefraction] = meshMaterial?.indexOfRefraction ?: 1f
if (meshMaterial != null) {
setMaterialLight(ctx, ambient, meshMaterial.ambient)
setMaterialLight(ctx, diffuse, meshMaterial.diffuse)
setMaterialLight(ctx, emission, meshMaterial.emission)
setMaterialLight(ctx, specular, meshMaterial.specular)
}
this[u_AmbientColor] = ctx.ambientColor
ctx.lights.fastForEachWithIndex { index, light: Light3D ->
val lightColor = light.color
this[lights[index].u_sourcePos] = light.transform.translation
this[lights[index].u_color] =
light.colorVec.setTo(lightColor.rf, lightColor.gf, lightColor.bf, 1f)
this[lights[index].u_attenuation] = light.attenuationVec.setTo(
light.constantAttenuation,
light.linearAttenuation,
light.quadraticAttenuation
)
}
},
renderState = rs
)
}
}
}
}
| apache-2.0 | dffadc23a715d12b2180675e3ea14d6b | 35.031579 | 115 | 0.528922 | 4.166768 | false | false | false | false |
donald-w/Anki-Android | AnkiDroid/src/main/java/com/ichi2/anki/multimediacard/AudioPlayer.kt | 1 | 2409 | /*
* Copyright (c) 2013 Bibek Shrestha <[email protected]>
* Copyright (c) 2013 Zaur Molotnikov <[email protected]>
* Copyright (c) 2013 Nicolas Raoul <[email protected]>
* Copyright (c) 2013 Flavio Lerda <[email protected]>
* Copyright (c) 2021 David Allison <[email protected]>
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.ichi2.anki.multimediacard
import android.media.MediaPlayer
import timber.log.Timber
import java.io.IOException
import java.lang.Exception
import kotlin.Throws
class AudioPlayer {
private var mPlayer: MediaPlayer? = null
private var mOnStoppingListener: Runnable? = null
private var mOnStoppedListener: Runnable? = null
@Throws(IOException::class)
fun play(audioPath: String?) {
mPlayer = MediaPlayer()
mPlayer!!.setDataSource(audioPath)
mPlayer!!.setOnCompletionListener {
onStopping()
mPlayer!!.stop()
onStopped()
}
mPlayer!!.prepare()
mPlayer!!.start()
}
private fun onStopped() {
if (mOnStoppedListener == null) {
return
}
mOnStoppedListener!!.run()
}
private fun onStopping() {
if (mOnStoppingListener == null) {
return
}
mOnStoppingListener!!.run()
}
fun start() {
mPlayer!!.start()
}
fun stop() {
try {
mPlayer!!.prepare()
mPlayer!!.seekTo(0)
} catch (e: Exception) {
Timber.e(e)
}
}
fun pause() {
mPlayer!!.pause()
}
fun setOnStoppingListener(listener: Runnable?) {
mOnStoppingListener = listener
}
fun setOnStoppedListener(listener: Runnable?) {
mOnStoppedListener = listener
}
}
| gpl-3.0 | e9796a8c048238ce19f7630c31644106 | 27.678571 | 83 | 0.64093 | 4.132075 | false | false | false | false |
panpf/sketch | sketch/src/androidTest/java/com/github/panpf/sketch/test/utils/TestAnimatableDrawable3.kt | 1 | 2379 | /*
* Copyright (C) 2022 panpf <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.panpf.sketch.test.utils
import android.annotation.SuppressLint
import android.graphics.drawable.Drawable
import android.os.Handler
import android.os.Looper
import androidx.appcompat.graphics.drawable.DrawableWrapper
import androidx.vectordrawable.graphics.drawable.Animatable2Compat
import androidx.vectordrawable.graphics.drawable.Animatable2Compat.AnimationCallback
class TestAnimatableDrawable3(drawable: Drawable) : DrawableWrapper(drawable),
Animatable2Compat {
private var running = false
private var callbacks: MutableList<AnimationCallback> = mutableListOf()
private val handler by lazy { Handler(Looper.getMainLooper()) }
override fun start() {
running = true
handler.post {
for (callback in callbacks) {
callback.onAnimationStart(this)
}
}
}
override fun stop() {
running = false
handler.post {
for (callback in callbacks) {
callback.onAnimationEnd(this)
}
}
}
override fun isRunning(): Boolean {
return running
}
override fun registerAnimationCallback(callback: AnimationCallback) {
callbacks.add(callback)
}
override fun unregisterAnimationCallback(callback: AnimationCallback): Boolean {
return callbacks.remove(callback)
}
override fun clearAnimationCallbacks() {
callbacks.clear()
}
@SuppressLint("RestrictedApi")
override fun mutate(): TestAnimatableDrawable3 {
val mutateDrawable = wrappedDrawable.mutate()
return if (mutateDrawable !== wrappedDrawable) {
TestAnimatableDrawable3(drawable = mutateDrawable)
} else {
this
}
}
} | apache-2.0 | 3b2b8d930138d3bf815d433cde1bc6cf | 30.733333 | 84 | 0.693148 | 4.835366 | false | true | false | false |
GlobalTechnology/android-thekey | thekey-view-dialog-fragment/src/main/java/me/thekey/android/view/dialog/LoginDialogFragment.kt | 1 | 5013 | package me.thekey.android.view.dialog
import android.app.Dialog
import android.content.Context
import android.content.DialogInterface
import android.os.Bundle
import android.view.KeyEvent
import android.view.LayoutInflater
import android.webkit.WebView
import android.widget.FrameLayout
import androidx.annotation.UiThread
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.commit
import me.thekey.android.view.Builder
import me.thekey.android.view.LoginWebViewClient
import me.thekey.android.view.fragment.FragmentBuilder
import me.thekey.android.view.fragment.findListener
import me.thekey.android.view.util.DisplayUtil
import timber.log.Timber
private const val TAG = "LoginDialogFragment"
open class LoginDialogFragment : DialogFragment() {
companion object {
@JvmStatic
fun builder() = builder(LoginDialogFragment::class.java)
@JvmStatic
fun <T : LoginDialogFragment> builder(clazz: Class<T>): Builder<T> = FragmentBuilder(clazz)
}
interface Listener {
fun onLoginSuccess(dialog: LoginDialogFragment, guid: String)
@JvmDefault
fun onLoginCanceled(dialog: LoginDialogFragment) = Unit
@JvmDefault
fun onLoginFailure(dialog: LoginDialogFragment) = Unit
}
// region Lifecycle
override fun onAttach(context: Context) {
super.onAttach(context)
updateLoginWebViewClient()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
retainInstance = true
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
return AlertDialog.Builder(requireActivity())
.apply {
// build dialog
val frame = LayoutInflater.from(context).inflate(R.layout.thekey_login, null) as FrameLayout
setView(frame.attachLoginView(frame))
}
// handle back button presses to navigate back in the WebView if possible
// TODO: switch this to the new back listener
.setOnKeyListener { _, keyCode, event ->
if (event.action == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK && !event.isCanceled) {
return@setOnKeyListener DisplayUtil.navigateBackIfPossible(loginView)
}
false
}
.create()
}
override fun onCancel(dialog: DialogInterface) {
super.onCancel(dialog)
findListener<Listener>()?.onLoginCanceled(this)
}
override fun onDestroyView() {
// HACK: Work around bug
// http://code.google.com/p/android/issues/detail?id=17423
// https://issuetracker.google.com/issues/36929400
if (retainInstance) dialog?.setDismissMessage(null)
super.onDestroyView()
}
// endregion Lifecycle
// region Login WebView
private var currentFrame: FrameLayout? = null
private var loginView: WebView? = null
@UiThread
private fun FrameLayout.attachLoginView(frame: FrameLayout): FrameLayout {
detachLoginView()
// create the LoginWebViewClient if we don't have one yet
val webViewClient = loginWebViewClient ?: LoginDialogWebViewClient(this@LoginDialogFragment).also {
loginWebViewClient = it
updateLoginWebViewClient()
}
// create a Login WebView if one doesn't exist already
loginView = loginView ?: DisplayUtil.createLoginWebView(context, webViewClient, arguments)
// attach the login view to the current frame
addView(loginView)
currentFrame = this
return this
}
@UiThread
private fun detachLoginView() {
// remove the login view from any existing frame
try {
currentFrame?.removeView(loginView)
} catch (e: IllegalArgumentException) {
// XXX: KEYAND-12 IllegalArgumentException: Receiver not registered: android.webkit.WebViewClassic
Timber.tag(TAG)
.e(e, "error removing Login WebView, let's just reset the login view")
loginView = null
loginWebViewClient = null
}
currentFrame = null
}
// region LoginWebViewClient
private var loginWebViewClient: LoginWebViewClient? = null
private fun updateLoginWebViewClient() = loginWebViewClient?.setActivity(activity)
// endregion LoginWebViewClient
// endregion Login WebView
override fun dismissAllowingStateLoss() {
try {
super.dismissAllowingStateLoss()
} catch (suppressed: IllegalStateException) {
// HACK: work around state loss exception if the dialog was added to the back stack
Timber.tag(TAG).e(suppressed, "Error dismissing the LoginDialogFragment, probably because of a Back Stack.")
fragmentManager?.commit(allowStateLoss = true) { remove(this@LoginDialogFragment) }
}
}
}
| mit | d475cbfd8e3f355b2eb195d2e775c015 | 34.807143 | 120 | 0.674845 | 5.068756 | false | false | false | false |
UnsignedInt8/d.Wallet-Core | android/lib/src/main/java/dWallet/core/bitcoin/application/bip32/ByteUtil.kt | 1 | 4597 | package dwallet.core.bitcoin.application.bip32
import org.spongycastle.util.encoders.Hex
import java.math.BigInteger
import java.util.*
import kotlin.experimental.and
/**
* Created by Jesion on 2015-01-14.
*/
internal object ByteUtil {
fun toHex(bytes: ByteArray): String {
val sb = StringBuffer()
for (i in bytes.indices) {
sb.append(Integer.toString((bytes[i] and 0xff.toByte()) + 0x100, 16).substring(1))
}
return sb.toString()
}
fun fromHex(hex: String): ByteArray {
return Hex.decode(hex)
}
fun reverseBytes(bytes: ByteArray): ByteArray {
val buf = ByteArray(bytes.size)
for (i in bytes.indices)
buf[i] = bytes[bytes.size - 1 - i]
return buf
}
/**
* Base58 - Encoding of BIP32 Keys
*/
private val b58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz".toCharArray()
private val indexes58 = IntArray(128)
init {
for (i in indexes58.indices) {
indexes58[i] = -1
}
for (i in b58.indices) {
indexes58[b58[i].toInt()] = i
}
}
fun toBase58(b: ByteArray): String {
if (b.size == 0) {
return ""
}
var lz = 0
while (lz < b.size && b[lz].toInt() == 0) {
++lz
}
val s = StringBuffer()
var n = BigInteger(1, b)
while (n.compareTo(BigInteger.ZERO) > 0) {
val r = n.divideAndRemainder(BigInteger.valueOf(58))
n = r[0]
val digit = b58[r[1].toInt()]
s.append(digit)
}
while (lz > 0) {
--lz
s.append("1")
}
return s.reverse().toString()
}
fun toBase58WithChecksum(b: ByteArray): String {
val cs = Hash.hash(b)
val extended = ByteArray(b.size + 4)
System.arraycopy(b, 0, extended, 0, b.size)
System.arraycopy(cs, 0, extended, b.size, 4)
return toBase58(extended)
}
@Throws(Exception::class)
fun fromBase58WithChecksum(s: String): ByteArray {
val b = fromBase58(s)
if (b.size < 4) {
throw Exception("Too short for checksum: " + s + " l: " + b.size)
}
val cs = ByteArray(4)
System.arraycopy(b, b.size - 4, cs, 0, 4)
val data = ByteArray(b.size - 4)
System.arraycopy(b, 0, data, 0, b.size - 4)
val h = ByteArray(4)
System.arraycopy(Hash.hash(data), 0, h, 0, 4)
if (Arrays.equals(cs, h)) {
return data
}
throw Exception("Checksum mismatch: " + s)
}
@Throws(Exception::class)
fun fromBase58(input: String): ByteArray {
if (input.length == 0) {
return ByteArray(0)
}
val input58 = ByteArray(input.length)
// Transform the String to a base58 byte sequence
for (i in 0..input.length - 1) {
val c = input[i]
var digit58 = -1
if (c.toInt() >= 0 && c.toInt() < 128) {
digit58 = indexes58[c.toInt()]
}
if (digit58 < 0) {
throw Exception("Illegal character $c at $i")
}
input58[i] = digit58.toByte()
}
// Count leading zeroes
var zeroCount = 0
while (zeroCount < input58.size && input58[zeroCount].toInt() == 0) {
++zeroCount
}
// The encoding
val temp = ByteArray(input.length)
var j = temp.size
var startAt = zeroCount
while (startAt < input58.size) {
val mod = divmod256(input58, startAt)
if (input58[startAt].toInt() == 0) {
++startAt
}
temp[--j] = mod
}
// Do no add extra leading zeroes, move j to first non null byte.
while (j < temp.size && temp[j].toInt() == 0) {
++j
}
return copyOfRange(temp, j - zeroCount, temp.size)
}
private fun divmod256(number58: ByteArray, startAt: Int): Byte {
var remainder = 0
for (i in startAt..number58.size - 1) {
val digit58 = number58[i].toInt() and 0xFF
val temp = remainder * 58 + digit58
number58[i] = (temp / 256).toByte()
remainder = temp % 256
}
return remainder.toByte()
}
private fun copyOfRange(source: ByteArray, from: Int, to: Int): ByteArray {
val range = ByteArray(to - from)
System.arraycopy(source, from, range, 0, range.size)
return range
}
}
| gpl-3.0 | 92a7eaaad6b2bc2490dcf6f9bf64bda2 | 27.73125 | 96 | 0.524255 | 3.808616 | false | false | false | false |
exponent/exponent | packages/expo-media-library/android/src/test/java/expo/modules/medialibrary/TestUtils.kt | 2 | 1317 | package expo.modules.medialibrary
import android.content.ContentResolver
import android.content.Context
import android.database.Cursor
import io.mockk.every
import io.mockk.mockk
import org.robolectric.fakes.RoboCursor
typealias CursorResults = Array<Array<out Any?>>
fun mockCursor(cursorResults: CursorResults): RoboCursor {
val cursor = RoboCursor()
cursor.setColumnNames(ASSET_PROJECTION.toMutableList())
cursor.setResults(cursorResults)
return cursor
}
fun mockContentResolver(cursor: Cursor?): ContentResolver {
val contentResolver = mockk<ContentResolver>()
every {
contentResolver.query(
EXTERNAL_CONTENT_URI,
any(), any(), any(), any()
)
} returns cursor
return contentResolver
}
fun mockContentResolverForResult(cursorResults: CursorResults) =
mockContentResolver(mockCursor(cursorResults))
fun throwableContentResolver(throwable: Throwable): ContentResolver {
val contentResolver = mockk<ContentResolver>()
every { contentResolver.query(any(), any(), any(), any(), any()) } throws throwable
return contentResolver
}
class MockContext {
private val context = mockk<Context>()
infix fun with(contentResolver: ContentResolver): Context {
every { context.getContentResolver() } returns contentResolver
return context
}
fun get() = context
}
| bsd-3-clause | 2b01cd6e27a0409d4bed45f14ef0d329 | 26.4375 | 85 | 0.763857 | 4.58885 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/ide/hints/type/RsTypeHintsPresentationFactory.kt | 2 | 12891 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.hints.type
import com.intellij.codeInsight.hints.presentation.InlayPresentation
import com.intellij.codeInsight.hints.presentation.PresentationFactory
import org.rust.ide.presentation.shortPresentableText
import org.rust.lang.core.psi.RsTraitItem
import org.rust.lang.core.psi.RsTypeAlias
import org.rust.lang.core.psi.RsTypeParameter
import org.rust.lang.core.psi.ext.typeParameters
import org.rust.lang.core.types.BoundElement
import org.rust.lang.core.types.Kind
import org.rust.lang.core.types.consts.Const
import org.rust.lang.core.types.consts.CtConstParameter
import org.rust.lang.core.types.consts.CtValue
import org.rust.lang.core.types.normType
import org.rust.lang.core.types.ty.*
@Suppress("UnstableApiUsage")
class RsTypeHintsPresentationFactory(
private val factory: PresentationFactory,
private val showObviousTypes: Boolean
) {
fun typeHint(type: Ty): InlayPresentation = factory.roundWithBackground(
listOf(text(": "), hint(type, 1)).join()
)
private fun hint(kind: Kind, level: Int): InlayPresentation {
if (kind is Ty) {
val alias = kind.aliasedBy
if (alias != null) {
return aliasTypeHint(alias, level)
}
}
return when (kind) {
is TyTuple -> tupleTypeHint(kind, level)
is TyAdt -> adtTypeHint(kind, level)
is TyFunction -> functionTypeHint(kind, level)
is TyReference -> referenceTypeHint(kind, level)
is TyPointer -> pointerTypeHint(kind, level)
is TyProjection -> projectionTypeHint(kind, level)
is TyTypeParameter -> typeParameterTypeHint(kind)
is TyArray -> arrayTypeHint(kind, level)
is TySlice -> sliceTypeHint(kind, level)
is TyTraitObject -> traitObjectTypeHint(kind, level)
is TyAnon -> anonTypeHint(kind, level)
is CtConstParameter -> constParameterTypeHint(kind)
is CtValue -> text(kind.expr.toString())
is Ty -> text(kind.shortPresentableText)
else -> text(null)
}
}
private fun functionTypeHint(type: TyFunction, level: Int): InlayPresentation {
val parameters = type.paramTypes
val returnType = type.retType
val startWithPlaceholder = checkSize(level, parameters.size + 1)
val fn = if (parameters.isEmpty()) {
text("fn()")
} else {
factory.collapsible(
prefix = text("fn("),
collapsed = text(PLACEHOLDER),
expanded = { parametersHint(parameters, level + 1) },
suffix = text(")"),
startWithPlaceholder = startWithPlaceholder
)
}
if (returnType !is TyUnit) {
val ret = factory.collapsible(
prefix = text(" → "),
collapsed = text(PLACEHOLDER),
expanded = { hint(returnType, level + 1) },
suffix = text(""),
startWithPlaceholder = startWithPlaceholder
)
return factory.seq(fn, ret)
}
return fn
}
private fun tupleTypeHint(type: TyTuple, level: Int): InlayPresentation =
factory.collapsible(
prefix = text("("),
collapsed = text(PLACEHOLDER),
expanded = { tupleTypesHint(type.types, level + 1) },
suffix = text(")"),
startWithPlaceholder = checkSize(level, type.types.size)
)
private fun tupleTypesHint(types: List<Ty>, level: Int): InlayPresentation = if (types.size == 1) {
factory.seq(hint(types.single(), level), text(","))
} else {
types.map { hint(it, level) }.join(", ")
}
private fun adtTypeHint(type: TyAdt, level: Int): InlayPresentation {
val adtName = type.item.name
val typeDeclaration = type.item
val typeNamePresentation = factory.psiSingleReference(text(adtName)) { typeDeclaration }
val typeArguments = type.typeArguments.zip(type.item.typeParameters)
return withGenericsTypeHint(typeNamePresentation, typeArguments, type.constArguments, level)
}
private fun aliasTypeHint(boundElement: BoundElement<RsTypeAlias>, level: Int): InlayPresentation {
val alias = boundElement.element
val adtName = alias.name
val typeNamePresentation = factory.psiSingleReference(text(adtName)) { alias }
val typeArguments = alias.typeParameters.map { (boundElement.subst[it] ?: TyUnknown) to it }
return withGenericsTypeHint(typeNamePresentation, typeArguments, emptyList(), level)
}
private fun withGenericsTypeHint(
typeNamePresentation: InlayPresentation,
typeArguments: List<Pair<Ty, RsTypeParameter>>,
constArguments: List<Const>,
level: Int
): InlayPresentation {
val userVisibleKindArguments = mutableListOf<Kind>()
for ((argument, parameter) in typeArguments) {
if (!showObviousTypes && isDefaultTypeParameter(argument, parameter)) {
// don't show default types
continue
}
userVisibleKindArguments.add(argument)
}
for (argument in constArguments) {
userVisibleKindArguments.add(argument)
}
if (userVisibleKindArguments.isNotEmpty()) {
val collapsible = factory.collapsible(
prefix = text("<"),
collapsed = text(PLACEHOLDER),
expanded = { parametersHint(userVisibleKindArguments, level + 1) },
suffix = text(">"),
startWithPlaceholder = checkSize(level, userVisibleKindArguments.size)
)
return listOf(typeNamePresentation, collapsible).join()
}
return typeNamePresentation
}
private fun referenceTypeHint(type: TyReference, level: Int): InlayPresentation = listOf(
text("&" + if (type.mutability.isMut) "mut " else ""),
hint(type.referenced, level) // level is not incremented intentionally
).join()
private fun pointerTypeHint(type: TyPointer, level: Int): InlayPresentation = listOf(
text("*" + if (type.mutability.isMut) "mut " else "const "),
hint(type.referenced, level) // level is not incremented intentionally
).join()
private fun projectionTypeHint(type: TyProjection, level: Int): InlayPresentation {
val collapsible = factory.collapsible(
prefix = text("<"),
collapsed = text(PLACEHOLDER),
expanded = {
val typePresentation = hint(type.type, level + 1)
val traitPresentation = traitItemTypeHint(type.trait, level + 1, false)
listOf(typePresentation, traitPresentation).join(" as ")
},
suffix = text(">"),
startWithPlaceholder = checkSize(level, 2)
)
val targetDeclaration = type.target
val targetPresentation = factory.psiSingleReference(text(targetDeclaration.name)) { targetDeclaration }
return listOf(collapsible, targetPresentation).join("::")
}
private fun typeParameterTypeHint(type: TyTypeParameter): InlayPresentation {
val parameter = type.parameter
if (parameter is TyTypeParameter.Named) {
return factory.psiSingleReference(text(parameter.name)) { parameter.parameter }
}
return text(parameter.name)
}
private fun constParameterTypeHint(const: CtConstParameter): InlayPresentation =
factory.psiSingleReference(text(const.parameter.name)) { const.parameter }
private fun arrayTypeHint(type: TyArray, level: Int): InlayPresentation =
factory.collapsible(
prefix = text("["),
collapsed = text(PLACEHOLDER),
expanded = {
val basePresentation = hint(type.base, level + 1)
val sizePresentation = text(type.size?.toString())
listOf(basePresentation, sizePresentation).join("; ")
},
suffix = text("]"),
startWithPlaceholder = checkSize(level, 1)
)
private fun sliceTypeHint(type: TySlice, level: Int): InlayPresentation =
factory.collapsible(
prefix = text("["),
collapsed = text(PLACEHOLDER),
expanded = { hint(type.elementType, level + 1) },
suffix = text("]"),
startWithPlaceholder = checkSize(level, 1)
)
private fun traitObjectTypeHint(type: TyTraitObject, level: Int): InlayPresentation =
factory.collapsible(
prefix = text("dyn "),
collapsed = text(PLACEHOLDER),
expanded = { type.traits.map { traitItemTypeHint(it, level + 1, true) }.join("+") },
suffix = text(""),
startWithPlaceholder = checkSize(level, 1)
)
private fun anonTypeHint(type: TyAnon, level: Int): InlayPresentation =
factory.collapsible(
prefix = text("impl "),
collapsed = text(PLACEHOLDER),
expanded = { type.traits.map { traitItemTypeHint(it, level + 1, true) }.join("+") },
suffix = text(""),
startWithPlaceholder = checkSize(level, type.traits.size)
)
private fun parametersHint(kinds: List<Kind>, level: Int): InlayPresentation =
kinds.map { hint(it, level) }.join(", ")
private fun traitItemTypeHint(
trait: BoundElement<RsTraitItem>,
level: Int,
includeAssoc: Boolean
): InlayPresentation {
val traitPresentation = factory.psiSingleReference(text(trait.element.name)) { trait.element }
val typeParametersPresentations = mutableListOf<InlayPresentation>()
for (parameter in trait.element.typeParameters) {
val argument = trait.subst[parameter] ?: continue
if (!showObviousTypes && isDefaultTypeParameter(argument, parameter)) {
// don't show default types
continue
}
val parameterPresentation = hint(argument, level + 1)
typeParametersPresentations.add(parameterPresentation)
}
val assocTypesPresentations = mutableListOf<InlayPresentation>()
if (includeAssoc) {
for (alias in trait.element.associatedTypesTransitively) {
val aliasName = alias.name ?: continue
val type = trait.assoc[alias] ?: continue
if (!showObviousTypes && isDefaultTypeAlias(type, alias)) {
// don't show default types
continue
}
val aliasPresentation = factory.psiSingleReference(text(aliasName)) { alias }
val presentation = listOf(aliasPresentation, text("="), hint(type, level + 1)).join()
assocTypesPresentations.add(presentation)
}
}
val innerPresentations = typeParametersPresentations + assocTypesPresentations
return if (innerPresentations.isEmpty()) {
traitPresentation
} else {
val expanded = innerPresentations.join(", ")
val traitTypesPresentation = factory.collapsible(
prefix = text("<"),
collapsed = text(PLACEHOLDER),
expanded = { expanded },
suffix = text(">"),
startWithPlaceholder = checkSize(level, innerPresentations.size)
)
listOf(traitPresentation, traitTypesPresentation).join()
}
}
private fun checkSize(level: Int, elementsCount: Int): Boolean =
level + elementsCount > FOLDING_THRESHOLD
private fun isDefaultTypeParameter(argument: Ty, parameter: RsTypeParameter): Boolean =
argument.isEquivalentTo(parameter.typeReference?.normType)
private fun isDefaultTypeAlias(argument: Ty, alias: RsTypeAlias): Boolean =
argument.isEquivalentTo(alias.typeReference?.normType)
private fun List<InlayPresentation>.join(separator: String = ""): InlayPresentation {
if (separator.isEmpty()) {
return factory.seq(*toTypedArray())
}
val presentations = mutableListOf<InlayPresentation>()
var first = true
for (presentation in this) {
if (!first) {
presentations.add(text(separator))
}
presentations.add(presentation)
first = false
}
return factory.seq(*presentations.toTypedArray())
}
private fun text(text: String?): InlayPresentation = factory.smallText(text ?: "?")
companion object {
private const val PLACEHOLDER: String = "…"
private const val FOLDING_THRESHOLD: Int = 3
}
}
| mit | d724a558571265f67b44a9e9d52550e5 | 39.146417 | 111 | 0.618375 | 4.966089 | false | false | false | false |
Jonatino/JOGL2D | src/main/kotlin/org/anglur/joglext/jogl2d/shape/impl/ArcIterator.kt | 1 | 7002 | /*
* Copyright 2016 Jonathan Beaudoin <https://github.com/Jonatino>
*
* 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.anglur.joglext.jogl2d.shape.impl
import java.awt.geom.AffineTransform
import java.awt.geom.Arc2D
import java.awt.geom.PathIterator
import java.util.*
object ArcIterator : PathIterator {
private lateinit var a: Arc2D
private var affine: AffineTransform? = null
private var x: Double = 0.toDouble()
private var y: Double = 0.toDouble()
private var w: Double = 0.toDouble()
private var h: Double = 0.toDouble()
private var angStRad: Double = 0.toDouble()
private var increment: Double = 0.toDouble()
private var cv: Double = 0.toDouble()
private var arcSegs: Int = 0
private var lineSegs: Int = 0
private var index: Int = 0
fun set(a: Arc2D, affine: AffineTransform?) = apply {
this.index = 0
this.a = a
this.w = a.width / 2
this.h = a.height / 2
this.x = a.x + w
this.y = a.y + h
this.angStRad = -Math.toRadians(a.angleStart)
this.affine = affine
val ext = -a.angleExtent
if (ext >= 360.0 || ext <= -360) {
arcSegs = 4
this.increment = Math.PI / 2
this.cv = 0.5522847498307933
if (ext < 0) {
increment = -increment
cv = -cv
}
} else {
arcSegs = Math.ceil(Math.abs(ext) / 90.0).toInt()
this.increment = Math.toRadians(ext / arcSegs)
this.cv = btan(increment)
if (cv == 0.0) {
arcSegs = 0
}
}
when (a.arcType) {
Arc2D.OPEN -> lineSegs = 0
Arc2D.CHORD -> lineSegs = 1
Arc2D.PIE -> lineSegs = 2
}
if (w < 0 || h < 0) {
arcSegs = -1
lineSegs = -1
}
}
/**
* Return the winding rule for determining the insideness of the
* path.
* @see #WIND_EVEN_ODD
* @see #WIND_NON_ZERO
*/
override fun getWindingRule() = PathIterator.WIND_NON_ZERO
/**
* Tests if there are more points to read.
* @return true if there are more points to read
*/
override fun isDone() = index > arcSegs + lineSegs
/**
* Moves the iterator to the next segment of the path forwards
* along the primary direction of traversal as long as there are
* more points in that direction.
*/
override fun next() {
index++
}
private fun btan(increment: Double): Double {
var increment = increment
increment /= 2.0
return 4.0 / 3.0 * Math.sin(increment) / (1.0 + Math.cos(increment))
}
/**
* Returns the coordinates and type of the current path segment in
* the iteration.
* The return value is the path segment type:
* SEG_MOVETO, SEG_LINETO, SEG_QUADTO, SEG_CUBICTO, or SEG_CLOSE.
* A float array of length 6 must be passed in and may be used to
* store the coordinates of the point(s).
* Each point is stored as a pair of float x,y coordinates.
* SEG_MOVETO and SEG_LINETO types will return one point,
* SEG_QUADTO will return two points,
* SEG_CUBICTO will return 3 points
* and SEG_CLOSE will not return any points.
* @see #SEG_MOVETO
* @see #SEG_LINETO
* @see #SEG_QUADTO
* @see #SEG_CUBICTO
* @see #SEG_CLOSE
*/
override fun currentSegment(coords: FloatArray): Int {
if (isDone) {
throw NoSuchElementException("arc iterator out of bounds")
}
var angle = angStRad
if (index == 0) {
coords[0] = (x + Math.cos(angle) * w).toFloat()
coords[1] = (y + Math.sin(angle) * h).toFloat()
affine?.transform(coords, 0, coords, 0, 1)
return PathIterator.SEG_MOVETO
}
if (index > arcSegs) {
if (index == arcSegs + lineSegs) {
return PathIterator.SEG_CLOSE
}
coords[0] = x.toFloat()
coords[1] = y.toFloat()
affine?.transform(coords, 0, coords, 0, 1)
return PathIterator.SEG_LINETO
}
angle += increment * (index - 1)
var relx = Math.cos(angle)
var rely = Math.sin(angle)
coords[0] = (x + (relx - cv * rely) * w).toFloat()
coords[1] = (y + (rely + cv * relx) * h).toFloat()
angle += increment
relx = Math.cos(angle)
rely = Math.sin(angle)
coords[2] = (x + (relx + cv * rely) * w).toFloat()
coords[3] = (y + (rely - cv * relx) * h).toFloat()
coords[4] = (x + relx * w).toFloat()
coords[5] = (y + rely * h).toFloat()
affine?.transform(coords, 0, coords, 0, 3)
return PathIterator.SEG_CUBICTO
}
/**
* Returns the coordinates and type of the current path segment in
* the iteration.
* The return value is the path segment type:
* SEG_MOVETO, SEG_LINETO, SEG_QUADTO, SEG_CUBICTO, or SEG_CLOSE.
* A double array of length 6 must be passed in and may be used to
* store the coordinates of the point(s).
* Each point is stored as a pair of double x,y coordinates.
* SEG_MOVETO and SEG_LINETO types will return one point,
* SEG_QUADTO will return two points,
* SEG_CUBICTO will return 3 points
* and SEG_CLOSE will not return any points.
* @see #SEG_MOVETO
* @see #SEG_LINETO
* @see #SEG_QUADTO
* @see #SEG_CUBICTO
* @see #SEG_CLOSE
*/
override fun currentSegment(coords: DoubleArray): Int {
if (isDone) {
throw NoSuchElementException("arc iterator out of bounds")
}
var angle = angStRad
if (index == 0) {
coords[0] = x + Math.cos(angle) * w
coords[1] = y + Math.sin(angle) * h
affine?.transform(coords, 0, coords, 0, 1)
return PathIterator.SEG_MOVETO
}
if (index > arcSegs) {
if (index == arcSegs + lineSegs) {
return PathIterator.SEG_CLOSE
}
coords[0] = x
coords[1] = y
affine?.transform(coords, 0, coords, 0, 1)
return PathIterator.SEG_LINETO
}
angle += increment * (index - 1)
var relx = Math.cos(angle)
var rely = Math.sin(angle)
coords[0] = x + (relx - cv * rely) * w
coords[1] = y + (rely + cv * relx) * h
angle += increment
relx = Math.cos(angle)
rely = Math.sin(angle)
coords[2] = x + (relx + cv * rely) * w
coords[3] = y + (rely - cv * relx) * h
coords[4] = x + relx * w
coords[5] = y + rely * h
affine?.transform(coords, 0, coords, 0, 3)
return PathIterator.SEG_CUBICTO
}
operator fun invoke(rect: Arc2D, affine: AffineTransform? = null) = set(rect, affine)
// ArcIterator.btan(Math.PI/2)
val CtrlVal = 0.5522847498307933
/*
* ctrlpts contains the control points for a set of 4 cubic
* bezier curves that approximate a circle of radius 0.5
* centered at 0.5, 0.5
*/
private val pcv = 0.5 + CtrlVal * 0.5
private val ncv = 0.5 - CtrlVal * 0.5
private val ctrlpts = arrayOf(doubleArrayOf(1.0, pcv, pcv, 1.0, 0.5, 1.0), doubleArrayOf(ncv, 1.0, 0.0, pcv, 0.0, 0.5), doubleArrayOf(0.0, ncv, ncv, 0.0, 0.5, 0.0), doubleArrayOf(pcv, 0.0, 1.0, ncv, 1.0, 0.5))
}
| apache-2.0 | 181a19e0e6f9b2a0bfba41887b00ff70 | 28.923077 | 210 | 0.647244 | 2.890999 | false | false | false | false |
arsich/messenger | app/src/main/kotlin/ru/arsich/messenger/vk/VKApiChat.kt | 1 | 1989 | package ru.arsich.messenger.vk
import com.vk.sdk.api.VKParameters
import com.vk.sdk.api.VKParser
import com.vk.sdk.api.VKRequest
import com.vk.sdk.api.model.VKList
import org.json.JSONObject
object VKApiChat {
fun get():VKRequest {
val request = VKRequest("execute", VKParameters.from("code", code))
request.setResponseParser(parser)
return request
}
private val parser = object: VKParser() {
override fun createModel(json: JSONObject?): VKList<VKChat> = VKList(json, VKChat::class.java)
}
private val code = """
var chats = API.messages.getChat({"chat_ids": API.messages.getDialogs({"preview_length":50, "count":25})[email protected]@.chat_id, "fields": "photo_100"});
var messages = API.messages.getDialogs({"preview_length":50, "count":25})[email protected];
var b = 0;
var messagesLength = messages.length;
var messagesProcessed = [];
while (b < messagesLength) {
var info = messages[b];
if (info.chat_id) {
messagesProcessed.push({"date": info.date, "body": info.body, "id": info.chat_id});
}
b = b + 1;
}
var a = 0;
var chatsLength = chats.length;
var messagesProcessedLength = messagesProcessed.length;
var result = [];
while (a < chatsLength) {
if (chats[a].kicked < 1 && chats[a].left < 1) {
var b = 0;
var messageInfo = {};
while (b < messagesProcessedLength) {
if (chats[a].id == messagesProcessed[b].id) {
messageInfo = messagesProcessed[b];
b = messagesProcessedLength;
}
b = b + 1;
}
var resultItem = chats[a] + messageInfo;
result.push(resultItem);
}
a = a + 1;
}
return result;
""".trimIndent()
} | mit | 49d1459a18ba5a87c40f67d858ba52ad | 32.166667 | 162 | 0.540473 | 4.002012 | false | false | false | false |
Undin/intellij-rust | toml/src/main/kotlin/org/rust/toml/crates/local/CratesLocalIndexServiceImpl.kt | 2 | 25665 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.toml.crates.local
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.json.JsonMapper
import com.fasterxml.jackson.module.kotlin.readValue
import com.fasterxml.jackson.module.kotlin.registerKotlinModule
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.newvfs.RefreshQueue
import com.intellij.openapi.vfs.newvfs.events.VFileEvent
import com.intellij.util.EnvironmentUtil
import com.intellij.util.io.*
import com.intellij.util.ui.UIUtil
import org.eclipse.jgit.api.Git
import org.eclipse.jgit.api.errors.GitAPIException
import org.eclipse.jgit.errors.RepositoryNotFoundException
import org.eclipse.jgit.errors.RevisionSyntaxException
import org.eclipse.jgit.lib.ObjectId
import org.eclipse.jgit.lib.Repository
import org.eclipse.jgit.lib.RepositoryCache
import org.eclipse.jgit.revwalk.RevWalk
import org.eclipse.jgit.storage.file.FileRepositoryBuilder
import org.eclipse.jgit.treewalk.CanonicalTreeParser
import org.eclipse.jgit.treewalk.TreeWalk
import org.eclipse.jgit.treewalk.filter.OrTreeFilter
import org.eclipse.jgit.treewalk.filter.PathFilter
import org.eclipse.jgit.treewalk.filter.TreeFilter
import org.jetbrains.annotations.TestOnly
import org.rust.openapiext.RsPathManager
import org.rust.openapiext.checkIsBackgroundThread
import org.rust.openapiext.isUnitTestMode
import org.rust.openapiext.toThreadSafeProgressIndicator
import org.rust.stdext.RsResult
import org.rust.stdext.RsResult.Err
import org.rust.stdext.RsResult.Ok
import org.rust.stdext.cleanDirectory
import org.rust.stdext.supplyAsync
import org.rust.toml.crates.local.CratesLocalIndexService.Error
import org.rust.util.RsBackgroundTaskQueue
import java.io.DataInput
import java.io.DataOutput
import java.io.IOException
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import java.util.concurrent.CompletionException
import java.util.concurrent.Executors
import java.util.concurrent.atomic.AtomicInteger
import java.util.stream.Collectors
/**
* Crates local index, created from user cargo registry index on host machine.
* Used for dependency code insight in project's `Cargo.toml`
*/
class CratesLocalIndexServiceImpl : CratesLocalIndexService, Disposable {
private val queue: RsBackgroundTaskQueue = RsBackgroundTaskQueue()
private val innerStateLock: Any = Any()
// Writing is guarded by `innerStateLock`
@Volatile
private var innerState: InnerState = InnerState.Loading
/** [isUpdating] is true when index is performing [CratesLocalIndexUpdateTask] */
private val isUpdating: Boolean
get() = updateTaskCount.get() != 0
private val updateTaskCount = AtomicInteger(0)
private sealed class InnerState {
object Loading : InnerState() {
override fun toString(): String = "InnerState.Loading"
}
data class Loaded(val inner: CratesLocalIndexServiceImplInner) : InnerState()
data class Err(val err: Error.InternalError) : InnerState()
object Disposed : InnerState() {
override fun toString(): String = "InnerState.Disposed"
}
}
/**
* Please, avoid heavy operations in [action]
*
* @return new state or `null` if the state is not changed
*/
private fun stateTransition(action: (InnerState) -> InnerState): InnerState? {
return synchronized(innerStateLock) {
val oldState = innerState
val newState = action(oldState)
innerState = newState
if (newState != oldState) {
LOG.debug("CratesLocalIndexService state transition $oldState -> $newState")
newState
} else {
null
}
}
}
init {
loadAsync()
}
private fun loadAsync() {
LOG.debug("Loading CratesLocalIndexService")
ApplicationManager.getApplication().executeOnPooledThread {
try {
resetIndexIfNeeded()
} catch (e: IOException) {
LOG.error(e)
}
val inner = CratesLocalIndexServiceImplInner.tryCreate(
cargoRegistryIndexPath,
baseCratesLocalIndexDir
)
stateTransition { oldState ->
when (oldState) {
InnerState.Loading -> when (inner) {
is Ok -> {
updateIndex(inner.ok)
InnerState.Loaded(inner.ok)
}
is Err -> InnerState.Err(inner.err)
}
is InnerState.Loaded, is InnerState.Err -> error("unreachable")
InnerState.Disposed -> {
inner.ok()?.close()
InnerState.Disposed
}
}
}
LOG.debug("Loading CratesLocalIndexService finished")
}
}
override fun getCrate(crateName: String): RsResult<CargoRegistryCrate?, Error> =
handleErrors { it.getCrate(crateName) }
override fun getAllCrateNames(): RsResult<List<String>, Error> =
handleErrors(CratesLocalIndexServiceImplInner::getAllCrateNames)
private fun <T> handleErrors(action: (CratesLocalIndexServiceImplInner) -> T): RsResult<T, Error> {
if (isUpdating) {
return Err(Error.Updating)
}
return when (val innerState = innerState) {
InnerState.Loading -> Err(Error.NotYetLoaded)
is InnerState.Loaded -> try {
Ok(action(innerState.inner))
} catch (e: IOException) {
Err(onPersistentHashMapError(innerState, e))
}
is InnerState.Err -> Err(innerState.err)
is InnerState.Disposed -> Err(Error.Disposed)
}
}
private fun onPersistentHashMapError(lastInnerState: InnerState.Loaded, e: IOException): Error.InternalError {
val err = Error.InternalError.PersistentHashMapReadError(e.toString())
stateTransition { oldState ->
if (oldState == lastInnerState) {
lastInnerState.inner.close()
InnerState.Err(err)
} else {
oldState
}
}
LOG.warn(e)
return err
}
fun recoverIfNeeded() {
val newState = stateTransition { oldState ->
when (oldState) {
is InnerState.Err -> InnerState.Loading
else -> oldState
}
}
if (newState != null) {
loadAsync()
}
}
fun hasInterestingEvent(events: List<VFileEvent>): Boolean {
val innerState = innerState
if (innerState !is InnerState.Loaded) return false
val cargoRegistryIndexRefsLocation = innerState.inner.cargoRegistryIndexRefsLocation
return events.any { it.path.startsWith(cargoRegistryIndexRefsLocation) }
}
fun updateIndex() {
val innerState = innerState
if (innerState !is InnerState.Loaded) return
updateIndex(innerState.inner)
}
private fun updateIndex(inner: CratesLocalIndexServiceImplInner) {
updateTaskCount.incrementAndGet()
queue.run(inner.createUpdateTask(this::updateTaskFailed, this::updateTaskFinished))
}
override fun dispose() {
queue.dispose()
stateTransition { oldState ->
if (oldState is InnerState.Loaded) {
oldState.inner.close()
}
InnerState.Disposed
}
}
// Called from a background thread
private fun updateTaskFailed(inner: CratesLocalIndexServiceImplInner, err: Error.InternalError) {
stateTransition { oldState ->
if (oldState is InnerState.Loaded && oldState.inner == inner) {
InnerState.Err(err)
} else {
oldState
}
}
}
// Called from EDT
private fun updateTaskFinished() {
// `runWriteAction` is needed to restart inspections that depends on this index
runWriteAction {
updateTaskCount.decrementAndGet()
}
}
@TestOnly
fun awaitLoadedAndUpdated() {
while (innerState is InnerState.Loading || isUpdating) {
Thread.sleep(10)
UIUtil.dispatchAllInvocationEvents()
}
}
companion object {
private val baseCratesLocalIndexDir: Path
get() = RsPathManager.pluginDirInSystem().resolve("crates-local-index")
private val corruptionMarkerFile: Path
get() = baseCratesLocalIndexDir.resolve(CORRUPTION_MARKER_NAME)
private val cargoHome: String
get() = EnvironmentUtil.getValue("CARGO_HOME")
?: Paths.get(System.getProperty("user.home"), ".cargo/").toString()
// Currently, for crates.io only
private val cargoRegistryIndexPath: Path
get() = Paths.get(cargoHome, "registry/index/", CRATES_IO_HASH, ".git/")
// Crates.io index hash is permanent.
// See https://github.com/rust-lang/cargo/issues/8572
private const val CRATES_IO_HASH = "github.com-1ecc6299db9ec823"
private const val CORRUPTION_MARKER_NAME: String = "corruption.marker"
// Must not load the service!
@JvmStatic
@Throws(IOException::class)
fun invalidateCaches() {
corruptionMarkerFile.apply {
parent?.createDirectories()
Files.createFile(this)
}
}
@Throws(IOException::class)
fun resetIndexIfNeeded() {
if (corruptionMarkerFile.exists()) {
baseCratesLocalIndexDir.cleanDirectory()
}
}
}
}
private class CratesLocalIndexServiceImplInner(
private val cargoRegistryIndexPath: Path,
private val crates: PersistentHashMap<String, CargoRegistryCrate>,
val cargoRegistryIndexRefsLocation: String,
private val cargoRegistryIndexRefsWatchRequest: LocalFileSystem.WatchRequest?,
private val indexedCommitHashFile: Path,
// Read/mutated only within `CratesLocalIndexUpdateTask`, there isn't concurrent access
private var indexedCommitHash: String,
) {
private val isClosedLock: Any = Any()
// Guarded by `isClosedLock`
private var isClosed: Boolean = false
@Throws(IOException::class)
fun getCrate(crateName: String): CargoRegistryCrate? {
return crates.get(crateName) // throws IOException
}
@Throws(IOException::class)
fun getAllCrateNames(): List<String> {
val crateNames = mutableListOf<String>()
// throws IOException
crates.processKeys { name ->
crateNames.add(name)
}
return crateNames
}
@Throws(IOException::class)
private fun writeCratesUpdate(update: CratesUpdate) {
synchronized(isClosedLock) {
if (isClosed) return
// An extra protection from a crash
writeCommitHash(indexedCommitHashFile, INVALID_COMMIT_HASH)
}
for ((name, crate) in update.updatedCrates) {
crates.put(name, crate)
}
crates.force() // Force to save everything on the disk
synchronized(isClosedLock) {
if (isClosed) return
// Write the new hash only if the writing to PersistentHashMap succeed
writeCommitHash(indexedCommitHashFile, update.newHeadHash)
indexedCommitHash = update.newHeadHash
}
}
fun createUpdateTask(onError: (CratesLocalIndexServiceImplInner, Error.InternalError) -> Unit, onFinish: () -> Unit) =
CratesLocalIndexUpdateTask(
cargoRegistryIndexPath,
{ indexedCommitHash },
this::writeCratesUpdate,
{ onError(this, it) },
onFinish
)
fun close() {
synchronized(isClosedLock) {
isClosed = true
}
cargoRegistryIndexRefsWatchRequest?.let { LocalFileSystem.getInstance().removeWatchedRoot(it) }
catchAndWarn(crates::close)
}
companion object {
fun tryCreate(
cargoRegistryIndexPath: Path,
baseCratesLocalRegistryDir: Path,
): RsResult<CratesLocalIndexServiceImplInner, Error.InternalError> {
if (!isUnitTestMode) {
checkIsBackgroundThread()
}
val cargoRegistryIndexRefsPath = cargoRegistryIndexPath.resolve("refs")
if (!cargoRegistryIndexPath.exists() || !cargoRegistryIndexRefsPath.exists()) {
return Err(Error.InternalError.NoCargoIndex(cargoRegistryIndexPath))
}
val cargoRegistryIndexRefsLocation = cargoRegistryIndexRefsPath.toString()
val cargoRegistryIndexRefsVFile =
LocalFileSystem.getInstance().refreshAndFindFileByPath(cargoRegistryIndexRefsLocation)
if (cargoRegistryIndexRefsVFile == null) {
LOG.error("Failed to subscribe to cargo registry changes in $cargoRegistryIndexRefsLocation")
return Err(Error.InternalError.NoCargoIndex(cargoRegistryIndexRefsPath))
}
val indexedCommitHashFile = baseCratesLocalRegistryDir.resolve("indexed-commit-hash")
var indexedCommitHash = readCommitHash(indexedCommitHashFile)
if (indexedCommitHash == INVALID_COMMIT_HASH && baseCratesLocalRegistryDir.exists()) {
try {
baseCratesLocalRegistryDir.cleanDirectory() // throws IOException
} catch (e: IOException) {
LOG.error("Cannot clean directory $baseCratesLocalRegistryDir", e)
}
}
val cratesFilePath = baseCratesLocalRegistryDir.resolve("crates-local-index")
val crates: PersistentHashMap<String, CargoRegistryCrate> = try {
IOUtil.openCleanOrResetBroken({
PersistentHashMap(
cratesFilePath,
EnumeratorStringDescriptor.INSTANCE,
CrateExternalizer,
4 * 1024,
CRATES_INDEX_VERSION
)
}, {
baseCratesLocalRegistryDir.cleanDirectory() // Also deletes `indexedCommitHashFile`
indexedCommitHash = INVALID_COMMIT_HASH
})
} catch (e: IOException) {
LOG.error("Cannot open or create PersistentHashMap in $cratesFilePath", e)
return Err(Error.InternalError.PersistentHashMapInitError(cratesFilePath, e.toString()))
}
val watchRequest = LocalFileSystem.getInstance().addRootToWatch(cargoRegistryIndexRefsLocation, true)
// VFS fills up lazily, therefore we need to explicitly add root directory and go through children
VfsUtilCore.processFilesRecursively(cargoRegistryIndexRefsVFile) { true }
RefreshQueue.getInstance().refresh(true, true, null, cargoRegistryIndexRefsVFile)
val inner = CratesLocalIndexServiceImplInner(
cargoRegistryIndexPath,
crates,
cargoRegistryIndexRefsLocation,
watchRequest,
indexedCommitHashFile,
indexedCommitHash
)
return Ok(inner)
}
private fun readCommitHash(indexedCommitHashFile: Path): String {
return if (indexedCommitHashFile.exists()) {
try {
Files.readString(indexedCommitHashFile)
} catch (e: IOException) {
LOG.warn("Cannot read file $indexedCommitHashFile", e)
INVALID_COMMIT_HASH
}
} else {
INVALID_COMMIT_HASH
}
}
@Throws(IOException::class)
private fun writeCommitHash(indexedCommitHashFile: Path, hash: String) {
Files.writeString(indexedCommitHashFile, hash)
}
@JvmStatic
private fun catchAndWarn(runnable: () -> Unit) {
try {
runnable()
} catch (e: IOException) {
LOG.warn(e)
} catch (t: Throwable) {
LOG.error(t)
}
}
}
}
private data class CratesUpdate(
val updatedCrates: List<Pair<String, CargoRegistryCrate>>,
val newHeadHash: String
)
private class CratesLocalIndexUpdateTask(
private val cargoRegistryIndexPath: Path,
private val indexedCommitHashGetter: () -> String,
private val writeCratesUpdate: (CratesUpdate) -> Unit,
private val onError: (Error.InternalError) -> Unit,
private val onFinish: () -> Unit
) : Task.Backgroundable(null, "Loading cargo registry index", false) {
override fun run(indicator: ProgressIndicator) {
val builder = FileRepositoryBuilder()
.setGitDir(cargoRegistryIndexPath.toFile())
val update = try {
val repository = builder.build() // throws IOException
try {
val indexedCommitHash = indexedCommitHashGetter()
val newHead = readRegistryHeadCommitHash(repository) // throws IOException
if (newHead == indexedCommitHash) return
indicator.checkCanceled()
val crateList = readNewCrates(indicator, repository, newHead, indexedCommitHash) // throws IOException
CratesUpdate(crateList, newHead)
} finally {
// Ensure `repository` is really closed and all file descriptors are closed
RepositoryCache.unregister(repository)
repository.close()
}
} catch (e: RepositoryNotFoundException) {
LOG.warn(e)
onError(Error.InternalError.NoCargoIndex(cargoRegistryIndexPath))
return
} catch (e: IOException) {
onError(Error.InternalError.RepoReadError(cargoRegistryIndexPath, e.toString()))
LOG.warn(e)
return
}
if (update.updatedCrates.isNotEmpty()) {
ProgressManager.getInstance().executeNonCancelableSection {
try {
writeCratesUpdate(update)
} catch (e: IOException) {
LOG.warn(e)
onError(Error.InternalError.PersistentHashMapWriteError(e.toString()))
}
}
}
}
// Always called on EDT
override fun onFinished() {
onFinish()
}
@Throws(IOException::class, RevisionSyntaxException::class)
private fun readRegistryHeadCommitHash(repository: Repository): String {
// BACKCOMPAT: Rust 1.49
// Since 1.50 there should always be CARGO_REGISTRY_INDEX_TAG
val objectId = repository.resolve(CARGO_REGISTRY_INDEX_TAG)
?: repository.resolve(CARGO_REGISTRY_INDEX_TAG_PRE_1_50) // throws IOException
return objectId?.name ?: run {
LOG.error("Failed to resolve remote branch in the cargo registry index repository")
INVALID_COMMIT_HASH
}
}
@Throws(IOException::class)
private fun readNewCrates(
indicator: ProgressIndicator,
repository: Repository,
newHeadHash: String,
prevHeadHash: String
): List<Pair<String, CargoRegistryCrate>> {
val reader = repository.newObjectReader()
val currentTreeIter = CanonicalTreeParser().apply {
val currentHeadTree = repository.resolve("$newHeadHash^{tree}") ?: run {
LOG.error("Git revision `$newHeadHash^{tree}` cannot be resolved to any object id")
return emptyList()
}
reset(reader, currentHeadTree)
}
val filter = run {
val prevHeadTree = repository.resolve("$prevHeadHash^{tree}") ?: return@run TreeFilter.ALL
val prevTreeIter = CanonicalTreeParser().apply {
reset(reader, prevHeadTree)
}
val git = Git(repository)
val changes = try {
git.diff()
.setNewTree(currentTreeIter)
.setOldTree(prevTreeIter)
.call()
} catch (e: GitAPIException) {
LOG.error("Failed to calculate diff due to Git API error: ${e.message}")
return@run TreeFilter.ALL
}
when (changes.size) {
0 -> TreeFilter.ALL
1 -> PathFilter.create(changes.single().newPath)
else -> OrTreeFilter.create(changes.map { PathFilter.create(it.newPath) })
}
}
val revTree = RevWalk(repository).parseCommit(ObjectId.fromString(newHeadHash)).tree
val mapper = JsonMapper()
.registerKotlinModule()
.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
val objectIds = TreeWalk(repository).use { treeWalk ->
treeWalk.addTree(revTree)
treeWalk.filter = filter
treeWalk.isRecursive = true
treeWalk.isPostOrderTraversal = false
val objectIds = mutableListOf<Pair<ObjectId, String>>()
while (treeWalk.next()) {
if (treeWalk.isSubtree) continue
val path = treeWalk.pathString
// Ignore paths starting with dot (e.g. .github/) and config.json
if (path.startsWith(".") || path == "config.json") continue
indicator.checkCanceled()
val objectId = treeWalk.getObjectId(0)
objectIds.add(objectId to treeWalk.nameString)
}
objectIds
}
val pool = Executors.newWorkStealingPool(2)
val threadSafeIndicator = indicator.toThreadSafeProgressIndicator()
val future = supplyAsync(pool) {
objectIds
.parallelStream()
.map { (objectId, name) ->
threadSafeIndicator.checkCanceled()
val loader = repository.open(objectId)
val versions = mutableListOf<CargoRegistryCrateVersion>()
val fileReader = loader.openStream().bufferedReader(Charsets.UTF_8)
fileReader.forEachLine { line ->
if (line.isBlank()) return@forEachLine
try {
versions.add(crateFromJson(line, mapper))
} catch (e: Exception) {
LOG.warn("Failed to parse JSON for crate $name, line $line", e)
}
}
name to CargoRegistryCrate(versions)
}
.collect(Collectors.toList())
}
return try {
future.join()
} catch (e: CompletionException) {
throw e.cause ?: e
} finally {
pool.shutdownNow()
}
}
}
private val LOG: Logger = logger<CratesLocalIndexServiceImpl>()
private const val CARGO_REGISTRY_INDEX_TAG_PRE_1_50: String = "origin/master"
private const val CARGO_REGISTRY_INDEX_TAG: String = "origin/HEAD"
private const val INVALID_COMMIT_HASH: String = "<invalid>"
private const val CRATES_INDEX_VERSION: Int = 1
private object CrateExternalizer : DataExternalizer<CargoRegistryCrate> {
override fun save(out: DataOutput, value: CargoRegistryCrate) {
out.writeInt(value.versions.size)
value.versions.forEach { version ->
out.writeUTF(version.version)
out.writeBoolean(version.isYanked)
out.writeInt(version.features.size)
version.features.forEach { feature ->
out.writeUTF(feature)
}
}
}
override fun read(inp: DataInput): CargoRegistryCrate {
val versions = mutableListOf<CargoRegistryCrateVersion>()
val versionsSize = inp.readInt()
repeat(versionsSize) {
val version = inp.readUTF()
val yanked = inp.readBoolean()
val features = mutableListOf<String>()
val featuresSize = inp.readInt()
repeat(featuresSize) {
@Suppress("BlockingMethodInNonBlockingContext")
features.add(inp.readUTF())
}
versions.add(CargoRegistryCrateVersion(version, yanked, features))
}
return CargoRegistryCrate(versions)
}
}
data class ParsedVersion(
val name: String,
val vers: String,
val yanked: Boolean,
val features: HashMap<String, List<String>>
)
private fun crateFromJson(json: String, mapper: ObjectMapper): CargoRegistryCrateVersion {
val parsedVersion = mapper.readValue<ParsedVersion>(json)
return CargoRegistryCrateVersion(
parsedVersion.vers,
parsedVersion.yanked,
parsedVersion.features.map { it.key }
)
}
| mit | 4eb6fbf74730417d092d773967dde17f | 35.25 | 122 | 0.619443 | 4.892299 | false | false | false | false |
MGaetan89/Tetrinet | app/src/main/kotlin/io/tetrinet/MainActivity.kt | 1 | 1312 | package io.tetrinet
import android.app.Activity
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.widget.TextView
import io.tetrinet.model.Tetrimino
import io.tetrinet.view.TetrisView
import kotlin.properties.Delegates
class MainActivity : Activity(), TetrisView.TetrisEventListener {
private var lines: TextView? = null
private var nextTetrimino: TextView? = null
private var totalRemovedLines by Delegates.observable(0) { _, _, newValue ->
this.lines?.text = this.resources.getQuantityString(R.plurals.lines, newValue, newValue)
}
override fun onGameOver() {
this.totalRemovedLines = 0
}
override fun onLinesRemoved(count: Int) {
this.totalRemovedLines += count
}
override fun onNextTetriminoChanged(nextTetrimino: Tetrimino) {
this.nextTetrimino?.let {
it.text = nextTetrimino.name
it.setTextColor(ContextCompat.getColor(this, nextTetrimino.color))
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
this.setContentView(R.layout.activity_main)
this.lines = this.findViewById(R.id.lines) as TextView
this.nextTetrimino = this.findViewById(R.id.next) as TextView
val tetris = this.findViewById(R.id.tetris) as TetrisView
tetris.eventListener = this
this.totalRemovedLines = 0
}
}
| apache-2.0 | 33d00632821835c275ae278e72b52437 | 27.521739 | 90 | 0.776677 | 3.27182 | false | false | false | false |
androidx/androidx | work/work-lint/src/main/java/androidx/work/lint/RxWorkerSetProgressDetector.kt | 3 | 2879 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("UnstableApiUsage")
package androidx.work.lint
import com.android.tools.lint.detector.api.Category
import com.android.tools.lint.detector.api.Detector
import com.android.tools.lint.detector.api.Implementation
import com.android.tools.lint.detector.api.Issue
import com.android.tools.lint.detector.api.JavaContext
import com.android.tools.lint.detector.api.LintFix
import com.android.tools.lint.detector.api.Scope
import com.android.tools.lint.detector.api.Severity
import com.android.tools.lint.detector.api.SourceCodeScanner
import com.intellij.psi.PsiMethod
import org.jetbrains.uast.UCallExpression
import java.util.EnumSet
class RxWorkerSetProgressDetector : Detector(), SourceCodeScanner {
companion object {
private const val SET_COMPLETABLE_PROGRESS = "setCompletableProgress"
private const val DESCRIPTION =
"`setProgress` is deprecated. Use `$SET_COMPLETABLE_PROGRESS` instead."
val ISSUE = Issue.create(
id = "UseRxSetProgress2",
briefDescription = DESCRIPTION,
explanation = """
Use `$SET_COMPLETABLE_PROGRESS(...)` instead of `setProgress(...) in `RxWorker`.
""",
androidSpecific = true,
category = Category.CORRECTNESS,
severity = Severity.FATAL,
implementation = Implementation(
RxWorkerSetProgressDetector::class.java,
EnumSet.of(Scope.JAVA_FILE)
)
)
}
override fun getApplicableMethodNames(): List<String> = listOf("setProgress")
override fun visitMethodCall(context: JavaContext, node: UCallExpression, method: PsiMethod) {
if (context.evaluator.isMemberInClass(method, "androidx.work.RxWorker")) {
val lintFix = LintFix.create()
.name("Use $SET_COMPLETABLE_PROGRESS instead")
.replace()
.text(method.name)
.with(SET_COMPLETABLE_PROGRESS)
.independent(true)
.build()
context.report(
issue = ISSUE,
location = context.getLocation(node),
message = DESCRIPTION,
quickfixData = lintFix
)
}
}
}
| apache-2.0 | 55b585c8ce5c769b7874a7e455943ecd | 36.38961 | 98 | 0.664119 | 4.591707 | false | false | false | false |
androidx/androidx | compose/material3/material3/src/androidMain/kotlin/androidx/compose/material3/AndroidAlertDialog.android.kt | 3 | 6872 | /*
* 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.compose.material3
import androidx.compose.material3.tokens.DialogTokens
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.semantics.paneTitle
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
/**
* <a href="https://m3.material.io/components/dialogs/overview" class="external" target="_blank">Material Design basic dialog</a>.
*
* Dialogs provide important prompts in a user flow. They can require an action, communicate
* information, or help users accomplish a task.
*
* 
*
* The dialog will position its buttons, typically [TextButton]s, based on the available space.
* By default it will try to place them horizontally next to each other and fallback to horizontal
* placement if not enough space is available.
*
* Simple usage:
* @sample androidx.compose.material3.samples.AlertDialogSample
*
* Usage with a "Hero" icon:
* @sample androidx.compose.material3.samples.AlertDialogWithIconSample
*
* @param onDismissRequest called when the user tries to dismiss the Dialog by clicking outside
* or pressing the back button. This is not called when the dismiss button is clicked.
* @param confirmButton button which is meant to confirm a proposed action, thus resolving what
* triggered the dialog. The dialog does not set up any events for this button so they need to be
* set up by the caller.
* @param modifier the [Modifier] to be applied to this dialog
* @param dismissButton button which is meant to dismiss the dialog. The dialog does not set up any
* events for this button so they need to be set up by the caller.
* @param icon optional icon that will appear above the [title] or above the [text], in case a
* title was not provided.
* @param title title which should specify the purpose of the dialog. The title is not mandatory,
* because there may be sufficient information inside the [text].
* @param text text which presents the details regarding the dialog's purpose.
* @param shape defines the shape of this dialog's container
* @param containerColor the color used for the background of this dialog. Use [Color.Transparent]
* to have no color.
* @param iconContentColor the content color used for the icon.
* @param titleContentColor the content color used for the title.
* @param textContentColor the content color used for the text.
* @param tonalElevation when [containerColor] is [ColorScheme.surface], a translucent primary color
* overlay is applied on top of the container. A higher tonal elevation value will result in a
* darker color in light theme and lighter color in dark theme. See also: [Surface].
* @param properties typically platform specific properties to further configure the dialog.
*/
@Composable
fun AlertDialog(
onDismissRequest: () -> Unit,
confirmButton: @Composable () -> Unit,
modifier: Modifier = Modifier,
dismissButton: @Composable (() -> Unit)? = null,
icon: @Composable (() -> Unit)? = null,
title: @Composable (() -> Unit)? = null,
text: @Composable (() -> Unit)? = null,
shape: Shape = AlertDialogDefaults.shape,
containerColor: Color = AlertDialogDefaults.containerColor,
iconContentColor: Color = AlertDialogDefaults.iconContentColor,
titleContentColor: Color = AlertDialogDefaults.titleContentColor,
textContentColor: Color = AlertDialogDefaults.textContentColor,
tonalElevation: Dp = AlertDialogDefaults.TonalElevation,
properties: DialogProperties = DialogProperties()
) {
Dialog(
onDismissRequest = onDismissRequest,
properties = properties
) {
val dialogPaneDescription = getString(Strings.Dialog)
AlertDialogContent(
buttons = {
AlertDialogFlowRow(
mainAxisSpacing = ButtonsMainAxisSpacing,
crossAxisSpacing = ButtonsCrossAxisSpacing
) {
dismissButton?.invoke()
confirmButton()
}
},
modifier = modifier.then(Modifier
.semantics { paneTitle = dialogPaneDescription }
),
icon = icon,
title = title,
text = text,
shape = shape,
containerColor = containerColor,
tonalElevation = tonalElevation,
// Note that a button content color is provided here from the dialog's token, but in
// most cases, TextButtons should be used for dismiss and confirm buttons.
// TextButtons will not consume this provided content color value, and will used their
// own defined or default colors.
buttonContentColor = DialogTokens.ActionLabelTextColor.toColor(),
iconContentColor = iconContentColor,
titleContentColor = titleContentColor,
textContentColor = textContentColor,
)
}
}
/**
* Contains default values used for [AlertDialog]
*/
object AlertDialogDefaults {
/** The default shape for alert dialogs */
val shape: Shape @Composable get() = DialogTokens.ContainerShape.toShape()
/** The default container color for alert dialogs */
val containerColor: Color @Composable get() = DialogTokens.ContainerColor.toColor()
/** The default icon color for alert dialogs */
val iconContentColor: Color @Composable get() = DialogTokens.IconColor.toColor()
/** The default title color for alert dialogs */
val titleContentColor: Color @Composable get() = DialogTokens.HeadlineColor.toColor()
/** The default text color for alert dialogs */
val textContentColor: Color @Composable get() = DialogTokens.SupportingTextColor.toColor()
/** The default tonal elevation for alert dialogs */
val TonalElevation: Dp = DialogTokens.ContainerElevation
}
private val ButtonsMainAxisSpacing = 8.dp
private val ButtonsCrossAxisSpacing = 12.dp
| apache-2.0 | aa701e79dad31ca1fecd731e9351470a | 44.813333 | 130 | 0.71915 | 4.762301 | false | false | false | false |
androidx/androidx | external/paparazzi/paparazzi/src/test/java/app/cash/paparazzi/internal/parsers/InMemoryParserTest.kt | 3 | 3645 | package app.cash.paparazzi.internal.parsers
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
import org.xmlpull.v1.XmlPullParserException
class InMemoryParserTest {
@Test
fun parse() {
val root = parseResourceTree("plus_sign.xml")
val parser = RealInMemoryParser(root)
assertThat(parser.name).isNull() // START_DOCUMENT
assertThat(parser.depth).isEqualTo(0)
parser.next() // START_TAG = "vector"
assertThat(parser.name).isEqualTo(VECTOR_TAG_NAME)
assertThat(parser.depth).isEqualTo(1)
assertThat(parser.attributeCount).isEqualTo(4)
assertThat(parser.getAttributeName(0)).isEqualTo("height")
assertThat(parser.getAttributeName(1)).isEqualTo("viewportHeight")
assertThat(parser.getAttributeName(2)).isEqualTo("viewportWidth")
assertThat(parser.getAttributeName(3)).isEqualTo("width")
assertThat(parser.getAttributeNamespace(0)).isEqualTo(ANDROID_NAMESPACE)
assertThat(parser.getAttributeNamespace(1)).isEqualTo(ANDROID_NAMESPACE)
assertThat(parser.getAttributeNamespace(2)).isEqualTo(ANDROID_NAMESPACE)
assertThat(parser.getAttributeNamespace(3)).isEqualTo(ANDROID_NAMESPACE)
assertThat(parser.getAttributePrefix(0)).isEqualTo(ANDROID_PREFIX)
assertThat(parser.getAttributePrefix(1)).isEqualTo(ANDROID_PREFIX)
assertThat(parser.getAttributePrefix(2)).isEqualTo(ANDROID_PREFIX)
assertThat(parser.getAttributePrefix(3)).isEqualTo(ANDROID_PREFIX)
assertThat(parser.getAttributeValue(0)).isEqualTo("24dp")
assertThat(parser.getAttributeValue(1)).isEqualTo("40")
assertThat(parser.getAttributeValue(2)).isEqualTo("40")
assertThat(parser.getAttributeValue(3)).isEqualTo("24dp")
parser.next() // START_TAG = "path"
assertThat(parser.name).isEqualTo(PATH_TAG_NAME)
assertThat(parser.depth).isEqualTo(2)
assertThat(parser.attributeCount).isEqualTo(2)
assertThat(parser.getAttributeName(0)).isEqualTo(FILL_COLOR_ATTR_NAME)
assertThat(parser.getAttributeName(1)).isEqualTo(PATH_DATA_ATTR_NAME)
assertThat(parser.getAttributeNamespace(0)).isEqualTo(ANDROID_NAMESPACE)
assertThat(parser.getAttributeNamespace(1)).isEqualTo(ANDROID_NAMESPACE)
assertThat(parser.getAttributePrefix(0)).isEqualTo(ANDROID_PREFIX)
assertThat(parser.getAttributePrefix(1)).isEqualTo(ANDROID_PREFIX)
assertThat(parser.getAttributeValue(0)).isEqualTo("#999999")
assertThat(parser.getAttributeValue(1)).isNotNull // pathData
parser.next() // END_TAG = "path"
assertThat(parser.name).isEqualTo(PATH_TAG_NAME)
assertThat(parser.depth).isEqualTo(2)
parser.next() // END_TAG = "vector"
assertThat(parser.name).isEqualTo(VECTOR_TAG_NAME)
assertThat(parser.depth).isEqualTo(1)
parser.next() // END_DOCUMENT
assertThat(parser.name).isNull() // START_DOCUMENT
assertThat(parser.depth).isEqualTo(0)
try {
parser.next()
} catch (expected: XmlPullParserException) {
}
}
private fun parseResourceTree(resourceId: String): TagSnapshot {
val resourceInputStream = javaClass.classLoader.getResourceAsStream(resourceId)!!
return ResourceParser(resourceInputStream).createTagSnapshot()
}
class RealInMemoryParser(private val root: TagSnapshot) : InMemoryParser() {
override fun rootTag(): TagSnapshot = root
}
companion object {
const val ANDROID_NAMESPACE = "http://schemas.android.com/apk/res/android"
const val ANDROID_PREFIX = "android"
const val VECTOR_TAG_NAME = "vector"
const val PATH_TAG_NAME = "path"
const val PATH_DATA_ATTR_NAME = "pathData"
const val FILL_COLOR_ATTR_NAME = "fillColor"
}
}
| apache-2.0 | 57d101a7a06a7cbd0a91c47100a446b1 | 36.193878 | 85 | 0.747599 | 4.209007 | false | false | false | false |
ealva-com/ealvalog | ealvalog-log4j/src/main/java/com/ealva/ealvalog/log4j/LogRecordEvent.kt | 1 | 6115 | /*
* Copyright 2017 Eric A. Snell
*
* This file is part of eAlvaLog.
*
* 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.ealva.ealvalog.log4j
import com.ealva.ealvalog.LogEntry
import com.ealva.ealvalog.LogLevel
import com.ealva.ealvalog.Marker
import com.ealva.ealvalog.core.ExtLogRecord
import org.apache.logging.log4j.Level
import org.apache.logging.log4j.ThreadContext
import org.apache.logging.log4j.core.LogEvent
import org.apache.logging.log4j.core.impl.ThrowableProxy
import org.apache.logging.log4j.core.time.Instant
import org.apache.logging.log4j.core.time.MutableInstant
import org.apache.logging.log4j.message.Message
import org.apache.logging.log4j.message.ReusableMessageFactory
import org.apache.logging.log4j.util.ReadOnlyStringMap
/**
* Created by Eric A. Snell on 8/29/18.
*/
class LogRecordEvent(logEntry: LogEntry?) : ExtLogRecord(logEntry) {
@field:Transient private val contextData = ReadOnlyStringMapAdapter()
@field:Transient private val contextStack = ContextStackAdapter()
override fun reserve(): LogRecordEvent {
super.reserve()
return this
}
val logEvent: LogEvent = object : LogEvent {
override fun getLevel(): Level {
return logLevel.log4jLevel
}
/**
* We are obtaining a thread local [org.apache.logging.log4j.message.ReusableSimpleMessage] or
* [org.apache.logging.log4j.message.ParameterizedMessage] from the factory, so any client
* should not use the returned [Message] past the lifetime of this LogRecordEvent.
*/
override fun getMessage(): Message {
return if (parameterCount == 0) {
messageFactory.newMessage([email protected])
} else {
messageFactory.newMessage([email protected], *parameters)
}
}
override fun getThreadName(): String? {
return [email protected]
}
override fun getMarker(): org.apache.logging.log4j.Marker? {
return Log4jMarkerFactory.asLog4jMarker([email protected])
}
override fun getInstant(): Instant {
return MutableInstant().apply { initFromEpochMilli(millis, 0) }
}
override fun getSource(): StackTraceElement? {
return location
}
override fun getNanoTime(): Long {
return [email protected]
}
/**
* We have either already included the location at the point this event was "created" or
* it is not needed. We don't want downstream components trying to determine stack
* position of the original log call (client code)
*/
override fun isIncludeLocation(): Boolean {
return false
}
@Deprecated(
"Use getContextData()",
ReplaceWith("getContextData()", "org.apache.logging.log4j.util.ReadOnlyStringMap")
)
override fun getContextMap(): Map<String, String> {
return contextData.toMap()
}
override fun getLoggerName(): String? {
return [email protected]
}
override fun getThrown(): Throwable? {
return [email protected]
}
override fun setEndOfBatch(endOfBatch: Boolean) {}
override fun toImmutable(): LogEvent {
return LogRecordEvent(this@LogRecordEvent).logEvent
}
override fun getTimeMillis(): Long {
return millis
}
override fun getThreadPriority(): Int {
return [email protected]
}
override fun getLoggerFqcn(): String {
return [email protected]
}
override fun getContextData(): ReadOnlyStringMap {
return [email protected] { map = mdc ?: emptyMap() }
}
override fun getContextStack(): ThreadContext.ContextStack {
return [email protected] {
list = ndc?.toMutableList() ?: mutableListOf()
}
}
override fun getThrownProxy(): ThrowableProxy? {
[email protected]?.let { thrown ->
return ThrowableProxy(thrown)
} ?: return null
}
override fun getThreadId(): Long {
return [email protected]()
}
override fun isEndOfBatch(): Boolean {
return false
}
override fun setIncludeLocation(locationRequired: Boolean) {}
}
companion object {
/**
* Returns [entry] if it is already a LogRecordEvent, else creates a new LogRecordEvent.
* The only time a new LogRecordEvent will be created is if a client logs a [LogEntry] it
* did not originally obtain from the [com.ealva.ealvalog.Logger] to which it is logging.
* See [com.ealva.ealvalog.Logger.getLogEntry]
*/
fun fromLogEntry(entry: LogEntry): LogRecordEvent {
return entry as? LogRecordEvent ?: LogRecordEvent(entry)
}
private val messageFactory = ReusableMessageFactory.INSTANCE
private val threadLocal = ThreadLocal<LogRecordEvent>().apply { set(LogRecordEvent(null)) }
fun get(
loggerFQCN: String,
logLevel: LogLevel,
name: String,
marker: Marker?,
throwable: Throwable?,
mdc: Map<String, String>?,
ndc: List<String>?
): LogRecordEvent {
return reserveRecord().apply {
setLogLevel(logLevel) // sets LogLevel and java.util.logging.Level
this.marker = marker
setThrown(throwable)
setLoggerName(name)
setLoggerFQCN(loggerFQCN)
setMdc(mdc)
setNdc(ndc)
}
}
private fun reserveRecord(): LogRecordEvent {
val record = threadLocal.get()
return if (record.isReserved) {
LogRecordEvent(null).reserve()
} else {
record.reserve()
}
}
}
} | apache-2.0 | 5e0d05b25ce7b6060b1c7de92c0c464a | 29.733668 | 98 | 0.693704 | 4.185489 | false | false | false | false |
IRA-Team/VKPlayer | app/src/main/java/com/irateam/vkplayer/adapter/CurrentPlaylistRecyclerAdapter.kt | 1 | 6186 | /*
* Copyright (C) 2016 IRA-Team
*
* 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.irateam.vkplayer.adapter
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.ViewGroup
import com.irateam.vkplayer.R
import com.irateam.vkplayer.adapter.event.BaseAudioAdapterEvent
import com.irateam.vkplayer.event.Event
import com.irateam.vkplayer.model.Audio
import com.irateam.vkplayer.model.Header
import com.irateam.vkplayer.player.*
import com.irateam.vkplayer.ui.viewholder.AudioViewHolder
import com.irateam.vkplayer.ui.viewholder.HeaderViewHolder
import com.irateam.vkplayer.util.extension.isNullOrEmpty
import com.irateam.vkplayer.util.extension.v
import org.greenrobot.eventbus.Subscribe
import java.util.*
class CurrentPlaylistRecyclerAdapter : BaseAudioRecyclerAdapter<Audio, RecyclerView.ViewHolder> {
override val searchDelegate: LocalSearchDelegate<Audio> = LocalSearchDelegate(this)
override var audios: List<Audio> = emptyList()
override var checkedAudios: HashSet<Audio> = HashSet()
private var data: ArrayList<Any>
constructor() {
this.audios = Player.playlist
this.data = buildRecyclerData()
}
private fun buildRecyclerData(): ArrayList<Any> {
val data = ArrayList<Any>()
val playNext = Player.playNext
if (playNext.isNotEmpty()) {
data.add(Header("Play next"))
data.addAll(playNext)
data.add(Header("Playlist"))
}
val playlist = Player.playlist
data.addAll(playlist)
return data
}
override fun getItemViewType(position: Int) = when (data[position]) {
is Header -> TYPE_HEADER
is Audio -> TYPE_AUDIO
else -> throw IllegalStateException("Unsupported data type")
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
val inflater = LayoutInflater.from(parent.context)
return when (viewType) {
TYPE_HEADER -> {
HeaderViewHolder(inflater.inflate(R.layout.item_header, parent, false))
}
TYPE_AUDIO -> {
AudioViewHolder(inflater.inflate(R.layout.item_audio, parent, false))
}
else -> throw IllegalStateException("Unsupported view type")
}
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder,
position: Int,
payload: MutableList<Any>?) {
when (holder) {
is AudioViewHolder -> {
val audio = data[position] as Audio
if (payload.isNullOrEmpty()) {
configureAudio(holder, audio)
configurePlayingState(holder, audio)
if (isSortMode()) {
configureSortMode(holder)
} else {
configureCheckedState(holder, audio)
}
} else {
payload?.let {
val events = it.filterIsInstance<Event>()
dispatchEvents(holder, audio, events)
}
}
}
is HeaderViewHolder -> {
val header = data[position] as Header
holder.setHeader(header)
}
}
}
private fun dispatchEvents(holder: AudioViewHolder,
audio: Audio,
events: Collection<Event>) = events.forEach {
when (it) {
BaseAudioAdapterEvent.ItemUncheckedEvent -> {
holder.setChecked(checked = false, shouldAnimate = true)
}
BaseAudioAdapterEvent.SortModeStarted -> {
holder.setSorting(sorting = true, shouldAnimate = true)
setupDragTouchListener(holder)
}
BaseAudioAdapterEvent.SortModeFinished -> {
holder.setSorting(sorting = false, shouldAnimate = true)
setupCheckedClickListener(holder, audio)
}
}
}
private fun configureAudio(holder: AudioViewHolder, audio: Audio) {
holder.setAudio(audio)
if (searchDelegate.isSearching) {
holder.setQuery(searchDelegate.query)
}
holder.contentHolder.setOnClickListener {
Player.play(audios, audio)
}
}
@Subscribe
fun onPlaylistPlayNextEvent(e: PlaylistPlayNextEvent) {
val from = e.playNextPosition + 1
val playNext = data[from] // +1 cause header
data.removeAt(from)
val to = e.playNextSize + e.playlistPosition + 3
data.add(to, playNext) // +3 cause of 2 headers and new position
notifyItemMoved(from, to)
//Remove 2 headers if playNext is empty now
if (e.playNextSize == 0) {
data.removeAt(0)
removeViewByPosition(0)
data.removeAt(0)
removeViewByPosition(0)
}
}
@Subscribe
fun onPlaylistChangedEvent(e: PlaylistChangedEvent) {
val newData = buildRecyclerData()
newData.forEachIndexed { index, item ->
val from = data.indexOf(item)
data.removeAt(from)
data.add(index, item)
notifyItemMoved(from, index)
}
scrollToTop()
}
override fun getItemCount(): Int {
return data.size
}
companion object {
val TAG: String = CurrentPlaylistRecyclerAdapter::class.java.name
private val TYPE_HEADER = 1
private val TYPE_AUDIO = 2
}
} | apache-2.0 | 7f1bc17febade62f3c0b92e354a2ecb9 | 31.223958 | 97 | 0.606693 | 4.840376 | false | false | false | false |
minecraft-dev/MinecraftDev | src/main/kotlin/platform/mixin/util/LocalVariables.kt | 1 | 37294 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2022 minecraft-dev
*
* MIT License
*/
/*
* This file contains substantial amounts of code from Mixin, licensed under the MIT License (MIT).
* See https://github.com/SpongePowered/Mixin/blob/master/src/main/java/org/spongepowered/asm/util/Locals.java
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.demonwav.mcdev.platform.mixin.util
import com.demonwav.mcdev.facet.MinecraftFacet
import com.demonwav.mcdev.platform.mixin.MixinModuleType
import com.demonwav.mcdev.util.SemanticVersion
import com.demonwav.mcdev.util.cached
import com.demonwav.mcdev.util.mapToArray
import com.demonwav.mcdev.util.psiType
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Key
import com.intellij.psi.CommonClassNames
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.JavaRecursiveElementVisitor
import com.intellij.psi.PsiArrayType
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiForeachStatement
import com.intellij.psi.PsiLambdaExpression
import com.intellij.psi.PsiMethod
import com.intellij.psi.PsiModifier
import com.intellij.psi.PsiStatement
import com.intellij.psi.PsiType
import com.intellij.psi.PsiVariable
import com.intellij.psi.controlFlow.ControlFlow
import com.intellij.psi.controlFlow.ControlFlowFactory
import com.intellij.psi.controlFlow.ControlFlowInstructionVisitor
import com.intellij.psi.controlFlow.ControlFlowOptions
import com.intellij.psi.controlFlow.Instruction
import com.intellij.psi.controlFlow.LocalsControlFlowPolicy
import com.intellij.psi.controlFlow.WriteVariableInstruction
import com.intellij.psi.scope.util.PsiScopesUtil
import com.intellij.psi.util.PsiModificationTracker
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.util.parentOfType
import kotlin.math.min
import org.objectweb.asm.Opcodes
import org.objectweb.asm.Type
import org.objectweb.asm.tree.AbstractInsnNode
import org.objectweb.asm.tree.ClassNode
import org.objectweb.asm.tree.FrameNode
import org.objectweb.asm.tree.InsnList
import org.objectweb.asm.tree.LabelNode
import org.objectweb.asm.tree.LineNumberNode
import org.objectweb.asm.tree.MethodNode
import org.objectweb.asm.tree.VarInsnNode
import org.objectweb.asm.tree.analysis.BasicValue
object LocalVariables {
private val LOCAL_INDEX_KEY = Key<Int>("mcdev.local_index")
/**
* Guesses the local variable index of the given variable, or of implicit locals at the given element.
* Only valid after [guessLocalsAt] has been called.
*/
fun guessLocalVariableIndex(element: PsiElement): Int? {
return element.getUserData(LOCAL_INDEX_KEY)
}
fun guessLocalsAt(element: PsiElement, argsOnly: Boolean, start: Boolean): List<SourceLocalVariable> {
val method = PsiTreeUtil.getParentOfType(element, PsiMethod::class.java, PsiLambdaExpression::class.java)
?: return emptyList()
val actualMethod = method.parentOfType<PsiMethod>(withSelf = true) ?: return emptyList()
val args = mutableListOf<SourceLocalVariable>()
var argsIndex = 0
if (!actualMethod.hasModifierProperty(PsiModifier.STATIC)) {
args += SourceLocalVariable("this", actualMethod.containingClass?.psiType ?: return emptyList(), 0)
argsIndex++
}
for (parameter in method.parameterList.parameters) {
val mixinName = if (argsOnly) "var$argsIndex" else parameter.name
args += SourceLocalVariable(parameter.name, parameter.type, argsIndex, mixinName = mixinName)
argsIndex++
if (parameter.isDoubleSlot) {
argsIndex++
}
}
if (argsOnly) {
return args
}
val body = method.body ?: return args
val controlFlow = ControlFlowFactory.getControlFlow(
body,
LocalsControlFlowPolicy(body),
ControlFlowOptions.NO_CONST_EVALUATE
)
val allLocalVariables = guessAllLocalVariables(argsIndex, body, controlFlow)
val elementOffset = if (start) controlFlow.getStartOffset(element) else controlFlow.getEndOffset(element)
return args + (allLocalVariables.getOrNull(elementOffset) ?: emptyList())
}
private fun guessAllLocalVariables(
argsSize: Int,
body: PsiElement,
controlFlow: ControlFlow
): Array<List<SourceLocalVariable>> {
return body.cached(PsiModificationTracker.MODIFICATION_COUNT) {
guessAllLocalVariablesUncached(argsSize, body, controlFlow)
}
}
private fun guessAllLocalVariablesUncached(
argsSize: Int,
body: PsiElement,
controlFlow: ControlFlow
): Array<List<SourceLocalVariable>> {
val method = body.parent
val allLocalVariables = getAllLocalVariables(body)
for (variable in allLocalVariables) {
var localIndex = argsSize
// gets all local variable declarations in scope at the declaration of variable
PsiScopesUtil.treeWalkUp(
{ elem, _ ->
localIndex += getLocalVariableSize(elem)
true
},
variable,
method
)
// add on other implicit declarations in scope
for (parent in generateSequence(variable.parent, PsiElement::getParent).takeWhile { it != method }) {
localIndex += getLocalVariableSize(parent)
}
variable.putUserData(LOCAL_INDEX_KEY, localIndex)
}
// take into account implicit locals for certain constructs (e.g. foreach loops)
val extraVariables = mutableMapOf<Int, MutableList<SourceLocalVariable>>()
for (variable in allLocalVariables) {
val extraVars = when (variable) {
is PsiVariable -> continue
is PsiForeachStatement -> variable.getExtraLocals()
else -> continue
}
val enclosingStatement = variable.parentOfType<PsiStatement>(withSelf = true) ?: continue
extraVariables.getOrPut(controlFlow.getStartOffset(enclosingStatement)) { mutableListOf() } += extraVars
}
// compute the local variables that are definitely initialized and not overwritten at each offset
class MyVisitor : ControlFlowInstructionVisitor() {
val locals = arrayOfNulls<Array<SourceLocalVariable?>>(controlFlow.size + 1)
val instructionQueue = ArrayDeque<Int>()
override fun visitWriteVariableInstruction(
instruction: WriteVariableInstruction,
offset: Int,
nextOffset: Int
) {
if (instruction.variable in allLocalVariables) {
val localIndex = instruction.variable.getUserData(LOCAL_INDEX_KEY)!!
var localsHere = this.locals[offset]
?: arrayOfNulls<SourceLocalVariable>(localIndex + 1).also { this.locals[offset] = it }
if (localIndex >= localsHere.size) {
localsHere = localsHere.copyOf(localIndex + 1)
}
val name = instruction.variable.name ?: return
localsHere[localIndex] = SourceLocalVariable(name, instruction.variable.type, localIndex)
if (instruction.variable.isDoubleSlot && localIndex + 1 < localsHere.size) {
localsHere[localIndex + 1] = null
}
this.locals[offset] = localsHere
}
visitInstruction(instruction, offset, nextOffset)
}
override fun visitInstruction(instruction: Instruction, offset: Int, nextOffset: Int) {
val extraVars = extraVariables[offset]
if (extraVars != null) {
for (variable in extraVars) {
val localsHere = this.locals[offset]
?: arrayOfNulls<SourceLocalVariable>(variable.index + 1).also { this.locals[offset] = it }
localsHere[variable.index] = variable
if (variable.type == PsiType.LONG || variable.type == PsiType.DOUBLE) {
if (variable.index + 1 < localsHere.size) {
localsHere[variable.index + 1] = null
}
}
}
}
for (i in 0 until instruction.nNext()) {
visitEdge(offset, instruction.getNext(offset, i))
}
}
private fun visitEdge(offset: Int, nextOffset: Int) {
val localsHere = this.locals[offset] ?: emptyArray()
var changed = false
val nextLocals = this.locals[nextOffset]
if (nextLocals == null) {
this.locals[nextOffset] = localsHere.clone()
changed = true
} else {
for (i in localsHere.size until nextLocals.size) {
if (nextLocals[i] != null) {
nextLocals[i] = null
changed = true
}
}
for (i in 0 until min(localsHere.size, nextLocals.size)) {
if (nextLocals[i] != localsHere[i]) {
if (nextLocals[i] != null) {
nextLocals[i] = null
changed = true
}
}
}
}
if (changed) {
instructionQueue.add(nextOffset)
}
}
}
// walk the control flow graph
val visitor = MyVisitor()
visitor.instructionQueue.add(0)
while (visitor.instructionQueue.isNotEmpty()) {
val offset = visitor.instructionQueue.removeFirst()
val insn = controlFlow.instructions.getOrNull(offset) ?: continue
insn.accept(visitor, offset, offset + 1)
}
return visitor.locals.mapToArray { it?.filterNotNull() ?: emptyList() }
}
private fun getAllLocalVariables(body: PsiElement): List<PsiElement> {
val locals = mutableListOf<PsiElement>()
body.accept(
object : JavaRecursiveElementVisitor() {
override fun visitVariable(variable: PsiVariable) {
locals += variable
super.visitVariable(variable)
}
override fun visitForeachStatement(statement: PsiForeachStatement) {
locals += statement
super.visitForeachStatement(statement)
}
override fun visitClass(aClass: PsiClass?) {
// don't recurse into classes
}
override fun visitMethod(method: PsiMethod?) {
// don't recurse into methods
}
override fun visitLambdaExpression(expression: PsiLambdaExpression?) {
// don't recurse into lambdas
}
}
)
return locals
}
fun getLocalVariableSize(element: PsiElement): Int {
return when (element) {
// longs and doubles take two slots
is PsiVariable -> if (element.isDoubleSlot) 2 else 1
// arrays have copy of array, length and index variables, iterables have the iterator variable
is PsiForeachStatement -> if (element.iterationParameter.type is PsiArrayType) 3 else 1
else -> 0
}
}
private val PsiVariable.isDoubleSlot: Boolean
get() = type == PsiType.DOUBLE || type == PsiType.LONG
private fun PsiForeachStatement.getExtraLocals(): List<SourceLocalVariable> {
val localIndex = getUserData(LOCAL_INDEX_KEY)!!
val iterable = iteratedValue ?: return emptyList()
val type = iterable.type
if (type is PsiArrayType) {
return listOf(
// array
SourceLocalVariable(
"var$localIndex",
type,
localIndex,
implicitLoadCountBefore = 1,
implicitStoreCountBefore = 1
),
// length
SourceLocalVariable(
"var${localIndex + 1}",
PsiType.INT,
localIndex + 1,
implicitStoreCountBefore = 1,
implicitLoadCountAfter = 1
),
// index
SourceLocalVariable(
"var${localIndex + 2}",
PsiType.INT,
localIndex + 2,
implicitStoreCountBefore = 1,
implicitLoadCountBefore = 1,
implicitLoadCountAfter = 1
)
)
} else {
val iteratorType = JavaPsiFacade.getElementFactory(project)
.createTypeByFQClassName(
CommonClassNames.JAVA_UTIL_ITERATOR,
resolveScope
)
return listOf(
// iterator
SourceLocalVariable(
"var$localIndex",
iteratorType,
localIndex,
implicitStoreCountBefore = 1,
implicitLoadCountBefore = 1
)
)
}
}
fun getLocals(
module: Module,
classNode: ClassNode,
method: MethodNode,
node: AbstractInsnNode
): Array<LocalVariable?>? {
return getLocals(module.project, classNode, method, node, detectCurrentSettings(module))
}
private fun getLocals(
project: Project,
classNode: ClassNode,
method: MethodNode,
nodeArg: AbstractInsnNode,
settings: Settings
): Array<LocalVariable?>? {
return try {
doGetLocals(project, classNode, method, nodeArg, settings)
} catch (e: LocalAnalysisFailedException) {
null
}
}
private val resurrectLocalsChange = SemanticVersion.release(0, 8, 3)
private fun detectCurrentSettings(module: Module): Settings {
val mixinVersion = MinecraftFacet.getInstance(module, MixinModuleType)?.mixinVersion
?: throw LocalAnalysisFailedException()
return if (mixinVersion < resurrectLocalsChange) {
Settings.NO_RESURRECT
} else {
Settings.DEFAULT
}
}
private fun doGetLocals(
project: Project,
classNode: ClassNode,
method: MethodNode,
nodeArg: AbstractInsnNode,
settings: Settings
): Array<LocalVariable?> {
var node = nodeArg
for (i in 0 until 3) {
if (node !is LabelNode && node !is LineNumberNode) {
break
}
val nextNode = method.instructions.nextNode(node)
if (nextNode is FrameNode) { // Do not ffwd over frames
break
}
node = nextNode
}
val frames = method.instructions.iterator().asSequence().filterIsInstance<FrameNode>().toList()
val frame = arrayOfNulls<LocalVariable>(method.maxLocals)
var local = 0
var index = 0
// Initialise implicit "this" reference in non-static methods
if (!method.hasAccess(Opcodes.ACC_STATIC)) {
frame[local++] = LocalVariable("this", Type.getObjectType(classNode.name).toString(), null, null, null, 0)
}
// Initialise method arguments
for (argType in Type.getArgumentTypes(method.desc)) {
frame[local] = LocalVariable("arg" + index++, argType.toString(), null, null, null, local)
local += argType.size
}
val initialFrameSize = local
var frameSize = local
var frameIndex = -1
var lastFrameSize = local
var knownFrameSize = local
var storeInsn: VarInsnNode? = null
for (insn in method.instructions) {
// Tick the zombies
for (zombie in frame.asSequence().filterIsInstance<ZombieLocalVariable>()) {
zombie.lifetime++
if (insn is FrameNode) {
zombie.frames++
}
}
if (storeInsn != null) {
val storedLocal = getLocalVariableAt(project, classNode, method, insn, storeInsn.`var`)
frame[storeInsn.`var`] = storedLocal
knownFrameSize = knownFrameSize.coerceAtLeast(storeInsn.`var` + 1)
if (storedLocal != null &&
storeInsn.`var` < method.maxLocals - 1 &&
storedLocal.desc != null &&
Type.getType(storedLocal.desc).size == 2
) {
frame[storeInsn.`var` + 1] = null // TOP
knownFrameSize = knownFrameSize.coerceAtLeast(storeInsn.`var` + 2)
if (settings.resurrectExposedOnStore) {
resurrect(frame, knownFrameSize, settings)
}
}
storeInsn = null
}
if (insn is FrameNode) {
fun handleFrame() {
frameIndex++
if (insn.type == Opcodes.F_SAME || insn.type == Opcodes.F_SAME1) {
return
}
val frameNodeSize = insn.computeFrameSize(initialFrameSize)
val frameData = frames.getOrNull(frameIndex)
if (frameData != null) {
if (frameData.type == Opcodes.F_FULL) {
frameSize = frameNodeSize.coerceAtLeast(initialFrameSize)
lastFrameSize = frameSize
knownFrameSize = lastFrameSize
} else {
frameSize = getAdjustedFrameSize(
frameSize,
frameData.type,
frameData.computeFrameSize(initialFrameSize),
initialFrameSize
)
}
} else {
frameSize =
getAdjustedFrameSize(
frameSize,
insn.type,
frameNodeSize,
initialFrameSize
)
}
// Sanity check
if (frameSize < initialFrameSize) {
throw IllegalStateException(
"Locals entered an invalid state evaluating " +
"${classNode.name}::${method.name}${method.desc} at instruction " +
"${method.instructions.indexOf(insn)}. Initial frame size is" +
" $initialFrameSize, calculated a frame size of $frameSize"
)
}
if ((
(frameData == null && (insn.type == Opcodes.F_CHOP || insn.type == Opcodes.F_NEW)) ||
(frameData != null && frameData.type == Opcodes.F_CHOP)
)
) {
for (framePos in frameSize until frame.size) {
frame[framePos] = ZombieLocalVariable.of(frame[framePos], ZombieLocalVariable.CHOP)
}
lastFrameSize = frameSize
knownFrameSize = lastFrameSize
return
}
var framePos = if (insn.type == Opcodes.F_APPEND) lastFrameSize else 0
lastFrameSize = frameSize
// localPos tracks the location in the frame node's locals list, which doesn't leave space for TOP entries
var localPos = 0
while (framePos < frame.size) {
// Get the local at the current position in the FrameNode's locals list
val localType = if ((localPos < insn.local.size)) insn.local[localPos] else null
if (localType is String) { // String refers to a reference type
frame[framePos] =
getLocalVariableAt(
project,
classNode,
method,
method.instructions.indexOf(insn),
framePos
)
} else if (localType is Int) { // Integer refers to a primitive type or other marker
val isMarkerType = localType == Opcodes.UNINITIALIZED_THIS || localType == Opcodes.NULL
val is32bitValue = localType == Opcodes.INTEGER || localType == Opcodes.FLOAT
val is64bitValue = localType == Opcodes.DOUBLE || localType == Opcodes.LONG
if (localType == Opcodes.TOP) {
// Explicit TOP entries are pretty much always bogus, but depending on our resurrection
// strategy we may want to resurrect eligible zombies here. Real TOP entries are handled below
if (frame[framePos] is ZombieLocalVariable && settings.resurrectForBogusTop) {
val zombie = frame[framePos] as ZombieLocalVariable
if (zombie.type == ZombieLocalVariable.TRIM) {
frame[framePos] = zombie.ancestor
}
}
} else if (isMarkerType) {
frame[framePos] = null
} else if (is32bitValue || is64bitValue) {
frame[framePos] =
getLocalVariableAt(
project,
classNode,
method,
method.instructions.indexOf(insn),
framePos
)
if (is64bitValue) {
framePos++
frame[framePos] = null // TOP
}
} else {
throw IllegalStateException(
"Unrecognised locals opcode $localType in locals array at position" +
" $localPos in ${classNode.name}.${method.name}${method.desc}"
)
}
} else if (localType == null) {
if ((framePos >= initialFrameSize) && (framePos >= frameSize) && (frameSize > 0)) {
if (framePos < knownFrameSize) {
frame[framePos] = getLocalVariableAt(
project,
classNode,
method,
insn,
framePos
)
} else {
frame[framePos] = ZombieLocalVariable.of(frame[framePos], ZombieLocalVariable.TRIM)
}
}
} else if (localType is LabelNode) {
// Uninitialised
} else {
throw IllegalStateException(
"Invalid value $localType in locals array at position" +
" $localPos in ${classNode.name}.${method.name}${method.desc}"
)
}
framePos++
localPos++
}
}
handleFrame()
} else if (insn is VarInsnNode) {
val isLoad = insn.getOpcode() >= Opcodes.ILOAD && insn.getOpcode() <= Opcodes.SALOAD
if (isLoad) {
val loadedVar = getLocalVariableAt(project, classNode, method, insn, insn.`var`)
frame[insn.`var`] = loadedVar
val varSize = loadedVar?.desc?.let { Type.getType(it).size } ?: 1
knownFrameSize = (insn.`var` + varSize).coerceAtLeast(knownFrameSize)
if (settings.resurrectExposedOnLoad) {
resurrect(frame, knownFrameSize, settings)
}
} else {
// Update the LVT for the opcode AFTER this one, since we always want to know
// the frame state BEFORE the *current* instruction to match the contract of
// injection points
storeInsn = insn
}
}
if (insn === node) {
break
}
}
// Null out any "unknown" or mixin-provided locals
for (l in frame.indices) {
val variable = frame[l]
if (variable is ZombieLocalVariable) {
// preserve zombies where the frame node which culled them was immediately prior to
// the matched instruction, or *was itself* the matched instruction, the returned
// frame will contain the original node (the zombie ancestor)
frame[l] = if (variable.lifetime > 1) null else variable.ancestor
}
if (variable != null && variable.desc == null) {
frame[l] = null
}
}
return frame
}
private fun getAdjustedFrameSize(currentSize: Int, type: Int, size: Int, initialFrameSize: Int): Int {
return when (type) {
Opcodes.F_NEW, Opcodes.F_FULL -> size.coerceAtLeast(initialFrameSize)
Opcodes.F_APPEND -> currentSize + size
Opcodes.F_CHOP -> (size - currentSize).coerceAtLeast(initialFrameSize)
Opcodes.F_SAME, Opcodes.F_SAME1 -> currentSize
else -> currentSize
}
}
private fun resurrect(frame: Array<LocalVariable?>, knownFrameSize: Int, settings: Settings) {
for ((index, node) in frame.withIndex()) {
if (index >= knownFrameSize) {
break
}
if (node is ZombieLocalVariable && node.checkResurrect(settings)) {
frame[index] = node.ancestor
}
}
}
private fun FrameNode.computeFrameSize(initialFrameSize: Int): Int {
if (this.local == null) {
return initialFrameSize
}
var size = 0
for (local in this.local) {
size += if (local == Opcodes.DOUBLE || local == Opcodes.LONG) 2 else 1
}
return size.coerceAtLeast(initialFrameSize)
}
private fun getLocalVariableAt(
project: Project,
classNode: ClassNode,
method: MethodNode,
pos: AbstractInsnNode,
index: Int
): LocalVariable? {
return getLocalVariableAt(project, classNode, method, method.instructions.indexOf(pos), index)
}
private fun getLocalVariableAt(
project: Project,
classNode: ClassNode,
method: MethodNode,
pos: Int,
index: Int
): LocalVariable? {
var localVariableNode: LocalVariable? = null
var fallbackNode: LocalVariable? = null
for (local in method.getLocalVariableTable(project, classNode)) {
if (local.index != index) {
continue
}
if (local.isInRange(pos)) {
localVariableNode = local
} else if (localVariableNode == null) {
fallbackNode = local
}
}
if (localVariableNode == null && method.localVariables.isNotEmpty()) {
for (local in getGeneratedLocalVariableTable(project, classNode, method)) {
if (local.index == index && local.isInRange(pos)) {
localVariableNode = local
}
}
}
return localVariableNode ?: fallbackNode
}
private fun InsnList.nextNode(insn: AbstractInsnNode): AbstractInsnNode {
val index = indexOf(insn) + 1
if (index > 0 && index < size()) {
return get(index)
}
return insn
}
private fun MethodNode.getLocalVariableTable(project: Project, classNode: ClassNode): List<LocalVariable> {
if (localVariables.isEmpty()) {
return getGeneratedLocalVariableTable(project, classNode, this)
}
return localVariables.map {
LocalVariable(
it.name,
it.desc,
it.signature,
instructions.indexOf(it.start),
instructions.indexOf(it.end),
it.index
)
}
}
private fun getGeneratedLocalVariableTable(
project: Project,
classNode: ClassNode,
method: MethodNode
): List<LocalVariable> {
val frames = AsmDfaUtil.analyzeMethod(project, classNode, method) ?: throw LocalAnalysisFailedException()
// Record the original size of the method
val methodSize = method.instructions.size()
// List of LocalVariableNodes to return
val localVariables = mutableListOf<LocalVariable>()
// LocalVariableNodes for current frame
val localVars = arrayOfNulls<LocalVariable>(method.maxLocals)
// locals in previous frame, used to work out what changes between frames
val locals = arrayOfNulls<BasicValue>(method.maxLocals)
val lastKnownType = arrayOfNulls<String>(method.maxLocals)
// Traverse the frames and work out when locals begin and end
for (i in 0 until methodSize) {
val f = frames[i] ?: continue
for (j in 0 until f.locals) {
val local = f.getLocal(j)
if (local == null && locals[j] == null) {
continue
}
if (local != null && local == locals[j]) {
continue
}
if (local == null && locals[j] != null) {
val localVar = localVars[j]!!
localVariables.add(localVar)
localVar.end = i
localVars[j] = null
} else if (local != null) {
if (locals[j] != null) {
val localVar = localVars[j]!!
localVariables.add(localVar)
localVar.end = i
localVars[j] = null
}
var desc = lastKnownType[j]
val localType = local.type
if (localType != null) {
desc = if (localType.sort >= Type.ARRAY && localType.internalName == "null") {
"Ljava/lang/Object;"
} else {
localType.descriptor
}
}
localVars[j] = LocalVariable("var$j", desc, null, i, null, j)
if (desc != null) {
lastKnownType[j] = desc
}
}
locals[j] = local
}
}
// Reached the end of the method so flush all current locals and mark the end
for (k in localVars.indices) {
val localVar = localVars[k]
if (localVar != null) {
localVar.end = methodSize
localVariables.add(localVar)
}
}
return localVariables
}
data class Settings(
val choppedInsnThreshold: Int,
val trimmedInsnThreshold: Int,
val choppedFrameThreshold: Int,
val trimmedFrameThreshold: Int,
val resurrectExposedOnLoad: Boolean,
val resurrectExposedOnStore: Boolean,
val resurrectForBogusTop: Boolean
) {
companion object {
val NO_RESURRECT = Settings(
choppedInsnThreshold = 0,
choppedFrameThreshold = 0,
trimmedInsnThreshold = 0,
trimmedFrameThreshold = 0,
resurrectExposedOnLoad = false,
resurrectExposedOnStore = false,
resurrectForBogusTop = false
)
val DEFAULT = Settings(
choppedInsnThreshold = -1,
choppedFrameThreshold = 1,
trimmedInsnThreshold = -1,
trimmedFrameThreshold = -1,
resurrectExposedOnLoad = true,
resurrectExposedOnStore = true,
resurrectForBogusTop = true
)
}
}
data class SourceLocalVariable(
val name: String,
val type: PsiType,
val index: Int,
val mixinName: String = name,
val implicitLoadCountBefore: Int = 0,
val implicitLoadCountAfter: Int = 0,
val implicitStoreCountBefore: Int = 0,
val implicitStoreCountAfter: Int = 0
)
open class LocalVariable(
val name: String,
val desc: String?,
val signature: String?,
val start: Int?,
var end: Int?,
val index: Int
) {
fun isInRange(index: Int): Boolean {
val end = this.end
return (start == null || index >= start) && (end == null || index < end)
}
}
private class LocalAnalysisFailedException : Exception() {
override fun fillInStackTrace(): Throwable {
return this
}
}
private class ZombieLocalVariable private constructor(
val ancestor: LocalVariable,
val type: Char
) : LocalVariable(
ancestor.name,
ancestor.desc,
ancestor.signature,
ancestor.start,
ancestor.end,
ancestor.index
) {
var lifetime = 0
var frames = 0
fun checkResurrect(settings: Settings): Boolean {
val insnThreshold = if (type == CHOP) settings.choppedInsnThreshold else settings.trimmedInsnThreshold
if (insnThreshold > -1 && lifetime > insnThreshold) {
return false
}
val frameThreshold = if (type == CHOP) settings.choppedFrameThreshold else settings.trimmedFrameThreshold
return frameThreshold == -1 || frames <= frameThreshold
}
override fun toString(): String {
return String.format("Z(%s,%-2d)", type, lifetime)
}
companion object {
const val CHOP = 'C'
const val TRIM = 'X'
fun of(ancestor: LocalVariable?, type: Char): ZombieLocalVariable? {
return if (ancestor is ZombieLocalVariable) {
ancestor
} else {
ancestor?.let { ZombieLocalVariable(it, type) }
}
}
}
}
}
| mit | a79c2d8ff55f41edcf19367ad2b5bf1a | 40.117971 | 126 | 0.531346 | 5.405711 | false | false | false | false |
CruGlobal/android-gto-support | gto-support-androidx-fragment/src/main/kotlin/org/ccci/gto/android/common/androidx/fragment/app/BindingFragment.kt | 2 | 1927 | package org.ccci.gto.android.common.androidx.fragment.app
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.LayoutRes
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.viewbinding.ViewBinding
abstract class BindingFragment<B : ViewBinding> protected constructor(@LayoutRes private val contentLayoutId: Int) :
Fragment(contentLayoutId) {
protected constructor() : this(0)
private var binding: B? = null
// region Lifecycle
final override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = onCreateBinding(inflater, container, savedInstanceState)
?.also { if (it is ViewDataBinding && it.lifecycleOwner == null) it.lifecycleOwner = viewLifecycleOwner }
return binding?.root ?: super.onCreateView(inflater, container, savedInstanceState)
}
@Suppress("UNCHECKED_CAST")
protected open fun onCreateBinding(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): B? {
if (contentLayoutId != 0)
return DataBindingUtil.inflate<ViewDataBinding>(inflater, contentLayoutId, container, false) as? B
return null
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding?.let { onBindingCreated(it, savedInstanceState) }
}
open fun onBindingCreated(binding: B, savedInstanceState: Bundle?) = Unit
override fun onDestroyView() {
binding?.let { onDestroyBinding(it) }
binding = null
super.onDestroyView()
}
open fun onDestroyBinding(binding: B) = Unit
// endregion Lifecycle
}
| mit | 15bea0a280f0c9287805984275a95611 | 33.410714 | 117 | 0.714063 | 5.111406 | false | false | false | false |
hpedrorodrigues/GZMD | app/src/main/kotlin/com/hpedrorodrigues/gzmd/listener/AppBarStateChangeListener.kt | 1 | 1686 | /*
* Copyright 2016 Pedro Rodrigues
*
* 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.hpedrorodrigues.gzmd.listener
import android.support.design.widget.AppBarLayout
abstract class AppBarStateChangeListener() : AppBarLayout.OnOffsetChangedListener {
enum class State { EXPANDED, COLLAPSED, IDLE }
private var currentState = State.IDLE;
override fun onOffsetChanged(appBarLayout: AppBarLayout, verticalOffset: Int) {
if (verticalOffset == 0) {
if (currentState != State.EXPANDED) {
onStateChanged(appBarLayout, State.EXPANDED);
}
currentState = State.EXPANDED;
} else if (Math.abs(verticalOffset) >= appBarLayout.totalScrollRange) {
if (currentState != State.COLLAPSED) {
onStateChanged(appBarLayout, State.COLLAPSED);
}
currentState = State.COLLAPSED;
} else {
if (currentState != State.IDLE) {
onStateChanged(appBarLayout, State.IDLE);
}
currentState = State.IDLE;
}
}
abstract fun onStateChanged(appBarLayout: AppBarLayout, state: State)
} | apache-2.0 | 825f1afe91c7443c5a2022d394ca6e70 | 32.078431 | 83 | 0.669632 | 4.929825 | false | false | false | false |
revbingo/SPIFF | src/main/java/com/revbingo/spiff/parser/SpiffVisitor.kt | 1 | 10023 | package com.revbingo.spiff.parser
import java.nio.ByteOrder
import java.nio.charset.Charset
import java.util.ArrayList
import java.util.HashMap
import com.revbingo.spiff.AdfFormatException
import com.revbingo.spiff.datatypes.*
import com.revbingo.spiff.instructions.*
import com.revbingo.spiff.parser.gen.*
import com.revbingo.spiff.parser.gen.SpiffTreeParserConstants.*
import java.lang.reflect.Constructor
class SpiffVisitor : SpiffTreeParserVisitor {
private var defaultEncoding = Charset.defaultCharset().displayName()
private val defines = HashMap<String, List<Instruction>>()
private val datatypes = HashMap<String, Class<Datatype>>()
fun SimpleNode.getLastTokenImage(): String = this.jjtGetLastToken().image
fun SimpleNode.getFirstTokenImage(): String = this.jjtGetFirstToken().image
fun SimpleNode.findTokenValue(kind: Int, count: Int = 1): String? {
var count = count
var t = this.jjtGetFirstToken()
do {
if (t.kind == kind && --count == 0) return t.image
t = t.next
} while (t !== this.jjtGetLastToken().next)
return null
}
fun SimpleNode.getExpression(): String {
val exprNode = this.jjtGetChild(0) as ASTexpression
var t = exprNode.jjtGetFirstToken()
val expression = StringBuffer()
do {
var tokenText = t.image
if (t.kind == SpiffTreeParserConstants.ID_ADDRESS) {
tokenText = tokenText.substring(1, tokenText.length) + "_address"
}
expression.append(tokenText)
t = t.next
} while (t !== exprNode.jjtGetLastToken().next)
return expression.toString()
}
override fun visit(node: SimpleNode, data: List<Instruction>): List<Instruction> {
node.childrenAccept(this, data)
return data
}
override fun visit(node: ASTadf, data: List<Instruction>): List<Instruction> {
node.childrenAccept(this, data)
return data
}
override fun visit(node: ASTdatatypeDef, data: List<Instruction>): List<Instruction> {
val className = node.findTokenValue(CLASS)
try {
val datatypeClass = Class.forName(className) as Class<Datatype>
if (!Datatype::class.java.isAssignableFrom(datatypeClass)) {
throw AdfFormatException("Custom datatype $datatypeClass does not extend com.revbingo.spiff.datatypes.Datatype")
}
val identifier = node.findTokenValue(IDENTIFIER) ?: throw AdfFormatException("Can't find identifier for ${node.getLastTokenImage()}")
datatypes.put(identifier, datatypeClass)
} catch (e: ClassNotFoundException) {
throw AdfFormatException("Unknown datatype class " + className)
}
return data
}
override fun visit(node: ASTlist, data: List<Instruction>): List<Instruction> {
node.childrenAccept(this, data)
return data
}
override fun visit(node: ASTuserDefinedType, data: MutableList<Instruction>): List<Instruction> {
val typeName = node.findTokenValue(IDENTIFIER, 1)
val identifier = node.findTokenValue(IDENTIFIER, 2)
val userType: Class<out Datatype> = datatypes[typeName] ?: throw AdfFormatException("Undefined datatype " + typeName)
try {
val constructor: Constructor<out Datatype> = userType.getConstructor(String::class.java)
val inst: Instruction = constructor.newInstance(identifier)
return decorateAndAdd(node, inst, data)
} catch (e: NoSuchMethodException) {
throw AdfFormatException("Custom datatype ${userType.name} does not have a no-args constructor or threw an exception: ${e.message}")
} catch (e: IllegalAccessException) {
throw AdfFormatException("Custom datatype ${userType.name} does not have a publically accessible no args constructor")
}
}
override fun visit(node: ASTbits, data: MutableList<Instruction>): List<Instruction> {
val inst = BitsInstruction(node.getLastTokenImage())
inst.numberOfBitsExpr = node.getExpression()
return decorateAndAdd(node, inst, data)
}
override fun visit(node: ASTbytes, data: MutableList<Instruction>): List<Instruction> {
val inst = BytesInstruction(node.getLastTokenImage())
inst.lengthExpr = node.getExpression()
return decorateAndAdd(node, inst, data)
}
override fun visit(node: ASTincludeInstruction,
data: MutableList<Instruction>): List<Instruction> {
val include = defines[node.getLastTokenImage()] ?: throw AdfFormatException("Could not get defined block with name " + node.getLastTokenImage())
data.addAll(include)
return data
}
override fun visit(node: ASTdefineInstruction,
data: List<Instruction>): List<Instruction> {
val nestedInstructions = ArrayList<Instruction>()
node.childrenAccept(this, nestedInstructions)
val identifier = node.findTokenValue(IDENTIFIER)!!
defines.put(identifier, nestedInstructions)
return data
}
override fun visit(node: ASTsetEncodingInstruction,
data: List<Instruction>): List<Instruction> {
this.defaultEncoding = node.findTokenValue(ENCODING)
return data
}
override fun visit(node: ASTsetInstruction,
data: MutableList<Instruction>): List<Instruction> {
val inst = SetInstruction(node.getExpression(), node.findTokenValue(IDENTIFIER) ?: "undefined")
return decorateAndAdd(node, inst, data)
}
override fun visit(node: ASTifElseBlock, data: MutableList<Instruction>): List<Instruction> {
val ifInsts = node.jjtGetChild(1).jjtAccept(this, ArrayList<Instruction>())
var elseInsts: List<Instruction> = arrayListOf()
if (node.jjtGetNumChildren() == 3) {
elseInsts = node.jjtGetChild(2).jjtAccept(this, ArrayList<Instruction>())
}
val inst = IfBlock(node.getExpression(), ifInsts, Block(elseInsts))
return decorateAndAdd(node, inst, data)
}
override fun visit(node: ASTsetOrderInstruction,
data: MutableList<Instruction>): List<Instruction> {
val order = when(node.findTokenValue(BYTEORDER)) {
"LITTLE_ENDIAN" -> ByteOrder.LITTLE_ENDIAN
else -> ByteOrder.BIG_ENDIAN
}
val inst = SetOrderInstruction(order)
return decorateAndAdd(node, inst, data)
}
override fun visit(node: ASTrepeatInstruction,
data: MutableList<Instruction>): List<Instruction> {
val inst = RepeatBlock(node.getExpression(), ArrayList<Instruction>())
node.childrenAccept(this, inst.instructions)
return decorateAndAdd(node, inst, data)
}
override fun visit(node: ASTgroupInstruction,
data: MutableList<Instruction>): List<Instruction> {
val groupName = node.findTokenValue(IDENTIFIER)
decorateAndAdd(node, GroupInstruction(groupName!!), data)
node.childrenAccept(this, data)
val endGroupInst = EndGroupInstruction(groupName)
endGroupInst.lineNumber = node.jjtGetLastToken().beginLine
data.add(endGroupInst)
return data
}
override fun visit(node: ASTjumpInstruction,
data: MutableList<Instruction>): List<Instruction> {
val inst = JumpInstruction(node.getExpression())
return decorateAndAdd(node, inst, data)
}
override fun visit(node: ASTskipInstruction,
data: MutableList<Instruction>): List<Instruction> {
val inst = SkipInstruction(node.getExpression())
return decorateAndAdd(node, inst, data)
}
override fun visit(node: ASTmarkInstruction,
data: MutableList<Instruction>): List<Instruction> {
val inst = MarkInstruction(node.getLastTokenImage())
return decorateAndAdd(node, inst, data)
}
override fun visit(node: ASTfixedNumber, data: MutableList<Instruction>): List<Instruction> {
val insF = FixedLengthNumberFactory()
val inst = insF.getInstruction( node.getLastTokenImage(), node.getFirstTokenImage())
if (node.jjtGetNumChildren() == 1) {
inst.literalExpr = node.getExpression()
}
return decorateAndAdd(node, inst, data)
}
override fun visit(node: ASTexpression, data: List<Instruction>): List<Instruction> {
return data
}
private fun decorateAndAdd(node: SimpleNode, inst: Instruction?, list: MutableList<Instruction>): List<Instruction> {
if (inst is AdfInstruction) {
inst.lineNumber = node.jjtGetFirstToken().beginLine
}
list.add(inst!!)
return list
}
override fun visit(node: ASTfixedString, data: MutableList<Instruction>): List<Instruction> {
var encoding = node.findTokenValue(ENCODING) ?: defaultEncoding
val inst = FixedLengthString(node.getLastTokenImage(), node.getExpression(), encoding)
return decorateAndAdd(node, inst, data)
}
override fun visit(node: ASTliteralString, data: MutableList<Instruction>): List<Instruction> {
var encoding: String = node.findTokenValue(ENCODING) ?: defaultEncoding
val literal = (node.jjtGetChild(0) as ASTIdentifier).getFirstTokenImage()
val inst = LiteralStringInstruction(node.getLastTokenImage(), literal, encoding)
return decorateAndAdd(node, inst, data)
}
override fun visit(node: ASTterminatedString, data: MutableList<Instruction>): List<Instruction> {
var encoding: String = node.findTokenValue(ENCODING) ?: defaultEncoding
val inst = TerminatedString(node.getLastTokenImage(), encoding)
return decorateAndAdd(node, inst, data)
}
override fun visit(node: ASTIdentifier, data: List<Instruction>): List<Instruction>? {
return null
}
}
| mit | 0d4c3b4c7ace5902692829f8f0bf1e0e | 39.415323 | 152 | 0.66527 | 4.539402 | false | false | false | false |
rhdunn/xquery-intellij-plugin | src/plugin-api/main/uk/co/reecedunn/intellij/plugin/processor/run/execution/process/QueryProcessHandlerBase.kt | 1 | 2970 | /*
* Copyright (C) 2018-2021 Reece H. Dunn
*
* 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 uk.co.reecedunn.intellij.plugin.processor.run.execution.process
import com.intellij.codeInsight.actions.ReformatCodeProcessor
import com.intellij.execution.process.ProcessHandler
import com.intellij.openapi.fileTypes.PlainTextLanguage
import com.intellij.psi.PsiFile
import com.intellij.util.containers.ContainerUtil
import uk.co.reecedunn.intellij.plugin.processor.query.QueryResult
import uk.co.reecedunn.intellij.plugin.xdm.types.XsDurationValue
import java.io.OutputStream
abstract class QueryProcessHandlerBase : ProcessHandler() {
// region Configuration
private var reformat: Boolean = false
fun reformat(reformat: Boolean): QueryProcessHandlerBase {
this.reformat = reformat
return this
}
// endregion
// region Results
private val queryResultListeners = ContainerUtil.createLockFreeCopyOnWriteList<QueryResultListener>()
fun addQueryResultListener(listener: QueryResultListener) {
queryResultListeners.add(listener)
}
fun removeQueryResultListener(listener: QueryResultListener) {
queryResultListeners.add(listener)
}
fun notifyBeginResults() {
queryResultListeners.forEach { it.onBeginResults() }
}
fun notifyEndResults() {
queryResultListeners.forEach {
it.onEndResults { file -> notifyQueryResultsPsiFile(file) }
}
}
fun notifyException(e: Throwable) {
queryResultListeners.forEach { it.onException(e) }
}
fun notifyResult(result: QueryResult) {
queryResultListeners.forEach { it.onQueryResult(result) }
}
fun notifyElapsedTime(time: XsDurationValue) {
queryResultListeners.forEach { it.onQueryElapsedTime(time) }
}
@Suppress("MemberVisibilityCanBePrivate")
fun notifyQueryResultsPsiFile(psiFile: PsiFile) {
if (psiFile.language == PlainTextLanguage.INSTANCE) return
queryResultListeners.forEach { it.onQueryResultsPsiFile(psiFile) }
if (reformat) {
val reformatter = ReformatCodeProcessor(psiFile, false)
reformatter.run()
}
}
// endregion
// region ProcessHandler
override fun getProcessInput(): OutputStream? = null
override fun detachIsDefault(): Boolean = false
override fun detachProcessImpl() {}
override fun destroyProcessImpl() {}
// endregion
}
| apache-2.0 | 6d0b513eb2875efeb3ac2b0887b5b567 | 30.263158 | 105 | 0.724916 | 4.759615 | false | false | false | false |
jiaminglu/kotlin-native | backend.native/tests/external/codegen/box/arrays/kt2997.kt | 5 | 1835 | //KT-2997 Automatically cast error (Array)
fun foo(a: Any): Int {
if (a is IntArray) {
a.get(0)
a.set(0, 1)
a.iterator()
return a.size
}
if (a is ShortArray) {
a.get(0)
a.set(0, 1)
a.iterator()
return a.size
}
if (a is ByteArray) {
a.get(0)
a.set(0, 1)
a.iterator()
return a.size
}
if (a is FloatArray) {
a.get(0)
a.set(0, 1.toFloat())
a.iterator()
return a.size
}
if (a is DoubleArray) {
a.get(0)
a.set(0, 1.0)
a.iterator()
return a.size
}
if (a is BooleanArray) {
a.get(0)
a.set(0, false)
a.iterator()
return a.size
}
if (a is CharArray) {
a.get(0)
a.set(0, 'a')
a.iterator()
return a.size
}
if (a is Array<*>) {
if (a.size > 0) a.get(0)
a.iterator()
return a.size
}
return 0
}
fun box(): String {
// Only run this test if primitive array `is` checks work (KT-17137)
if ((intArrayOf() as Any) is Array<*>) return "OK"
val iA = IntArray(1)
if (foo(iA) != 1) return "fail int[]"
val sA = ShortArray(1)
if (foo(sA) != 1) return "fail short[]"
val bA = ByteArray(1)
if (foo(bA) != 1) return "fail byte[]"
val fA = FloatArray(1)
if (foo(fA) != 1) return "fail float[]"
val dA = DoubleArray(1)
if (foo(dA) != 1) return "fail double[]"
val boolA = BooleanArray(1)
if (foo(boolA) != 1) return "fail boolean[]"
val cA = CharArray(1)
if (foo(cA) != 1) return "fail char[]"
val oA = arrayOfNulls<Int>(1)
if (foo(oA) != 1) return "fail Any[]"
val sArray = arrayOfNulls<String>(0)
if (foo(sArray) != 0) return "fail String[]"
return "OK"
}
| apache-2.0 | 02492af4e1ecb5886bdea72a0875ed4a | 21.9375 | 72 | 0.493733 | 3.078859 | false | false | false | false |
StepicOrg/stepic-android | app/src/main/java/org/stepik/android/presentation/course_revenue/reducer/CourseBenefitsReducer.kt | 1 | 3247 | package org.stepik.android.presentation.course_revenue.reducer
import org.stepik.android.domain.course_revenue.model.CourseBenefitListItem
import org.stepik.android.presentation.course_revenue.CourseBenefitsFeature.State
import org.stepik.android.presentation.course_revenue.CourseBenefitsFeature.Message
import org.stepik.android.presentation.course_revenue.CourseBenefitsFeature.Action
import ru.nobird.android.core.model.concatWithPagedList
import ru.nobird.android.presentation.redux.reducer.StateReducer
import javax.inject.Inject
class CourseBenefitsReducer
@Inject
constructor() : StateReducer<State, Message, Action> {
override fun reduce(state: State, message: Message): Pair<State, Set<Action>> =
when (message) {
is Message.FetchCourseBenefitsSuccess -> {
if (state is State.Loading) {
val courseBenefitsState =
if (message.courseBenefitListDataItems.isEmpty()) {
State.Empty
} else {
State.Content(message.courseBenefitListDataItems, message.courseBenefitListDataItems, message.courseBeneficiary)
}
courseBenefitsState to emptySet()
} else {
null
}
}
is Message.FetchCourseBenefitsFailure -> {
if (state is State.Loading) {
State.Error to emptySet()
} else {
null
}
}
is Message.FetchNextPage -> {
if (state is State.Content) {
if (state.courseBenefitListDataItems.hasNext && state.courseBenefitListItems.last() !is CourseBenefitListItem.Placeholder) {
state.copy(courseBenefitListItems = state.courseBenefitListItems + CourseBenefitListItem.Placeholder) to
setOf(Action.FetchCourseBenefitsNext(message.courseId, state.courseBenefitListDataItems.page + 1))
} else {
null
}
} else {
null
}
}
is Message.FetchCourseBenefitsNextSuccess -> {
if (state is State.Content) {
val resultingItems = state.courseBenefitListDataItems.concatWithPagedList(message.courseBenefitListDataItems)
state.copy(courseBenefitListDataItems = resultingItems, courseBenefitListItems = resultingItems) to emptySet()
} else {
null
}
}
is Message.FetchCourseBenefitsNextFailure -> {
if (state is State.Content) {
state.copy(courseBenefitListItems = state.courseBenefitListDataItems) to emptySet()
} else {
null
}
}
is Message.TryAgain -> {
if (state is State.Error) {
State.Loading to setOf(Action.FetchCourseBenefits(message.courseId))
} else {
null
}
}
} ?: state to emptySet()
} | apache-2.0 | d7c1c46028a42b49ded410cb01605678 | 44.111111 | 144 | 0.565137 | 5.550427 | false | false | false | false |
Commit451/GitLabAndroid | app/src/main/java/com/commit451/gitlab/viewHolder/FeedEntryViewHolder.kt | 2 | 1580 | package com.commit451.gitlab.viewHolder
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import coil.api.load
import coil.transform.CircleCropTransformation
import com.commit451.addendum.recyclerview.bindView
import com.commit451.gitlab.R
import com.commit451.gitlab.extension.formatAsHtml
import com.commit451.gitlab.model.rss.Entry
import com.commit451.gitlab.util.DateUtil
/**
* Represents the view of an item in the RSS feed
*/
class FeedEntryViewHolder(view: View) : RecyclerView.ViewHolder(view) {
companion object {
fun inflate(parent: ViewGroup): FeedEntryViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.item_entry, parent, false)
return FeedEntryViewHolder(view)
}
}
private val image: ImageView by bindView(R.id.image)
private val textTitle: TextView by bindView(R.id.title)
private val textSummary: TextView by bindView(R.id.description)
private val textUpdated: TextView by bindView(R.id.updated)
fun bind(entry: Entry) {
image.load(entry.thumbnail.url) {
transformations(CircleCropTransformation())
}
textTitle.text = entry.title.formatAsHtml()
textSummary.text = entry.summary.formatAsHtml()
val updatedRelative = DateUtil.getRelativeTimeSpanString(itemView.context, entry.updated)
textUpdated.text = updatedRelative
}
}
| apache-2.0 | d3b541f4a481a9138a9b39a57bc7bf09 | 32.617021 | 97 | 0.739873 | 4.340659 | false | false | false | false |
MarcBob/SmartRecyclerViewAdapter | app/src/main/kotlin/bobzien/com/smartrecyclerviewadapter/ViewHolder/TypedViewHolder1.kt | 1 | 1376 | package bobzien.com.smartrecyclerviewadapter.ViewHolder
import android.content.Context
import android.view.View
import android.widget.TextView
import bobzien.com.smartrecyclerviewadapter.R
import bobzien.com.smartrecyclerviewadapter.TypedObject
import bobzien.com.smartrecyclerviewadapter.SmartRecyclerViewAdapter.*
class TypedViewHolder1(context: Context, clazz: Class<TypedObject>, itemView: View?) : TypeViewHolder<TypedObject>(context, clazz as Class<Any>, itemView) {
protected lateinit var textView: TextView
init {
if (itemView != null) {
textView = itemView.findViewById(R.id.text) as TextView
}
}
override fun getInstance(itemView: View): ViewHolder<Any> {
return TypedViewHolder1(context, getHandledClass() as Class<TypedObject>, itemView) as ViewHolder<Any>
}
override val layoutResourceId: Int
get() = R.layout.list_item_typed1
override fun bindViewHolder(item: TypedObject, selected: Boolean) {
textView.text = "Type " + item.type
}
override fun canHandle(item: TypedObject): Boolean {
if (item.type == 1) {
return true
}
return false
}
override fun getWrappedObject(item: TypedObject?): Wrapper {
return object : Wrapper {
override val item: Any
get() = item as Any
}
}
}
| apache-2.0 | e5feb474828cb231bd0303cf39d93b74 | 30.272727 | 156 | 0.683866 | 4.496732 | false | false | false | false |
CarlosEsco/tachiyomi | app/src/main/java/eu/kanade/tachiyomi/util/storage/DiskUtil.kt | 1 | 3606 | package eu.kanade.tachiyomi.util.storage
import android.content.Context
import android.media.MediaScannerConnection
import android.net.Uri
import android.os.Environment
import android.os.StatFs
import androidx.core.content.ContextCompat
import com.hippo.unifile.UniFile
import eu.kanade.tachiyomi.util.lang.Hash
import java.io.File
object DiskUtil {
fun hashKeyForDisk(key: String): String {
return Hash.md5(key)
}
fun getDirectorySize(f: File): Long {
var size: Long = 0
if (f.isDirectory) {
for (file in f.listFiles().orEmpty()) {
size += getDirectorySize(file)
}
} else {
size = f.length()
}
return size
}
/**
* Gets the available space for the disk that a file path points to, in bytes.
*/
fun getAvailableStorageSpace(f: UniFile): Long {
return try {
val stat = StatFs(f.uri.path)
stat.availableBlocksLong * stat.blockSizeLong
} catch (_: Exception) {
-1L
}
}
/**
* Returns the root folders of all the available external storages.
*/
fun getExternalStorages(context: Context): List<File> {
return ContextCompat.getExternalFilesDirs(context, null)
.filterNotNull()
.mapNotNull {
val file = File(it.absolutePath.substringBefore("/Android/"))
val state = Environment.getExternalStorageState(file)
if (state == Environment.MEDIA_MOUNTED || state == Environment.MEDIA_MOUNTED_READ_ONLY) {
file
} else {
null
}
}
}
/**
* Don't display downloaded chapters in gallery apps creating `.nomedia`.
*/
fun createNoMediaFile(dir: UniFile?, context: Context?) {
if (dir != null && dir.exists()) {
val nomedia = dir.findFile(".nomedia")
if (nomedia == null) {
dir.createFile(".nomedia")
context?.let { scanMedia(it, dir.uri) }
}
}
}
/**
* Scans the given file so that it can be shown in gallery apps, for example.
*/
fun scanMedia(context: Context, uri: Uri) {
MediaScannerConnection.scanFile(context, arrayOf(uri.path), null, null)
}
/**
* Mutate the given filename to make it valid for a FAT filesystem,
* replacing any invalid characters with "_". This method doesn't allow hidden files (starting
* with a dot), but you can manually add it later.
*/
fun buildValidFilename(origName: String): String {
val name = origName.trim('.', ' ')
if (name.isEmpty()) {
return "(invalid)"
}
val sb = StringBuilder(name.length)
name.forEach { c ->
if (isValidFatFilenameChar(c)) {
sb.append(c)
} else {
sb.append('_')
}
}
// Even though vfat allows 255 UCS-2 chars, we might eventually write to
// ext4 through a FUSE layer, so use that limit minus 15 reserved characters.
return sb.toString().take(240)
}
/**
* Returns true if the given character is a valid filename character, false otherwise.
*/
private fun isValidFatFilenameChar(c: Char): Boolean {
if (0x00.toChar() <= c && c <= 0x1f.toChar()) {
return false
}
return when (c) {
'"', '*', '/', ':', '<', '>', '?', '\\', '|', 0x7f.toChar() -> false
else -> true
}
}
}
| apache-2.0 | d534f75d397636f291b4b0dfa6f3c7fd | 30.356522 | 105 | 0.557682 | 4.440887 | false | false | false | false |
lhw5123/GmailKotlinSample | GmailKotlion/app/src/main/java/org/hevin/gmailkotlion/helper/FlipAnimator.kt | 1 | 1222 | package org.hevin.gmailkotlion.helper
import android.animation.AnimatorInflater
import android.animation.AnimatorSet
import android.content.Context
import android.view.View
import org.hevin.gmailkotlion.R
class FlipAnimator(context: Context) {
var leftIn: AnimatorSet = AnimatorInflater.loadAnimator(context, R.animator.card_flip_left_in) as AnimatorSet
var leftOut: AnimatorSet = AnimatorInflater.loadAnimator(context, R.animator.card_flip_left_out) as AnimatorSet
var rightIn: AnimatorSet = AnimatorInflater.loadAnimator(context, R.animator.card_flip_right_in) as AnimatorSet
var rightOut: AnimatorSet = AnimatorInflater.loadAnimator(context, R.animator.card_flip_right_out) as AnimatorSet
fun flipView(back: View, front: View, showFront: Boolean) {
val showFrontAnim = AnimatorSet()
val showBackAnim = AnimatorSet()
leftIn.setTarget(back)
rightOut.setTarget(front)
showFrontAnim.playTogether(leftIn, rightOut)
leftOut.setTarget(back)
rightIn.setTarget(front)
showBackAnim.playTogether(rightIn, leftOut)
if (showFront) {
showFrontAnim.start()
} else {
showBackAnim.start()
}
}
} | apache-2.0 | 40aae8d55fe4ea4a89936c778369234d | 36.060606 | 117 | 0.726678 | 4.019737 | false | false | false | false |
Maccimo/intellij-community | platform/diagnostic/src/opentelemetry/TraceManager.kt | 2 | 3524 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.diagnostic.opentelemetry
import com.intellij.diagnostic.telemetry.JaegerJsonSpanExporter
import com.intellij.openapi.application.ApplicationInfo
import com.intellij.openapi.application.ApplicationNamesInfo
import com.intellij.openapi.util.ShutDownTracker
import io.opentelemetry.api.OpenTelemetry
import io.opentelemetry.api.common.Attributes
import io.opentelemetry.api.trace.Tracer
import io.opentelemetry.exporter.jaeger.JaegerGrpcSpanExporter
import io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporter
import io.opentelemetry.sdk.OpenTelemetrySdk
import io.opentelemetry.sdk.resources.Resource
import io.opentelemetry.sdk.trace.SdkTracerProvider
import io.opentelemetry.sdk.trace.export.BatchSpanProcessor
import io.opentelemetry.sdk.trace.export.SpanExporter
import io.opentelemetry.semconv.resource.attributes.ResourceAttributes
import org.jetbrains.annotations.ApiStatus
import java.nio.file.Path
import java.util.concurrent.TimeUnit
/**
* See [Span](https://opentelemetry.io/docs/reference/specification),
* [Manual Instrumentation](https://opentelemetry.io/docs/instrumentation/java/manual/#create-spans-with-events).
*/
@ApiStatus.Experimental
object TraceManager {
private var sdk: OpenTelemetry = OpenTelemetry.noop()
fun init() {
val serviceName = ApplicationNamesInfo.getInstance().fullProductName
val appInfo = ApplicationInfo.getInstance()
val serviceVersion = appInfo.build.asStringWithoutProductCode()
val serviceNamespace = appInfo.build.productCode
val traceFile = System.getProperty("idea.diagnostic.opentelemetry.file")
val spanExporters = mutableListOf<SpanExporter>()
if (traceFile != null) {
val jsonSpanExporter = JaegerJsonSpanExporter()
JaegerJsonSpanExporter.setOutput(file = Path.of(traceFile),
serviceName = serviceName,
serviceVersion = serviceVersion,
serviceNamespace = serviceNamespace)
spanExporters.add(jsonSpanExporter)
}
val jaegerEndpoint = System.getProperty("idea.diagnostic.opentelemetry.jaeger")
if (jaegerEndpoint != null) {
spanExporters.add(JaegerGrpcSpanExporter.builder().setEndpoint(jaegerEndpoint).build())
}
val endpoint = System.getProperty("idea.diagnostic.opentelemetry.otlp")
if (endpoint != null) {
spanExporters.add(OtlpGrpcSpanExporter.builder().setEndpoint(endpoint).build())
}
val tracerProvider = SdkTracerProvider.builder()
.addSpanProcessor(BatchSpanProcessor.builder(SpanExporter.composite(spanExporters)).build())
.setResource(Resource.create(Attributes.of(
ResourceAttributes.SERVICE_NAME, serviceName,
ResourceAttributes.SERVICE_VERSION, serviceVersion,
ResourceAttributes.SERVICE_NAMESPACE, serviceNamespace
)))
.build()
sdk = OpenTelemetrySdk.builder()
.setTracerProvider(tracerProvider)
.buildAndRegisterGlobal()
if (spanExporters.isNotEmpty()) {
ShutDownTracker.getInstance().registerShutdownTask(Runnable {
tracerProvider?.forceFlush()?.join(10, TimeUnit.SECONDS)
JaegerJsonSpanExporter.finish()
})
}
}
/**
* We do not provide default tracer - we enforce using of separate scopes for subsystems.
*/
fun getTracer(scopeName: String): Tracer = sdk.getTracer(scopeName)
} | apache-2.0 | 36be22bf4c628283f2028198f47d631a | 41.987805 | 120 | 0.752554 | 4.558862 | false | false | false | false |
Yubico/yubioath-desktop | android/app/src/main/kotlin/com/yubico/authenticator/MainViewModel.kt | 1 | 2020 | /*
* Copyright (C) 2022 Yubico.
*
* 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.yubico.authenticator
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.yubico.authenticator.device.Info
import com.yubico.yubikit.android.transport.usb.UsbYubiKeyDevice
enum class OperationContext(val value: Int) {
Oath(0), Yubikey(1), Invalid(-1);
companion object {
fun getByValue(value: Int) = values().firstOrNull { it.value == value } ?: Invalid
}
}
class MainViewModel : ViewModel() {
private var _appContext = MutableLiveData(OperationContext.Oath)
val appContext: LiveData<OperationContext> = _appContext
fun setAppContext(appContext: OperationContext) {
// Don't reset the context unless it actually changes
if(appContext != _appContext.value) {
_appContext.postValue(appContext)
}
}
private val _connectedYubiKey = MutableLiveData<UsbYubiKeyDevice?>()
val connectedYubiKey: LiveData<UsbYubiKeyDevice?> = _connectedYubiKey
fun setConnectedYubiKey(device: UsbYubiKeyDevice, onDisconnect: () -> Unit ) {
_connectedYubiKey.postValue(device)
device.setOnClosed {
_connectedYubiKey.postValue(null)
onDisconnect()
}
}
private val _deviceInfo = MutableLiveData<Info?>()
val deviceInfo: LiveData<Info?> = _deviceInfo
fun setDeviceInfo(info: Info?) = _deviceInfo.postValue(info)
}
| apache-2.0 | 38ad858647f8021f9abeb62685f70625 | 34.438596 | 90 | 0.715347 | 4.097363 | false | false | false | false |
Maccimo/intellij-community | platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/generatedCodeCompatibility.kt | 4 | 3711 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.workspaceModel.storage
import org.jetbrains.annotations.TestOnly
object CodeGeneratorVersions {
@set:TestOnly
var API_VERSION = 1
@set:TestOnly
var IMPL_VERSION = 1
var checkApiInInterface = true
var checkApiInImpl = true
}
@Target(AnnotationTarget.CLASS)
@Retention(AnnotationRetention.RUNTIME)
annotation class GeneratedCodeApiVersion(val version: Int)
@Target(AnnotationTarget.CLASS)
@Retention(AnnotationRetention.RUNTIME)
annotation class GeneratedCodeImplVersion(val version: Int)
object GeneratedCodeCompatibilityChecker {
fun checkCode(entity: Class<WorkspaceEntity>) {
val builderClass: Class<*>
if (CodeGeneratorVersions.checkApiInInterface) { // Check that builder interface has the correct api version
builderClass = entity.toBuilderClass()
val annotations = builderClass.annotations
val entityApiVersion = annotations.filterIsInstance<GeneratedCodeApiVersion>().singleOrNull()?.version
?: error("Generated interface '$builderClass' doesn't have an api version marker. " +
"You should regenerate the code of your entities")
assert(entityApiVersion == CodeGeneratorVersions.API_VERSION) {
"""
Current API version of the generator is '${CodeGeneratorVersions.API_VERSION}',
but the generated code is marked as version '$entityApiVersion'.
Please, regenerate your entities.
Checked entity: $builderClass
""".trimIndent()
}
}
val implClass = entity.toImplClass()
val implAnnotations = implClass.annotations
if (CodeGeneratorVersions.checkApiInImpl) { // Check that impl class has the correct api version
val entityImplApiVersion = implAnnotations.filterIsInstance<GeneratedCodeApiVersion>().singleOrNull()?.version
?: error("Generated class '$implClass' doesn't have an api version marker. " +
"You should regenerate the code of your entities")
assert(entityImplApiVersion == CodeGeneratorVersions.API_VERSION) {
"""
Current API version of the generator is '${CodeGeneratorVersions.API_VERSION}',
but the generated code is marked as version '$entityImplApiVersion'.
Please, regenerate your entities.
Checked entity: $implClass
""".trimIndent()
}
}
// Check that impl class has the correct impl version
val entityImplImplVersion = implAnnotations.filterIsInstance<GeneratedCodeImplVersion>().singleOrNull()?.version
?: error("Generated class '$implClass' doesn't have an impl version marker. " +
"You should regenerate the code of your entities")
assert(entityImplImplVersion == CodeGeneratorVersions.IMPL_VERSION) {
"""
Current IMPL version of the generator is '${CodeGeneratorVersions.IMPL_VERSION}',
but the generated code is marked as version '$entityImplImplVersion'.
Please, regenerate your entities.
Checked entity: $implClass
""".trimIndent()
}
}
}
// Something more stable?
private fun Class<WorkspaceEntity>.toBuilderClass(): Class<*> {
return loadClassByName("$name\$Builder", classLoader)
}
private fun Class<WorkspaceEntity>.toImplClass(): Class<*> {
return loadClassByName(name + "Impl", classLoader)
}
| apache-2.0 | 9997a476d6a87fac8519322a8015b206 | 41.655172 | 120 | 0.68526 | 5.286325 | false | false | false | false |
ksmirenko/cards-toefl | app/src/main/java/io/github/ksmirenko/toeflcards/adapters/ModuleCursorAdapter.kt | 1 | 3376 | package io.github.ksmirenko.toeflcards.adapters
import android.content.Context
import android.database.CharArrayBuffer
import android.database.Cursor
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CursorAdapter
import android.widget.ImageView
import android.widget.TextView
import io.github.ksmirenko.toeflcards.ToeflCardsDatabase
import io.github.ksmirenko.toeflcards.R
import kotlinx.android.synthetic.main.listview_item_modules.view.*
/**
* CursorAdapter for module selection.
*
* @author Kirill Smirenko
*/
class ModuleCursorAdapter(context : Context, cursor : Cursor?) : CursorAdapter(context, cursor, 0) {
companion object {
private val NAME_BUFFER_SIZE = 256
}
override fun newView(context : Context, cursor : Cursor, parent : ViewGroup) : View {
val view = LayoutInflater.from(context).inflate(R.layout.listview_item_modules, parent, false)
view.tag = ModuleListItemViewHolder(
view.icon_catscr_module as ImageView,
view.textview_catscr_module_name as TextView,
CharArrayBuffer(NAME_BUFFER_SIZE)
)
return view
}
override fun bindView(view : View, context : Context, cursor : Cursor) {
val holder = view.tag as ModuleListItemViewHolder
cursor.copyStringToBuffer(ToeflCardsDatabase.ModuleQuery.COLUMN_INDEX_NAME, holder.nameBuffer)
holder.nameView.setText(holder.nameBuffer.data, 0, holder.nameBuffer.sizeCopied)
// set an icon, if available for this module
try {
holder.iconView.setImageResource(iconResIds[cursor.getInt(0)])
}
catch (e : IndexOutOfBoundsException) {
}
}
/**
* Icons for modules of 'Cards for the TOEFL test'
*/
private val iconResIds = arrayOf(
R.drawable.ic_module_advanced, // default for index 0
R.drawable.ic_module_advanced,
R.drawable.ic_module_advanced,
R.drawable.ic_module_advanced,
R.drawable.ic_module_anthropology,
R.drawable.ic_module_art,
R.drawable.ic_module_disaster,
R.drawable.ic_module_employment,
R.drawable.ic_module_entertainment,
R.drawable.ic_module_evolution,
R.drawable.ic_module_expertise,
R.drawable.ic_module_family_relationships,
R.drawable.ic_module_fashion,
R.drawable.ic_module_finance,
R.drawable.ic_module_food_crops,
R.drawable.ic_module_friendship,
R.drawable.ic_module_fuel,
R.drawable.ic_module_history,
R.drawable.ic_module_illness,
R.drawable.ic_module_memory,
R.drawable.ic_module_military_operations,
R.drawable.ic_module_negative_emotions,
R.drawable.ic_module_paranormal,
R.drawable.ic_module_passion,
R.drawable.ic_module_personal_property,
R.drawable.ic_module_politics,
R.drawable.ic_module_rebels,
R.drawable.ic_module_scientific_terms,
R.drawable.ic_module_social_inequality,
R.drawable.ic_module_spirituality,
R.drawable.ic_module_trade,
R.drawable.ic_module_wealth,
R.drawable.ic_module_word
)
private data class ModuleListItemViewHolder(
var iconView : ImageView,
var nameView : TextView,
var nameBuffer : CharArrayBuffer
) {}
} | apache-2.0 | 26bdcff266a7140d6b6ee8adc7468995 | 35.311828 | 102 | 0.684834 | 3.827664 | false | false | false | false |
pyamsoft/pydroid | ui/src/main/java/com/pyamsoft/pydroid/ui/internal/preference/PYDroidPreferencesImpl.kt | 1 | 4087 | /*
* Copyright 2022 Peter Kenji Yamanaka
*
* 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.pyamsoft.pydroid.ui.internal.preference
import android.content.Context
import androidx.core.content.edit
import androidx.preference.PreferenceManager
import com.pyamsoft.pydroid.bootstrap.changelog.ChangeLogPreferences
import com.pyamsoft.pydroid.bootstrap.datapolicy.DataPolicyPreferences
import com.pyamsoft.pydroid.core.Enforcer
import com.pyamsoft.pydroid.ui.R
import com.pyamsoft.pydroid.ui.theme.Theming.Mode
import com.pyamsoft.pydroid.ui.theme.Theming.Mode.SYSTEM
import com.pyamsoft.pydroid.ui.theme.ThemingPreferences
import com.pyamsoft.pydroid.ui.theme.toRawString
import com.pyamsoft.pydroid.ui.theme.toThemingMode
import com.pyamsoft.pydroid.util.booleanFlow
import com.pyamsoft.pydroid.util.intFlow
import com.pyamsoft.pydroid.util.stringFlow
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.withContext
internal class PYDroidPreferencesImpl
internal constructor(
context: Context,
private val versionCode: Int,
) : ThemingPreferences, ChangeLogPreferences, DataPolicyPreferences {
private val darkModeKey = context.getString(R.string.dark_mode_key)
private val prefs by lazy {
Enforcer.assertOffMainThread()
PreferenceManager.getDefaultSharedPreferences(context.applicationContext)
}
override suspend fun listenForShowChangelogChanges(): Flow<Boolean> =
withContext(context = Dispatchers.IO) {
Enforcer.assertOffMainThread()
return@withContext prefs.intFlow(LAST_SHOWN_CHANGELOG, -1).map { it < versionCode }
}
override suspend fun markChangeLogShown() =
withContext(context = Dispatchers.IO) {
Enforcer.assertOffMainThread()
// Mark the changelog as shown for this version
return@withContext prefs.edit { putInt(LAST_SHOWN_CHANGELOG, versionCode) }
}
override suspend fun listenForDarkModeChanges(): Flow<Mode> =
withContext(context = Dispatchers.IO) {
Enforcer.assertOffMainThread()
// Initialize this key here so the preference screen can be populated
if (!prefs.contains(darkModeKey)) {
prefs.edit(commit = true) { putString(darkModeKey, DEFAULT_DARK_MODE) }
}
return@withContext prefs.stringFlow(darkModeKey, DEFAULT_DARK_MODE).map {
it.toThemingMode()
}
}
override suspend fun setDarkMode(mode: Mode) =
withContext(context = Dispatchers.IO) {
Enforcer.assertOffMainThread()
return@withContext prefs.edit(commit = true) { putString(darkModeKey, mode.toRawString()) }
}
override suspend fun listenForPolicyAcceptedChanges(): Flow<Boolean> =
withContext(context = Dispatchers.IO) {
Enforcer.assertOffMainThread()
return@withContext prefs.booleanFlow(
KEY_DATA_POLICY_CONSENTED,
DEFAULT_DATA_POLICY_CONSENTED,
)
}
override suspend fun respondToPolicy(accepted: Boolean) =
withContext(context = Dispatchers.IO) {
Enforcer.assertOffMainThread()
return@withContext prefs.edit(commit = true) {
putBoolean(KEY_DATA_POLICY_CONSENTED, accepted)
}
}
companion object {
private val DEFAULT_DARK_MODE = SYSTEM.toRawString()
private const val LAST_SHOWN_CHANGELOG = "changelog_app_last_shown"
private const val DEFAULT_DATA_POLICY_CONSENTED = false
private const val KEY_DATA_POLICY_CONSENTED = "data_policy_consented_v1"
}
}
| apache-2.0 | d573042c65ae2d70504e42fcf49bd9b0 | 34.850877 | 99 | 0.738928 | 4.306639 | false | false | false | false |
DuncanCasteleyn/DiscordModBot | src/main/kotlin/be/duncanc/discordmodbot/bot/commands/UserInfo.kt | 1 | 5559 | /*
* Copyright 2018 Duncan Casteleyn
*
* 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 be.duncanc.discordmodbot.bot.commands
import be.duncanc.discordmodbot.bot.utils.nicknameAndUsername
import be.duncanc.discordmodbot.data.services.UserBlockService
import net.dv8tion.jda.api.EmbedBuilder
import net.dv8tion.jda.api.entities.ChannelType
import net.dv8tion.jda.api.entities.PrivateChannel
import net.dv8tion.jda.api.events.message.MessageReceivedEvent
import org.springframework.stereotype.Component
import java.time.format.DateTimeFormatter
import java.util.*
/**
* User info command.
*/
@Component
class UserInfo(
userBlockService: UserBlockService
) : CommandModule(
ALIASES,
ARGUMENTATION_SYNTAX,
DESCRIPTION,
userBlockService = userBlockService
) {
companion object {
private val DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("dd-M-yyyy hh:mm:ss a O")
private val ALIASES = arrayOf("UserInfo", "GetUserInfo")
private const val ARGUMENTATION_SYNTAX = "[Username#Discriminator] (Without @)"
private const val DESCRIPTION = "Prints out user information of the user given as argument"
}
/**
* Do something with the event, command and arguments.
*
* @param event A MessageReceivedEvent that came with the command
* @param command The command alias that was used to trigger this commandExec
* @param arguments The arguments that where entered after the command alias
*/
public override fun commandExec(event: MessageReceivedEvent, command: String, arguments: String?) {
if (event.isFromType(ChannelType.TEXT)) {
val privateChannel: PrivateChannel = event.author.openPrivateChannel().complete()
if (arguments == null) {
privateChannel.sendMessage("Please mention the user you want to get the dates from by using username#discriminator without @ sign, e.g.: \"Puck#5244\"\n")
.queue()
} else if (!arguments.contains("#")) {
privateChannel.sendMessage("Discriminator missing use username#discrimanator without @ sign, e.g.: \"Puck#5244\"")
.queue()
} else {
val searchTerms =
event.message.contentRaw.substring(command.length + 2).lowercase(Locale.getDefault())
.split("#".toRegex())
.dropLastWhile { it.isBlank() }.toTypedArray()
var targetFound = false
for (member in event.guild.members) {
if (searchTerms[0] == member.user.name.lowercase(Locale.getDefault()) && searchTerms[1] == member.user.discriminator) {
// privateChannel.sendMessage("Dates from user " + member.toString() + "\n" +
// "Guild join date: " + member.getJoinDate().format(DATE_TIME_FORMATTER) + "\n" +
// "Account creation date: " + member.getUser().getCreationTime().format(DATE_TIME_FORMATTER)).queue();
val userDateMessage = EmbedBuilder()
.setAuthor(member.nicknameAndUsername, null, member.user.effectiveAvatarUrl)
.setThumbnail(member.user.effectiveAvatarUrl)
.setTitle("Guild: " + member.guild.name, null)
.addField("User id", member.user.id, false)
.addField("Discriminator", member.user.discriminator, false)
.addField("Online status", member.onlineStatus.name, false)
.addField("In voice channel?", member.voiceState?.inVoiceChannel().toString(), true)
.addField("Guild owner?", member.isOwner.toString(), true)
.addField("is a bot?", member.user.isBot.toString(), true)
.addField("Permissions", member.permissions.toString(), false)
.addField("Roles", member.roles.toString(), false)
.addField("Guild join date", member.timeJoined.format(DATE_TIME_FORMATTER), true)
.addField(
"Account creation date",
member.user.timeCreated.format(DATE_TIME_FORMATTER),
true
)
.build()
privateChannel.sendMessageEmbeds(userDateMessage).queue()
targetFound = true
break
}
}
if (!targetFound) {
privateChannel.sendMessage("The specified user was not found.").queue()
}
}
} else {
event.channel.sendMessage("This command only works in a guild text channel.").queue()
}
}
}
| apache-2.0 | 15973f16bce2e5f0f2ef61dfc6b8ffff | 50.472222 | 170 | 0.588055 | 5.07208 | false | false | false | false |
iskandar1023/template | app/src/main/kotlin/substratum/theme/template/AdvancedConstants.kt | 1 | 2015 | package substratum.theme.template
object AdvancedConstants {
// Custom message on theme launch, see theme_strings.xml for changing the dialog content
// Set SHOW_DIALOG_REPEATEDLY to true if you want the dialog to be showed on every theme launch
const val SHOW_LAUNCH_DIALOG = false
const val SHOW_DIALOG_REPEATEDLY = false
// Blacklisted APKs to prevent theme launching, these include simple regex formatting, without
// full regex formatting (e.g. com.android. will block everything that starts with com.android.)
val BLACKLISTED_APPLICATIONS = arrayOf(
"cc.madkite.freedom",
"zone.jasi2169.uretpatcher",
"uret.jasi2169.patcher",
"p.jasi2169.al3",
"com.dimonvideo.luckypatcher",
"com.chelpus.lackypatch",
"com.forpda.lp",
"com.android.vending.billing.InAppBillingService",
"com.android.vending.billing.InAppBillingSorvice",
"com.android.vendinc",
"com.appcake",
"ac.market.store",
"org.sbtools.gamehack",
"com.zune.gamekiller",
"com.aag.killer",
"com.killerapp.gamekiller",
"cn.lm.sq",
"net.schwarzis.game_cih",
"org.creeplays.hack",
"com.baseappfull.fwd",
"com.zmapp",
"com.dv.marketmod.installer",
"org.mobilism.android",
"com.blackmartalpha",
"org.blackmart.market"
)
// List of all organization theming systems officially supported by the team
val ORGANIZATION_THEME_SYSTEMS = arrayOf(
"projekt.substratum",
"projekt.substratum.lite",
"projekt.themer"
)
// List of other theme systems that are officially unsupported by the team, but fully supported
// by their corresponding organizations
val OTHER_THEME_SYSTEMS = arrayOf(
"com.slimroms.thememanager",
"com.slimroms.omsbackend"
)
}
| apache-2.0 | e12bb610164e8bbe3a3f4742f85af18a | 37.018868 | 100 | 0.614392 | 3.974359 | false | false | false | false |
SuperWangKai/Urho3D | android/launcher-app/src/main/java/io/urho3d/launcher/MainActivity.kt | 1 | 2085 | //
// Copyright (c) 2008-2020 the Urho3D project.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
package io.urho3d.launcher
import io.urho3d.UrhoActivity
class MainActivity : UrhoActivity() {
companion object {
const val argument = "argument"
}
private lateinit var arguments: List<String>
override fun getArguments() = arguments.toTypedArray()
override fun onLoadLibrary(libraryNames: MutableList<String>) {
// All runtime shared libraries must always be loaded if available
val regex = Regex("^(?:Urho3D|.+_shared)\$")
libraryNames.retainAll { regex.matches(it) }
// Parse the argument string
val argumentString = intent.getStringExtra(argument)
if (argumentString != null) arguments = argumentString.split(':')
else throw IllegalArgumentException("The MainActivity requires an argument to start")
// Must add the chosen sample library to the last of the list
libraryNames.add(arguments[0])
super.onLoadLibrary(libraryNames)
}
}
| mit | 351bbb9b0b79d9c852fb6ce87b042d2b | 38.339623 | 93 | 0.726619 | 4.654018 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/stories/media/StoryMediaSaveUploadBridge.kt | 1 | 13411 | package org.wordpress.android.ui.stories.media
import android.content.Context
import android.net.Uri
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import com.wordpress.stories.compose.frame.StorySaveEvents.StorySaveResult
import com.wordpress.stories.compose.story.StoryFrameItem
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode.MAIN
import org.wordpress.android.R.string
import org.wordpress.android.WordPress
import org.wordpress.android.fluxc.model.LocalOrRemoteId.LocalId
import org.wordpress.android.fluxc.model.MediaModel
import org.wordpress.android.fluxc.model.PostImmutableModel
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.modules.UI_THREAD
import org.wordpress.android.ui.posts.EditPostActivity.OnPostUpdatedFromUIListener
import org.wordpress.android.ui.posts.EditPostRepository
import org.wordpress.android.ui.posts.PostUtilsWrapper
import org.wordpress.android.ui.posts.SavePostToDbUseCase
import org.wordpress.android.ui.posts.editor.media.AddLocalMediaToPostUseCase
import org.wordpress.android.ui.posts.editor.media.EditorMediaListener
import org.wordpress.android.ui.stories.SaveStoryGutenbergBlockUseCase
import org.wordpress.android.ui.stories.StoriesTrackerHelper
import org.wordpress.android.ui.stories.StoryComposerActivity
import org.wordpress.android.ui.stories.StoryRepositoryWrapper
import org.wordpress.android.ui.stories.prefs.StoriesPrefs
import org.wordpress.android.ui.stories.prefs.StoriesPrefs.TempId
import org.wordpress.android.ui.uploads.UploadServiceFacade
import org.wordpress.android.util.EventBusWrapper
import org.wordpress.android.util.NetworkUtilsWrapper
import org.wordpress.android.util.ToastUtils
import org.wordpress.android.util.ToastUtils.Duration.LONG
import org.wordpress.android.util.helpers.MediaFile
import javax.inject.Inject
import javax.inject.Named
import kotlin.coroutines.CoroutineContext
/*
* StoryMediaSaveUploadBridge listens for StorySaveResult events triggered from the StorySaveService, and
* then transforms its result data into something the UploadService can use to upload the Story frame media
* first, then obtain the media Ids and collect them, and finally create a Post with the Story block
* with the obtained media Ids.
* This is different than uploading media to a regular Post because we don't need to replace the URLs for final Urls as
* we do in Aztec / Gutenberg.
*/
class StoryMediaSaveUploadBridge @Inject constructor(
private val addLocalMediaToPostUseCase: AddLocalMediaToPostUseCase,
private val savePostToDbUseCase: SavePostToDbUseCase,
private val storiesPrefs: StoriesPrefs,
private val uploadService: UploadServiceFacade,
private val networkUtils: NetworkUtilsWrapper,
private val postUtils: PostUtilsWrapper,
private val eventBusWrapper: EventBusWrapper,
private val storyRepositoryWrapper: StoryRepositoryWrapper,
@Named(UI_THREAD) private val mainDispatcher: CoroutineDispatcher
) : CoroutineScope, DefaultLifecycleObserver {
// region Fields
private var job: Job = Job()
private lateinit var appContext: Context
override val coroutineContext: CoroutineContext
get() = mainDispatcher + job
@Inject lateinit var editPostRepository: EditPostRepository
@Inject lateinit var storiesTrackerHelper: StoriesTrackerHelper
@Inject lateinit var saveStoryGutenbergBlockUseCase: SaveStoryGutenbergBlockUseCase
override fun onCreate(owner: LifecycleOwner) {
eventBusWrapper.register(this)
}
override fun onDestroy(owner: LifecycleOwner) {
// note: not sure whether this is ever going to get called if we attach it to the lifecycle of the Application
// class, but leaving it here prepared for the case when this class is attached to some other LifeCycleOwner
// other than the Application.
cancelAddMediaToEditorActions()
eventBusWrapper.unregister(this)
}
fun init(context: Context) {
appContext = context
}
// region Adding new composed / processed frames to a Story post
private fun addNewStoryFrameMediaItemsToPostAndUploadAsync(site: SiteModel, saveResult: StorySaveResult) {
// let's invoke the UploadService and enqueue all the files that were saved by the FrameSaveService
val frames = storyRepositoryWrapper.getStoryAtIndex(saveResult.storyIndex).frames
addNewMediaItemsInStoryFramesToPostAsync(site, frames, saveResult.isEditMode)
}
private fun addNewMediaItemsInStoryFramesToPostAsync(
site: SiteModel,
frames: List<StoryFrameItem>,
isEditMode: Boolean
) {
val uriList = frames.map { Uri.fromFile(it.composedFrameFile) }
// this is similar to addNewMediaItemsToEditorAsync in EditorMedia
launch {
val localEditorMediaListener = object : EditorMediaListener {
override fun appendMediaFiles(mediaFiles: Map<String, MediaFile>) {
if (!isEditMode) {
saveStoryGutenbergBlockUseCase.assignAltOnEachMediaFile(frames, ArrayList(mediaFiles.values))
saveStoryGutenbergBlockUseCase.buildJetpackStoryBlockInPost(
editPostRepository,
ArrayList(mediaFiles.values)
)
} else {
// no op: in edit mode, we're handling replacing of the block's mediaFiles in Gutenberg
}
}
override fun getImmutablePost(): PostImmutableModel {
return editPostRepository.getPost()!!
}
override fun syncPostObjectWithUiAndSaveIt(listener: OnPostUpdatedFromUIListener?) {
// no op
// WARNING: don't remove this, we need to call the listener no matter what,
// so save & upload actually happen
listener?.onPostUpdatedFromUI(null)
}
override fun advertiseImageOptimization(listener: () -> Unit) {
// no op
}
override fun onMediaModelsCreatedFromOptimizedUris(oldUriToMediaFiles: Map<Uri, MediaModel>) {
// in order to support Story editing capabilities, we save a serialized version of the Story slides
// after their composedFrameFiles have been processed.
// here we change the ids on the actual StoryFrameItems, and also update the flattened / composed
// image urls with the new URLs which may have been replaced after image optimization
// find the MediaModel for a given Uri from composedFrameFile
for (frame in frames) {
// if the old URI in frame.composedFrameFile exists as a key in the passed map, then update that
// value with the new (probably optimized) URL and also keep track of the new id.
val oldUri = Uri.fromFile(frame.composedFrameFile)
val mediaModel = oldUriToMediaFiles.get(oldUri)
mediaModel?.let {
val oldTemporaryId = frame.id ?: ""
frame.id = it.id.toString()
// set alt text on MediaModel too
mediaModel.alt = StoryFrameItem.getAltTextFromFrameAddedViews(frame)
// if prefs has this Slide with the temporary key, replace it
// if not, let's now save the new slide with the local key
storiesPrefs.replaceTempMediaIdKeyedSlideWithLocalMediaIdKeyedSlide(
TempId(oldTemporaryId),
LocalId(it.id),
it.localSiteId.toLong()
) ?: storiesPrefs.saveSlideWithLocalId(
it.localSiteId.toLong(),
// use the local id to save the original, will be replaced later
// with mediaModel.mediaId after uploading to the remote site
LocalId(it.id),
frame
)
// for editMode, we'll need to tell the Gutenberg Editor to replace their mediaFiles
// ids with the new MediaModel local ids are created so, broadcasting the event.
if (isEditMode) {
// finally send the event that this frameId has changed
eventBusWrapper.postSticky(
StoryFrameMediaModelCreatedEvent(
oldTemporaryId,
it.id,
oldUri.toString(),
frame
)
)
}
}
}
}
override fun showVideoDurationLimitWarning(fileName: String) {
ToastUtils.showToast(
appContext,
string.error_media_video_duration_exceeds_limit,
LONG
)
}
}
addLocalMediaToPostUseCase.addNewMediaToEditorAsync(
uriList,
site,
freshlyTaken = false, // we don't care about this
editorMediaListener = localEditorMediaListener,
doUploadAfterAdding = true,
trackEvent = false // Already tracked event when media were first added to the story
)
// only save this post if we're not currently in edit mode
// In edit mode, we'll let the Gutenberg editor save the edited block if / when needed.
if (!isEditMode) {
postUtils.preparePostForPublish(requireNotNull(editPostRepository.getEditablePost()), site)
savePostToDbUseCase.savePostToDb(editPostRepository, site)
if (networkUtils.isNetworkAvailable()) {
postUtils.trackSavePostAnalytics(
editPostRepository.getPost(),
site
)
uploadService.uploadPost(appContext, editPostRepository.id, true)
// SAVED_ONLINE
storiesTrackerHelper.trackStoryPostSavedEvent(uriList.size, site, false)
} else {
// SAVED_LOCALLY
storiesTrackerHelper.trackStoryPostSavedEvent(uriList.size, site, true)
// no op, when network is available the offline mode in WPAndroid will gather the queued Post
// and try to upload.
}
}
}
}
// endregion
private fun cancelAddMediaToEditorActions() {
job.cancel()
}
@Subscribe(sticky = true, threadMode = MAIN)
fun onEventMainThread(event: StorySaveResult) {
// track event
storiesTrackerHelper.trackStorySaveResultEvent(event)
event.metadata?.let {
val site = it.getSerializable(WordPress.SITE) as SiteModel
val story = storyRepositoryWrapper.getStoryAtIndex(event.storyIndex)
saveStoryGutenbergBlockUseCase.saveNewLocalFilesToStoriesPrefsTempSlides(
site,
event.storyIndex,
story.frames
)
// only trigger the bridge preparation and the UploadService if the Story is now complete
// otherwise we can be receiving successful retry events for individual frames we shouldn't care about just
// yet.
if (isStorySavingComplete(event) && !event.isRetry) {
// only remove it if it was successful - we want to keep it and show a snackbar once when the user
// comes back to the app if it wasn't, see MySiteFragment for details.
eventBusWrapper.removeStickyEvent(event)
editPostRepository.loadPostByLocalPostId(it.getInt(StoryComposerActivity.KEY_POST_LOCAL_ID))
// media upload tracking already in addLocalMediaToPostUseCase.addNewMediaToEditorAsync
addNewStoryFrameMediaItemsToPostAndUploadAsync(site, event)
}
}
}
private fun isStorySavingComplete(event: StorySaveResult): Boolean {
return (event.isSuccess() &&
event.frameSaveResult.size == storyRepositoryWrapper.getStoryAtIndex(event.storyIndex).frames.size)
}
data class StoryFrameMediaModelCreatedEvent(
val oldId: String,
val newId: Int,
val oldUrl: String,
val frame: StoryFrameItem
)
}
| gpl-2.0 | 331c298c300822dd4ca3162c65f9bb33 | 48.67037 | 120 | 0.629558 | 5.51666 | false | false | false | false |
NCBSinfo/NCBSinfo | app/src/main/java/com/rohitsuratekar/NCBSinfo/viewmodels/EditTransportViewModel.kt | 1 | 5852 | package com.rohitsuratekar.NCBSinfo.viewmodels
import android.os.AsyncTask
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.rohitsuratekar.NCBSinfo.common.Constants
import com.rohitsuratekar.NCBSinfo.common.serverTimestamp
import com.rohitsuratekar.NCBSinfo.database.TripData
import com.rohitsuratekar.NCBSinfo.di.Repository
import com.rohitsuratekar.NCBSinfo.models.EditTransportStep
import com.rohitsuratekar.NCBSinfo.models.Route
import java.util.*
class EditTransportViewModel : ViewModel() {
val origin = MutableLiveData<String>()
val destination = MutableLiveData<String>()
val stepUpdate = MutableLiveData<MutableList<EditTransportStep>>()
val tripList = MutableLiveData<MutableList<String>>()
val tripSelected = MutableLiveData<Boolean>()
val transportType = MutableLiveData<Int>()
val transportFrequency = MutableLiveData<Int>()
val frequencyDetails = MutableLiveData<MutableList<Int>>()
val inputRouteID = MutableLiveData<Int>()
val currentRoute = MutableLiveData<Route>()
val routeDeleted = MutableLiveData<Boolean>()
val selectedTrip = MutableLiveData<TripData>()
val skippedTrips = MutableLiveData<Boolean>()
fun setInputRouteID(routeID: Int) {
inputRouteID.postValue(routeID)
}
fun setOrigin(string: String) {
origin.postValue(string)
}
fun setDestination(string: String) {
destination.postValue(string)
}
fun setRoute(route: Route) {
currentRoute.postValue(route)
}
fun setSelectedTrip(tripData: TripData) {
selectedTrip.postValue(tripData)
}
fun addSteps(list: List<EditTransportStep>) {
val k = mutableListOf<EditTransportStep>()
k.addAll(list)
stepUpdate.postValue(k)
}
fun setType(type: Int) {
transportType.postValue(type)
updateConfirmState(Constants.EDIT_TYPE, true)
}
fun setFrequency(id: Int) {
transportFrequency.postValue(id)
}
fun setFrequencyData(list: MutableList<Int>) {
frequencyDetails.postValue(list)
if (list.sum() > 0) {
updateConfirmState(Constants.EDIT_FREQUENCY, true)
} else {
updateConfirmState(Constants.EDIT_FREQUENCY, false)
}
}
fun updateReadState(step: Int) {
val returnList = mutableListOf<EditTransportStep>()
stepUpdate.value?.let {
for (t in it) {
if (t.number == step) {
t.isSeen = true
}
returnList.add(t)
}
}
if (returnList.isNotEmpty()) {
stepUpdate.postValue(returnList)
}
}
fun updateConfirmState(step: Int, isConfirmed: Boolean) {
val returnList = mutableListOf<EditTransportStep>()
stepUpdate.value?.let {
for (t in it) {
if (t.number == step) {
t.isComplete = isConfirmed
}
returnList.add(t)
}
}
if (returnList.isNotEmpty()) {
stepUpdate.postValue(returnList)
}
}
fun updateTrips(list: List<String>) {
val k = mutableListOf<String>()
k.addAll(list)
tripList.postValue(k)
updateConfirmState(Constants.EDIT_TRIPS, k.isNotEmpty())
}
fun updateTripSelection(value: Boolean) {
tripSelected.postValue(value)
updateConfirmState(Constants.EDIT_START_TRIP, value)
}
fun skipTrips(value: Boolean) {
skippedTrips.postValue(value)
}
fun clearAllAttributes() {
origin.postValue(null)
destination.postValue(null)
transportType.postValue(null)
transportFrequency.postValue(null)
tripList.postValue(null)
frequencyDetails.postValue(null)
tripSelected.postValue(null)
val returnList = mutableListOf<EditTransportStep>()
stepUpdate.value?.let {
for (t in it) {
t.isSeen = false
t.isComplete = false
returnList.add(t)
}
}
stepUpdate.postValue(returnList)
}
fun deleteRoute(repository: Repository, route: Route, selectedTrip: TripData?) {
DeleteRoute(repository, route, selectedTrip, object : OnDeleteRoute {
override fun deleted() {
routeDeleted.postValue(true)
}
}).execute()
}
class DeleteRoute(
private val repository: Repository,
private val route: Route,
private val selectedTrip: TripData?,
private val listener: OnDeleteRoute
) : AsyncTask<Void?, Void?, Void?>() {
override fun doInBackground(vararg params: Void?): Void? {
selectedTrip?.let {
repository.data()
.updateModifiedDate(route.routeData, Calendar.getInstance().serverTimestamp())
repository.data().deleteTrip(it)
//Check if any trip is available for the route. If not, delete the route
var totalTrips = 0
for (trip in repository.data().getTrips(route.routeData)) {
trip.trips?.let { p ->
totalTrips += p.size
}
}
if (totalTrips == 0) {
repository.data().deleteRoute(route.routeData)
}
} ?: kotlin.run {
repository.data().deleteRoute(route.routeData)
}
listener.deleted()
return null
}
}
interface OnDeleteRoute {
fun deleted()
}
} | mit | 85db8a2301c2505966ef402ac0374f70 | 29.989071 | 98 | 0.587662 | 4.864505 | false | false | false | false |
mdaniel/intellij-community | java/idea-ui/src/com/intellij/ide/projectWizard/generators/BuildSystemJavaNewProjectWizardData.kt | 9 | 925 | // 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.ide.projectWizard.generators
import com.intellij.ide.wizard.BuildSystemNewProjectWizardData
import com.intellij.ide.wizard.NewProjectWizardStep
import com.intellij.openapi.util.Key
interface BuildSystemJavaNewProjectWizardData: BuildSystemNewProjectWizardData {
companion object {
@JvmStatic val KEY = Key.create<BuildSystemJavaNewProjectWizardData>(BuildSystemJavaNewProjectWizardData::class.java.name)
@JvmStatic val NewProjectWizardStep.buildSystemData get() = data.getUserData(KEY)!!
@JvmStatic val NewProjectWizardStep.buildSystemProperty get() = buildSystemData.buildSystemProperty
@JvmStatic var NewProjectWizardStep.buildSystem get() = buildSystemData.buildSystem; set(it) { buildSystemData.buildSystem = it }
}
} | apache-2.0 | 9e9a11cf0e0914b87283adb38c200597 | 53.470588 | 158 | 0.820541 | 5.054645 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/compiler-plugins/kotlinx-serialization/common/src/org/jetbrains/kotlin/idea/compilerPlugin/kotlinxSerialization/quickfixes/JsonRedundantQuickFix.kt | 1 | 3562 | // 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.compilerPlugin.kotlinxSerialization.quickfixes
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.ScrollType
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction
import org.jetbrains.kotlin.idea.quickfix.KotlinSingleIntentionActionFactory
import org.jetbrains.kotlin.idea.refactoring.chooseContainerElementIfNecessary
import org.jetbrains.kotlin.idea.refactoring.getExtractionContainers
import org.jetbrains.kotlin.idea.refactoring.introduce.introduceProperty.KotlinIntroducePropertyHandler
import org.jetbrains.kotlin.idea.refactoring.introduce.showErrorHintByKey
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getOutermostParentContainedIn
import org.jetbrains.kotlinx.serialization.compiler.diagnostic.SerializationErrors
import org.jetbrains.kotlin.idea.compilerPlugin.kotlinxSerialization.KotlinSerializationBundle
internal class JsonRedundantQuickFix(expression: KtCallExpression) : KotlinQuickFixAction<KtCallExpression>(expression) {
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
editor ?: return
val element = element ?: return
selectContainer(element, project, editor) {
editor.scrollingModel.scrollToCaret(ScrollType.MAKE_VISIBLE)
val outermostParent = element.getOutermostParentContainedIn(it)
if (outermostParent == null) {
showErrorHintByKey(project, editor, "cannot.refactor.no.container", text)
return@selectContainer
}
KotlinIntroducePropertyHandler().doInvoke(project, editor, file, listOf(element), outermostParent)
}
}
override fun getFamilyName(): String = text
override fun getText(): String = KotlinSerializationBundle.message("extract.json.to.property")
object Factory : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): IntentionAction? {
if (diagnostic.factory != SerializationErrors.JSON_FORMAT_REDUNDANT) return null
val castedDiagnostic = SerializationErrors.JSON_FORMAT_REDUNDANT.cast(diagnostic)
val element: KtCallExpression = castedDiagnostic.psiElement as? KtCallExpression ?: return null
return JsonRedundantQuickFix(element)
}
}
private fun selectContainer(element: PsiElement, project: Project, editor: Editor, onSelect: (PsiElement) -> Unit) {
val parent = element.parent ?: throw AssertionError("Should have at least one parent")
val containers = parent.getExtractionContainers(strict = true, includeAll = true)
.filter { it is KtClassBody || (it is KtFile && !it.isScript()) }
if (containers.isEmpty()) {
showErrorHintByKey(project, editor, "cannot.refactor.no.container", text)
return
}
chooseContainerElementIfNecessary(
containers,
editor,
KotlinBundle.message("title.select.target.code.block"),
true,
{ it },
{ onSelect(it) }
)
}
}
| apache-2.0 | 488975df321a67d42b3d0a3c9158f9ed | 46.493333 | 158 | 0.740314 | 5.03819 | false | false | false | false |
JavaEden/Orchid-Core | OrchidCore/src/main/kotlin/com/eden/orchid/api/resources/resourcesource/FileResourceSource.kt | 2 | 3418 | package com.eden.orchid.api.resources.resourcesource
import com.eden.common.util.EdenUtils
import com.eden.orchid.api.OrchidContext
import com.eden.orchid.api.resources.resource.FileResource
import com.eden.orchid.api.resources.resource.OrchidResource
import com.eden.orchid.api.theme.pages.OrchidReference
import com.eden.orchid.utilities.OrchidUtils
import org.apache.commons.io.FileUtils
import java.io.File
import java.nio.file.Path
import java.util.ArrayList
/**
* An OrchidResourceSource that loads resource files from a directory on disk.
*/
class FileResourceSource(
private val baseDirectory: Path,
override val priority: Int,
override val scope: OrchidResourceSource.Scope
) : OrchidResourceSource {
override fun getResourceEntry(context: OrchidContext, fileName: String): OrchidResource? {
val file = baseDirectory.resolve(OrchidUtils.normalizePath(fileName)).toFile()
return if (file.exists() && !file.isDirectory)
FileResource(
OrchidReference(
context,
FileResource.pathFromFile(file, baseDirectory)
),
file
) else null
}
override fun getResourceEntries(
context: OrchidContext,
dirName: String,
fileExtensions: Array<String>?,
recursive: Boolean
): List<OrchidResource> {
val entries = ArrayList<OrchidResource>()
val file = baseDirectory.resolve(OrchidUtils.normalizePath(dirName)).toFile()
if (file.exists() && file.isDirectory) {
val newFiles = FileUtils.listFiles(file, fileExtensions, recursive)
if (!EdenUtils.isEmpty(newFiles)) {
for (resourceAsFile in newFiles) {
val newFile = resourceAsFile as File
if (!isIgnoredFile(context, file)) {
entries.add(
FileResource(
OrchidReference(
context,
FileResource.pathFromFile(newFile, baseDirectory)
),
newFile
)
)
}
}
}
}
return entries
}
private fun isIgnoredFile(context: OrchidContext, file: File): Boolean {
return context.ignoredFilenames?.any { file.name == it } ?: false
}
override fun compareTo(other: OrchidResourceSource): Int {
val superValue = super.compareTo(other)
return if (superValue != 0) superValue
else if (other is FileResourceSource) other.baseDirectory.compareTo(baseDirectory)
else superValue
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as FileResourceSource
if (baseDirectory != other.baseDirectory) return false
if (priority != other.priority) return false
if (scope != other.scope) return false
return true
}
private val _hashcode by lazy {
var result = baseDirectory.hashCode()
result = 31 * result + priority
result = 31 * result + scope.hashCode()
result
}
override fun hashCode(): Int {
return _hashcode
}
}
| mit | 6d4d385a7686a60e28bda69bacfdeb99 | 32.184466 | 94 | 0.598303 | 5.258462 | false | false | false | false |
JavaEden/Orchid-Core | OrchidCore/src/main/kotlin/com/eden/orchid/api/resources/ResourceServiceImpl.kt | 2 | 4596 | package com.eden.orchid.api.resources
import com.eden.orchid.Orchid.Lifecycle.ClearCache
import com.eden.orchid.api.OrchidContext
import com.eden.orchid.api.events.On
import com.eden.orchid.api.events.OrchidEventListener
import com.eden.orchid.api.options.annotations.Archetype
import com.eden.orchid.api.options.annotations.Description
import com.eden.orchid.api.options.annotations.Option
import com.eden.orchid.api.options.annotations.StringDefault
import com.eden.orchid.api.options.archetypes.ConfigArchetype
import com.eden.orchid.api.resources.resource.OrchidResource
import com.eden.orchid.api.resources.resourcesource.CachingResourceSourceCacheKey
import com.eden.orchid.api.resources.resourcesource.DataResourceSource
import com.eden.orchid.api.resources.resourcesource.DelegatingResourceSource
import com.eden.orchid.api.resources.resourcesource.FlexibleResourceSource
import com.eden.orchid.api.resources.resourcesource.LocalResourceSource
import com.eden.orchid.api.resources.resourcesource.OrchidResourceSource
import com.eden.orchid.api.resources.resourcesource.TemplateResourceSource
import com.eden.orchid.api.resources.resourcesource.cached
import com.eden.orchid.api.resources.resourcesource.flexible
import com.eden.orchid.api.resources.resourcesource.useForData
import com.eden.orchid.api.resources.resourcesource.useForTemplates
import com.eden.orchid.api.theme.AbstractTheme
import com.eden.orchid.utilities.LRUCache
import com.eden.orchid.utilities.SuppressedWarnings
import java.util.ArrayList
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
@Description(value = "How Orchid locates resources.", name = "Resources")
@Archetype(value = ConfigArchetype::class, key = "services.resources")
@JvmSuppressWildcards
class ResourceServiceImpl
@Inject
constructor(
private val resourceSources: Set<OrchidResourceSource>
) : ResourceService, OrchidEventListener {
private val resourceCache: LRUCache<CachingResourceSourceCacheKey, OrchidResource?> = LRUCache()
// TODO: this is not available early enough because we need options to be loaded before they can be extracted, but
// this class needs to be extracted before we can properly load the options to ignore specific files. It's a
// circular dependency that needs to be refactored. Maybe create a "primordial resource source" for the initial
// bootstrapping of Orchid?
@Option
@StringDefault(".DS_store", ".localized")
@Description("A list of filenames to globally filter out files from being sourced. Should be used primarily for ignoring pesky hidden or system files that are not intended to be used as site content.")
private var ignoredFilenames: Array<String> = arrayOf(".DS_store", ".localized")
override fun initialize(context: OrchidContext) {}
override fun getDefaultResourceSource(
scopes: OrchidResourceSource.Scope?,
theme: AbstractTheme?
): OrchidResourceSource {
val delegates = if (theme != null) resourceSources + theme.resourceSource else resourceSources
val validScopes = scopes?.let { listOf(it) } ?: emptyList()
return DelegatingResourceSource(
delegates,
validScopes,
0,
LocalResourceSource
).cached(resourceCache, theme, validScopes)
}
override fun getFlexibleResourceSource(
scopes: OrchidResourceSource.Scope?,
theme: AbstractTheme?
): FlexibleResourceSource {
return getDefaultResourceSource(scopes, theme).flexible()
}
override fun getTemplateResourceSource(
scopes: OrchidResourceSource.Scope?,
theme: AbstractTheme
): TemplateResourceSource {
return getDefaultResourceSource(scopes, theme).useForTemplates(theme)
}
override fun getDataResourceSource(scopes: OrchidResourceSource.Scope?): DataResourceSource {
return getDefaultResourceSource(scopes, null).useForData()
}
// Delombok
//----------------------------------------------------------------------------------------------------------------------
override fun getIgnoredFilenames(): Array<String> {
return ignoredFilenames
}
fun setIgnoredFilenames(ignoredFilenames: Array<String>) {
this.ignoredFilenames = ignoredFilenames
}
// Cache Implementation
//----------------------------------------------------------------------------------------------------------------------
@On(ClearCache::class)
@Suppress(SuppressedWarnings.UNUSED_PARAMETER)
fun onClearCache(event: ClearCache?) {
resourceCache.clear()
}
}
| mit | e8bcac4ac6b50d2499ddd7f8574e1a0d | 42.358491 | 205 | 0.731723 | 4.868644 | false | false | false | false |
phicdy/toto-anticipation | android/api/src/main/java/com/phicdy/totoanticipation/api/RakutenTotoInfoParser.kt | 1 | 3370 | package com.phicdy.totoanticipation.api
import android.text.TextUtils
import com.phicdy.totoanticipation.domain.Deadline
import com.phicdy.totoanticipation.domain.Game
import org.jsoup.Jsoup
import java.util.ArrayList
import java.util.regex.Pattern
import javax.inject.Inject
class RakutenTotoInfoParser @Inject constructor() {
/**
*
* Parse rakuten toto info page and return game list.
*
* e.g.
* <table class="tbl-result" border="1" cellspacing="0">
* <thead>
* <tr>
* <th class="date">開催日</th>
* <th class="place">競技場</th>
* <th class="num">No</th>
* <th colspan="3" class="game">指定試合(ホームvsアウェイ)</th>
</tr> *
</thead> *
* <tbody>
* <tr>
* <td class="date">04/22</td>
* <td class="place">埼玉</td>
* <td class="num">1</td>
* <td class="home">浦和</td>
* <td class="vs">VS</td>
* <td class="away">札幌</td>
</tr> *
* <tr>
* <td class="date">04/22</td>
* <td class="place">中銀スタ</td>
* <td class="num">2</td>
* <td class="home">甲府</td>
* <td class="vs">VS</td>
* <td class="away">C大阪</td>
</tr> *
* ...
</tbody> *
</table> *
*
* @param body HTML string of rakuten toto info page
* @return Game list of toto or empty list
*/
fun games(body: String): ArrayList<Game> {
val games = ArrayList<Game>()
if (TextUtils.isEmpty(body)) return games
val bodyDoc = Jsoup.parse(body)
val gameTable = bodyDoc.getElementsByClass("tbl-result").first() ?: return games
val trs = gameTable.getElementsByTag("tr")
for (i in 1 until trs.size) {
val tr = trs[i]
val tds = tr.getElementsByTag("td")
val homeTeam = tds[3].text()
val awayTeam = tds[5].text()
games.add(Game(homeTeam, awayTeam))
}
return games
}
/**
*
* Parse rakuten toto info page and return deadline time.
*
* e.g. Return 13:50 from below
* <table class=\"tbl-result-day\border=\"1\cellspacing=\"0\">
* <tr>
* <th rowspan=\"2\class=\"title\">販売予定<br></br>結果発表</th>
* <th>販売開始日</th>
* <th>販売終了日</th>
* <th>結果発表確定日</th>
</tr> *
* <tr>
* <td>2017年4月15日(土)</td>
* <td>2017年4月22日(土)<br></br>(ネット13:50)</td>
* <td>2017年4月24日(月)</td>
</tr> *
</table> *
*
* @param body HTML string of rakuten toto info page
* @return Deadline like "13:50" or null
*/
fun deadlineTime(body: String): Deadline? {
if (body.isEmpty()) return null
val bodyDoc = Jsoup.parse(body)
val gameTable = bodyDoc.getElementsByClass("tbl-result-day").first() ?: return null
val trs = gameTable.getElementsByTag("tr")
if (trs.size != 2) return null
val dayElement = trs[1]
val tds = dayElement.getElementsByTag("td")
if (tds.size != 3) return null
val deadlineDayElement = tds[1]
val deadlineDayStr = deadlineDayElement.text()
val pattern = Pattern.compile("[0-9]+:[0-9]+")
val matcher = pattern.matcher(deadlineDayStr)
return if (matcher.find()) Deadline(matcher.group()) else null
}
}
| apache-2.0 | 0aa0e36a924f5eb9ff0e7be82f02e07f | 29.980769 | 91 | 0.564556 | 3.077364 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/tests/testData/formatter/trailingComma/typeParameters/TypeParameterList.kt | 13 | 2780 | class A1<
x: String,
y: String,
>
class F<x: String, y: String>
class F2<x: String, y
: String>
class B1<
x: String,
y: String
>
class C1<
x: String,
y: String,>
class D1<
x: String,
y: String
,>
class A2<
x: String,
y: String,
z: String,
>
class B2<
x: String,
y: String,
z: String
>
class C2<
x: String,
y: String,
z: String,>
class D2<
x: String,
y: String,
z: String
,>
class A3<
x: String,
>
class B3<
x: String
>
class C3<
x: String,>
class D3<
x: String
,>
class A4<
x: String ,
y: String,
z ,
>
class B4<
x: String,
y,
z: String
>
class C4<
x: String,
y: String,
z: String ,>
class D4<
x: String,
y,
z: String
, >
class E1<
x, y: String,
z: String
, >
class E2<
x: String, y: String, z: String
>
class C<
z: String, v
>
fun <x: String,
y: String,
> a1() = Unit
fun <x: String,
y: String
> b1() = Unit
fun <
x: String,
y: String,> c1() = Unit
fun <
x: String,
y: String
,> d1() = Unit
fun <
x: String,
y: String,
z: String,
> a2() = Unit
fun <
x: String,
y: String,
z: String
> b2() = Unit
fun <
x: String,
y: String,
z: String,> c2() = Unit
fun <
x: String,
y: String,
z: String
,> d2() = Unit
fun <
x: String,
> a3() = Unit
fun <
x: String
> b3() = Unit
fun <
x: String,> c3() = Unit
fun <
x: String
,> d3() = Unit
fun <
x: String
,
y: String,
z: String ,
> a4() = Unit
fun <
x: String,
y: String,
z: String
> b4() = Unit
fun <x: String,
y: String,
z: String ,> c4() = Unit
fun <
x: String,
y: String,
z: String
, > d4() = Unit
fun <
x
> foo() {
}
fun <T> ag() {
}
fun <T,> ag() {
}
fun <
T> ag() {
}
class C<
x: Int
>
class G<
x: String, y: String
, /* */ z: String
>
class G<
x: String, y: String
/* */, /* */ z: String
>()
class H<
x: String, /*
*/ y: String,
z: String ,>
class J<
x: String, y: String , z: String /*
*/
, >
class K<
x: String, y: String,
z: String
, >
class L<
x: String, y: String, z: String
>
class C<
x: Int // adad
>
class G<
x: String, y: String
, /* */ z: String // adad
>
class G<
x: String, y: String
/* */, /* */ z: String /**/,
>()
class H<
x: String, /*
*/ y: String,
z: String /*
*/ ,>
class J<
x: String, y: String , z: String /*
*/
, /**/ >
class K<
x: String, y: String,
z: String // aw
, >
class L<
x: String, y: String, z: String //awd
>
// SET_TRUE: ALLOW_TRAILING_COMMA
| apache-2.0 | 91fc783035d875177055cbfb745a4ba8 | 9.570342 | 41 | 0.451079 | 2.529572 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/dfa/KtThisDescriptor.kt | 4 | 1117 | // 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.inspections.dfa
import com.intellij.codeInspection.dataFlow.types.DfType
import com.intellij.codeInspection.dataFlow.value.DfaVariableValue
import com.intellij.codeInspection.dataFlow.value.VariableDescriptor
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameUnsafe
class KtThisDescriptor(val descriptor: DeclarationDescriptor, private val dfType : DfType) : VariableDescriptor {
override fun isStable(): Boolean {
return true
}
override fun isImplicitReadPossible(): Boolean {
return true
}
override fun getDfType(qualifier: DfaVariableValue?): DfType = dfType
override fun equals(other: Any?): Boolean = other is KtThisDescriptor && other.descriptor == descriptor
override fun hashCode(): Int = descriptor.hashCode()
override fun toString(): String = "${descriptor.fqNameUnsafe.asString()}.this"
} | apache-2.0 | 4cb10e83e8cd824e84f80cbe1218bec2 | 42 | 158 | 0.777081 | 4.942478 | false | false | false | false |
asedunov/intellij-community | plugins/settings-repository/src/upstreamEditor.kt | 2 | 4465 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.settingsRepository
import com.intellij.internal.statistic.ActionsCollector
import com.intellij.notification.NotificationType
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.ui.TextFieldWithBrowseButton
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.text.StringUtil
import com.intellij.util.ArrayUtil
import com.intellij.util.text.nullize
import org.jetbrains.settingsRepository.actions.NOTIFICATION_GROUP
import java.awt.Container
import java.awt.event.ActionEvent
import javax.swing.AbstractAction
import javax.swing.Action
internal fun checkUrl(url: String?): Boolean {
try {
return url != null && url.length > 1 && icsManager.repositoryService.checkUrl(url, false)
}
catch (e: Throwable) {
return false
}
}
fun updateSyncButtonState(url: String?, syncActions: Array<Action>) {
val enabled = checkUrl(url)
for (syncAction in syncActions) {
syncAction.isEnabled = enabled
}
}
fun createMergeActions(project: Project?, urlTextField: TextFieldWithBrowseButton, dialogParent: Container, okAction: (() -> Unit)): Array<Action> {
var syncTypes = SyncType.values()
if (SystemInfo.isMac) {
syncTypes = ArrayUtil.reverseArray(syncTypes)
}
val icsManager = icsManager
return Array(3) {
val syncType = syncTypes[it]
object : AbstractAction(icsMessage("action.${if (syncType == SyncType.MERGE) "Merge" else (if (syncType == SyncType.OVERWRITE_LOCAL) "ResetToTheirs" else "ResetToMy")}Settings.text")) {
private fun saveRemoteRepositoryUrl(): Boolean {
val url = urlTextField.text.nullize()
if (url != null && !icsManager.repositoryService.checkUrl(url, true, project)) {
return false
}
val repositoryManager = icsManager.repositoryManager
repositoryManager.createRepositoryIfNeed()
repositoryManager.setUpstream(url, null)
return true
}
override fun actionPerformed(event: ActionEvent) {
ActionsCollector.getInstance().record("Ics." + getValue(Action.NAME))
val repositoryWillBeCreated = !icsManager.repositoryManager.isRepositoryExists()
var upstreamSet = false
try {
if (!saveRemoteRepositoryUrl()) {
if (repositoryWillBeCreated) {
// remove created repository
icsManager.repositoryManager.deleteRepository()
}
return
}
upstreamSet = true
if (repositoryWillBeCreated) {
icsManager.setApplicationLevelStreamProvider()
}
if (repositoryWillBeCreated && syncType != SyncType.OVERWRITE_LOCAL) {
ApplicationManager.getApplication().saveSettings()
icsManager.sync(syncType, project, { copyLocalConfig() })
}
else {
icsManager.sync(syncType, project, null)
}
}
catch (e: Throwable) {
if (repositoryWillBeCreated) {
// remove created repository
icsManager.repositoryManager.deleteRepository()
}
LOG.warn(e)
if (!upstreamSet || e is NoRemoteRepositoryException) {
Messages.showErrorDialog(dialogParent, icsMessage("set.upstream.failed.message", e.message), icsMessage("set.upstream.failed.title"))
}
else {
Messages.showErrorDialog(dialogParent, StringUtil.notNullize(e.message, "Internal error"), icsMessage(if (e is AuthenticationException) "sync.not.authorized.title" else "sync.rejected.title"))
}
return
}
NOTIFICATION_GROUP.createNotification(icsMessage("sync.done.message"), NotificationType.INFORMATION).notify(project)
okAction()
}
}
}
} | apache-2.0 | 2e5322083bff2b08779b6014d58c0852 | 35.308943 | 204 | 0.692721 | 4.739915 | false | false | false | false |
code-disaster/lwjgl3 | modules/lwjgl/opengles/src/templates/kotlin/opengles/templates/OES_tessellation_shader.kt | 4 | 8997 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package opengles.templates
import org.lwjgl.generator.*
import opengles.*
val OES_tessellation_shader = "OESTessellationShader".nativeClassGLES("OES_tessellation_shader", postfix = OES) {
documentation =
"""
Native bindings to the $registryLink extension.
This extension introduces new tessellation stages and two new shader types to the OpenGL ES primitive processing pipeline. These pipeline stages
operate on a new basic primitive type, called a patch. A patch consists of a fixed-size collection of vertices, each with per-vertex attributes, plus a
number of associated per-patch attributes. Tessellation control shaders transform an input patch specified by the application, computing per-vertex and
per-patch attributes for a new output patch. A fixed-function tessellation primitive generator subdivides the patch, and tessellation evaluation
shaders are used to compute the position and attributes of each vertex produced by the tessellator.
When tessellation is active, it begins by running the optional tessellation control shader. This shader consumes an input patch and produces a new
fixed-size output patch. The output patch consists of an array of vertices, and a set of per-patch attributes. The per-patch attributes include
tessellation levels that control how finely the patch will be tessellated. For each patch processed, multiple tessellation control shader invocations
are performed -- one per output patch vertex. Each tessellation control shader invocation writes all the attributes of its corresponding output patch
vertex. A tessellation control shader may also read the per-vertex outputs of other tessellation control shader invocations, as well as read and write
shared per-patch outputs. The tessellation control shader invocations for a single patch effectively run as a group. A built-in barrier() function is
provided to allow synchronization points where no shader invocation will continue until all shader invocations have reached the barrier.
The tessellation primitive generator then decomposes a patch into a new set of primitives using the tessellation levels to determine how finely
tessellated the output should be. The primitive generator begins with either a triangle or a quad, and splits each outer edge of the primitive into a
number of segments approximately equal to the corresponding element of the outer tessellation level array. The interior of the primitive is tessellated
according to elements of the inner tessellation level array. The primitive generator has three modes: "triangles" and "quads" split a triangular or
quad-shaped patch into a set of triangles that cover the original patch; "isolines" splits a quad-shaped patch into a set of line strips running across
the patch horizontally. Each vertex generated by the tessellation primitive generator is assigned a (u,v) or (u,v,w) coordinate indicating its relative
location in the subdivided triangle or quad.
For each vertex produced by the tessellation primitive generator, the tessellation evaluation shader is run to compute its position and other
attributes of the vertex, using its (u,v) or (u,v,w) coordinate. When computing final vertex attributes, the tessellation evaluation shader can also
read the attributes of any of the vertices of the patch written by the tessellation control shader. Tessellation evaluation shader invocations are
completely independent, although all invocations for a single patch share the same collection of input vertices and per-patch attributes.
The tessellator operates on vertices after they have been transformed by a vertex shader. The primitives generated by the tessellator are passed
further down the OpenGL ES pipeline, where they can be used as inputs to geometry shaders, transform feedback, and the rasterizer.
The tessellation control and evaluation shaders are both optional. If neither shader type is present, the tessellation stage has no effect. However, if
either a tessellation control or a tessellation evaluation shader is present, the other must also be present.
Not all tessellation shader implementations have the ability to write the point size from a tessellation shader. Thus a second extension string and
shading language enable are provided for implementations which do support tessellation shader point size.
This extension relies on the OES_shader_io_blocks or EXT_shader_io_blocks extension to provide the required functionality for declaring input and
output blocks and interfacing between shaders.
This extension relies on the OES_gpu_shader5 or EXT_gpu_shader5 extension to provide the 'precise' and 'fma' functionality which are necessary to
ensure crack-free tessellation.
Requires ${GLES31.core}, ${OES_shader_io_blocks.capLink} or ${EXT_shader_io_blocks.capLink} and ${OES_gpu_shader5.capLink} or ${EXT_gpu_shader5.capLink}.
"""
IntConstant(
"Accepted by the {@code mode} parameter of DrawArrays, DrawElements, and other commands which draw primitives.",
"PATCHES_OES"..0xE
)
IntConstant(
"Accepted by the {@code pname} parameter of PatchParameteriOES, GetBooleanv, GetFloatv, GetIntegerv, and GetInteger64v.",
"PATCH_VERTICES_OES"..0x8E72
)
IntConstant(
"Accepted by the {@code pname} parameter of GetProgramiv.",
"TESS_CONTROL_OUTPUT_VERTICES_OES"..0x8E75,
"TESS_GEN_MODE_OES"..0x8E76,
"TESS_GEN_SPACING_OES"..0x8E77,
"TESS_GEN_VERTEX_ORDER_OES"..0x8E78,
"TESS_GEN_POINT_MODE_OES"..0x8E79
)
IntConstant(
"Returned by GetProgramiv when {@code pname} is TESS_GEN_MODE_OES.",
"ISOLINES_OES"..0x8E7A,
"QUADS_OES"..0x0007
)
IntConstant(
"Returned by GetProgramiv when {@code pname} is TESS_GEN_SPACING_OES.",
"FRACTIONAL_ODD_OES"..0x8E7B,
"FRACTIONAL_EVEN_OES"..0x8E7C
)
IntConstant(
"Accepted by the {@code pname} parameter of GetBooleanv, GetFloatv, GetIntegerv, and GetInteger64v.",
"MAX_PATCH_VERTICES_OES"..0x8E7D,
"MAX_TESS_GEN_LEVEL_OES"..0x8E7E,
"MAX_TESS_CONTROL_UNIFORM_COMPONENTS_OES"..0x8E7F,
"MAX_TESS_EVALUATION_UNIFORM_COMPONENTS_OES"..0x8E80,
"MAX_TESS_CONTROL_TEXTURE_IMAGE_UNITS_OES"..0x8E81,
"MAX_TESS_EVALUATION_TEXTURE_IMAGE_UNITS_OES"..0x8E82,
"MAX_TESS_CONTROL_OUTPUT_COMPONENTS_OES"..0x8E83,
"MAX_TESS_PATCH_COMPONENTS_OES"..0x8E84,
"MAX_TESS_CONTROL_TOTAL_OUTPUT_COMPONENTS_OES"..0x8E85,
"MAX_TESS_EVALUATION_OUTPUT_COMPONENTS_OES"..0x8E86,
"MAX_TESS_CONTROL_UNIFORM_BLOCKS_OES"..0x8E89,
"MAX_TESS_EVALUATION_UNIFORM_BLOCKS_OES"..0x8E8A,
"MAX_TESS_CONTROL_INPUT_COMPONENTS_OES"..0x886C,
"MAX_TESS_EVALUATION_INPUT_COMPONENTS_OES"..0x886D,
"MAX_COMBINED_TESS_CONTROL_UNIFORM_COMPONENTS_OES"..0x8E1E,
"MAX_COMBINED_TESS_EVALUATION_UNIFORM_COMPONENTS_OES"..0x8E1F,
"MAX_TESS_CONTROL_ATOMIC_COUNTER_BUFFERS_OES"..0x92CD,
"MAX_TESS_EVALUATION_ATOMIC_COUNTER_BUFFERS_OES"..0x92CE,
"MAX_TESS_CONTROL_ATOMIC_COUNTERS_OES"..0x92D3,
"MAX_TESS_EVALUATION_ATOMIC_COUNTERS_OES"..0x92D4,
"MAX_TESS_CONTROL_IMAGE_UNIFORMS_OES"..0x90CB,
"MAX_TESS_EVALUATION_IMAGE_UNIFORMS_OES"..0x90CC,
"MAX_TESS_CONTROL_SHADER_STORAGE_BLOCKS_OES"..0x90D8,
"MAX_TESS_EVALUATION_SHADER_STORAGE_BLOCKS_OES"..0x90D9,
"PRIMITIVE_RESTART_FOR_PATCHES_SUPPORTED_OES"..0x8221
)
IntConstant(
"Accepted by the {@code props} parameter of GetProgramResourceiv.",
"IS_PER_PATCH_OES"..0x92E7,
"REFERENCED_BY_TESS_CONTROL_SHADER_OES"..0x9307,
"REFERENCED_BY_TESS_EVALUATION_SHADER_OES"..0x9308
)
IntConstant(
"""
Accepted by the {@code type} parameter of CreateShader, by the {@code pname} parameter of GetProgramPipelineiv, and returned by the {@code params}
parameter of GetShaderiv.
""",
"TESS_EVALUATION_SHADER_OES"..0x8E87,
"TESS_CONTROL_SHADER_OES"..0x8E88
)
IntConstant(
"Accepted by the {@code stages} parameter of UseProgramStages.",
"TESS_CONTROL_SHADER_BIT_OES"..0x00000008,
"TESS_EVALUATION_SHADER_BIT_OES"..0x00000010
)
void(
"PatchParameteriOES",
"",
GLenum("pname", ""),
GLint("value", "")
)
}
val OES_tessellation_point_size = EXT_FLAG.nativeClassGLES("OES_tessellation_point_size", postfix = OES) {
documentation =
"""
When true, the ${registryLink("OES_tessellation_shader")} extension is supported.
"""
} | bsd-3-clause | 47719c24ec64200df8401f61a18da0bc | 53.533333 | 161 | 0.71735 | 4.221962 | false | false | false | false |
google/android-fhir | engine/src/main/java/com/google/android/fhir/sync/download/DownloaderImpl.kt | 1 | 2401 | /*
* 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.android.fhir.sync.download
import com.google.android.fhir.SyncDownloadContext
import com.google.android.fhir.sync.DataSource
import com.google.android.fhir.sync.DownloadState
import com.google.android.fhir.sync.DownloadWorkManager
import com.google.android.fhir.sync.Downloader
import com.google.android.fhir.sync.ResourceSyncException
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import org.hl7.fhir.r4.model.ResourceType
/**
* Implementation of the [Downloader]. It orchestrates the pre & post processing of resources via
* [DownloadWorkManager] and downloading of resources via [DataSource]. [Downloader] clients should
* call download and listen to the various states emitted by [DownloadWorkManager] as
* [DownloadState].
*/
internal class DownloaderImpl(
private val dataSource: DataSource,
private val downloadWorkManager: DownloadWorkManager
) : Downloader {
private val resourceTypeList = ResourceType.values().map { it.name }
override suspend fun download(context: SyncDownloadContext): Flow<DownloadState> = flow {
var resourceTypeToDownload: ResourceType = ResourceType.Bundle
emit(DownloadState.Started(resourceTypeToDownload))
var url = downloadWorkManager.getNextRequestUrl(context)
while (url != null) {
try {
resourceTypeToDownload =
ResourceType.fromCode(url.findAnyOf(resourceTypeList, ignoreCase = true)!!.second)
emit(
DownloadState.Success(
downloadWorkManager.processResponse(dataSource.download(url!!)).toList()
)
)
} catch (exception: Exception) {
emit(DownloadState.Failure(ResourceSyncException(resourceTypeToDownload, exception)))
}
url = downloadWorkManager.getNextRequestUrl(context)
}
}
}
| apache-2.0 | 7bc43baedd3d3cf186268d745651eb22 | 37.725806 | 99 | 0.752603 | 4.48785 | false | false | false | false |
emoji-gen/Emoji-Android | app/src/main/java/moe/pine/emoji/fragment/webview/WebViewLazyFragment.kt | 1 | 1635 | package moe.pine.emoji.fragment.webview
import android.animation.ObjectAnimator
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import kotlinx.android.synthetic.main.fragment_webview_lazy.*
import moe.pine.emoji.R
import moe.pine.emoji.view.common.WebView
/**
* Fragment for lazy loaded web view
* Created by pine on 2017/06/06.
*/
class WebViewLazyFragment : Fragment() {
companion object {
private val URL_KEY = "url"
fun newInstance(uri: String): WebViewLazyFragment {
val fragment = WebViewLazyFragment()
val arguments = Bundle()
arguments.putString(URL_KEY, uri)
fragment.arguments = arguments
return fragment
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_webview_lazy, container, false)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
val url = this.arguments!!.getString(URL_KEY)
this.web_view.loadUrl(url)
this.web_view.onPageFinishedListener = { this.onPageFinishedListener() }
}
private fun onPageFinishedListener() {
val webView: WebView? = this.web_view
webView ?: return
val showAnimator = ObjectAnimator.ofFloat(webView, View.ALPHA, 0f, 1f)
webView.visibility = View.VISIBLE
showAnimator.duration = 800
showAnimator.start()
}
} | mit | 081395f844b141f6cf9ba12389cf27fa | 31.078431 | 116 | 0.695413 | 4.504132 | false | false | false | false |
mdanielwork/intellij-community | plugins/copyright/src/com/intellij/copyright/CopyrightManager.kt | 1 | 10792 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.copyright
import com.intellij.configurationStore.*
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.AppUIExecutor
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.State
import com.intellij.openapi.components.Storage
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.editor.EditorFactory
import com.intellij.openapi.editor.event.DocumentEvent
import com.intellij.openapi.editor.event.DocumentListener
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.options.SchemeManagerFactory
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.startup.StartupActivity
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.InvalidDataException
import com.intellij.openapi.util.WriteExternalException
import com.intellij.openapi.util.text.StringUtil
import com.intellij.packageDependencies.DependencyValidationManager
import com.intellij.project.isDirectoryBased
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiManager
import com.intellij.util.attribute
import com.maddyhome.idea.copyright.CopyrightProfile
import com.maddyhome.idea.copyright.actions.UpdateCopyrightProcessor
import com.maddyhome.idea.copyright.options.LanguageOptions
import com.maddyhome.idea.copyright.options.Options
import com.maddyhome.idea.copyright.util.FileTypeUtil
import com.maddyhome.idea.copyright.util.NewFileTracker
import org.jdom.Element
import org.jetbrains.annotations.TestOnly
import java.util.*
import java.util.function.Function
private const val DEFAULT = "default"
private const val MODULE_TO_COPYRIGHT = "module2copyright"
private const val COPYRIGHT = "copyright"
private const val ELEMENT = "element"
private const val MODULE = "module"
private val LOG = Logger.getInstance(CopyrightManager::class.java)
@State(name = "CopyrightManager", storages = [(Storage(value = "copyright/profiles_settings.xml", exclusive = true))])
class CopyrightManager @JvmOverloads constructor(private val project: Project, schemeManagerFactory: SchemeManagerFactory, isSupportIprProjects: Boolean = true) : PersistentStateComponent<Element> {
companion object {
@JvmStatic
fun getInstance(project: Project) = project.service<CopyrightManager>()
}
private var defaultCopyrightName: String? = null
var defaultCopyright: CopyrightProfile?
get() = defaultCopyrightName?.let { schemeManager.findSchemeByName(it)?.scheme }
set(value) {
defaultCopyrightName = value?.name
}
val scopeToCopyright = LinkedHashMap<String, String>()
val options = Options()
private val schemeWriter = { scheme: CopyrightProfile ->
val element = scheme.writeScheme()
if (project.isDirectoryBased) wrapScheme(element) else element
}
private val schemeManagerIprProvider = if (project.isDirectoryBased || !isSupportIprProjects) null else SchemeManagerIprProvider("copyright")
private val schemeManager = schemeManagerFactory.create("copyright", object : LazySchemeProcessor<SchemeWrapper<CopyrightProfile>, SchemeWrapper<CopyrightProfile>>("myName") {
override fun createScheme(dataHolder: SchemeDataHolder<SchemeWrapper<CopyrightProfile>>,
name: String,
attributeProvider: Function<in String, String?>,
isBundled: Boolean): SchemeWrapper<CopyrightProfile> {
return CopyrightLazySchemeWrapper(name, dataHolder, schemeWriter)
}
override fun isSchemeFile(name: CharSequence) = !StringUtil.equals(name, "profiles_settings.xml")
override fun getSchemeKey(attributeProvider: Function<String, String?>, fileNameWithoutExtension: String): String {
val schemeKey = super.getSchemeKey(attributeProvider, fileNameWithoutExtension)
if (schemeKey != null) {
return schemeKey
}
LOG.warn("Name is not specified for scheme $fileNameWithoutExtension, file name will be used instead")
return fileNameWithoutExtension
}
}, schemeNameToFileName = OLD_NAME_CONVERTER, streamProvider = schemeManagerIprProvider)
init {
val app = ApplicationManager.getApplication()
if (project.isDirectoryBased || !app.isUnitTestMode) {
schemeManager.loadSchemes()
}
}
@TestOnly
fun loadSchemes() {
LOG.assertTrue(ApplicationManager.getApplication().isUnitTestMode)
schemeManager.loadSchemes()
}
fun mapCopyright(scopeName: String, copyrightProfileName: String) {
scopeToCopyright.put(scopeName, copyrightProfileName)
}
fun unmapCopyright(scopeName: String) {
scopeToCopyright.remove(scopeName)
}
fun hasAnyCopyrights(): Boolean {
return defaultCopyrightName != null || !scopeToCopyright.isEmpty()
}
override fun getState(): Element? {
val result = Element("settings")
try {
schemeManagerIprProvider?.writeState(result)
if (!scopeToCopyright.isEmpty()) {
val map = Element(MODULE_TO_COPYRIGHT)
for ((scopeName, profileName) in scopeToCopyright) {
val e = Element(ELEMENT)
e
.attribute(MODULE, scopeName)
.attribute(COPYRIGHT, profileName)
map.addContent(e)
}
result.addContent(map)
}
options.writeExternal(result)
}
catch (e: WriteExternalException) {
LOG.error(e)
return null
}
defaultCopyrightName?.let {
result.setAttribute(DEFAULT, it)
}
return wrapState(result, project)
}
override fun loadState(state: Element) {
val data = unwrapState(state, project, schemeManagerIprProvider, schemeManager) ?: return
data.getChild(MODULE_TO_COPYRIGHT)?.let {
for (element in it.getChildren(ELEMENT)) {
scopeToCopyright.put(element.getAttributeValue(MODULE), element.getAttributeValue(COPYRIGHT))
}
}
try {
defaultCopyrightName = data.getAttributeValue(DEFAULT)
options.readExternal(data)
}
catch (e: InvalidDataException) {
LOG.error(e)
}
}
private fun addCopyright(profile: CopyrightProfile) {
schemeManager.addScheme(InitializedSchemeWrapper(profile, schemeWriter))
}
fun getCopyrights(): Collection<CopyrightProfile> = schemeManager.allSchemes.map { it.scheme }
fun clearMappings() {
scopeToCopyright.clear()
}
fun removeCopyright(copyrightProfile: CopyrightProfile) {
schemeManager.removeScheme(copyrightProfile.name)
val it = scopeToCopyright.keys.iterator()
while (it.hasNext()) {
if (scopeToCopyright.get(it.next()) == copyrightProfile.name) {
it.remove()
}
}
}
fun replaceCopyright(name: String, profile: CopyrightProfile) {
val existingScheme = schemeManager.findSchemeByName(name)
if (existingScheme == null) {
addCopyright(profile)
}
else {
existingScheme.scheme.copyFrom(profile)
}
}
fun getCopyrightOptions(file: PsiFile): CopyrightProfile? {
val virtualFile = file.virtualFile
if (virtualFile == null || options.getOptions(virtualFile.fileType.name).getFileTypeOverride() == LanguageOptions.NO_COPYRIGHT) {
return null
}
val validationManager = DependencyValidationManager.getInstance(project)
for (scopeName in scopeToCopyright.keys) {
val packageSet = validationManager.getScope(scopeName)?.value ?: continue
if (packageSet.contains(file, validationManager)) {
scopeToCopyright.get(scopeName)?.let { schemeManager.findSchemeByName(it) }?.let { return it.scheme }
}
}
return defaultCopyright
}
}
private class CopyrightManagerPostStartupActivity : StartupActivity {
val newFileTracker = NewFileTracker()
override fun runActivity(project: Project) {
Disposer.register(project, Disposable { newFileTracker.clear() })
EditorFactory.getInstance().eventMulticaster.addDocumentListener(object : DocumentListener {
override fun documentChanged(e: DocumentEvent) {
val virtualFile = FileDocumentManager.getInstance().getFile(e.document) ?: return
val module = ProjectRootManager.getInstance(project).fileIndex.getModuleForFile(virtualFile) ?: return
if (!newFileTracker.poll(virtualFile) ||
!FileTypeUtil.getInstance().isSupportedFile(virtualFile) ||
PsiManager.getInstance(project).findFile(virtualFile) == null) {
return
}
AppUIExecutor.onUiThread(ModalityState.NON_MODAL).later().withDocumentsCommitted(project).execute {
if (!virtualFile.isValid) {
return@execute
}
val file = PsiManager.getInstance(project).findFile(virtualFile)
if (file != null && file.isWritable) {
CopyrightManager.getInstance(project).getCopyrightOptions(file)?.let {
UpdateCopyrightProcessor(project, module, file).run()
}
}
}
}
}, project)
}
}
private fun wrapScheme(element: Element): Element {
val wrapper = Element("component")
.attribute("name", "CopyrightManager")
wrapper.addContent(element)
return wrapper
}
private class CopyrightLazySchemeWrapper(name: String,
dataHolder: SchemeDataHolder<SchemeWrapper<CopyrightProfile>>,
writer: (scheme: CopyrightProfile) -> Element,
private val subStateTagName: String = "copyright") : LazySchemeWrapper<CopyrightProfile>(name, dataHolder, writer) {
override val lazyScheme = lazy {
val scheme = CopyrightProfile()
@Suppress("NAME_SHADOWING")
val dataHolder = this.dataHolder.getAndSet(null)
var element = dataHolder.read()
if (element.name != subStateTagName) {
element = element.getChild(subStateTagName)
}
element.deserializeInto(scheme)
// use effective name instead of probably missed from the serialized
// https://youtrack.jetbrains.com/v2/issue/IDEA-186546
scheme.profileName = name
@Suppress("DEPRECATION")
val allowReplaceKeyword = scheme.allowReplaceKeyword
if (allowReplaceKeyword != null && scheme.allowReplaceRegexp == null) {
scheme.allowReplaceRegexp = StringUtil.escapeToRegexp(allowReplaceKeyword)
@Suppress("DEPRECATION")
scheme.allowReplaceKeyword = null
}
scheme.resetModificationCount()
dataHolder.updateDigest(writer(scheme))
scheme
}
} | apache-2.0 | 36419f0479ec60988a95182bb8260fb9 | 36.737762 | 198 | 0.728595 | 5.007889 | false | false | false | false |
mdanielwork/intellij-community | plugins/github/src/org/jetbrains/plugins/github/pullrequest/action/GithubPullRequestRefreshPreviewAction.kt | 1 | 984 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.pullrequest.action
import com.intellij.icons.AllIcons
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.project.DumbAwareAction
class GithubPullRequestRefreshPreviewAction : DumbAwareAction("Refresh Pull Request Details", null, AllIcons.Actions.Refresh) {
override fun update(e: AnActionEvent) {
val component = e.getData(GithubPullRequestKeys.PULL_REQUESTS_COMPONENT)
val selection = e.getData(GithubPullRequestKeys.SELECTED_PULL_REQUEST)
e.presentation.isEnabled = component != null && selection != null
}
override fun actionPerformed(e: AnActionEvent) {
val selection = e.getRequiredData(GithubPullRequestKeys.SELECTED_PULL_REQUEST)
e.getRequiredData(GithubPullRequestKeys.PULL_REQUESTS_COMPONENT).refreshPullRequest(selection.number)
}
} | apache-2.0 | 5157a38b6d770399ce77ae6e1c9d417b | 48.25 | 140 | 0.802846 | 4.534562 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/git4idea/src/git4idea/update/GitSubmoduleUpdater.kt | 17 | 2065 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package git4idea.update
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.project.Project
import com.intellij.openapi.vcs.update.UpdatedFiles
import git4idea.branch.GitBranchPair
import git4idea.commands.Git
import git4idea.commands.GitCommand
import git4idea.commands.GitLineHandler
import git4idea.repo.GitRepository
private val LOG = logger<GitSubmoduleUpdater>()
internal class GitSubmoduleUpdater(val project: Project,
val git: Git,
private val parentRepository: GitRepository,
private val repository: GitRepository,
progressIndicator: ProgressIndicator,
updatedFiles: UpdatedFiles) :
GitUpdater(project, git, repository, progressIndicator, updatedFiles) {
override fun isSaveNeeded(): Boolean = true
override fun doUpdate(): GitUpdateResult {
try {
val result = git.runCommand {
val handler = GitLineHandler(project, parentRepository.root, GitCommand.SUBMODULE)
handler.addParameters("update", "--recursive")
handler.setSilent(false)
handler.setStdoutSuppressed(false)
handler
}
if (result.success()) {
return GitUpdateResult.SUCCESS
}
LOG.info("Submodule update failed for submodule [$repository] called from parent root [$parentRepository]: " +
result.errorOutputAsJoinedString)
return GitUpdateResult.ERROR
}
catch (pce: ProcessCanceledException) {
return GitUpdateResult.CANCEL
}
}
// general logic doesn't apply to submodules
override fun isUpdateNeeded(branchPair: GitBranchPair): Boolean = true
override fun toString(): String = "Submodule updater"
}
| apache-2.0 | 8b09329337db96ec4432d24df545584e | 37.240741 | 140 | 0.6954 | 5.175439 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/j2k/old/src/org/jetbrains/kotlin/j2k/usageProcessing/AccessorToPropertyProcessing.kt | 6 | 4378 | // 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.j2k.usageProcessing
import com.intellij.psi.*
import org.jetbrains.kotlin.j2k.AccessorKind
import org.jetbrains.kotlin.j2k.CodeConverter
import org.jetbrains.kotlin.j2k.ast.*
import org.jetbrains.kotlin.j2k.dot
import org.jetbrains.kotlin.psi.*
class AccessorToPropertyProcessing(val accessorMethod: PsiMethod, val accessorKind: AccessorKind, val propertyName: String) : UsageProcessing {
override val targetElement: PsiElement get() = accessorMethod
override val convertedCodeProcessor = object : ConvertedCodeProcessor {
override fun convertMethodUsage(methodCall: PsiMethodCallExpression, codeConverter: CodeConverter): Expression? {
val isNullable = codeConverter.typeConverter.methodNullability(accessorMethod).isNullable(codeConverter.settings)
val methodExpr = methodCall.methodExpression
val arguments = methodCall.argumentList.expressions
val propertyName = Identifier.withNoPrototype(propertyName, isNullable)
val qualifier = methodExpr.qualifierExpression
val propertyAccess = if (qualifier != null)
QualifiedExpression(codeConverter.convertExpression(qualifier), propertyName, methodExpr.dot()).assignNoPrototype()
else
propertyName
if (accessorKind == AccessorKind.GETTER) {
if (arguments.isNotEmpty()) return null // incorrect call
return propertyAccess
}
else {
if (arguments.size != 1) return null // incorrect call
val argument = codeConverter.convertExpression(arguments[0])
return AssignmentExpression(propertyAccess, argument, Operator.EQ)
}
}
}
override val javaCodeProcessors = emptyList<ExternalCodeProcessor>()
override val kotlinCodeProcessors =
if (accessorMethod.hasModifierProperty(PsiModifier.PRIVATE))
emptyList()
else
listOf(AccessorToPropertyProcessor(propertyName, accessorKind))
class AccessorToPropertyProcessor(
private val propertyName: String,
private val accessorKind: AccessorKind
) : ExternalCodeProcessor {
override fun processUsage(reference: PsiReference): Array<PsiReference>? {
return processUsage(reference.element, propertyName, accessorKind)
}
}
companion object {
fun processUsage(element: PsiElement, propertyName: String, accessorKind: AccessorKind): Array<PsiReference>? {
val nameExpr = element as? KtSimpleNameExpression ?: return null
val callExpr = nameExpr.parent as? KtCallExpression ?: return null
val arguments = callExpr.valueArguments
val factory = KtPsiFactory(nameExpr.project)
var propertyNameExpr = factory.createSimpleName(propertyName)
if (accessorKind == AccessorKind.GETTER) {
if (arguments.size != 0) return null // incorrect call
propertyNameExpr = callExpr.replace(propertyNameExpr) as KtSimpleNameExpression
return propertyNameExpr.references
} else {
val value = arguments.singleOrNull()?.getArgumentExpression() ?: return null
var assignment = factory.createExpression("a = b") as KtBinaryExpression
assignment.right!!.replace(value)
val qualifiedExpression = callExpr.parent as? KtQualifiedExpression
return if (qualifiedExpression != null && qualifiedExpression.selectorExpression == callExpr) {
callExpr.replace(propertyNameExpr)
assignment.left!!.replace(qualifiedExpression)
assignment = qualifiedExpression.replace(assignment) as KtBinaryExpression
(assignment.left as KtQualifiedExpression).selectorExpression!!.references
} else {
assignment.left!!.replace(propertyNameExpr)
assignment = callExpr.replace(assignment) as KtBinaryExpression
assignment.left!!.references
}
}
}
}
}
| apache-2.0 | cd9e7f3dbefcbd32540f4926f4191cdb | 47.10989 | 158 | 0.669484 | 5.892328 | false | false | false | false |
JonathanxD/CodeAPI | src/main/kotlin/com/github/jonathanxd/kores/base/InvokeType.kt | 1 | 4322 | /*
* Kores - Java source and Bytecode generation framework <https://github.com/JonathanxD/Kores>
*
* The MIT License (MIT)
*
* Copyright (c) 2020 TheRealBuggy/JonathanxD (https://github.com/JonathanxD/) <[email protected]>
* Copyright (c) contributors
*
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.github.jonathanxd.kores.base
import com.github.jonathanxd.kores.base.InvokeType.*
import com.github.jonathanxd.kores.type.isInterface
import java.lang.reflect.Type
/**
* Type of the invocation. In JVM, the invocation type depends on where the element is declared and
* which modifiers it has. [INVOKE_VIRTUAL] is used to invoke instance methods in `class`es, [INVOKE_INTERFACE]
* is used to invoke interface methods in `interface`s, a special opcode is required for methods declared
* in `interface` because JVM needs to resolve the position of the method in the method table. [INVOKE_STATIC] is used
* for invocation of static methods, does not matter where it is declared or if it is private. [INVOKE_SPECIAL] is used to invoke
* constructors, super constructors and for private methods, for private methods,
* [INVOKE_SPECIAL] is required because [INVOKE_VIRTUAL] will always call the method of `current class`, which
* is bad for private methods, because class inheritance can hide the private method and can cause a unexpected
* behavior.
*
*/
enum class InvokeType {
/**
* Static method invocation.
*/
INVOKE_STATIC,
/**
* Virtual method invocation (instance methods).
*/
INVOKE_VIRTUAL,
/**
* Special invocation.
*
* - Constructor methods.
* - Private methods.
* - Super constructor invocation. (or this constructor invocation).
*/
INVOKE_SPECIAL,
/**
* Interface method invocation.
*/
INVOKE_INTERFACE;
/**
* Returns true if the InvokeType is [INVOKE_STATIC].
*
* @return True if the InvokeType is [INVOKE_STATIC].
*/
fun isStatic() = this == INVOKE_STATIC
/**
* Returns true if the InvokeType is [INVOKE_VIRTUAL].
*
* @return True if the InvokeType is [INVOKE_VIRTUAL].
*/
fun isVirtual() = this == INVOKE_VIRTUAL
/**
* Returns true if the InvokeType is [INVOKE_SPECIAL].
*
* @return True if the InvokeType is [INVOKE_SPECIAL].
*/
fun isSpecial() = this == INVOKE_SPECIAL
/**
* Returns true if the InvokeType is [INVOKE_INTERFACE].
*
* @return True if the InvokeType is [INVOKE_INTERFACE].
*/
fun isInterface() = this == INVOKE_INTERFACE
companion object {
/**
* Get InvokeType corresponding to the [type]. If [type] is null, [INVOKE_STATIC], if [type]
* [com.github.jonathanxd.kores.util.isInterface], [INVOKE_INTERFACE], if not, [INVOKE_VIRTUAL].
*
* @param type Type
* @return [INVOKE_STATIC] if null, [INVOKE_INTERFACE] if is is an interface, or is not an interface [INVOKE_VIRTUAL]
*/
@JvmStatic
fun get(type: Type?) =
if (type == null) INVOKE_STATIC else if (type.isInterface) INVOKE_INTERFACE else INVOKE_VIRTUAL
}
} | mit | 0716fb974cd2e552fc9a9e1d480da86d | 37.256637 | 129 | 0.674688 | 4.356855 | false | false | false | false |
cdietze/klay | src/main/kotlin/klay/core/TexturedBatch.kt | 1 | 2973 | package klay.core
/**
* A batch that renders textured primitives.
*/
open class TexturedBatch protected constructor(val gl: GL20) : GLBatch() {
/** Provides some standard bits for a shader program that uses a tint and a texture. */
abstract class Source {
/** Returns the source of the texture fragment shader program. Note that this program
* *must* preserve the use of the existing varying attributes. You can add new varying
* attributes, but you cannot remove or change the defaults. */
open fun fragment(): String {
val str = StringBuilder(FRAGMENT_PREAMBLE)
str.append(textureUniforms())
str.append(textureVaryings())
str.append("void main(void) {\n")
str.append(textureColor())
str.append(textureTint())
str.append(textureAlpha())
str.append(" gl_FragColor = textureColor;\n" + "}")
return str.toString()
}
protected fun textureUniforms(): String {
return "uniform lowp sampler2D u_Texture;\n"
}
protected fun textureVaryings(): String {
return "varying mediump vec2 v_TexCoord;\n" + "varying lowp vec4 v_Color;\n"
}
protected fun textureColor(): String {
return " vec4 textureColor = texture2D(u_Texture, v_TexCoord);\n"
}
protected open fun textureTint(): String {
return " textureColor.rgb *= v_Color.rgb;\n"
}
protected fun textureAlpha(): String {
return " textureColor *= v_Color.a;\n"
}
companion object {
val FRAGMENT_PREAMBLE =
"#ifdef GL_ES\n" +
"precision lowp float;\n" +
"#else\n" +
// Not all versions of regular OpenGL supports precision qualifiers, define placeholders
"#define lowp\n" +
"#define mediump\n" +
"#define highp\n" +
"#endif\n"
}
}
protected var curTexId: Int = 0
/** Prepares this batch to render using the supplied texture. If pending operations have been
* added to this batch for a different texture, this call will trigger a [.flush].
*
* Note: if you call `add` methods that take a texture, you do not need to call this
* method manually. Only if you're adding bare primitives is it needed. */
fun setTexture(texture: Texture) {
if (curTexId != 0 && curTexId != texture.id) flush()
this.curTexId = texture.id
}
override fun end() {
super.end()
curTexId = 0
}
/** Binds our current texture. Subclasses need to call this in [.flush]. */
protected fun bindTexture() {
gl.glBindTexture(GL20.GL_TEXTURE_2D, curTexId)
gl.checkError("QuadBatch glBindTexture")
}
}
| apache-2.0 | cb473b559dad853a2e0757716b5554fd | 35.256098 | 116 | 0.568113 | 4.490937 | false | false | false | false |
elpassion/mainframer-intellij-plugin | src/main/kotlin/com/elpassion/mainframerplugin/action/configure/templater/Templater.kt | 1 | 1023 | package com.elpassion.mainframerplugin.action.configure.templater
import com.intellij.openapi.project.Project
import io.reactivex.Completable
import io.reactivex.Maybe
import io.reactivex.Observable
fun templateChooser(project: Project): Maybe<ProjectType> = templateApplicationDialog(project)
fun templateSetter(project: Project): (ProjectType) -> Observable<Pair<String, String>> = { projectType ->
Observable.just("ignore", "remoteignore", "localignore")
.map { fileName ->
val sourceFile = createSourcePath(projectType.resourceDir, fileName)
val targetFile = createTargetPath(project, fileName)
sourceFile to targetFile
}
}
private fun createTargetPath(project: Project, fileName: String) = "${project.basePath}/.mainframer/$fileName"
private fun createSourcePath(projectTypeResourceDir: String, fileName: String) = "templates/$projectTypeResourceDir/$fileName"
typealias FileCopier = (source: String, destination: String) -> Completable | apache-2.0 | 49734f857d802d9d003f83dec08a2320 | 43.521739 | 126 | 0.747801 | 4.692661 | false | false | false | false |
CAD97/AndensMountain | TextAdventureCreationTool/src/cad97/fx/controlsfx.kt | 1 | 1811 | package cad97.fx
import javafx.beans.property.Property
import javafx.event.EventTarget
import javafx.scene.Node
import javafx.scene.control.TextField
import org.controlsfx.control.textfield.CustomTextField
import org.controlsfx.control.textfield.TextFields
import tornadofx.bind
import tornadofx.opcr
fun EventTarget.autocompletefield(values: Set<String>, value: String? = null, left: Node? = null, right: Node? = null,
op: (TextField.() -> Unit)? = null): TextField =
customtextfield(value, left, right, op).apply {
TextFields.bindAutoCompletion(this) {
suggestion ->
values.filter { it.startsWith(suggestion.userText) }
}
}
fun EventTarget.autocompletefield(values: Set<String>, property: Property<String>, left: Node? = null, right: Node? = null,
op: (TextField.() -> Unit)? = null): TextField =
autocompletefield(values, left = left, right = right, op = op).apply {
bind(property)
}
fun EventTarget.customtextfield(value: String? = null, left: Node? = null, right: Node? = null,
op: (TextField.() -> Unit)? = null): TextField =
opcr(
parent = this,
node = CustomTextField().apply {
if (value != null) text = value
if (left != null) setLeft(left)
if (right != null) setRight(right)
},
op = op
)
fun EventTarget.customtextfield(property: Property<String>, left: Node? = null, right: Node? = null,
op: (TextField.() -> Unit)? = null): TextField =
customtextfield(left = left, right = right, op = op).apply {
bind(property)
}
| gpl-3.0 | 0da612b029fdb373107ef735f24f152a | 41.116279 | 123 | 0.574821 | 4.395631 | false | false | false | false |
nick-rakoczy/Conductor | conductor-engine/src/main/java/urn/conductor/internal/EngineImpl.kt | 1 | 2798 | package urn.conductor.internal
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import jdk.nashorn.api.scripting.ScriptObjectMirror
import urn.conductor.Engine
import urn.conductor.attempt
import urn.conductor.ssh.SessionProvider
import java.nio.file.Path
import java.nio.file.Paths
import java.util.Stack
import javax.script.ScriptContext
import javax.script.ScriptEngine
import javax.xml.bind.Unmarshaller
class EngineImpl(scriptEngine: ScriptEngine, override val jaxbReader: Unmarshaller, override val sessionProvider: SessionProvider) : Engine, ScriptEngine by scriptEngine {
private val workingDirectoryStack = Stack<Path>()
override val currentWorkingDirectory: Path
get() = attempt { workingDirectoryStack.peek() } ?: Paths.get("")
override val gson: Gson by lazy {
GsonBuilder().setPrettyPrinting().create()
}
private fun ScriptEngine.put(attribute: Pair<String, *>) {
this.put(attribute.first, attribute.second)
}
override fun <T> runWithContext(vararg attributes: Pair<String, *>, block: () -> T): T {
attributes.forEach { this.put(it) }
return block().also {
attributes.forEach { this.delete(it.first) }
}
}
override fun <T> runWithUniqueContext(vararg attributes: Pair<String, *>, block: () -> T): T {
attributes.map {
it.first
}.filter {
this[it] != null
}.takeIf {
it.isNotEmpty()
}?.let {
error(it.joinToString(
prefix = "Attributes already defined [",
postfix = "]. Nested Contexts not allowed.",
separator = ", ")
)
}
return this.runWithContext(*attributes) {
block()
}
}
override fun delete(name: String) {
this.context.removeAttribute(name, ScriptContext.ENGINE_SCOPE)
}
override fun interpolate(expression: String) = StringBuilder().apply {
fun String.evalAndAppend() = this.let(this@EngineImpl::eval).let(this@apply::append)
val OPEN_MARKER = "{{"
val CLOSE_MARKER = "}}"
val ESCAPED_OPEN_MARKER = "\\$OPEN_MARKER"
var left = expression
while (left.isNotEmpty()) {
when {
left.startsWith(OPEN_MARKER) -> {
left.substring(2).substringBefore(CLOSE_MARKER).evalAndAppend()
left = left.substringAfter(CLOSE_MARKER)
}
left.startsWith(ESCAPED_OPEN_MARKER) -> {
this.append(OPEN_MARKER)
left = left.substringAfter(OPEN_MARKER)
}
else -> {
this.append(left[0])
left = left.substring(1)
}
}
}
}.toString()
override fun getObjectMirror(name: String) = this[name] as? ScriptObjectMirror?
override fun pushWorkingDirectory(path: Path) {
path.toAbsolutePath().normalize().let(workingDirectoryStack::push)
}
override fun popWorkingDirectory() {
workingDirectoryStack.pop()
}
override fun getPath(name: String): Path = currentWorkingDirectory
.resolve(name)
.toAbsolutePath()
.normalize()
} | gpl-3.0 | 7564cc47f3f7fc740e681178b5cd2ff2 | 26.441176 | 171 | 0.710865 | 3.532828 | false | false | false | false |
JetBrains/intellij-community | java/java-impl/src/com/intellij/lang/java/actions/CreateEnumConstantAction.kt | 1 | 4334 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.lang.java.actions
import com.intellij.codeInsight.CodeInsightUtil.positionCursor
import com.intellij.codeInsight.CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement
import com.intellij.codeInsight.ExpectedTypeUtil
import com.intellij.codeInsight.daemon.impl.quickfix.CreateFromUsageBaseFix.startTemplate
import com.intellij.codeInsight.daemon.impl.quickfix.EmptyExpression
import com.intellij.codeInsight.intention.HighPriorityAction
import com.intellij.codeInsight.intention.preview.IntentionPreviewInfo
import com.intellij.codeInsight.template.TemplateBuilderImpl
import com.intellij.codeInspection.CommonQuickFixBundle
import com.intellij.ide.highlighter.JavaFileType
import com.intellij.lang.jvm.actions.CreateEnumConstantActionGroup
import com.intellij.lang.jvm.actions.CreateFieldRequest
import com.intellij.lang.jvm.actions.ExpectedTypes
import com.intellij.lang.jvm.actions.JvmActionGroup
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiEnumConstant
import com.intellij.psi.PsiFile
import com.intellij.psi.util.JavaElementKind
import com.intellij.psi.util.PsiTreeUtil
internal class CreateEnumConstantAction(
target: PsiClass,
override val request: CreateFieldRequest
) : CreateFieldActionBase(target, request), HighPriorityAction {
override fun getActionGroup(): JvmActionGroup = CreateEnumConstantActionGroup
override fun getText(): String = CommonQuickFixBundle.message("fix.create.title.x", JavaElementKind.ENUM_CONSTANT.`object`(), request.fieldName)
override fun generatePreview(project: Project, editor: Editor, file: PsiFile): IntentionPreviewInfo {
val constructor = target.constructors.firstOrNull() ?: return IntentionPreviewInfo.EMPTY
val hasParameters = constructor.parameters.isNotEmpty()
val text = if (hasParameters) "${request.fieldName}(...)" else request.fieldName
return IntentionPreviewInfo.CustomDiff(JavaFileType.INSTANCE, "", text)
}
override fun invoke(project: Project, editor: Editor?, file: PsiFile?) {
val name = request.fieldName
val targetClass = target
val elementFactory = JavaPsiFacade.getElementFactory(project)!!
// add constant
var enumConstant: PsiEnumConstant
enumConstant = elementFactory.createEnumConstantFromText(name, null)
enumConstant = targetClass.add(enumConstant) as PsiEnumConstant
// start template
val constructor = targetClass.constructors.firstOrNull() ?: return
val parameters = constructor.parameterList.parameters
if (parameters.isEmpty()) return
val paramString = parameters.joinToString(",") { it.name }
enumConstant = enumConstant.replace(elementFactory.createEnumConstantFromText("$name($paramString)", null)) as PsiEnumConstant
val builder = TemplateBuilderImpl(enumConstant)
val argumentList = enumConstant.argumentList!!
for (expression in argumentList.expressions) {
builder.replaceElement(expression, EmptyExpression())
}
enumConstant = forcePsiPostprocessAndRestoreElement(enumConstant) ?: return
val template = builder.buildTemplate()
val newEditor = positionCursor(project, targetClass.containingFile, enumConstant) ?: return
val range = enumConstant.textRange
newEditor.document.deleteString(range.startOffset, range.endOffset)
startTemplate(newEditor, template, project)
}
}
internal fun canCreateEnumConstant(targetClass: PsiClass, request: CreateFieldRequest): Boolean {
if (!targetClass.isEnum) return false
val lastConstant = targetClass.fields.filterIsInstance<PsiEnumConstant>().lastOrNull()
if (lastConstant != null && PsiTreeUtil.hasErrorElements(lastConstant)) return false
return checkExpectedTypes(request.fieldType, targetClass, targetClass.project)
}
private fun checkExpectedTypes(types: ExpectedTypes, targetClass: PsiClass, project: Project): Boolean {
val typeInfos = extractExpectedTypes(project, types)
if (typeInfos.isEmpty()) return true
val enumType = JavaPsiFacade.getElementFactory(project).createType(targetClass)
return typeInfos.any {
ExpectedTypeUtil.matches(enumType, it)
}
}
| apache-2.0 | d748aed5fc1f68e860637214b2ab47c5 | 46.108696 | 146 | 0.805491 | 5.033682 | false | false | false | false |
aquatir/remember_java_api | code-sample-kotlin/spring-boot/code-sample-kotlin-spring-security/src/main/kotlin/codesample/kotlin/controller/UserController.kt | 1 | 1882 | package codesample.kotlin.controller
import codesample.kotlin.exception.UserExistException
import codesample.kotlin.service.UserService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Controller
import org.springframework.ui.Model
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.servlet.ModelAndView
@Controller
class UserController (@Autowired private val userService: UserService){
@GetMapping("/login")
fun login() = "login"
@GetMapping("/logout")
fun logout() = "logout"
@GetMapping("/login-error")
fun loginError(model: Model): String {
model.addAttribute("loginError", true)
return "login"
}
@GetMapping("/secure/user")
fun secureUser(): ModelAndView {
val mav = ModelAndView("hello")
val user = userService.getCurrentAuthenticatedUser()
mav.addObject("userName", user.username)
mav.addObject("userPassword", user.password)
mav.addObject("userSecondName", user.secondName)
return mav
}
@PostMapping("/secure/user")
fun createUser(@RequestParam username: String,
@RequestParam password: String,
@RequestParam secondName: String): ModelAndView {
return try {
val mav = ModelAndView("hello")
val user = userService.createNewAndSave(username, password, secondName)
mav.addObject("userName", user.username)
mav.addObject("userPassword", user.password)
mav
} catch (userExist: UserExistException) {
val mav = ModelAndView("error")
mav.addObject("error", userExist.message!!)
mav
}
}
} | mit | 647bf08e02f0026b99aa22d2164f0adf | 30.915254 | 83 | 0.682253 | 4.693267 | false | false | false | false |
lomza/screenlookcount | app/src/main/java/com/totemsoft/screenlookcount/utils/AppPreferences.kt | 1 | 679 | package com.totemsoft.screenlookcount.utils
import android.content.Context
import android.content.SharedPreferences
/**
* Object for managing app's Shared Preferences
*
* @author Antonina
*/
object AppPreferences {
private const val NAME = "SLCPreferenceFile"
private const val IS_SERVICE_RUNNING = "service_running_bool"
private lateinit var preferences: SharedPreferences
fun init(ctx: Context) {
preferences = ctx.getSharedPreferences(NAME, 0)
}
var shouldRunCountingService: Boolean
get() = preferences.getBoolean(IS_SERVICE_RUNNING, true)
set(value) = preferences.edit().putBoolean(IS_SERVICE_RUNNING, value).apply()
} | gpl-3.0 | cbf86ab2f7a8b6fa5253670bd89ea7ac | 28.565217 | 85 | 0.734904 | 4.297468 | false | false | false | false |
Skatteetaten/boober | src/main/kotlin/no/skatteetaten/aurora/boober/service/AuroraTemplateService.kt | 1 | 1287 | package no.skatteetaten.aurora.boober.service
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import org.springframework.beans.factory.annotation.Value
import org.springframework.stereotype.Service
@Service
class AuroraTemplateService(
val bitbucketService: BitbucketService,
@Value("\${integrations.aurora.templates.ref}") val templatesRef: String,
@Value("\${integrations.aurora.templates.repo}") val templateRepo: String,
@Value("\${integrations.aurora.templates.project}") val templateProject: String
) {
fun findTemplate(templateName: String): JsonNode {
val content = try {
bitbucketService.getFile(templateProject, templateRepo, "$templateName.json", templatesRef)
} catch (e: Exception) {
throw AuroraDeploymentSpecValidationException("Error fetching template=$templateName message=${e.localizedMessage}")
} ?: throw AuroraDeploymentSpecValidationException("Could not find template=$templateName")
return try {
jacksonObjectMapper().readTree(content)
} catch (e: Exception) {
throw AuroraDeploymentSpecValidationException("Could not parse template as json message=${e.localizedMessage}")
}
}
}
| apache-2.0 | ce450e7ddb381840a65b973a1fe526bd | 44.964286 | 128 | 0.738151 | 5.148 | false | false | false | false |
allotria/intellij-community | platform/testGuiFramework/src/com/intellij/testGuiFramework/fixtures/extended/ExtendedTableFixture.kt | 10 | 2409 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.testGuiFramework.fixtures.extended
import com.intellij.testGuiFramework.cellReader.ExtendedJTableCellReader
import com.intellij.testGuiFramework.fixtures.CheckBoxFixture
import org.fest.swing.core.Robot
import org.fest.swing.fixture.JTableFixture
import javax.swing.JCheckBox
import javax.swing.JTable
class ExtendedTableFixture(private val myRobot: Robot, val myTable: JTable) : JTableFixture(myRobot, myTable) {
init {
replaceCellReader(ExtendedJTableCellReader())
}
fun row(i: Int): RowFixture = RowFixture(myRobot, i, this)
fun row(value: String): RowFixture = RowFixture(myRobot, cell(value).row(), this)
}
class RowFixture(private val myRobot: Robot, val rowNumber: Int, val tableFixture: ExtendedTableFixture) {
val myTable: JTable = tableFixture.myTable
fun hasCheck(): Boolean =
(0 until myTable.columnCount)
.map { myTable.prepareRenderer(myTable.getCellRenderer(rowNumber, it), rowNumber, it) }
.any { it is JCheckBox }
fun isCheck(): Boolean = getCheckBox().isSelected
fun check() {
val checkBox = getCheckBox()
if (!checkBox.isSelected) CheckBoxFixture(myRobot, checkBox).click()
}
fun uncheck() {
val checkBox = getCheckBox()
if (checkBox.isSelected) CheckBoxFixture(myRobot, checkBox).click()
}
fun values(): List<String> {
val cellReader = ExtendedJTableCellReader()
return (0 until myTable.columnCount)
.map { cellReader.valueAt(myTable, rowNumber, it) ?: "null" }
}
private fun getCheckBox(): JCheckBox {
if (!hasCheck()) throw Exception("Unable to find checkbox cell in row: $rowNumber")
return (0 until myTable.columnCount)
.map { myTable.prepareRenderer(myTable.getCellRenderer(rowNumber, it), rowNumber, it) }
.find { it is JCheckBox } as JCheckBox
}
} | apache-2.0 | 673cadf77ba0f9ecd1502fedb84f38d8 | 33.927536 | 111 | 0.73599 | 4.035176 | false | false | false | false |
allotria/intellij-community | uast/uast-common/src/org/jetbrains/uast/UastLanguagePlugin.kt | 3 | 6251 | // 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
import com.intellij.lang.Language
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.psi.*
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.uast.analysis.UastAnalysisPlugin
import org.jetbrains.uast.util.ClassSet
import org.jetbrains.uast.util.classSetOf
interface UastLanguagePlugin {
companion object {
val extensionPointName = ExtensionPointName<UastLanguagePlugin>("org.jetbrains.uast.uastLanguagePlugin")
fun getInstances(): Collection<UastLanguagePlugin> = extensionPointName.extensionList
fun byLanguage(language: Language): UastLanguagePlugin? = extensionPointName.extensionList.firstOrNull { it.language === language }
}
data class ResolvedMethod(val call: UCallExpression, val method: PsiMethod)
data class ResolvedConstructor(val call: UCallExpression, val constructor: PsiMethod, val clazz: PsiClass)
val language: Language
/**
* Checks if the file with the given [fileName] is supported.
*
* @param fileName the source file name.
* @return true, if the file is supported by this converter, false otherwise.
*/
fun isFileSupported(fileName: String): Boolean
/**
* Returns the converter priority. Might be positive, negative or 0 (Java's is 0).
* UastConverter with the higher priority will be queried earlier.
*
* Priority is useful when a language N wraps its own elements (NElement) to, for example, Java's PsiElements,
* and Java resolves the reference to such wrapped PsiElements, not the original NElement.
* In this case N implementation can handle such wrappers in UastConverter earlier than Java's converter,
* so N language converter will have a higher priority.
*/
val priority: Int
/**
* Converts a PSI element, the parent of which already has an UAST representation, to UAST.
*
* @param element the element to convert
* @param parent the parent as an UAST element, or null if the element is a file
* @param requiredType the expected type of the result.
* @return the converted element, or null if the element isn't supported or doesn't match the required result type.
*/
fun convertElement(element: PsiElement, parent: UElement?, requiredType: Class<out UElement>? = null): UElement?
/**
* Converts a PSI element, along with its chain of parents, to UAST.
*
* @param element the element to convert
* @param requiredType the expected type of the result.
* @return the converted element, or null if the element isn't supported or doesn't match the required result type.
*/
fun convertElementWithParent(element: PsiElement, requiredType: Class<out UElement>?): UElement?
fun getMethodCallExpression(
element: PsiElement,
containingClassFqName: String?,
methodName: String
): ResolvedMethod?
fun getConstructorCallExpression(
element: PsiElement,
fqName: String
): ResolvedConstructor?
fun getMethodBody(element: PsiMethod): UExpression? {
if (element is UMethod) return element.uastBody
return (convertElementWithParent(element, null) as? UMethod)?.uastBody
}
fun getInitializerBody(element: PsiClassInitializer): UExpression {
if (element is UClassInitializer) return element.uastBody
return (convertElementWithParent(element, null) as? UClassInitializer)?.uastBody ?: UastEmptyExpression(null)
}
fun getInitializerBody(element: PsiVariable): UExpression? {
if (element is UVariable) return element.uastInitializer
return (convertElementWithParent(element, null) as? UVariable)?.uastInitializer
}
/**
* Returns true if the expression value is used.
* Do not rely on this property too much, its value can be approximate in some cases.
*/
fun isExpressionValueUsed(element: UExpression): Boolean
@JvmDefault
@Suppress("UNCHECKED_CAST")
fun <T : UElement> convertElementWithParent(element: PsiElement, requiredTypes: Array<out Class<out T>>): T? =
when {
requiredTypes.isEmpty() -> convertElementWithParent(element, null)
requiredTypes.size == 1 -> convertElementWithParent(element, requiredTypes.single())
else -> convertElementWithParent(element, null)
?.takeIf { result -> requiredTypes.any { it.isAssignableFrom(result.javaClass) } }
} as? T
@JvmDefault
fun <T : UElement> convertToAlternatives(element: PsiElement, requiredTypes: Array<out Class<out T>>): Sequence<T> =
sequenceOf(convertElementWithParent(element, requiredTypes)).filterNotNull()
@JvmDefault
val analysisPlugin: UastAnalysisPlugin?
@ApiStatus.Experimental
get() = null
/**
* Serves for optimization purposes. Helps to filter PSI elements which in principle
* can be sources for UAST types of an interest.
*
* Note: it is already used inside [UastLanguagePlugin] conversion methods implementations
* for Java, Kotlin and Scala.
*
* @return types of possible source PSI elements, which instances in principle
* can be converted to at least one of the specified [uastTypes]
* (or to [UElement] if no type was specified)
*/
@JvmDefault
fun getPossiblePsiSourceTypes(vararg uastTypes: Class<out UElement>): ClassSet<PsiElement> {
logger<UastLanguagePlugin>().warn(Exception("fallback to the PsiElement for ${this.javaClass}, it can have a performance impact"))
return classSetOf(PsiElement::class.java)
}
}
inline fun <reified T : UElement> UastLanguagePlugin.convertOpt(element: PsiElement?, parent: UElement?): T? {
if (element == null) return null
return convertElement(element, parent, T::class.java) as? T
}
@Deprecated("will throw exception if conversion fails", ReplaceWith("convertOpt"))
inline fun <reified T : UElement> UastLanguagePlugin.convert(element: PsiElement, parent: UElement?): T {
return convertElement(element, parent, T::class.java) as T
}
inline fun <reified T : UElement> UastLanguagePlugin.convertWithParent(element: PsiElement?): T? {
if (element == null) return null
return convertElementWithParent(element, T::class.java) as? T
} | apache-2.0 | 02452b3e5d2978a4c96848d1ab16f0fe | 41.243243 | 140 | 0.746601 | 4.714178 | false | false | false | false |
genonbeta/TrebleShot | app/src/main/java/org/monora/uprotocol/client/android/fragment/pickclient/PickClientFragment.kt | 1 | 4716 | /*
* Copyright (C) 2021 Veli Tasalı
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.monora.uprotocol.client.android.fragment.pickclient
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import dagger.hilt.android.AndroidEntryPoint
import org.monora.uprotocol.client.android.R
import org.monora.uprotocol.client.android.database.model.UClient
import org.monora.uprotocol.client.android.databinding.LayoutEmptyContentBinding
import org.monora.uprotocol.client.android.databinding.ListPickClientBinding
import org.monora.uprotocol.client.android.itemcallback.UClientItemCallback
import org.monora.uprotocol.client.android.viewmodel.ClientsViewModel
import org.monora.uprotocol.client.android.viewmodel.EmptyContentViewModel
import org.monora.uprotocol.client.android.viewmodel.content.ClientContentViewModel
@AndroidEntryPoint
class PickClientFragment : Fragment(R.layout.layout_clients) {
private val clientsViewModel: ClientsViewModel by viewModels()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val recyclerView = view.findViewById<RecyclerView>(R.id.recyclerView)
val emptyView = LayoutEmptyContentBinding.bind(view.findViewById(R.id.emptyView))
val adapter = Adapter { client, clickType ->
when (clickType) {
ClientContentViewModel.ClickType.Default -> findNavController().navigate(
PickClientFragmentDirections.actionClientsFragmentToClientConnectionFragment(client)
)
ClientContentViewModel.ClickType.Details -> findNavController().navigate(
PickClientFragmentDirections.actionClientsFragmentToClientDetailsFragment(client)
)
}
}
val emptyContentViewModel = EmptyContentViewModel()
emptyView.viewModel = emptyContentViewModel
emptyView.emptyText.setText(R.string.empty_clients_list)
emptyView.emptyImage.setImageResource(R.drawable.ic_devices_white_24dp)
adapter.setHasStableIds(true)
recyclerView.adapter = adapter
emptyView.executePendingBindings()
clientsViewModel.clients.observe(viewLifecycleOwner) {
adapter.submitList(it)
emptyContentViewModel.with(recyclerView, it.isNotEmpty())
}
}
class ClientViewHolder(
val binding: ListPickClientBinding,
val clickListener: (UClient, ClientContentViewModel.ClickType) -> Unit,
) : RecyclerView.ViewHolder(binding.root) {
fun bind(client: UClient) {
binding.viewModel = ClientContentViewModel(client)
binding.clickListener =
View.OnClickListener { clickListener(client, ClientContentViewModel.ClickType.Default) }
binding.detailsClickListener =
View.OnClickListener { clickListener(client, ClientContentViewModel.ClickType.Details) }
binding.executePendingBindings()
}
}
class Adapter(
private val clickListener: (UClient, ClientContentViewModel.ClickType) -> Unit,
) : ListAdapter<UClient, ClientViewHolder>(UClientItemCallback()) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ClientViewHolder {
return ClientViewHolder(
ListPickClientBinding.inflate(LayoutInflater.from(parent.context), parent, false),
clickListener
)
}
override fun onBindViewHolder(holder: ClientViewHolder, position: Int) {
holder.bind(getItem(position))
}
override fun getItemId(position: Int): Long {
return getItem(position).uid.hashCode().toLong()
}
}
}
| gpl-2.0 | debbc3979c726bb69e334688741c576a | 44.336538 | 104 | 0.730011 | 5.021299 | false | false | false | false |
mrlem/happy-cows | core/src/org/mrlem/happycows/ui/Sounds.kt | 1 | 854 | package org.mrlem.happycows.ui
import org.mrlem.happycows.ui.caches.MusicCache
import org.mrlem.happycows.ui.caches.SoundCache
/**
* @author Sébastien Guillemin <[email protected]>
*/
object Sounds {
// sound resources
private val pushSound = SoundCache.instance[SoundCache.THROW_SOUND_ID]!!
private val mooSound = SoundCache.instance[SoundCache.MOO_SOUND_ID]!!
private val glassSound = SoundCache.instance[SoundCache.GLASS_SOUND_ID]!!
private val music = MusicCache.instance[MusicCache.SCOTLAND_MUSIC_ID]!!
fun playMusic() {
music.isLooping = true
music.volume = 0.3f
music.play()
}
fun stopMusic() {
music.stop()
}
fun playMoo() {
mooSound.play(0.5f)
}
fun playJump() {
pushSound.play()
}
fun playDing() {
glassSound.play()
}
}
| gpl-3.0 | d2aea4a2443bb5f6defc48708ac240d3 | 20.871795 | 77 | 0.644783 | 3.584034 | false | false | false | false |
code-helix/slatekit | src/lib/kotlin/slatekit-telemetry/src/main/kotlin/slatekit/telemetry/Calls.kt | 1 | 1266 | package slatekit.telemetry
import slatekit.common.DateTime
import slatekit.common.Identity
import slatekit.results.Err
import java.util.concurrent.atomic.AtomicReference
/**
* Used for diagnostics / metrics to track calls made to some function/target identified by @param id
* This serves to track the following:
*
* 1. total calls made
* 2. total calls passed
* 3. total calls failed
* 4. last error
* 5. last time of call
*/
class Calls(val id: Identity) {
private val counters = Counters(id)
private val lastErr = AtomicReference<Err>()
private val lastRunTime = AtomicReference<DateTime>()
fun hasRun():Boolean = totalRuns() > 0
fun inc(): Long {
lastRunTime.set(DateTime.now())
return counters.processed.inc()
}
fun passed(): Long = counters.succeeded.inc()
fun failed(): Long = counters.errored.inc()
fun failed(ex:Exception): Long {
lastErr.set(Err.ex(ex))
return counters.unknown.inc()
}
fun totalRuns():Long = counters.processed.get()
fun totalPassed():Long = counters.succeeded.get()
fun totalFailed():Long = counters.errored.get() + counters.unknown.get()
fun lastError():Err? = lastErr.get()
fun lastTime():DateTime? = lastRunTime.get()
}
| apache-2.0 | 78547b638055098e28f2a4289ad79941 | 24.32 | 101 | 0.682464 | 4.006329 | false | false | false | false |
zdary/intellij-community | plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/panels/management/packagedetails/PackagesDetailsInfoPanel.kt | 1 | 10815 | package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packagedetails
import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle
import com.jetbrains.packagesearch.intellij.plugin.api.model.StandardV2Author
import com.jetbrains.packagesearch.intellij.plugin.api.model.StandardV2Package
import com.jetbrains.packagesearch.intellij.plugin.api.model.StandardV2Version
import com.jetbrains.packagesearch.intellij.plugin.ui.PackageSearchUI
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageModel
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageVersion
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.RepositoryModel
import com.jetbrains.packagesearch.intellij.plugin.ui.updateAndRepaint
import com.jetbrains.packagesearch.intellij.plugin.ui.util.ScaledPixels
import com.jetbrains.packagesearch.intellij.plugin.ui.util.emptyBorder
import com.jetbrains.packagesearch.intellij.plugin.ui.util.noInsets
import com.jetbrains.packagesearch.intellij.plugin.ui.util.scaled
import com.jetbrains.packagesearch.intellij.plugin.ui.util.scaledAsString
import com.jetbrains.packagesearch.intellij.plugin.ui.util.skipInvisibleComponents
import com.jetbrains.packagesearch.intellij.plugin.ui.util.withHtmlStyling
import net.miginfocom.layout.AC
import net.miginfocom.layout.CC
import net.miginfocom.layout.LC
import net.miginfocom.swing.MigLayout
import org.apache.commons.lang3.StringUtils
import java.awt.Component
import java.awt.Dimension
import javax.swing.JComponent
import javax.swing.JPanel
@Suppress("MagicNumber") // Thanks Swing...
internal class PackagesDetailsInfoPanel : JPanel() {
@ScaledPixels private val maxRowHeight = 180.scaled()
private val noDataLabel = PackageSearchUI.createLabel {
foreground = PackageSearchUI.GRAY_COLOR
text = PackageSearchBundle.message("packagesearch.ui.toolwindow.packages.details.noData")
.withHtmlStyling(wordWrap = true)
}.withMaxHeight(maxRowHeight)
private val repositoriesLabel = PackageSearchUI.createLabel()
.withMaxHeight(maxRowHeight)
private val authorsLabel = PackageSearchUI.createLabel()
.withMaxHeight(maxRowHeight)
private val gitHubPanel = GitHubInfoPanel()
.withMaxHeight(maxRowHeight)
private val licensesLinkLabel = PackageSearchUI.createLabelWithLink()
.withMaxHeight(maxRowHeight)
private val projectWebsiteLinkLabel = PackageSearchUI.createLabelWithLink()
private val documentationLinkLabel = PackageSearchUI.createLabelWithLink()
private val readmeLinkLabel = PackageSearchUI.createLabelWithLink()
private val kotlinPlatformsPanel = DependencyKotlinPlatformsPanel()
private val usagesPanel = DependencyUsagesPanel()
init {
layout = MigLayout(
LC().fillX()
.noInsets()
.skipInvisibleComponents()
.gridGap("0", 8.scaledAsString()),
AC().grow(), // One column only
AC().fill().gap() // All rows are filling all available width
.fill().gap()
.fill().gap()
.fill().gap()
.fill().gap()
.fill().gap()
.fill().gap()
)
background = PackageSearchUI.UsualBackgroundColor
alignmentX = Component.LEFT_ALIGNMENT
@ScaledPixels val horizontalBorder = 12.scaled()
border = emptyBorder(left = horizontalBorder, bottom = 20.scaled(), right = horizontalBorder)
fun CC.compensateForHighlightableComponentMarginLeft() = pad(0, (-2).scaled(), 0, 0)
add(noDataLabel, CC().wrap())
add(repositoriesLabel, CC().wrap())
add(authorsLabel, CC().wrap())
add(gitHubPanel, CC().wrap())
add(licensesLinkLabel, CC().compensateForHighlightableComponentMarginLeft().wrap())
add(projectWebsiteLinkLabel, CC().compensateForHighlightableComponentMarginLeft().wrap())
add(documentationLinkLabel, CC().compensateForHighlightableComponentMarginLeft().wrap())
add(readmeLinkLabel, CC().compensateForHighlightableComponentMarginLeft().wrap())
add(kotlinPlatformsPanel, CC().wrap())
add(usagesPanel, CC().wrap())
}
fun display(
packageModel: PackageModel,
selectedVersion: PackageVersion,
installedKnownRepositories: List<RepositoryModel>
) {
if (packageModel.remoteInfo == null) {
clearPanelContents()
return
}
noDataLabel.isVisible = false
val selectedVersionInfo = packageModel.remoteInfo.versions.find { it.version == selectedVersion.versionName }
displayRepositoriesIfAny(selectedVersionInfo, installedKnownRepositories)
displayAuthorsIfAny(packageModel.remoteInfo.authors)
val linkExtractor = LinkExtractor(packageModel.remoteInfo)
displayGitHubInfoIfAny(linkExtractor.scm())
displayLicensesIfAny(linkExtractor.licenses())
displayProjectWebsiteIfAny(linkExtractor.projectWebsite())
displayDocumentationIfAny(linkExtractor.documentation())
displayReadmeIfAny(linkExtractor.readme())
displayKotlinPlatformsIfAny(packageModel.remoteInfo)
displayUsagesIfAny(packageModel)
updateAndRepaint()
(parent as JComponent).updateAndRepaint()
}
private fun clearPanelContents() {
noDataLabel.isVisible = true
repositoriesLabel.isVisible = false
authorsLabel.isVisible = false
gitHubPanel.isVisible = false
licensesLinkLabel.isVisible = false
projectWebsiteLinkLabel.isVisible = false
documentationLinkLabel.isVisible = false
readmeLinkLabel.isVisible = false
kotlinPlatformsPanel.clear()
usagesPanel.clear()
updateAndRepaint()
}
private fun displayRepositoriesIfAny(
selectedVersionInfo: StandardV2Version?,
knownRepositories: List<RepositoryModel>
) {
if (selectedVersionInfo == null) {
repositoriesLabel.isVisible = false
return
}
val repositoryNames = selectedVersionInfo.repositoryIds
.mapNotNull { repoId -> knownRepositories.find { it.id == repoId }?.displayName }
.joinToString()
repositoriesLabel.text = if (selectedVersionInfo.repositoryIds.size == 1) {
PackageSearchBundle.message("packagesearch.ui.toolwindow.packages.details.info.repository", repositoryNames)
} else {
PackageSearchBundle.message("packagesearch.ui.toolwindow.packages.details.info.repositories", repositoryNames)
}.withHtmlStyling(wordWrap = true)
repositoriesLabel.isVisible = true
}
private fun displayAuthorsIfAny(authors: List<StandardV2Author>?) {
if (authors.isNullOrEmpty()) {
authorsLabel.isVisible = false
return
}
val authorNames = authors.filterNot { it.name.isNullOrBlank() }
.map { StringUtils.normalizeSpace(it.name) }
val authorsString = if (authorNames.size == 1) {
PackageSearchBundle.message("packagesearch.ui.toolwindow.packages.details.info.author", authorNames.joinToString())
} else {
PackageSearchBundle.message("packagesearch.ui.toolwindow.packages.details.info.authors", authorNames.joinToString())
}
authorsLabel.text = authorsString.withHtmlStyling(wordWrap = true)
authorsLabel.isVisible = true
}
private fun displayGitHubInfoIfAny(scmInfoLink: InfoLink.ScmRepository?) {
if (scmInfoLink !is InfoLink.ScmRepository.GitHub) {
gitHubPanel.isVisible = false
return
}
gitHubPanel.text = scmInfoLink.displayNameCapitalized
gitHubPanel.url = scmInfoLink.url
gitHubPanel.stars = scmInfoLink.stars
gitHubPanel.isVisible = true
}
private fun displayLicensesIfAny(licenseInfoLink: List<InfoLink.License>) {
if (licenseInfoLink.isEmpty()) {
licensesLinkLabel.isVisible = false
return
}
// TODO move this to a separate component, handle multiple licenses
val mainLicense = licenseInfoLink.first()
licensesLinkLabel.url = mainLicense.url
licensesLinkLabel.setDisplayText(
if (mainLicense.licenseName != null) {
PackageSearchBundle.message("packagesearch.ui.toolwindow.packages.details.info.license", mainLicense.licenseName)
} else {
mainLicense.displayNameCapitalized
}
)
licensesLinkLabel.isVisible = true
}
private fun displayProjectWebsiteIfAny(projectWebsiteLink: InfoLink.ProjectWebsite?) {
if (projectWebsiteLink == null) {
projectWebsiteLinkLabel.isVisible = false
return
}
projectWebsiteLinkLabel.isVisible = true
projectWebsiteLinkLabel.url = projectWebsiteLink.url
projectWebsiteLinkLabel.setDisplayText(projectWebsiteLink.displayNameCapitalized)
}
private fun displayDocumentationIfAny(documentationLink: InfoLink.Documentation?) {
if (documentationLink == null) {
documentationLinkLabel.isVisible = false
return
}
documentationLinkLabel.isVisible = true
documentationLinkLabel.url = documentationLink.url
documentationLinkLabel.setDisplayText(documentationLink.displayNameCapitalized)
}
private fun displayReadmeIfAny(readmeLink: InfoLink.Readme?) {
if (readmeLink == null) {
readmeLinkLabel.isVisible = false
return
}
readmeLinkLabel.isVisible = true
readmeLinkLabel.url = readmeLink.url
readmeLinkLabel.setDisplayText(readmeLink.displayNameCapitalized)
}
private fun displayKotlinPlatformsIfAny(packageDetails: StandardV2Package?) {
val isKotlinMultiplatform = packageDetails?.mpp != null
if (isKotlinMultiplatform && packageDetails?.platforms?.isNotEmpty() == true) {
kotlinPlatformsPanel.display(packageDetails.platforms)
kotlinPlatformsPanel.isVisible = true
} else {
kotlinPlatformsPanel.isVisible = false
}
}
private fun displayUsagesIfAny(packageModel: PackageModel) {
if (packageModel is PackageModel.Installed) {
usagesPanel.display(packageModel)
usagesPanel.isVisible = true
} else {
usagesPanel.clear()
usagesPanel.isVisible = false
}
}
private fun <T : JComponent> T.withMaxHeight(@ScaledPixels maxHeight: Int): T {
maximumSize = Dimension(Int.MAX_VALUE, maxHeight)
return this
}
}
| apache-2.0 | 1f46cab1e5bf18fd2ef0adff34fc689a | 38.327273 | 129 | 0.699769 | 5.426493 | false | false | false | false |
Mistchenko/KorlinExp | KotlinApp/app/src/main/kotlin/alef/mist/kotlinapp/TestAnkoComponent.kt | 1 | 605 | package alef.mist.kotlinapp
import android.graphics.Color
import android.view.View
import org.jetbrains.anko.*
/**
* Created by mist on 07.02.17.
*/
class TestAnkoComponent : AnkoComponent<AnkoActivity> {
override fun createView(ui: AnkoContext<AnkoActivity>): View = with(ui) {
relativeLayout {
padding = dip(6)
editText("this component") {
leftPadding = dip(6)
rightPadding = dip(6)
textSize = 26F
backgroundColor = Color.YELLOW
textColor = Color.RED
}
}
}
} | mit | 63f894da18d0dd0a1b69e46ada78608e | 24.25 | 77 | 0.575207 | 4.514925 | false | false | false | false |
smmribeiro/intellij-community | platform/feedback/src/com/intellij/feedback/dialog/ProjectCreationFeedbackDialog.kt | 1 | 14963 | // 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.feedback.dialog
import com.intellij.feedback.*
import com.intellij.feedback.bundle.FeedbackBundle
import com.intellij.feedback.state.projectCreation.ProjectCreationInfoService
import com.intellij.ide.feedback.RatingComponent
import com.intellij.openapi.application.ApplicationBundle
import com.intellij.openapi.observable.properties.GraphPropertyImpl.Companion.graphProperty
import com.intellij.openapi.observable.properties.PropertyGraph
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.ui.LicensingFacade
import com.intellij.ui.PopupBorder
import com.intellij.ui.components.JBCheckBox
import com.intellij.ui.components.JBScrollPane
import com.intellij.ui.components.JBTextField
import com.intellij.ui.components.TextComponentEmptyText
import com.intellij.ui.dsl.builder.*
import com.intellij.ui.dsl.gridLayout.Gaps
import com.intellij.util.ui.JBEmptyBorder
import com.intellij.util.ui.JBFont
import com.intellij.util.ui.JBUI
import kotlinx.serialization.Serializable
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.*
import java.awt.event.ActionEvent
import java.awt.event.KeyAdapter
import java.awt.event.KeyEvent
import java.util.function.Predicate
import javax.swing.Action
import javax.swing.JComponent
import javax.swing.SwingUtilities
class ProjectCreationFeedbackDialog(
private val project: Project?,
createdProjectTypeName: String,
private val forTest: Boolean
) : DialogWrapper(project) {
/** Increase the additional number when onboarding feedback format is changed */
private val FEEDBACK_JSON_VERSION = COMMON_FEEDBACK_SYSTEM_INFO_VERSION + 0
private val TICKET_TITLE_ZENDESK = "Project Creation Feedback"
private val FEEDBACK_TYPE_ZENDESK = "Project Creation Feedback"
private val NO_PROBLEM = "No problem"
private val EMPTY_PROJECT = "Empty project"
private val HARD_TO_FIND = "Hard to find"
private val LACK_OF_FRAMEWORK = "Lack of framework"
private val OTHER = "Other"
private val systemInfoData: ProjectCreationFeedbackSystemInfoData = createProjectCreationFeedbackSystemInfoData(createdProjectTypeName)
private val propertyGraph = PropertyGraph()
private val ratingProperty = propertyGraph.graphProperty { 0 }
private val checkBoxNoProblemProperty = propertyGraph.graphProperty { false }
private val checkBoxEmptyProjectDontWorkProperty = propertyGraph.graphProperty { false }
private val checkBoxHardFindDesireProjectProperty = propertyGraph.graphProperty { false }
private val checkBoxFrameworkProperty = propertyGraph.graphProperty { false }
private val checkBoxOtherProperty = propertyGraph.graphProperty { false }
private val textFieldOtherProblemProperty = propertyGraph.graphProperty { "" }
private val textAreaOverallFeedbackProperty = propertyGraph.graphProperty { "" }
private val checkBoxEmailProperty = propertyGraph.graphProperty { false }
private val textFieldEmailProperty = propertyGraph.graphProperty { LicensingFacade.INSTANCE?.getLicenseeEmail().orEmpty() }
private var ratingComponent: RatingComponent? = null
private var missingRatingTooltip: JComponent? = null
private var checkBoxOther: JBCheckBox? = null
private var checkBoxEmail: JBCheckBox? = null
private val textAreaRowSize = 4
private val textFieldEmailColumnSize = 25
private val textFieldOtherColumnSize = 41
private val textAreaOverallFeedbackColumnSize = 42
private val jsonConverter = Json { prettyPrint = true }
init {
init()
title = FeedbackBundle.message("dialog.creation.project.top.title")
isResizable = false
}
override fun doCancelAction() {
super.doCancelAction()
}
override fun doOKAction() {
super.doOKAction()
val projectCreationInfoState = ProjectCreationInfoService.getInstance().state
projectCreationInfoState.feedbackSent = true
val email = if (checkBoxEmailProperty.get()) textFieldEmailProperty.get() else DEFAULT_NO_EMAIL_ZENDESK_REQUESTER
submitGeneralFeedback(project,
TICKET_TITLE_ZENDESK,
createRequestDescription(),
FEEDBACK_TYPE_ZENDESK,
createCollectedDataJsonString(),
email,
{ },
{ },
if (forTest) FeedbackRequestType.TEST_REQUEST else FeedbackRequestType.PRODUCTION_REQUEST
)
}
private fun createRequestDescription(): String {
return buildString {
appendLine(FeedbackBundle.message("dialog.creation.project.zendesk.title"))
appendLine(FeedbackBundle.message("dialog.creation.project.zendesk.description"))
appendLine()
appendLine(FeedbackBundle.message("dialog.created.project.zendesk.rating.label"))
appendLine(" ${ratingProperty.get()}")
appendLine()
appendLine(FeedbackBundle.message("dialog.created.project.zendesk.problems.title"))
appendLine(createProblemsList())
appendLine()
appendLine(FeedbackBundle.message("dialog.created.project.zendesk.overallExperience.label"))
appendLine(textAreaOverallFeedbackProperty.get())
}
}
private fun createProblemsList(): String {
val resultProblemsList = mutableListOf<String>()
if (checkBoxNoProblemProperty.get()) {
resultProblemsList.add(FeedbackBundle.message("dialog.created.project.zendesk.problem.1.label"))
}
if (checkBoxEmptyProjectDontWorkProperty.get()) {
resultProblemsList.add(FeedbackBundle.message("dialog.created.project.zendesk.problem.2.label"))
}
if (checkBoxHardFindDesireProjectProperty.get()) {
resultProblemsList.add(FeedbackBundle.message("dialog.created.project.zendesk.problem.3.label"))
}
if (checkBoxFrameworkProperty.get()) {
resultProblemsList.add(FeedbackBundle.message("dialog.created.project.zendesk.problem.4.label"))
}
if (checkBoxOtherProperty.get()) {
resultProblemsList.add(textFieldOtherProblemProperty.get())
}
return resultProblemsList.joinToString(prefix = "- ", separator = "\n- ")
}
private fun createCollectedDataJsonString(): String {
val collectedData = buildJsonObject {
put(FEEDBACK_REPORT_ID_KEY, "new_project_creation_dialog")
put("format_version", FEEDBACK_JSON_VERSION)
put("rating", ratingProperty.get())
put("project_type", systemInfoData.createdProjectTypeName)
putJsonArray("problems") {
if (checkBoxNoProblemProperty.get()) {
add(createProblemJsonObject(NO_PROBLEM))
}
if (checkBoxEmptyProjectDontWorkProperty.get()) {
add(createProblemJsonObject(EMPTY_PROJECT))
}
if (checkBoxHardFindDesireProjectProperty.get()) {
add(createProblemJsonObject(HARD_TO_FIND))
}
if (checkBoxFrameworkProperty.get()) {
add(createProblemJsonObject(LACK_OF_FRAMEWORK))
}
if (checkBoxOtherProperty.get()) {
add(createProblemJsonObject(OTHER, textFieldOtherProblemProperty.get()))
}
}
put("overall_exp", textAreaOverallFeedbackProperty.get())
put("system_info", jsonConverter.encodeToJsonElement(systemInfoData.commonSystemInfo))
}
return jsonConverter.encodeToString(collectedData)
}
private fun createProblemJsonObject(name: String, description: String? = null): JsonObject {
return buildJsonObject {
put("name", name)
if (description != null) {
put("description", description)
}
}
}
override fun createCenterPanel(): JComponent {
val mainPanel = panel {
row {
label(FeedbackBundle.message("dialog.creation.project.title")).applyToComponent {
font = JBFont.h1()
}
}
row {
label(FeedbackBundle.message("dialog.creation.project.description"))
}.bottomGap(BottomGap.MEDIUM)
row {
ratingComponent = RatingComponent().also {
it.addPropertyChangeListener(RatingComponent.RATING_PROPERTY) { _ ->
ratingProperty.set(it.myRating)
missingRatingTooltip?.isVisible = false
}
cell(it)
.label(FeedbackBundle.message("dialog.created.project.rating.label"), LabelPosition.TOP)
}
missingRatingTooltip = label(FeedbackBundle.message("dialog.created.project.rating.required")).applyToComponent {
border = JBUI.Borders.compound(PopupBorder.Factory.createColored(JBUI.CurrentTheme.Validator.errorBorderColor()),
JBUI.Borders.empty(JBUI.scale(4), JBUI.scale(8)))
background = JBUI.CurrentTheme.Validator.errorBackgroundColor()
isVisible = false
isOpaque = true
}.component
}.bottomGap(BottomGap.MEDIUM)
row {
checkBox(FeedbackBundle.message("dialog.created.project.checkbox.1.label")).bindSelected(checkBoxNoProblemProperty)
.label(FeedbackBundle.message("dialog.created.project.group.checkbox.title"), LabelPosition.TOP)
}.topGap(TopGap.MEDIUM)
row {
checkBox(FeedbackBundle.message("dialog.created.project.checkbox.2.label")).bindSelected(checkBoxEmptyProjectDontWorkProperty)
}
row {
checkBox(FeedbackBundle.message("dialog.created.project.checkbox.3.label")).bindSelected(checkBoxHardFindDesireProjectProperty)
}
row {
checkBox(FeedbackBundle.message("dialog.created.project.checkbox.4.label")).bindSelected(checkBoxFrameworkProperty)
}
row {
checkBox("").bindSelected(checkBoxOtherProperty).applyToComponent {
checkBoxOther = this
}.customize(Gaps(right = JBUI.scale(4)))
textField()
.bindText(textFieldOtherProblemProperty)
.columns(textFieldOtherColumnSize)
.errorOnApply(FeedbackBundle.message("dialog.created.project.checkbox.5.required")) {
checkBoxOtherProperty.get() && it.text.isBlank()
}
.applyToComponent {
emptyText.text = FeedbackBundle.message("dialog.created.project.checkbox.5.placeholder")
textFieldOtherProblemProperty.afterChange {
if (it.isNotBlank()) {
checkBoxOtherProperty.set(true)
}
else {
checkBoxOtherProperty.set(false)
}
}
putClientProperty(TextComponentEmptyText.STATUS_VISIBLE_FUNCTION,
Predicate<JBTextField> { textField -> textField.text.isEmpty() })
}
}.bottomGap(BottomGap.MEDIUM)
row {
textArea()
.bindText(textAreaOverallFeedbackProperty)
.rows(textAreaRowSize)
.columns(textAreaOverallFeedbackColumnSize)
.label(FeedbackBundle.message("dialog.created.project.textarea.label"), LabelPosition.TOP)
.applyToComponent {
wrapStyleWord = true
lineWrap = true
addKeyListener(object : KeyAdapter() {
override fun keyPressed(e: KeyEvent) {
if (e.keyCode == KeyEvent.VK_TAB) {
if ((e.modifiersEx and KeyEvent.SHIFT_DOWN_MASK) != 0) {
transferFocusBackward()
}
else {
transferFocus()
}
e.consume()
}
}
})
}
}.bottomGap(BottomGap.MEDIUM).topGap(TopGap.SMALL)
row {
checkBox(FeedbackBundle.message("dialog.created.project.checkbox.email"))
.bindSelected(checkBoxEmailProperty).applyToComponent {
checkBoxEmail = this
}
}.topGap(TopGap.MEDIUM)
indent {
row {
textField().bindText(textFieldEmailProperty).columns(textFieldEmailColumnSize).applyToComponent {
emptyText.text = FeedbackBundle.message("dialog.created.project.textfield.email.placeholder")
isEnabled = checkBoxEmailProperty.get()
checkBoxEmail?.addActionListener { _ ->
isEnabled = checkBoxEmailProperty.get()
}
putClientProperty(TextComponentEmptyText.STATUS_VISIBLE_FUNCTION,
Predicate<JBTextField> { textField -> textField.text.isEmpty() })
}.errorOnApply(FeedbackBundle.message("dialog.created.project.textfield.email.required")) {
checkBoxEmailProperty.get() && it.text.isBlank()
}.errorOnApply(ApplicationBundle.message("feedback.form.email.invalid")) {
checkBoxEmailProperty.get() && it.text.isNotBlank() && !it.text.matches(Regex(".+@.+\\..+"))
}
}.bottomGap(BottomGap.MEDIUM)
}
row {
cell(createFeedbackAgreementComponent(project) {
showProjectCreationFeedbackSystemInfoDialog(project, systemInfoData)
})
}.bottomGap(BottomGap.SMALL).topGap(TopGap.MEDIUM)
}.also { dialog ->
dialog.border = JBEmptyBorder(JBUI.scale(15), JBUI.scale(10), JBUI.scale(0), JBUI.scale(10))
}
return JBScrollPane(mainPanel, JBScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JBScrollPane.HORIZONTAL_SCROLLBAR_NEVER).apply {
border = JBEmptyBorder(0)
}
}
override fun createActions(): Array<Action> {
return arrayOf(cancelAction, okAction)
}
override fun getOKAction(): Action {
return object : DialogWrapper.OkAction() {
init {
putValue(Action.NAME, FeedbackBundle.message("dialog.created.project.ok"))
}
override fun doAction(e: ActionEvent) {
val ratingComponent = ratingComponent
missingRatingTooltip?.isVisible = ratingComponent?.myRating == 0
if (ratingComponent == null || ratingComponent.myRating != 0) {
super.doAction(e)
}
else {
enabled = false
SwingUtilities.invokeLater {
ratingComponent.requestFocusInWindow()
}
}
}
}
}
}
@Serializable
private data class ProjectCreationFeedbackSystemInfoData(
val createdProjectTypeName: String,
val commonSystemInfo: CommonFeedbackSystemInfoData
)
private fun showProjectCreationFeedbackSystemInfoDialog(project: Project?,
systemInfoData: ProjectCreationFeedbackSystemInfoData
) = showFeedbackSystemInfoDialog(project, systemInfoData.commonSystemInfo) {
row(FeedbackBundle.message("dialog.created.project.system.info.panel.project.type")) {
label(systemInfoData.createdProjectTypeName) //NON-NLS
}
}
private fun createProjectCreationFeedbackSystemInfoData(createdProjectTypeName: String): ProjectCreationFeedbackSystemInfoData {
return ProjectCreationFeedbackSystemInfoData(createdProjectTypeName, CommonFeedbackSystemInfoData.getCurrentData())
}
| apache-2.0 | d24c46fa228db840583154efb960d0a8 | 41.030899 | 158 | 0.694647 | 5.024513 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/findUsages/java/findJavaClassUsages/JKAliasedClassAllUsages.1.kt | 9 | 529 | import AAA as A
import AAA
public class X(bar: String? = A.BAR) : A() {
var next: A? = A()
val myBar: String? = A.BAR
init {
A.BAR = ""
AAA.foos()
}
fun foo(a: A) {
val aa: AAA = a
aa.bar = ""
}
fun getNextFun(): A? {
return next
}
public override fun foo() {
super<A>.foo()
}
companion object : AAA() {
}
}
object O : A() {
}
fun X.bar(a: A = A()) {
}
fun Any.toA(): A? {
return if (this is A) this as A else null
}
| apache-2.0 | f8a9bf24ca2b2a0b196cb28ded2ec47a | 11.902439 | 45 | 0.453686 | 2.906593 | false | false | false | false |
smmribeiro/intellij-community | platform/script-debugger/backend/src/debugger/sourcemap/FileBackedSourceMap.kt | 13 | 2692 | // 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.debugger.sourcemap
import com.intellij.reference.SoftReference
import com.intellij.util.Url
import com.intellij.util.io.readText
import java.nio.file.Path
class FileBackedSourceMap private constructor(filePath: Path,
initialData: SourceMapDataEx,
sourceResolver: SourceResolver)
: SourceMapBase(FileBackedSourceMapData(filePath, initialData), sourceResolver) {
override val sourceIndexToMappings: Array<MappingList?>
get() = (this.sourceMapData as FileBackedSourceMapData).sourceIndexToMappings
override val generatedMappings: Mappings
get() = (sourceMapData as FileBackedSourceMapData).generatedMappings
companion object {
fun newFileBackedSourceMap(filePath: Path,
trimFileScheme: Boolean,
baseUrl: Url?,
baseUrlIsFile: Boolean): FileBackedSourceMap? {
val text = filePath.readText()
val data = SourceMapDataCache.getOrCreate(text, filePath.toString()) ?: return null
return FileBackedSourceMap(filePath, data, SourceResolver(data.sourceMapData.sources, trimFileScheme, baseUrl, baseUrlIsFile))
}
}
}
private class FileBackedSourceMapData(private val filePath: Path, initialData: SourceMapDataEx) : SourceMapData {
private var cachedData: SoftReference<SourceMapDataEx> = SoftReference(initialData)
override val file: String? = initialData.sourceMapData.file
override val sources: List<String> = initialData.sourceMapData.sources
override val sourcesContent: List<String?>?
get() = getData().sourceMapData.sourcesContent
override val hasNameMappings: Boolean = initialData.sourceMapData.hasNameMappings
override val mappings: List<MappingEntry>
get() = getData().sourceMapData.mappings
val sourceIndexToMappings: Array<MappingList?>
get() = getData().sourceIndexToMappings
val generatedMappings: Mappings
get() = getData().generatedMappings
private fun calculateData(): SourceMapDataEx? {
val text = filePath.readText()
// TODO invalidate map. Need to drop SourceResolver's rawSources at least.
return SourceMapDataCache.getOrCreate(text, filePath.toString())
}
private fun getData(): SourceMapDataEx {
val cached = cachedData.get()
if (cached != null) return cached
val calculated = calculateData() ?: throw RuntimeException("Cannot decode $filePath")
cachedData = SoftReference(calculated)
return calculated
}
}
| apache-2.0 | fa169561561aac9a9ec27851bc9ce86d | 41.730159 | 140 | 0.722511 | 4.930403 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ImportAllMembersIntention.kt | 1 | 4981 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.intentions
import com.intellij.codeInsight.intention.HighPriorityAction
import com.intellij.openapi.editor.Editor
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.core.ShortenReferences
import org.jetbrains.kotlin.idea.core.util.range
import org.jetbrains.kotlin.idea.imports.importableFqName
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.idea.references.resolveToDescriptors
import org.jetbrains.kotlin.idea.util.ImportDescriptorResult
import org.jetbrains.kotlin.idea.util.ImportInsertHelper
import org.jetbrains.kotlin.idea.util.safeAnalyzeNonSourceRootCode
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.collectDescendantsOfType
import org.jetbrains.kotlin.psi.psiUtil.getQualifiedElementSelector
import org.jetbrains.kotlin.psi.psiUtil.isInImportDirective
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.resolve.scopes.receivers.ClassQualifier
class ImportAllMembersIntention : SelfTargetingIntention<KtElement>(
KtElement::class.java,
KotlinBundle.lazyMessage("import.members.with")
), HighPriorityAction {
override fun isApplicableTo(element: KtElement, caretOffset: Int): Boolean {
val receiverExpression = element.receiverExpression() ?: return false
if (!receiverExpression.range.containsOffset(caretOffset)) return false
val target = target(element, receiverExpression) ?: return false
val targetFqName = target.importableFqName ?: return false
if (receiverExpression.isInImportDirective()) return false
val file = element.containingKtFile
val project = file.project
val dummyFileText = (file.packageDirective?.text ?: "") + "\n" + (file.importList?.text ?: "")
val dummyFile = KtPsiFactory(project).createAnalyzableFile("Dummy.kt", dummyFileText, file)
val helper = ImportInsertHelper.getInstance(project)
if (helper.importDescriptor(dummyFile, target, forceAllUnderImport = true) == ImportDescriptorResult.FAIL) return false
setTextGetter(KotlinBundle.lazyMessage("import.members.from.0", targetFqName.parent().asString()))
return true
}
override fun applyTo(element: KtElement, editor: Editor?) = element.importReceiverMembers()
companion object {
fun KtElement.importReceiverMembers() {
val target = target(this) ?: return
val classFqName = target.importableFqName!!.parent()
ImportInsertHelper.getInstance(project).importDescriptor(containingKtFile, target, forceAllUnderImport = true)
val qualifiedExpressions = containingKtFile.collectDescendantsOfType<KtDotQualifiedExpression> { qualifiedExpression ->
val qualifierName = qualifiedExpression.receiverExpression.getQualifiedElementSelector() as? KtNameReferenceExpression
qualifierName?.getReferencedNameAsName() == classFqName.shortName() && target(qualifiedExpression)?.importableFqName
?.parent() == classFqName
}
val userTypes = containingKtFile.collectDescendantsOfType<KtUserType> { userType ->
val receiver = userType.receiverExpression()?.getQualifiedElementSelector() as? KtNameReferenceExpression
receiver?.getReferencedNameAsName() == classFqName.shortName() && target(userType)?.importableFqName
?.parent() == classFqName
}
//TODO: not deep
ShortenReferences.DEFAULT.process(qualifiedExpressions + userTypes)
}
private fun target(qualifiedElement: KtElement, receiverExpression: KtExpression): DeclarationDescriptor? {
val bindingContext = qualifiedElement.safeAnalyzeNonSourceRootCode(BodyResolveMode.PARTIAL)
if (bindingContext[BindingContext.QUALIFIER, receiverExpression] !is ClassQualifier) {
return null
}
val selector = qualifiedElement.getQualifiedElementSelector() as? KtNameReferenceExpression ?: return null
return selector.mainReference.resolveToDescriptors(bindingContext).firstOrNull()
}
private fun target(qualifiedElement: KtElement): DeclarationDescriptor? {
val receiverExpression = qualifiedElement.receiverExpression() ?: return null
return target(qualifiedElement, receiverExpression)
}
private fun KtElement.receiverExpression(): KtExpression? = when (this) {
is KtDotQualifiedExpression -> receiverExpression
is KtUserType -> qualifier?.referenceExpression
else -> null
}
}
}
| apache-2.0 | f9d98579059add02c7ab64ccb3f6fbfe | 51.431579 | 158 | 0.740414 | 5.725287 | false | false | false | false |
Flank/flank | tool/junit/src/test/kotlin/flank/junit/mapper/StructuralKtTest.kt | 1 | 3259 | package flank.junit.mapper
import flank.junit.JUnit
import org.junit.Assert.assertEquals
import org.junit.Test
class StructuralKtTest {
private val suites = listOf(
JUnit.Suite(
name = "suite1",
tests = 3,
failures = 1,
errors = 1,
skipped = 0,
time = 9.0,
timestamp = JUnit.dateFormat.format(1_000),
testcases = listOf(
JUnit.Case(
name = "test1",
classname = "test1.Test1",
time = 4.0,
error = listOf("some error")
),
JUnit.Case(
name = "test2",
classname = "test1.Test1",
time = 2.0,
failure = listOf("some assertion failed"),
),
JUnit.Case(
name = "test1",
classname = "test1.Test2",
time = 3.0,
)
)
),
JUnit.Suite(
name = "suite2",
tests = 1,
failures = 0,
errors = 0,
skipped = 1,
time = 0.0,
timestamp = JUnit.dateFormat.format(0),
testcases = listOf(
JUnit.Case(
name = "test1",
classname = "test1.Test1",
time = 0.0,
skipped = null,
),
)
),
)
val testCases = listOf(
JUnit.TestResult(
testName = "test1",
className = "test1.Test1",
suiteName = "suite1",
startAt = 1_000,
endsAt = 5_000,
status = JUnit.TestResult.Status.Error,
stack = listOf("some error")
),
JUnit.TestResult(
testName = "test2",
className = "test1.Test1",
suiteName = "suite1",
startAt = 5_000,
endsAt = 7_000,
status = JUnit.TestResult.Status.Failed,
stack = listOf("some assertion failed")
),
JUnit.TestResult(
testName = "test1",
className = "test1.Test2",
suiteName = "suite1",
startAt = 7_000,
endsAt = 10_000,
status = JUnit.TestResult.Status.Passed,
stack = emptyList()
),
JUnit.TestResult(
testName = "test1",
className = "test1.Test1",
suiteName = "suite2",
startAt = 0,
endsAt = 0,
status = JUnit.TestResult.Status.Skipped,
stack = emptyList()
),
)
@Test
fun mapToTestSuitesTest() {
val expected = suites
val actual = testCases.mapToTestSuites()
println(xmlPrettyWriter.writeValueAsString(testCases))
println(xmlPrettyWriter.writeValueAsString(actual))
assertEquals(expected, actual)
}
@Test
fun mapToTestResultsTest() {
val expected = testCases
val actual = suites.mapToTestResults()
println(xmlPrettyWriter.writeValueAsString(suites))
assertEquals(expected, actual)
}
}
| apache-2.0 | a843cca433c814df0eb7ec21a43ca91e | 26.618644 | 62 | 0.454434 | 4.849702 | false | true | false | false |
siosio/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/KotlinDocumentationProvider.kt | 1 | 25262 | // 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
import com.google.common.html.HtmlEscapers
import com.intellij.codeInsight.documentation.DocumentationManagerUtil
import com.intellij.codeInsight.javadoc.JavaDocInfoGeneratorFactory
import com.intellij.lang.documentation.AbstractDocumentationProvider
import com.intellij.lang.documentation.DocumentationMarkup.*
import com.intellij.lang.java.JavaDocumentationProvider
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.editor.Editor
import com.intellij.psi.*
import com.intellij.psi.impl.compiled.ClsMethodImpl
import org.jetbrains.kotlin.asJava.LightClassUtil
import org.jetbrains.kotlin.asJava.elements.KtLightDeclaration
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde
import org.jetbrains.kotlin.idea.core.completion.DeclarationLookupObject
import org.jetbrains.kotlin.idea.decompiler.navigation.SourceNavigationHelper
import org.jetbrains.kotlin.idea.kdoc.*
import org.jetbrains.kotlin.idea.kdoc.KDocRenderer.appendKDocContent
import org.jetbrains.kotlin.idea.kdoc.KDocRenderer.appendKDocSections
import org.jetbrains.kotlin.idea.kdoc.KDocTemplate.DescriptionBodyTemplate
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.idea.references.resolveToDescriptors
import org.jetbrains.kotlin.idea.resolve.ResolutionFacade
import org.jetbrains.kotlin.idea.resolve.frontendService
import org.jetbrains.kotlin.idea.util.isRunningInCidrIde
import org.jetbrains.kotlin.js.resolve.diagnostics.findPsi
import org.jetbrains.kotlin.kdoc.psi.api.KDoc
import org.jetbrains.kotlin.kdoc.psi.impl.KDocSection
import org.jetbrains.kotlin.kdoc.psi.impl.KDocTag
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.load.java.NULLABILITY_ANNOTATIONS
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.*
import org.jetbrains.kotlin.renderer.AnnotationArgumentsRenderingPolicy
import org.jetbrains.kotlin.renderer.ClassifierNamePolicy
import org.jetbrains.kotlin.renderer.DescriptorRenderer
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.deprecation.DeprecationResolver
import org.jetbrains.kotlin.resolve.deprecation.deprecatedByAnnotationReplaceWithExpression
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameUnsafe
import org.jetbrains.kotlin.resolve.descriptorUtil.getSuperClassNotAny
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.resolve.source.getPsi
import org.jetbrains.kotlin.utils.addToStdlib.constant
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
class HtmlClassifierNamePolicy(val base: ClassifierNamePolicy) : ClassifierNamePolicy {
override fun renderClassifier(classifier: ClassifierDescriptor, renderer: DescriptorRenderer): String {
if (DescriptorUtils.isAnonymousObject(classifier)) {
val supertypes = classifier.typeConstructor.supertypes
return buildString {
append("<anonymous object")
if (supertypes.isNotEmpty()) {
append(" : ")
supertypes.joinTo(this) {
val ref = it.constructor.declarationDescriptor
if (ref != null)
renderClassifier(ref, renderer)
else
"<ERROR CLASS>"
}
}
append(">")
}
}
val name = base.renderClassifier(classifier, renderer)
if (classifier.isBoringBuiltinClass())
return name
return buildString {
val ref = classifier.fqNameUnsafe.toString()
DocumentationManagerUtil.createHyperlink(this, ref, name, true)
}
}
}
class WrapValueParameterHandler(val base: DescriptorRenderer.ValueParametersHandler) : DescriptorRenderer.ValueParametersHandler {
override fun appendBeforeValueParameters(parameterCount: Int, builder: StringBuilder) {
base.appendBeforeValueParameters(parameterCount, builder)
}
override fun appendBeforeValueParameter(
parameter: ValueParameterDescriptor,
parameterIndex: Int,
parameterCount: Int,
builder: StringBuilder
) {
builder.append("\n ")
base.appendBeforeValueParameter(parameter, parameterIndex, parameterCount, builder)
}
override fun appendAfterValueParameter(
parameter: ValueParameterDescriptor,
parameterIndex: Int,
parameterCount: Int,
builder: StringBuilder
) {
if (parameterIndex != parameterCount - 1) {
builder.append(",")
}
}
override fun appendAfterValueParameters(parameterCount: Int, builder: StringBuilder) {
if (parameterCount > 0) {
builder.appendLine()
}
base.appendAfterValueParameters(parameterCount, builder)
}
}
open class KotlinDocumentationProviderCompatBase : AbstractDocumentationProvider() {
override fun getCustomDocumentationElement(editor: Editor, fil: PsiFile, contextElement: PsiElement?): PsiElement? {
return if (contextElement.isModifier()) contextElement else null
}
override fun getQuickNavigateInfo(element: PsiElement?, originalElement: PsiElement?): String? {
return if (element == null) null else getText(element, originalElement, true)
}
override fun generateDoc(element: PsiElement, originalElement: PsiElement?): String? {
return getText(element, originalElement, false)
}
override fun getDocumentationElementForLink(psiManager: PsiManager, link: String, context: PsiElement?): PsiElement? {
val navElement = context?.navigationElement as? KtElement ?: return null
val resolutionFacade = navElement.getResolutionFacade()
val bindingContext = navElement.analyze(resolutionFacade, BodyResolveMode.PARTIAL)
val contextDescriptor = bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, navElement] ?: return null
val descriptors = resolveKDocLink(
bindingContext, resolutionFacade,
contextDescriptor, null, link.split('.')
)
val target = descriptors.firstOrNull() ?: return null
return DescriptorToSourceUtilsIde.getAnyDeclaration(psiManager.project, target)
}
override fun getDocumentationElementForLookupItem(psiManager: PsiManager, `object`: Any?, element: PsiElement?): PsiElement? {
if (`object` is DeclarationLookupObject) {
`object`.psiElement?.let { return it }
`object`.descriptor?.let { descriptor ->
return DescriptorToSourceUtilsIde.getAnyDeclaration(psiManager.project, descriptor)
}
}
return null
}
companion object {
private val LOG = Logger.getInstance(KotlinDocumentationProvider::class.java)
private val javaDocumentProvider = JavaDocumentationProvider()
private val DESCRIPTOR_RENDERER = DescriptorRenderer.HTML.withOptions {
classifierNamePolicy = HtmlClassifierNamePolicy(ClassifierNamePolicy.SHORT)
valueParametersHandler = WrapValueParameterHandler(valueParametersHandler)
annotationArgumentsRenderingPolicy = AnnotationArgumentsRenderingPolicy.UNLESS_EMPTY
renderCompanionObjectName = true
withDefinedIn = false
eachAnnotationOnNewLine = true
boldOnlyForNamesInHtml = true
excludedTypeAnnotationClasses = NULLABILITY_ANNOTATIONS
defaultParameterValueRenderer = { (it.source.getPsi() as? KtParameter)?.defaultValue?.text ?: "..." }
}
internal fun StringBuilder.renderKDoc(
contentTag: KDocTag,
sections: List<KDocSection> = if (contentTag is KDocSection) listOf(contentTag) else emptyList()
) {
insert(DescriptionBodyTemplate.Kotlin()) {
content {
appendKDocContent(contentTag)
}
sections {
appendKDocSections(sections)
}
}
}
private fun renderEnumSpecialFunction(element: KtClass, functionDescriptor: FunctionDescriptor, quickNavigation: Boolean): String {
val kdoc = run {
val declarationDescriptor = element.resolveToDescriptorIfAny()
val enumDescriptor = declarationDescriptor?.getSuperClassNotAny() ?: return@run null
val enumDeclaration =
DescriptorToSourceUtilsIde.getAnyDeclaration(element.project, enumDescriptor) as? KtDeclaration ?: return@run null
val enumSource = SourceNavigationHelper.getNavigationElement(enumDeclaration)
val functionName = functionDescriptor.fqNameSafe.shortName().asString()
return@run enumSource.findDescendantOfType<KDoc> {
it.getChildrenOfType<KDocSection>().any { it.findTagByName(functionName) != null }
}
}
return buildString {
insert(KDocTemplate()) {
definition {
renderDefinition(functionDescriptor, DESCRIPTOR_RENDERER)
}
if (!quickNavigation && kdoc != null) {
description {
renderKDoc(kdoc.getDefaultSection())
}
}
}
}
}
private fun renderEnum(element: KtClass, originalElement: PsiElement?, quickNavigation: Boolean): String? {
val referenceExpression = originalElement?.getNonStrictParentOfType<KtReferenceExpression>()
if (referenceExpression != null) {
// When caret on special enum function (e.g SomeEnum.values<caret>())
// element is not an KtReferenceExpression, but KtClass of enum
// so reference extracted from originalElement
val context = referenceExpression.analyze(BodyResolveMode.PARTIAL)
(context[BindingContext.REFERENCE_TARGET, referenceExpression]
?: context[BindingContext.REFERENCE_TARGET, referenceExpression.getChildOfType<KtReferenceExpression>()])?.let {
if (it is FunctionDescriptor) // To protect from Some<caret>Enum.values()
return renderEnumSpecialFunction(element, it, quickNavigation)
}
}
return renderKotlinDeclaration(element, quickNavigation)
}
private fun getText(element: PsiElement, originalElement: PsiElement?, quickNavigation: Boolean) =
getTextImpl(element, originalElement, quickNavigation)
private fun getTextImpl(element: PsiElement, originalElement: PsiElement?, quickNavigation: Boolean): String? {
if (element is PsiWhiteSpace) {
val itElement = findElementWithText(originalElement, "it")
val itReference = itElement?.getParentOfType<KtNameReferenceExpression>(false)
if (itReference != null) {
return getTextImpl(itReference, originalElement, quickNavigation)
}
}
if (element is KtTypeReference) {
val declaration = element.parent
if (declaration is KtCallableDeclaration && declaration.receiverTypeReference == element) {
val thisElement = findElementWithText(originalElement, "this")
if (thisElement != null) {
return getTextImpl(declaration, originalElement, quickNavigation)
}
}
}
if (element is KtClass && element.isEnum()) {
// When caret on special enum function (e.g SomeEnum.values<caret>())
// element is not an KtReferenceExpression, but KtClass of enum
return renderEnum(element, originalElement, quickNavigation)
} else if (element is KtEnumEntry && !quickNavigation) {
val ordinal = element.containingClassOrObject?.body?.run { getChildrenOfType<KtEnumEntry>().indexOf(element) }
return buildString {
insert(buildKotlinDeclaration(element, quickNavigation)) {
definition {
it.inherit()
ordinal?.let {
append("<br>").append(KotlinBundle.message("quick.doc.text.enum.ordinal", ordinal))
}
}
}
}
} else if (element is KtDeclaration) {
return renderKotlinDeclaration(element, quickNavigation)
} else if (element is KtNameReferenceExpression && element.getReferencedName() == "it") {
return renderKotlinImplicitLambdaParameter(element, quickNavigation)
} else if (element is KtLightDeclaration<*, *>) {
val origin = element.kotlinOrigin ?: return null
return renderKotlinDeclaration(origin, quickNavigation)
} else if (element is KtValueArgumentList) {
val referenceExpression = element.prevSibling as? KtSimpleNameExpression ?: return null
val calledElement = referenceExpression.mainReference.resolve()
if (calledElement is KtNamedFunction || calledElement is KtConstructor<*>) { // In case of Kotlin function or constructor
return renderKotlinDeclaration(calledElement as KtExpression, quickNavigation)
} else if (calledElement is ClsMethodImpl || calledElement is PsiMethod) { // In case of java function or constructor
return javaDocumentProvider.generateDoc(calledElement, referenceExpression)
}
} else if (element is KtCallExpression) {
val calledElement = element.referenceExpression()?.mainReference?.resolve()
return calledElement?.let { getTextImpl(it, originalElement, quickNavigation) }
} else if (element.isModifier()) {
when (element.text) {
KtTokens.LATEINIT_KEYWORD.value -> return KotlinBundle.message("quick.doc.text.lateinit")
KtTokens.TAILREC_KEYWORD.value -> return KotlinBundle.message("quick.doc.text.tailrec")
}
}
if (quickNavigation) {
val referenceExpression = originalElement?.getNonStrictParentOfType<KtReferenceExpression>()
if (referenceExpression != null) {
val context = referenceExpression.analyze(BodyResolveMode.PARTIAL)
val declarationDescriptor = context[BindingContext.REFERENCE_TARGET, referenceExpression]
if (declarationDescriptor != null) {
return mixKotlinToJava(declarationDescriptor, element, originalElement)
}
}
}
// This element was resolved to non-kotlin element, it will be rendered with own provider
return null
}
private fun renderKotlinDeclaration(declaration: KtExpression, quickNavigation: Boolean) = buildString {
insert(buildKotlinDeclaration(declaration, quickNavigation)) {}
}
private fun buildKotlinDeclaration(declaration: KtExpression, quickNavigation: Boolean): KDocTemplate {
val resolutionFacade = declaration.getResolutionFacade()
val context = declaration.analyze(resolutionFacade, BodyResolveMode.PARTIAL)
val declarationDescriptor = context[BindingContext.DECLARATION_TO_DESCRIPTOR, declaration]
if (declarationDescriptor == null) {
LOG.info("Failed to find descriptor for declaration " + declaration.getElementTextWithContext())
return KDocTemplate.NoDocTemplate().apply {
error {
append(KotlinBundle.message("quick.doc.no.documentation"))
}
}
}
return buildKotlin(context, declarationDescriptor, quickNavigation, declaration, resolutionFacade)
}
private fun renderKotlinImplicitLambdaParameter(element: KtReferenceExpression, quickNavigation: Boolean): String? {
val resolutionFacade = element.getResolutionFacade()
val context = element.analyze(resolutionFacade, BodyResolveMode.PARTIAL)
val target = element.mainReference.resolveToDescriptors(context).singleOrNull() as? ValueParameterDescriptor? ?: return null
return renderKotlin(context, target, quickNavigation, element, resolutionFacade)
}
private fun renderKotlin(
context: BindingContext,
declarationDescriptor: DeclarationDescriptor,
quickNavigation: Boolean,
ktElement: KtElement,
resolutionFacade: ResolutionFacade,
) = buildString {
insert(buildKotlin(context, declarationDescriptor, quickNavigation, ktElement, resolutionFacade)) {}
}
private fun buildKotlin(
context: BindingContext,
declarationDescriptor: DeclarationDescriptor,
quickNavigation: Boolean,
ktElement: KtElement,
resolutionFacade: ResolutionFacade,
): KDocTemplate {
@Suppress("NAME_SHADOWING")
var declarationDescriptor = declarationDescriptor
if (declarationDescriptor is ValueParameterDescriptor) {
val property = context[BindingContext.VALUE_PARAMETER_AS_PROPERTY, declarationDescriptor]
if (property != null) {
declarationDescriptor = property
}
}
@OptIn(FrontendInternals::class)
val deprecationProvider = resolutionFacade.frontendService<DeprecationResolver>()
return KDocTemplate().apply {
definition {
renderDefinition(declarationDescriptor, DESCRIPTOR_RENDERER)
}
insertDeprecationInfo(declarationDescriptor, deprecationProvider)
if (!quickNavigation) {
description {
declarationDescriptor.findKDoc { DescriptorToSourceUtilsIde.getAnyDeclaration(ktElement.project, it) }?.let {
renderKDoc(it)
return@description
}
if (declarationDescriptor is ClassConstructorDescriptor && !declarationDescriptor.isPrimary) {
declarationDescriptor.constructedClass.findKDoc {
DescriptorToSourceUtilsIde.getAnyDeclaration(
ktElement.project,
it
)
}?.let {
renderKDoc(it)
return@description
}
}
if (declarationDescriptor is CallableDescriptor) { // If we couldn't find KDoc, try to find javadoc in one of super's
insert(DescriptionBodyTemplate.FromJava()) {
body = extractJavaDescription(declarationDescriptor)
}
}
}
}
}
}
private fun StringBuilder.renderDefinition(descriptor: DeclarationDescriptor, renderer: DescriptorRenderer) {
if (!DescriptorUtils.isLocal(descriptor)) {
val containingDeclaration = descriptor.containingDeclaration
if (containingDeclaration != null) {
val fqName = containingDeclaration.fqNameSafe
if (!fqName.isRoot) {
DocumentationManagerUtil.createHyperlink(this, fqName.asString(), fqName.asString(), false)
}
val fileName =
descriptor
.safeAs<DeclarationDescriptorWithSource>()
?.source
?.containingFile
?.name
?.takeIf { containingDeclaration is PackageFragmentDescriptor }
if (fileName != null) {
if (!fqName.isRoot) {
append(" ")
}
wrap("<font color=\"808080\"><i>", "</i></font>") {
append(fileName)
}
}
if (fileName != null || !fqName.isRoot) {
append("<br>")
}
}
}
append(renderer.render(descriptor))
}
private fun extractJavaDescription(declarationDescriptor: DeclarationDescriptor): String {
val psi = declarationDescriptor.findPsi() as? KtFunction ?: return ""
val lightElement =
LightClassUtil.getLightClassMethod(psi) // Light method for super's scan in javadoc info gen
val javaDocInfoGenerator = JavaDocInfoGeneratorFactory.create(psi.project, lightElement)
val builder = StringBuilder()
if (javaDocInfoGenerator.generateDocInfoCore(builder, false)) {
val renderedJava = builder.toString()
return renderedJava.removeRange(
renderedJava.indexOf(DEFINITION_START),
renderedJava.indexOf(DEFINITION_END)
) // Cut off light method signature
}
return ""
}
private fun KDocTemplate.insertDeprecationInfo(
declarationDescriptor: DeclarationDescriptor,
deprecationResolver: DeprecationResolver
) {
val deprecationInfo = deprecationResolver.getDeprecations(declarationDescriptor).firstOrNull() ?: return
deprecation {
deprecationInfo.message?.let { message ->
append(SECTION_HEADER_START)
append(KotlinBundle.message("quick.doc.section.deprecated"))
append(SECTION_SEPARATOR)
append(message.htmlEscape())
append(SECTION_END)
}
deprecationInfo.deprecatedByAnnotationReplaceWithExpression()?.let { replaceWith ->
append(SECTION_HEADER_START)
append(KotlinBundle.message("quick.doc.section.replace.with"))
append(SECTION_SEPARATOR)
wrapTag("code") { append(replaceWith.htmlEscape()) }
append(SECTION_END)
}
}
}
private fun String.htmlEscape(): String = HtmlEscapers.htmlEscaper().escape(this)
private inline fun StringBuilder.wrap(prefix: String, postfix: String, crossinline body: () -> Unit) {
this.append(prefix)
body()
this.append(postfix)
}
private inline fun StringBuilder.wrapTag(tag: String, crossinline body: () -> Unit) {
wrap("<$tag>", "</$tag>", body)
}
private fun mixKotlinToJava(
declarationDescriptor: DeclarationDescriptor,
element: PsiElement,
originalElement: PsiElement?
): String? {
if (isRunningInCidrIde) return null // no Java support in CIDR
val originalInfo = JavaDocumentationProvider().getQuickNavigateInfo(element, originalElement)
if (originalInfo != null) {
val renderedDecl = constant { DESCRIPTOR_RENDERER.withOptions { withDefinedIn = false } }.render(declarationDescriptor)
return "$renderedDecl<br/>" + KotlinBundle.message("quick.doc.section.java.declaration") + "<br/>$originalInfo"
}
return null
}
private fun findElementWithText(element: PsiElement?, text: String): PsiElement? {
return when {
element == null -> null
element.text == text -> element
element.prevLeaf()?.text == text -> element.prevLeaf()
else -> null
}
}
private fun PsiElement?.isModifier() =
this != null && parent is KtModifierList && KtTokens.MODIFIER_KEYWORDS_ARRAY.firstOrNull { it.value == text } != null
}
}
| apache-2.0 | d230372a7b928791c702fa9a7bf0eb7b | 47.580769 | 158 | 0.626712 | 6.104882 | false | false | false | false |
DemonWav/MinecraftDev | src/main/kotlin/com/demonwav/mcdev/facet/MinecraftFacetDetector.kt | 1 | 5941 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2018 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.facet
import com.demonwav.mcdev.platform.PlatformType
import com.demonwav.mcdev.platform.sponge.framework.SPONGE_LIBRARY_KIND
import com.demonwav.mcdev.util.AbstractProjectComponent
import com.demonwav.mcdev.util.ifEmpty
import com.demonwav.mcdev.util.runWriteTaskLater
import com.intellij.ProjectTopics
import com.intellij.facet.FacetManager
import com.intellij.facet.ModifiableFacetModel
import com.intellij.facet.impl.ui.libraries.LibrariesValidatorContextImpl
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ModuleRootEvent
import com.intellij.openapi.roots.ModuleRootListener
import com.intellij.openapi.roots.libraries.LibraryKind
import com.intellij.openapi.roots.ui.configuration.libraries.LibraryPresentationManager
import com.intellij.openapi.startup.StartupManager
class MinecraftFacetDetector(project: Project) : AbstractProjectComponent(project) {
override fun projectOpened() {
val manager = StartupManager.getInstance(project)
val connection = project.messageBus.connect()
manager.registerStartupActivity {
MinecraftModuleRootListener.doCheck(project)
}
// Register a module root listener to check when things change
manager.registerPostStartupActivity {
connection.subscribe(ProjectTopics.PROJECT_ROOTS, MinecraftModuleRootListener)
}
}
private object MinecraftModuleRootListener : ModuleRootListener {
override fun rootsChanged(event: ModuleRootEvent) {
if (event.isCausedByFileTypesChange) {
return
}
val project = event.source as? Project ?: return
doCheck(project)
}
fun doCheck(project: Project) {
val moduleManager = ModuleManager.getInstance(project)
for (module in moduleManager.modules) {
val facetManager = FacetManager.getInstance(module)
val minecraftFacet = facetManager.getFacetByType(MinecraftFacet.ID)
if (minecraftFacet == null) {
checkNoFacet(module)
} else {
checkExistingFacet(module, minecraftFacet)
}
}
}
private fun checkNoFacet(module: Module) {
val platforms = autoDetectTypes(module).ifEmpty { return }
val facetManager = FacetManager.getInstance(module)
val configuration = MinecraftFacetConfiguration()
configuration.state.autoDetectTypes.addAll(platforms)
val facet = facetManager.createFacet(MinecraftFacet.facetType, "Minecraft", configuration, null)
runWriteTaskLater {
// Only add the new facet if there isn't a Minecraft facet already - double check here since this
// task may run much later
if (facetManager.getFacetByType(MinecraftFacet.ID) == null) {
val model = facetManager.createModifiableModel()
model.addFacet(facet)
model.commit()
}
}
}
private fun checkExistingFacet(module: Module, facet: MinecraftFacet) {
val platforms = autoDetectTypes(module).ifEmpty { return }
val types = facet.configuration.state.autoDetectTypes
types.clear()
types.addAll(platforms)
if (facet.configuration.state.forgePatcher) {
// make sure Forge and MCP are present
types.add(PlatformType.FORGE)
types.add(PlatformType.MCP)
}
facet.refresh()
}
private fun autoDetectTypes(module: Module): Set<PlatformType> {
val presentationManager = LibraryPresentationManager.getInstance()
val context = LibrariesValidatorContextImpl(module)
val platformKinds = mutableSetOf<LibraryKind>()
context.rootModel
.orderEntries()
.using(context.modulesProvider)
.recursively()
.librariesOnly()
.forEachLibrary forEach@ { library ->
MINECRAFT_LIBRARY_KINDS.forEach { kind ->
if (presentationManager.isLibraryOfKind(library, context.librariesContainer, setOf(kind))) {
platformKinds.add(kind)
}
}
return@forEach true
}
context.rootModel
.orderEntries()
.using(context.modulesProvider)
.recursively()
.withoutLibraries()
.withoutSdk()
.forEachModule forEach@ { m ->
if (m.name.startsWith("SpongeAPI")) {
// We don't want want to add parent modules in module groups
val moduleManager = ModuleManager.getInstance(m.project)
val groupPath = moduleManager.getModuleGroupPath(m)
if (groupPath == null) {
platformKinds.add(SPONGE_LIBRARY_KIND)
return@forEach true
}
val name = groupPath.lastOrNull() ?: return@forEach true
if (m.name == name) {
return@forEach true
}
platformKinds.add(SPONGE_LIBRARY_KIND)
}
return@forEach true
}
return platformKinds.mapNotNull { kind -> PlatformType.fromLibraryKind(kind) }.toSet()
}
}
}
| mit | c39b342ad14505717f02aac5f6cbb51c | 37.577922 | 116 | 0.601919 | 5.610009 | false | false | false | false |
google/android-fhir | engine/src/test-common/java/com/google/android/fhir/resource/TestingUtils.kt | 1 | 6759 | /*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.fhir.resource
import androidx.work.Data
import ca.uhn.fhir.parser.IParser
import com.google.android.fhir.FhirEngine
import com.google.android.fhir.LocalChange
import com.google.android.fhir.SyncDownloadContext
import com.google.android.fhir.db.impl.dao.LocalChangeToken
import com.google.android.fhir.search.Search
import com.google.android.fhir.sync.ConflictResolver
import com.google.android.fhir.sync.DataSource
import com.google.android.fhir.sync.DownloadWorkManager
import com.google.common.truth.Truth.assertThat
import java.time.OffsetDateTime
import java.util.Date
import java.util.LinkedList
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.collect
import org.hl7.fhir.r4.model.Bundle
import org.hl7.fhir.r4.model.Meta
import org.hl7.fhir.r4.model.Patient
import org.hl7.fhir.r4.model.Resource
import org.hl7.fhir.r4.model.ResourceType
import org.json.JSONArray
import org.json.JSONObject
/** Utilities for testing. */
class TestingUtils constructor(private val iParser: IParser) {
/** Asserts that the `expected` and the `actual` FHIR resources are equal. */
fun assertResourceEquals(expected: Resource?, actual: Resource?) {
assertThat(iParser.encodeResourceToString(actual))
.isEqualTo(iParser.encodeResourceToString(expected))
}
/** Asserts that the `expected` and the `actual` FHIR resources are not equal. */
fun assertResourceNotEquals(expected: Resource?, actual: Resource?) {
assertThat(iParser.encodeResourceToString(actual))
.isNotEqualTo(iParser.encodeResourceToString(expected))
}
fun assertJsonArrayEqualsIgnoringOrder(actual: JSONArray, expected: JSONArray) {
assertThat(actual.length()).isEqualTo(expected.length())
val actuals = mutableListOf<String>()
val expecteds = mutableListOf<String>()
for (i in 0 until actual.length()) {
actuals.add(actual.get(i).toString())
expecteds.add(expected.get(i).toString())
}
actuals.sorted()
expecteds.sorted()
assertThat(actuals).containsExactlyElementsIn(expecteds)
}
/** Reads a [Resource] from given file in the `sampledata` dir */
fun <R : Resource> readFromFile(clazz: Class<R>, filename: String): R {
val resourceJson = readJsonFromFile(filename)
return iParser.parseResource(clazz, resourceJson.toString()) as R
}
/** Reads a [JSONObject] from given file in the `sampledata` dir */
private fun readJsonFromFile(filename: String): JSONObject {
val inputStream = javaClass.getResourceAsStream(filename)
val content = inputStream!!.bufferedReader(Charsets.UTF_8).readText()
return JSONObject(content)
}
/** Reads a [JSONArray] from given file in the `sampledata` dir */
fun readJsonArrayFromFile(filename: String): JSONArray {
val inputStream = javaClass.getResourceAsStream(filename)
val content = inputStream!!.bufferedReader(Charsets.UTF_8).readText()
return JSONArray(content)
}
object TestDataSourceImpl : DataSource {
override suspend fun download(path: String): Resource {
return Bundle().apply { type = Bundle.BundleType.SEARCHSET }
}
override suspend fun upload(bundle: Bundle): Resource {
return Bundle().apply { type = Bundle.BundleType.TRANSACTIONRESPONSE }
}
}
open class TestDownloadManagerImpl(
queries: List<String> = listOf("Patient?address-city=NAIROBI")
) : DownloadWorkManager {
private val urls = LinkedList(queries)
override suspend fun getNextRequestUrl(context: SyncDownloadContext): String? = urls.poll()
override suspend fun processResponse(response: Resource): Collection<Resource> {
val patient = Patient().setMeta(Meta().setLastUpdated(Date()))
return listOf(patient)
}
}
class TestDownloadManagerImplWithQueue(
queries: List<String> = listOf("Patient/bob", "Encounter/doc")
) : TestDownloadManagerImpl(queries)
object TestFhirEngineImpl : FhirEngine {
override suspend fun create(vararg resource: Resource) = emptyList<String>()
override suspend fun update(vararg resource: Resource) {}
override suspend fun get(type: ResourceType, id: String): Resource {
return Patient()
}
override suspend fun delete(type: ResourceType, id: String) {}
override suspend fun <R : Resource> search(search: Search): List<R> {
return emptyList()
}
override suspend fun syncUpload(
upload: suspend (List<LocalChange>) -> Flow<Pair<LocalChangeToken, Resource>>
) {
upload(listOf())
}
override suspend fun syncDownload(
conflictResolver: ConflictResolver,
download: suspend (SyncDownloadContext) -> Flow<List<Resource>>
) {
download(
object : SyncDownloadContext {
override suspend fun getLatestTimestampFor(type: ResourceType): String {
return "123456788"
}
}
)
.collect {}
}
override suspend fun count(search: Search): Long {
return 0
}
override suspend fun getLastSyncTimeStamp(): OffsetDateTime? {
return OffsetDateTime.now()
}
override suspend fun clearDatabase() {}
override suspend fun getLocalChange(type: ResourceType, id: String): LocalChange? {
TODO("Not yet implemented")
}
override suspend fun purge(type: ResourceType, id: String, forcePurge: Boolean) {}
}
object TestFailingDatasource : DataSource {
override suspend fun download(path: String): Resource {
val allowedChars = ('A'..'Z') + ('a'..'z') + ('0'..'9')
// data size exceeding the bytes acceptable by WorkManager serializer
val dataSize = Data.MAX_DATA_BYTES + 1
val hugeStackTraceMessage = (1..dataSize).map { allowedChars.random() }.joinToString("")
throw Exception(hugeStackTraceMessage)
}
override suspend fun upload(bundle: Bundle): Resource {
throw Exception("Posting Bundle failed...")
}
}
class BundleDataSource(val onPostBundle: suspend (Bundle) -> Resource) : DataSource {
override suspend fun download(path: String): Resource {
TODO("Not yet implemented")
}
override suspend fun upload(bundle: Bundle) = onPostBundle(bundle)
}
}
| apache-2.0 | 5f2af8b9cbef00cbd2bd3227aac9d141 | 34.020725 | 95 | 0.719485 | 4.294155 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/highlighter/AbstractHighlightingVisitor.kt | 3 | 1729 | // 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.highlighter
import com.intellij.openapi.editor.colors.TextAttributesKey
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.psi.KtNamedDeclaration
import org.jetbrains.kotlin.psi.KtVisitorVoid
abstract class AbstractHighlightingVisitor: KtVisitorVoid() {
protected fun createInfoAnnotation(element: PsiElement, message: String? = null, textAttributes: TextAttributesKey) {
createInfoAnnotation(element.textRange, message, textAttributes)
}
protected fun createInfoAnnotation(element: PsiElement, message: String? = null) =
createInfoAnnotation(element.textRange, message)
protected abstract fun createInfoAnnotation(textRange: TextRange, message: String? = null, textAttributes: TextAttributesKey? = null)
protected fun highlightName(element: PsiElement, attributesKey: TextAttributesKey, message: String? = null) {
if (NameHighlighter.namesHighlightingEnabled && !element.textRange.isEmpty) {
createInfoAnnotation(element, message, attributesKey)
}
}
protected fun highlightName(textRange: TextRange, attributesKey: TextAttributesKey, message: String? = null) {
if (NameHighlighter.namesHighlightingEnabled) {
createInfoAnnotation(textRange, message, attributesKey)
}
}
protected fun highlightNamedDeclaration(declaration: KtNamedDeclaration, attributesKey: TextAttributesKey) {
declaration.nameIdentifier?.let { highlightName(it, attributesKey) }
}
}
| apache-2.0 | 3a303e9f5f78b8e262e97c165a43379d | 45.72973 | 158 | 0.766917 | 4.982709 | false | false | false | false |
OpenConference/DroidconBerlin2017 | businesslogic/schedule/src/main/java/de/droidcon/berlin2018/schedule/repository/SessionsRepository.kt | 1 | 2610 | package de.droidcon.berlin2018.schedule.repository
import de.droidcon.berlin2018.model.Session
import de.droidcon.berlin2018.notification.NotificationScheduler
import de.droidcon.berlin2018.schedule.database.dao.SessionDao
import de.droidcon.berlin2018.schedule.sync.ScheduleDataAwareObservableFactory
import io.reactivex.Completable
import io.reactivex.Observable
/**
* Responsible to load all sessions
*
* @author Hannes Dorfmann
*/
interface SessionsRepository {
/**
* Load all sessions
*/
fun allSessions(): Observable<List<Session>>
fun favoriteSessions(): Observable<List<Session>>
fun getSession(id: String): Observable<Session>
fun addSessionToSchedule(session: Session): Completable
fun removeSessionFromSchedule(session: Session): Completable
fun getSessionsOfSpeaker(speakerId: String): Observable<List<Session>>
fun findSessionsWith(query: String): Observable<List<Session>>
}
/**
* A [SessionsRepository] that uses the sessions from local database (synced with the backend)
*/
class LocalDbAndFirebaseRepository(
private val scheduleDataAwareObservableFactory: ScheduleDataAwareObservableFactory,
private val sessionDao: SessionDao,
private val notificationScheduler: NotificationScheduler
) : SessionsRepository {
override fun allSessions(): Observable<List<Session>> =
scheduleDataAwareObservableFactory.create(sessionDao.getSessions())
override fun favoriteSessions(): Observable<List<Session>> = scheduleDataAwareObservableFactory.create(
sessionDao.getFavoriteSessions())
override fun getSession(
id: String): Observable<Session> = scheduleDataAwareObservableFactory.create(
sessionDao.getById(id))
override fun addSessionToSchedule(session: Session): Completable = sessionDao.setFavorite(
session.id(),
true).map { it > 0 }
.flatMapCompletable {
Completable.fromCallable { notificationScheduler.addOrRescheduleNotification(session) }
}
override fun removeSessionFromSchedule(
session: Session): Completable = sessionDao.setFavorite(
session.id(),
false).map { it > 0 }
.flatMapCompletable {
Completable.fromCallable {
notificationScheduler.removeNotification(session)
}
}
override fun getSessionsOfSpeaker(speakerId: String): Observable<List<Session>> =
scheduleDataAwareObservableFactory.create(sessionDao.getSessionsOfSpeaker(speakerId))
override fun findSessionsWith(query: String): Observable<List<Session>> =
scheduleDataAwareObservableFactory.create(sessionDao.findSessionsWith(query))
}
| apache-2.0 | f08f19c7b3e3fc8bba1ce75a3cd8751f | 32.461538 | 105 | 0.768966 | 4.719711 | false | false | false | false |
androidx/androidx | compose/foundation/foundation/integration-tests/foundation-demos/src/main/java/androidx/compose/foundation/demos/text/TextFieldValueDemo.kt | 3 | 3597 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.foundation.demos.text
import android.os.Handler
import android.os.Looper
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.tooling.preview.Preview
@Preview
@Composable
fun TextFieldValueDemo() {
LazyColumn {
item {
TagLine("Empty callback")
val textFieldValue1 = remember { TextFieldValue("") }
BasicTextField(
value = textFieldValue1,
onValueChange = {},
textStyle = TextStyle(fontSize = fontSize8),
modifier = demoTextFieldModifiers
)
}
item {
TagLine("Regular string overload")
var string by remember { mutableStateOf("") }
BasicTextField(
value = string,
onValueChange = {
string = it
},
textStyle = TextStyle(fontSize = fontSize8),
modifier = demoTextFieldModifiers
)
}
item {
TagLine("Reformat by uppercase ")
var uppercaseValue by remember { mutableStateOf("") }
BasicTextField(
value = uppercaseValue,
onValueChange = {
uppercaseValue = it.uppercase(java.util.Locale.US)
},
textStyle = TextStyle(fontSize = fontSize8),
modifier = demoTextFieldModifiers
)
}
item {
TagLine("Clear text")
var clearedValue by remember { mutableStateOf("") }
BasicTextField(
value = clearedValue,
onValueChange = {
clearedValue = it
},
textStyle = TextStyle(fontSize = fontSize8),
modifier = demoTextFieldModifiers
)
Button(onClick = { clearedValue = "" }) {
Text("Clear")
}
}
item {
TagLine("Delayed callback")
var text by remember { mutableStateOf("") }
val handler = remember { Handler(Looper.getMainLooper()) }
BasicTextField(
value = text,
onValueChange = {
handler.removeCallbacksAndMessages(null)
handler.postDelayed({ text = it }, 50)
},
textStyle = TextStyle(fontSize = fontSize8),
modifier = demoTextFieldModifiers
)
}
}
}
| apache-2.0 | 06002d419db132cc7315c4b5b28361ac | 34.264706 | 75 | 0.58938 | 5.433535 | false | false | false | false |
androidx/androidx | compose/runtime/runtime/src/commonMain/kotlin/androidx/compose/runtime/collection/IdentityScopeMap.kt | 3 | 10427 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.runtime.collection
import androidx.compose.runtime.identityHashCode
import kotlin.contracts.ExperimentalContracts
/**
* Maps values to a set of scopes using the [identityHashCode] for both the value and the
* scope for uniqueness.
*/
@OptIn(ExperimentalContracts::class)
internal class IdentityScopeMap<T : Any> {
/**
* The array of indices into [values] and [scopeSets], in the order that they are sorted
* in the [IdentityScopeMap]. The length of the used values is [size], and all remaining values
* are the unused indices in [values] and [scopeSets].
*/
@PublishedApi
internal var valueOrder: IntArray = IntArray(50) { it }
/**
* The [identityHashCode] for the keys in the collection. We never use the actual
* values
*/
@PublishedApi
internal var values: Array<Any?> = arrayOfNulls(50)
/**
* The [IdentityArraySet]s for values, in the same index order as [values], indexed
* by [valueOrder]. The consumed values may extend beyond [size] if a value has been removed.
*/
@PublishedApi
internal var scopeSets: Array<IdentityArraySet<T>?> = arrayOfNulls(50)
/**
* The number of values in the map.
*/
@PublishedApi
internal var size = 0
/**
* Returns the value at the given [index] order in the map.
*/
@Suppress("NOTHING_TO_INLINE")
private inline fun valueAt(index: Int): Any {
return values[valueOrder[index]]!!
}
/**
* Returns the [IdentityArraySet] for the value at the given [index] order in the map.
*/
private fun scopeSetAt(index: Int): IdentityArraySet<T> {
return scopeSets[valueOrder[index]]!!
}
/**
* Adds a [value]/[scope] pair to the map and returns `true` if it was added or `false` if
* it already existed.
*/
fun add(value: Any, scope: T): Boolean {
val valueSet = getOrCreateIdentitySet(value)
return valueSet.add(scope)
}
/**
* Returns true if any scopes are associated with [element]
*/
operator fun contains(element: Any): Boolean = find(element) >= 0
/**
* Executes [block] for all scopes mapped to the given [value].
*/
inline fun forEachScopeOf(value: Any, block: (scope: T) -> Unit) {
val index = find(value)
if (index >= 0) {
scopeSetAt(index).fastForEach(block)
}
}
/**
* Returns the existing [IdentityArraySet] for the given [value] or creates a new one
* and insertes it into the map and returns it.
*/
private fun getOrCreateIdentitySet(value: Any): IdentityArraySet<T> {
val index: Int
if (size > 0) {
index = find(value)
if (index >= 0) {
return scopeSetAt(index)
}
} else {
index = -1
}
val insertIndex = -(index + 1)
if (size < valueOrder.size) {
val valueIndex = valueOrder[size]
values[valueIndex] = value
val scopeSet = scopeSets[valueIndex] ?: IdentityArraySet<T>().also {
scopeSets[valueIndex] = it
}
// insert into the right location in keyOrder
if (insertIndex < size) {
valueOrder.copyInto(
destination = valueOrder,
destinationOffset = insertIndex + 1,
startIndex = insertIndex,
endIndex = size
)
}
valueOrder[insertIndex] = valueIndex
size++
return scopeSet
}
// We have to increase the size of all arrays
val newSize = valueOrder.size * 2
val valueIndex = size
scopeSets = scopeSets.copyOf(newSize)
val scopeSet = IdentityArraySet<T>()
scopeSets[valueIndex] = scopeSet
values = values.copyOf(newSize)
values[valueIndex] = value
val newKeyOrder = IntArray(newSize)
for (i in size + 1 until newSize) {
newKeyOrder[i] = i
}
if (insertIndex < size) {
valueOrder.copyInto(
destination = newKeyOrder,
destinationOffset = insertIndex + 1,
startIndex = insertIndex,
endIndex = size
)
}
newKeyOrder[insertIndex] = valueIndex
if (insertIndex > 0) {
valueOrder.copyInto(
destination = newKeyOrder,
endIndex = insertIndex
)
}
valueOrder = newKeyOrder
size++
return scopeSet
}
/**
* Removes all values and scopes from the map
*/
fun clear() {
for (i in 0 until scopeSets.size) {
scopeSets[i]?.clear()
valueOrder[i] = i
values[i] = null
}
size = 0
}
/**
* Remove [scope] from the scope set for [value]. If the scope set is empty after [scope] has
* been remove the reference to [value] is removed as well.
*
* @param value the key of the scope map
* @param scope the scope being removed
* @return true if the value was removed from the scope
*/
fun remove(value: Any, scope: T): Boolean {
val index = find(value)
if (index >= 0) {
val valueOrderIndex = valueOrder[index]
val set = scopeSets[valueOrderIndex] ?: return false
val removed = set.remove(scope)
if (set.size == 0) {
val startIndex = index + 1
val endIndex = size
if (startIndex < endIndex) {
valueOrder.copyInto(
destination = valueOrder,
destinationOffset = index,
startIndex = startIndex,
endIndex = endIndex
)
}
valueOrder[size - 1] = valueOrderIndex
values[valueOrderIndex] = null
size--
}
return removed
}
return false
}
/**
* Removes all scopes that match [predicate]. If all scopes for a given value have been
* removed, that value is removed also.
*/
inline fun removeValueIf(predicate: (scope: T) -> Boolean) {
removingScopes { scopeSet ->
scopeSet.removeValueIf(predicate)
}
}
/**
* Removes given scope from all sets. If all scopes for a given value are removed, that value
* is removed as well.
*/
fun removeScope(scope: T) {
removingScopes { scopeSet ->
scopeSet.remove(scope)
}
}
private inline fun removingScopes(removalOperation: (IdentityArraySet<T>) -> Unit) {
var destinationIndex = 0
for (i in 0 until size) {
val valueIndex = valueOrder[i]
val set = scopeSets[valueIndex]!!
removalOperation(set)
if (set.size > 0) {
if (destinationIndex != i) {
// We'll bubble-up the now-free key-order by swapping the index with the one
// we're copying from. This means that the set can be reused later.
val destinationKeyOrder = valueOrder[destinationIndex]
valueOrder[destinationIndex] = valueIndex
valueOrder[i] = destinationKeyOrder
}
destinationIndex++
}
}
// Remove hard references to values that are no longer in the map
for (i in destinationIndex until size) {
values[valueOrder[i]] = null
}
size = destinationIndex
}
/**
* Returns the index into [valueOrder] of the found [value] of the
* value, or the negative index - 1 of the position in which it would be if it were found.
*/
private fun find(value: Any?): Int {
val valueIdentity = identityHashCode(value)
var low = 0
var high = size - 1
while (low <= high) {
val mid = (low + high).ushr(1)
val midValue = valueAt(mid)
val midValHash = identityHashCode(midValue)
when {
midValHash < valueIdentity -> low = mid + 1
midValHash > valueIdentity -> high = mid - 1
value === midValue -> return mid
else -> return findExactIndex(mid, value, valueIdentity)
}
}
return -(low + 1)
}
/**
* When multiple items share the same [identityHashCode], then we must find the specific
* index of the target item. This method assumes that [midIndex] has already been checked
* for an exact match for [value], but will look at nearby values to find the exact item index.
* If no match is found, the negative index - 1 of the position in which it would be will
* be returned, which is always after the last item with the same [identityHashCode].
*/
private fun findExactIndex(midIndex: Int, value: Any?, valueHash: Int): Int {
// hunt down first
for (i in midIndex - 1 downTo 0) {
val v = valueAt(i)
if (v === value) {
return i
}
if (identityHashCode(v) != valueHash) {
break // we've gone too far
}
}
for (i in midIndex + 1 until size) {
val v = valueAt(i)
if (v === value) {
return i
}
if (identityHashCode(v) != valueHash) {
// We've gone too far. We should insert here.
return -(i + 1)
}
}
// We should insert at the end
return -(size + 1)
}
} | apache-2.0 | a186e9ee02fa5860b949f41724069446 | 32.104762 | 99 | 0.560756 | 4.581283 | false | false | false | false |
GunoH/intellij-community | plugins/completion-ml-ranking/src/com/intellij/completion/ml/ranker/ExperimentModelProvider.kt | 5 | 2209 | // 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.completion.ml.ranker
import com.intellij.internal.ml.completion.RankingModelProvider
import com.intellij.lang.Language
import com.intellij.openapi.Disposable
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.extensions.Extensions
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.TestOnly
@ApiStatus.Internal
interface ExperimentModelProvider : RankingModelProvider {
fun experimentGroupNumber(): Int
companion object {
private val EP_NAME = ExtensionPointName<RankingModelProvider>("com.intellij.completion.ml.model")
@JvmStatic
fun findProvider(language: Language, groupNumber: Int): RankingModelProvider? {
val (experimentProviders, defaultProviders) = availableProviders()
.filter { it.match(language, groupNumber) }
.partition { it is ExperimentModelProvider }
check(defaultProviders.size <= 1) { "Too many default providers: $defaultProviders" }
val defaultProvider = defaultProviders.singleOrNull()
if (experimentProviders.isEmpty()) return defaultProvider
check(experimentProviders.size == 1) { "Too many experiment provider matching language ${language.displayName} and group number $groupNumber: $experimentProviders" }
return experimentProviders.singleOrNull() ?: defaultProvider
}
fun RankingModelProvider.match(language: Language, groupNumber: Int): Boolean =
isLanguageSupported(language) && (this !is ExperimentModelProvider || experimentGroupNumber() == groupNumber)
fun availableProviders(): List<RankingModelProvider> = EP_NAME.extensionList
@JvmStatic
fun enabledByDefault(): List<String> {
return availableProviders().asSequence().filter { it.isEnabledByDefault }.map { it.id }.toList()
}
@TestOnly
fun registerProvider(provider: RankingModelProvider, parentDisposable: Disposable) {
val extensionPoint = Extensions.getRootArea().getExtensionPoint(EP_NAME)
extensionPoint.registerExtension(provider, parentDisposable)
}
}
}
| apache-2.0 | 8686d277288cd2d98058da0bca4aaf2b | 43.18 | 171 | 0.767768 | 4.930804 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/gradle/gradle-java/tests/test/org/jetbrains/kotlin/gradle/workspace/Printers.kt | 2 | 3663 | // 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.gradle.workspace
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.ProjectJdkTable
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.roots.libraries.Library
import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar
import org.jetbrains.kotlin.utils.Printer
object WorkspaceModelPrinters {
val moduleNamesPrinter: WorkspaceModelPrinter
get() = ProjectPrinter {
addContributor(NoopModulePrinterContributor())
}
val moduleDependenciesPrinter get() = ProjectPrinter {
addContributor(SanitizingOrderEntryPrinterContributor())
}
val moduleKotlinFacetSettingsPrinter get() = ProjectPrinter {
addContributor(KotlinFacetSettingsPrinterContributor())
}
val libraryNamesPrinter get() = ProjectPrinter {
addContributor(SanitizingLibraryPrinterContributor())
}
val sdkNamesPrinter get() = ProjectPrinter {
addContributor(NoopSdkPrinterContributor())
}
val fullWorkspacePrinter get() = ProjectPrinter {
addContributor(KotlinFacetSettingsPrinterContributor())
addContributor(SanitizingOrderEntryPrinterContributor())
addContributor(SanitizingLibraryPrinterContributor())
addContributor(NoopSdkPrinterContributor())
}
}
class WorkspaceModelPrinter(
private val moduleContributor: WorkspaceModelPrinterContributor<ModulePrinterEntity>? = null,
private val libraryContributor: WorkspaceModelPrinterContributor<LibraryPrinterEntity>? = null,
private val sdkContributor: WorkspaceModelPrinterContributor<SdkPrinterEntity>? = null,
) {
private val printer = Printer(StringBuilder())
fun print(project: Project): String {
processModules(project)
processLibraries(project)
processSdks()
return printer.toString()
}
private fun processModules(project: Project) = processEntities(
title = "MODULES",
contributor = moduleContributor,
entities = runReadAction { ModuleManager.getInstance(project).modules }.map(Module::toPrinterEntity),
)
private fun processLibraries(project: Project) = processEntities(
title = "LIBRARIES",
contributor = libraryContributor,
entities = runReadAction { LibraryTablesRegistrar.getInstance().getLibraryTable(project).libraries }.map(Library::toPrinterEntity),
)
private fun processSdks() = processEntities(
title = "SDK",
contributor = sdkContributor,
entities = runReadAction { ProjectJdkTable.getInstance().allJdks }.map(Sdk::toPrinterEntity),
)
private fun <EntityType : ContributableEntity> processEntities(
title: String,
contributor: WorkspaceModelPrinterContributor<EntityType>?,
entities: List<EntityType>,
) {
if (contributor == null) return
val preprocessedEntities = contributor.preprocess(entities)
if (preprocessedEntities.isEmpty()) return
printer.println(title)
printer.indented {
for (entity in preprocessedEntities.sortedBy { it.presentableName }) {
printer.println(entity.presentableName)
contributor.process(entity, printer)
}
}
}
}
internal fun Printer.indented(block: () -> Unit) {
pushIndent()
block()
popIndent()
}
| apache-2.0 | f6b1cd2c8ca79d452629fd90cf769dc6 | 34.911765 | 139 | 0.72427 | 5.137447 | false | false | false | false |
rei-m/HBFav_material | app/src/main/kotlin/me/rei_m/hbfavmaterial/presentation/widget/adapter/BookmarkPagerAdapter.kt | 1 | 4007 | /*
* Copyright (c) 2017. Rei Matsushita
*
* 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 me.rei_m.hbfavmaterial.presentation.widget.adapter
import android.content.Context
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentStatePagerAdapter
import android.view.Menu
import me.rei_m.hbfavmaterial.R
import me.rei_m.hbfavmaterial.extension.hide
import me.rei_m.hbfavmaterial.extension.show
import me.rei_m.hbfavmaterial.presentation.widget.fragment.FavoriteBookmarkFragment
import me.rei_m.hbfavmaterial.presentation.widget.fragment.HotEntryFragment
import me.rei_m.hbfavmaterial.presentation.widget.fragment.NewEntryFragment
import me.rei_m.hbfavmaterial.presentation.widget.fragment.UserBookmarkFragment
/**
* メインページのフラグメントを管理するAdaptor.
*/
class BookmarkPagerAdapter(fm: FragmentManager) : FragmentStatePagerAdapter(fm) {
enum class Page(val navId: Int,
val titleResId: Int) {
BOOKMARK_FAVORITE(R.id.nav_bookmark_favorite, R.string.fragment_title_bookmark_favorite) {
override fun newInstance(): Fragment = FavoriteBookmarkFragment.newInstance(ordinal)
override fun toggleMenu(menu: Menu) {
menu.hide()
}
},
BOOKMARK_OWN(R.id.nav_bookmark_own, R.string.fragment_title_bookmark_own) {
override fun newInstance(): Fragment = UserBookmarkFragment.newInstance(ordinal)
override fun toggleMenu(menu: Menu) {
with(menu) {
hide()
findItem(R.id.menu_filter_bookmark_all).isVisible = true
findItem(R.id.menu_filter_bookmark_read_after).isVisible = true
}
}
},
HOT_ENTRY(R.id.nav_hot_entry, R.string.fragment_title_hot_entry) {
override fun newInstance(): Fragment = HotEntryFragment.newInstance(ordinal)
override fun toggleMenu(menu: Menu) {
with(menu) {
show()
findItem(R.id.menu_filter_bookmark_all).isVisible = false
findItem(R.id.menu_filter_bookmark_read_after).isVisible = false
}
}
},
NEW_ENTRY(R.id.nav_new_entry, R.string.fragment_title_new_entry) {
override fun newInstance(): Fragment = NewEntryFragment.newInstance(ordinal)
override fun toggleMenu(menu: Menu) {
with(menu) {
show()
findItem(R.id.menu_filter_bookmark_all).isVisible = false
findItem(R.id.menu_filter_bookmark_read_after).isVisible = false
}
}
};
companion object {
fun forMenuId(menuId: Int): Page {
values().filter { it.navId == menuId }.forEach { return it }
throw AssertionError("no menu enum found for the id. you forgot to implement?")
}
}
val index: Int = this.ordinal
fun title(context: Context, subTitle: String) = context.getString(titleResId) + if (subTitle.isNotEmpty()) " - $subTitle" else ""
abstract fun toggleMenu(menu: Menu)
abstract fun newInstance(): Fragment
}
override fun getItem(position: Int): Fragment? {
return Page.values()[position].newInstance()
}
override fun getCount(): Int {
return Page.values().count()
}
}
| apache-2.0 | 689a28041cdedc5a2e7dcba2f58bbe37 | 38.316832 | 137 | 0.646185 | 4.363736 | false | false | false | false |
kivensolo/UiUsingListView | library/network/src/main/java/com/zeke/reactivehttp/callback/RequestCallback.kt | 1 | 2985 | package com.zeke.reactivehttp.callback
/**
* @Author: leavesC
* @Date: 2020/10/28 18:16
* @Desc: Callback
* @GitHub:https://github.com/leavesC
*/
class RequestCallback<Data>(internal var onSuccess: ((Data) -> Unit)? = null,
internal var onSuccessIO: (suspend (Data) -> Unit)? = null) : BaseRequestCallback() {
/**
* 当网络请求成功时会调用此方法,随后会先后调用 onSuccessIO、onFinally 方法
*/
fun onSuccess(block: (data: Data) -> Unit) {
this.onSuccess = block
}
/**
* 在 onSuccess 方法之后,onFinally 方法之前执行
* 考虑到网络请求成功后有需要将数据保存到数据库之类的耗时需求,所以提供了此方法用于在 IO 线程进行执行
* 注意外部不要在此处另开子线程,此方法会等到耗时任务完成后再执行 onFinally 方法
*/
fun onSuccessIO(block: suspend (Data) -> Unit) {
this.onSuccessIO = block
}
}
class RequestPairCallback<DataA, DataB>(internal var onSuccess: ((dataA: DataA, dataB: DataB) -> Unit)? = null,
internal var onSuccessIO: (suspend (dataA: DataA, dataB: DataB) -> Unit)? = null) : BaseRequestCallback() {
/**
* 当网络请求成功时会调用此方法,随后会先后调用 onSuccessIO、onFinally 方法
*/
fun onSuccess(block: (dataA: DataA, dataB: DataB) -> Unit) {
this.onSuccess = block
}
/**
* 在 onSuccess 方法之后,onFinally 方法之前执行
* 考虑到网络请求成功后有需要将数据保存到数据库之类的耗时需求,所以提供了此方法用于在 IO 线程进行执行
* 注意外部不要在此处另开子线程,此方法会等到耗时任务完成后再执行 onFinally 方法
*/
fun onSuccessIO(block: suspend (dataA: DataA, dataB: DataB) -> Unit) {
this.onSuccessIO = block
}
}
class RequestTripleCallback<DataA, DataB, DataC>(internal var onSuccess: ((dataA: DataA, dataB: DataB, dataC: DataC) -> Unit)? = null,
internal var onSuccessIO: (suspend (dataA: DataA, dataB: DataB, dataC: DataC) -> Unit)? = null) : BaseRequestCallback() {
/**
* 当网络请求成功时会调用此方法,随后会先后调用 onSuccessIO、onFinally 方法
*/
fun onSuccess(block: (dataA: DataA, dataB: DataB, dataC: DataC) -> Unit) {
this.onSuccess = block
}
/**
* 在 onSuccess 方法之后,onFinally 方法之前执行
* 考虑到网络请求成功后有需要将数据保存到数据库之类的耗时需求,所以提供了此方法用于在 IO 线程进行执行
* 注意外部不要在此处另开子线程,此方法会等到耗时任务完成后再执行 onFinally 方法
*/
fun onSuccessIO(block: suspend (dataA: DataA, dataB: DataB, dataC: DataC) -> Unit) {
this.onSuccessIO = block
}
} | gpl-2.0 | 70a3bbc326840419634ef4bdc7987b73 | 31.6 | 170 | 0.623849 | 2.993438 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/caches/lightClasses/IdeLightClassInheritanceHelper.kt | 3 | 2565 | // 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.caches.lightClasses
import com.intellij.psi.CommonClassNames
import com.intellij.psi.PsiClass
import org.jetbrains.kotlin.asJava.ImpreciseResolveResult
import org.jetbrains.kotlin.asJava.ImpreciseResolveResult.*
import org.jetbrains.kotlin.asJava.classes.KtLightClass
import org.jetbrains.kotlin.asJava.classes.LightClassInheritanceHelper
import org.jetbrains.kotlin.asJava.classes.defaultJavaAncestorQualifiedName
import org.jetbrains.kotlin.idea.caches.resolve.util.isInDumbMode
import org.jetbrains.kotlin.idea.search.PsiBasedClassResolver
import org.jetbrains.kotlin.psi.KtSimpleNameExpression
import org.jetbrains.kotlin.psi.KtSuperTypeCallEntry
import org.jetbrains.kotlin.psi.KtSuperTypeListEntry
class IdeLightClassInheritanceHelper : LightClassInheritanceHelper {
override fun isInheritor(
lightClass: KtLightClass,
baseClass: PsiClass,
checkDeep: Boolean
): ImpreciseResolveResult {
if (baseClass.project.isInDumbMode()) return NO_MATCH
if (lightClass.manager.areElementsEquivalent(baseClass, lightClass)) return NO_MATCH
val classOrObject = lightClass.kotlinOrigin ?: return UNSURE
if (checkDeep && baseClass.qualifiedName == CommonClassNames.JAVA_LANG_OBJECT) {
return MATCH
}
val entries = classOrObject.superTypeListEntries
val hasSuperClass = entries.any { it is KtSuperTypeCallEntry }
if (baseClass.qualifiedName == classOrObject.defaultJavaAncestorQualifiedName() && (!hasSuperClass || checkDeep)) {
return MATCH
}
val amongEntries = isAmongEntries(baseClass, entries)
return when {
!checkDeep -> amongEntries
amongEntries == MATCH -> MATCH
else -> UNSURE
}
}
private fun isAmongEntries(baseClass: PsiClass, entries: List<KtSuperTypeListEntry>): ImpreciseResolveResult {
val psiBasedResolver = PsiBasedClassResolver.getInstance(baseClass)
entries@ for (entry in entries) {
val reference: KtSimpleNameExpression = entry.typeAsUserType?.referenceExpression ?: continue@entries
when (psiBasedResolver.canBeTargetReference(reference)) {
MATCH -> return MATCH
NO_MATCH -> continue@entries
UNSURE -> return UNSURE
}
}
return NO_MATCH
}
}
| apache-2.0 | a8eb4d237febf7e4908623b275fdaaf9 | 43.224138 | 158 | 0.725536 | 4.990272 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/uast/uast-kotlin-base/src/org/jetbrains/uast/kotlin/declarations/KotlinUMethodWithFakeLightDelegate.kt | 4 | 1444 | // 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.uast.kotlin
import com.intellij.openapi.util.TextRange
import com.intellij.psi.*
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.kotlin.psi.*
import org.jetbrains.uast.*
import org.jetbrains.uast.kotlin.psi.UastFakeLightMethod
@ApiStatus.Internal
class KotlinUMethodWithFakeLightDelegate(
val original: KtFunction,
fakePsi: UastFakeLightMethod,
givenParent: UElement?
) : KotlinUMethod(fakePsi, original, givenParent) {
constructor(original: KtFunction, containingLightClass: PsiClass, givenParent: UElement?)
: this(original, UastFakeLightMethod(original, containingLightClass), givenParent)
override val uAnnotations: List<UAnnotation> by lz {
original.annotationEntries.map {
baseResolveProviderService.baseKotlinConverter.convertAnnotation(it, this)
}
}
override fun getTextRange(): TextRange {
return original.textRange
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as KotlinUMethodWithFakeLightDelegate
if (original != other.original) return false
return true
}
override fun hashCode(): Int = original.hashCode()
}
| apache-2.0 | eac51b933b696e804852c03a1153bb54 | 34.219512 | 158 | 0.732687 | 4.765677 | false | false | false | false |
SimpleMobileTools/Simple-Calendar | app/src/main/kotlin/com/simplemobiletools/calendar/pro/activities/EventActivity.kt | 1 | 69187 | package com.simplemobiletools.calendar.pro.activities
import android.app.Activity
import android.app.DatePickerDialog
import android.app.TimePickerDialog
import android.content.Intent
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.graphics.drawable.LayerDrawable
import android.net.Uri
import android.os.Bundle
import android.provider.CalendarContract.Attendees
import android.provider.ContactsContract.CommonDataKinds
import android.provider.ContactsContract.CommonDataKinds.StructuredName
import android.provider.ContactsContract.Data
import android.text.TextUtils
import android.text.method.LinkMovementMethod
import android.view.View
import android.view.WindowManager
import android.view.inputmethod.EditorInfo
import android.widget.ImageView
import android.widget.RelativeLayout
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.simplemobiletools.calendar.pro.R
import com.simplemobiletools.calendar.pro.adapters.AutoCompleteTextViewAdapter
import com.simplemobiletools.calendar.pro.dialogs.*
import com.simplemobiletools.calendar.pro.extensions.*
import com.simplemobiletools.calendar.pro.helpers.*
import com.simplemobiletools.calendar.pro.helpers.Formatter
import com.simplemobiletools.calendar.pro.models.*
import com.simplemobiletools.commons.dialogs.ConfirmationAdvancedDialog
import com.simplemobiletools.commons.dialogs.RadioGroupDialog
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.*
import com.simplemobiletools.commons.models.RadioItem
import com.simplemobiletools.commons.views.MyAutoCompleteTextView
import kotlinx.android.synthetic.main.activity_event.*
import kotlinx.android.synthetic.main.activity_event.view.*
import kotlinx.android.synthetic.main.item_attendee.view.*
import org.joda.time.DateTime
import org.joda.time.DateTimeZone
import java.util.*
import java.util.regex.Pattern
class EventActivity : SimpleActivity() {
private val LAT_LON_PATTERN = "^[-+]?([1-8]?\\d(\\.\\d+)?|90(\\.0+)?)([,;])\\s*[-+]?(180(\\.0+)?|((1[0-7]\\d)|([1-9]?\\d))(\\.\\d+)?)\$"
private val SELECT_TIME_ZONE_INTENT = 1
private var mIsAllDayEvent = false
private var mReminder1Minutes = REMINDER_OFF
private var mReminder2Minutes = REMINDER_OFF
private var mReminder3Minutes = REMINDER_OFF
private var mReminder1Type = REMINDER_NOTIFICATION
private var mReminder2Type = REMINDER_NOTIFICATION
private var mReminder3Type = REMINDER_NOTIFICATION
private var mRepeatInterval = 0
private var mRepeatLimit = 0L
private var mRepeatRule = 0
private var mEventTypeId = REGULAR_EVENT_TYPE_ID
private var mEventOccurrenceTS = 0L
private var mLastSavePromptTS = 0L
private var mEventCalendarId = STORED_LOCALLY_ONLY
private var mWasContactsPermissionChecked = false
private var mWasCalendarChanged = false
private var mAttendees = ArrayList<Attendee>()
private var mAttendeeAutoCompleteViews = ArrayList<MyAutoCompleteTextView>()
private var mAvailableContacts = ArrayList<Attendee>()
private var mSelectedContacts = ArrayList<Attendee>()
private var mAvailability = Attendees.AVAILABILITY_BUSY
private var mStoredEventTypes = ArrayList<EventType>()
private var mOriginalTimeZone = DateTimeZone.getDefault().id
private var mOriginalStartTS = 0L
private var mOriginalEndTS = 0L
private var mIsNewEvent = true
private lateinit var mEventStartDateTime: DateTime
private lateinit var mEventEndDateTime: DateTime
private lateinit var mEvent: Event
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_event)
setupOptionsMenu()
refreshMenuItems()
if (checkAppSideloading()) {
return
}
val intent = intent ?: return
mWasContactsPermissionChecked = hasPermission(PERMISSION_READ_CONTACTS)
val eventId = intent.getLongExtra(EVENT_ID, 0L)
ensureBackgroundThread {
mStoredEventTypes = eventTypesDB.getEventTypes().toMutableList() as ArrayList<EventType>
val event = eventsDB.getEventWithId(eventId)
if (eventId != 0L && event == null) {
hideKeyboard()
finish()
return@ensureBackgroundThread
}
val localEventType = mStoredEventTypes.firstOrNull { it.id == config.lastUsedLocalEventTypeId }
runOnUiThread {
if (!isDestroyed && !isFinishing) {
gotEvent(savedInstanceState, localEventType, event)
}
}
}
}
override fun onResume() {
super.onResume()
setupToolbar(event_toolbar, NavigationIcon.Arrow)
}
private fun gotEvent(savedInstanceState: Bundle?, localEventType: EventType?, event: Event?) {
if (localEventType == null || localEventType.caldavCalendarId != 0) {
config.lastUsedLocalEventTypeId = REGULAR_EVENT_TYPE_ID
}
mEventTypeId = if (config.defaultEventTypeId == -1L) config.lastUsedLocalEventTypeId else config.defaultEventTypeId
if (event != null) {
mEvent = event
mEventOccurrenceTS = intent.getLongExtra(EVENT_OCCURRENCE_TS, 0L)
if (savedInstanceState == null) {
setupEditEvent()
}
if (intent.getBooleanExtra(IS_DUPLICATE_INTENT, false)) {
mEvent.id = null
event_toolbar.title = getString(R.string.new_event)
} else {
cancelNotification(mEvent.id!!)
}
} else {
mEvent = Event(null)
config.apply {
mReminder1Minutes = if (usePreviousEventReminders && lastEventReminderMinutes1 >= -1) lastEventReminderMinutes1 else defaultReminder1
mReminder2Minutes = if (usePreviousEventReminders && lastEventReminderMinutes2 >= -1) lastEventReminderMinutes2 else defaultReminder2
mReminder3Minutes = if (usePreviousEventReminders && lastEventReminderMinutes3 >= -1) lastEventReminderMinutes3 else defaultReminder3
}
if (savedInstanceState == null) {
setupNewEvent()
}
}
if (savedInstanceState == null) {
updateTexts()
updateEventType()
updateCalDAVCalendar()
}
event_show_on_map.setOnClickListener { showOnMap() }
event_start_date.setOnClickListener { setupStartDate() }
event_start_time.setOnClickListener { setupStartTime() }
event_end_date.setOnClickListener { setupEndDate() }
event_end_time.setOnClickListener { setupEndTime() }
event_time_zone.setOnClickListener { setupTimeZone() }
event_all_day.setOnCheckedChangeListener { _, isChecked -> toggleAllDay(isChecked) }
event_repetition.setOnClickListener { showRepeatIntervalDialog() }
event_repetition_rule_holder.setOnClickListener { showRepetitionRuleDialog() }
event_repetition_limit_holder.setOnClickListener { showRepetitionTypePicker() }
event_reminder_1.setOnClickListener {
handleNotificationAvailability {
if (config.wasAlarmWarningShown) {
showReminder1Dialog()
} else {
ReminderWarningDialog(this) {
config.wasAlarmWarningShown = true
showReminder1Dialog()
}
}
}
}
event_reminder_2.setOnClickListener { showReminder2Dialog() }
event_reminder_3.setOnClickListener { showReminder3Dialog() }
event_reminder_1_type.setOnClickListener {
showReminderTypePicker(mReminder1Type) {
mReminder1Type = it
updateReminderTypeImage(event_reminder_1_type, Reminder(mReminder1Minutes, mReminder1Type))
}
}
event_reminder_2_type.setOnClickListener {
showReminderTypePicker(mReminder2Type) {
mReminder2Type = it
updateReminderTypeImage(event_reminder_2_type, Reminder(mReminder2Minutes, mReminder2Type))
}
}
event_reminder_3_type.setOnClickListener {
showReminderTypePicker(mReminder3Type) {
mReminder3Type = it
updateReminderTypeImage(event_reminder_3_type, Reminder(mReminder3Minutes, mReminder3Type))
}
}
event_availability.setOnClickListener {
showAvailabilityPicker(mAvailability) {
mAvailability = it
updateAvailabilityText()
updateAvailabilityImage()
}
}
event_type_holder.setOnClickListener { showEventTypeDialog() }
event_all_day.apply {
isChecked = mEvent.getIsAllDay()
jumpDrawablesToCurrentState()
}
event_all_day_holder.setOnClickListener {
event_all_day.toggle()
}
updateTextColors(event_scrollview)
updateIconColors()
refreshMenuItems()
showOrHideTimeZone()
}
private fun refreshMenuItems() {
if (::mEvent.isInitialized) {
event_toolbar.menu.apply {
findItem(R.id.delete).isVisible = mEvent.id != null
findItem(R.id.share).isVisible = mEvent.id != null
findItem(R.id.duplicate).isVisible = mEvent.id != null
}
}
}
private fun setupOptionsMenu() {
event_toolbar.setOnMenuItemClickListener { menuItem ->
when (menuItem.itemId) {
R.id.save -> saveCurrentEvent()
R.id.delete -> deleteEvent()
R.id.duplicate -> duplicateEvent()
R.id.share -> shareEvent()
else -> return@setOnMenuItemClickListener false
}
return@setOnMenuItemClickListener true
}
}
private fun getStartEndTimes(): Pair<Long, Long> {
if (mIsAllDayEvent) {
val newStartTS = mEventStartDateTime.withTimeAtStartOfDay().seconds()
val newEndTS = mEventEndDateTime.withTimeAtStartOfDay().withHourOfDay(12).seconds()
return Pair(newStartTS, newEndTS)
} else {
val offset = if (!config.allowChangingTimeZones || mEvent.getTimeZoneString().equals(mOriginalTimeZone, true)) {
0
} else {
val original = mOriginalTimeZone.ifEmpty { DateTimeZone.getDefault().id }
val millis = System.currentTimeMillis()
val newOffset = DateTimeZone.forID(mEvent.getTimeZoneString()).getOffset(millis)
val oldOffset = DateTimeZone.forID(original).getOffset(millis)
(newOffset - oldOffset) / 1000L
}
val newStartTS = mEventStartDateTime.seconds() - offset
val newEndTS = mEventEndDateTime.seconds() - offset
return Pair(newStartTS, newEndTS)
}
}
private fun getReminders(): ArrayList<Reminder> {
var reminders = arrayListOf(
Reminder(mReminder1Minutes, mReminder1Type),
Reminder(mReminder2Minutes, mReminder2Type),
Reminder(mReminder3Minutes, mReminder3Type)
)
reminders = reminders.filter { it.minutes != REMINDER_OFF }.sortedBy { it.minutes }.toMutableList() as ArrayList<Reminder>
return reminders
}
private fun isEventChanged(): Boolean {
if (!::mEvent.isInitialized) {
return false
}
var newStartTS: Long
var newEndTS: Long
getStartEndTimes().apply {
newStartTS = first
newEndTS = second
}
val hasTimeChanged = if (mOriginalStartTS == 0L) {
mEvent.startTS != newStartTS || mEvent.endTS != newEndTS
} else {
mOriginalStartTS != newStartTS || mOriginalEndTS != newEndTS
}
val reminders = getReminders()
if (event_title.text.toString() != mEvent.title ||
event_location.text.toString() != mEvent.location ||
event_description.text.toString() != mEvent.description ||
event_time_zone.text != mEvent.getTimeZoneString() ||
reminders != mEvent.getReminders() ||
mRepeatInterval != mEvent.repeatInterval ||
mRepeatRule != mEvent.repeatRule ||
mEventTypeId != mEvent.eventType ||
mWasCalendarChanged ||
mIsAllDayEvent != mEvent.getIsAllDay() ||
hasTimeChanged
) {
return true
}
return false
}
override fun onBackPressed() {
if (System.currentTimeMillis() - mLastSavePromptTS > SAVE_DISCARD_PROMPT_INTERVAL && isEventChanged()) {
mLastSavePromptTS = System.currentTimeMillis()
ConfirmationAdvancedDialog(this, "", R.string.save_before_closing, R.string.save, R.string.discard) {
if (it) {
saveCurrentEvent()
} else {
super.onBackPressed()
}
}
} else {
super.onBackPressed()
}
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
if (!::mEvent.isInitialized) {
return
}
outState.apply {
putSerializable(EVENT, mEvent)
putLong(START_TS, mEventStartDateTime.seconds())
putLong(END_TS, mEventEndDateTime.seconds())
putString(TIME_ZONE, mEvent.timeZone)
putInt(REMINDER_1_MINUTES, mReminder1Minutes)
putInt(REMINDER_2_MINUTES, mReminder2Minutes)
putInt(REMINDER_3_MINUTES, mReminder3Minutes)
putInt(REMINDER_1_TYPE, mReminder1Type)
putInt(REMINDER_2_TYPE, mReminder2Type)
putInt(REMINDER_3_TYPE, mReminder3Type)
putInt(REPEAT_INTERVAL, mRepeatInterval)
putInt(REPEAT_RULE, mRepeatRule)
putLong(REPEAT_LIMIT, mRepeatLimit)
putString(ATTENDEES, getAllAttendees(false))
putInt(AVAILABILITY, mAvailability)
putLong(EVENT_TYPE_ID, mEventTypeId)
putInt(EVENT_CALENDAR_ID, mEventCalendarId)
putBoolean(IS_NEW_EVENT, mIsNewEvent)
putLong(ORIGINAL_START_TS, mOriginalStartTS)
putLong(ORIGINAL_END_TS, mOriginalEndTS)
}
}
override fun onRestoreInstanceState(savedInstanceState: Bundle) {
super.onRestoreInstanceState(savedInstanceState)
if (!savedInstanceState.containsKey(START_TS)) {
hideKeyboard()
finish()
return
}
savedInstanceState.apply {
mEvent = getSerializable(EVENT) as Event
mEventStartDateTime = Formatter.getDateTimeFromTS(getLong(START_TS))
mEventEndDateTime = Formatter.getDateTimeFromTS(getLong(END_TS))
mEvent.timeZone = getString(TIME_ZONE) ?: TimeZone.getDefault().id
mReminder1Minutes = getInt(REMINDER_1_MINUTES)
mReminder2Minutes = getInt(REMINDER_2_MINUTES)
mReminder3Minutes = getInt(REMINDER_3_MINUTES)
mReminder1Type = getInt(REMINDER_1_TYPE)
mReminder2Type = getInt(REMINDER_2_TYPE)
mReminder3Type = getInt(REMINDER_3_TYPE)
mAvailability = getInt(AVAILABILITY)
mRepeatInterval = getInt(REPEAT_INTERVAL)
mRepeatRule = getInt(REPEAT_RULE)
mRepeatLimit = getLong(REPEAT_LIMIT)
val token = object : TypeToken<List<Attendee>>() {}.type
mAttendees = Gson().fromJson<ArrayList<Attendee>>(getString(ATTENDEES), token) ?: ArrayList()
mEventTypeId = getLong(EVENT_TYPE_ID)
mEventCalendarId = getInt(EVENT_CALENDAR_ID)
mIsNewEvent = getBoolean(IS_NEW_EVENT)
mOriginalStartTS = getLong(ORIGINAL_START_TS)
mOriginalEndTS = getLong(ORIGINAL_END_TS)
}
checkRepeatTexts(mRepeatInterval)
checkRepeatRule()
updateTexts()
updateEventType()
updateCalDAVCalendar()
checkAttendees()
updateActionBarTitle()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, resultData: Intent?) {
if (requestCode == SELECT_TIME_ZONE_INTENT && resultCode == Activity.RESULT_OK && resultData?.hasExtra(TIME_ZONE) == true) {
val timeZone = resultData.getSerializableExtra(TIME_ZONE) as MyTimeZone
mEvent.timeZone = timeZone.zoneName
updateTimeZoneText()
}
super.onActivityResult(requestCode, resultCode, resultData)
}
private fun updateTexts() {
updateRepetitionText()
checkReminderTexts()
updateStartTexts()
updateEndTexts()
updateTimeZoneText()
updateCalDAVVisibility()
updateAvailabilityText()
updateAvailabilityImage()
}
private fun setupEditEvent() {
mIsNewEvent = false
val realStart = if (mEventOccurrenceTS == 0L) mEvent.startTS else mEventOccurrenceTS
val duration = mEvent.endTS - mEvent.startTS
mOriginalStartTS = realStart
mOriginalEndTS = realStart + duration
window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN)
event_toolbar.title = getString(R.string.edit_event)
mOriginalTimeZone = mEvent.timeZone
if (config.allowChangingTimeZones) {
try {
mEventStartDateTime = Formatter.getDateTimeFromTS(realStart).withZone(DateTimeZone.forID(mOriginalTimeZone))
mEventEndDateTime = Formatter.getDateTimeFromTS(realStart + duration).withZone(DateTimeZone.forID(mOriginalTimeZone))
} catch (e: Exception) {
showErrorToast(e)
mEventStartDateTime = Formatter.getDateTimeFromTS(realStart)
mEventEndDateTime = Formatter.getDateTimeFromTS(realStart + duration)
}
} else {
mEventStartDateTime = Formatter.getDateTimeFromTS(realStart)
mEventEndDateTime = Formatter.getDateTimeFromTS(realStart + duration)
}
event_title.setText(mEvent.title)
event_location.setText(mEvent.location)
event_description.setText(mEvent.description)
mReminder1Minutes = mEvent.reminder1Minutes
mReminder2Minutes = mEvent.reminder2Minutes
mReminder3Minutes = mEvent.reminder3Minutes
mReminder1Type = mEvent.reminder1Type
mReminder2Type = mEvent.reminder2Type
mReminder3Type = mEvent.reminder3Type
mRepeatInterval = mEvent.repeatInterval
mRepeatLimit = mEvent.repeatLimit
mRepeatRule = mEvent.repeatRule
mEventTypeId = mEvent.eventType
mEventCalendarId = mEvent.getCalDAVCalendarId()
mAvailability = mEvent.availability
val token = object : TypeToken<List<Attendee>>() {}.type
mAttendees = Gson().fromJson<ArrayList<Attendee>>(mEvent.attendees, token) ?: ArrayList()
checkRepeatTexts(mRepeatInterval)
checkAttendees()
}
private fun setupNewEvent() {
window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE)
event_title.requestFocus()
event_toolbar.title = getString(R.string.new_event)
if (config.defaultEventTypeId != -1L) {
config.lastUsedCaldavCalendarId = mStoredEventTypes.firstOrNull { it.id == config.defaultEventTypeId }?.caldavCalendarId ?: 0
}
val isLastCaldavCalendarOK = config.caldavSync && config.getSyncedCalendarIdsAsList().contains(config.lastUsedCaldavCalendarId)
mEventCalendarId = if (isLastCaldavCalendarOK) config.lastUsedCaldavCalendarId else STORED_LOCALLY_ONLY
if (intent.action == Intent.ACTION_EDIT || intent.action == Intent.ACTION_INSERT) {
val startTS = intent.getLongExtra("beginTime", System.currentTimeMillis()) / 1000L
mEventStartDateTime = Formatter.getDateTimeFromTS(startTS)
val endTS = intent.getLongExtra("endTime", System.currentTimeMillis()) / 1000L
mEventEndDateTime = Formatter.getDateTimeFromTS(endTS)
if (intent.getBooleanExtra("allDay", false)) {
mEvent.flags = mEvent.flags or FLAG_ALL_DAY
event_all_day.isChecked = true
toggleAllDay(true)
}
event_title.setText(intent.getStringExtra("title"))
event_location.setText(intent.getStringExtra("eventLocation"))
event_description.setText(intent.getStringExtra("description"))
if (event_description.value.isNotEmpty()) {
event_description.movementMethod = LinkMovementMethod.getInstance()
}
} else {
val startTS = intent.getLongExtra(NEW_EVENT_START_TS, 0L)
val dateTime = Formatter.getDateTimeFromTS(startTS)
mEventStartDateTime = dateTime
val addMinutes = if (intent.getBooleanExtra(NEW_EVENT_SET_HOUR_DURATION, false)) {
// if an event is created at 23:00 on the weekly view, make it end on 23:59 by default to avoid spanning across multiple days
if (mEventStartDateTime.hourOfDay == 23) {
59
} else {
60
}
} else {
config.defaultDuration
}
mEventEndDateTime = mEventStartDateTime.plusMinutes(addMinutes)
}
addDefValuesToNewEvent()
checkAttendees()
}
private fun addDefValuesToNewEvent() {
var newStartTS: Long
var newEndTS: Long
getStartEndTimes().apply {
newStartTS = first
newEndTS = second
}
mEvent.apply {
startTS = newStartTS
endTS = newEndTS
reminder1Minutes = mReminder1Minutes
reminder1Type = mReminder1Type
reminder2Minutes = mReminder2Minutes
reminder2Type = mReminder2Type
reminder3Minutes = mReminder3Minutes
reminder3Type = mReminder3Type
eventType = mEventTypeId
}
}
private fun checkAttendees() {
ensureBackgroundThread {
fillAvailableContacts()
updateAttendees()
}
}
private fun showReminder1Dialog() {
showPickSecondsDialogHelper(mReminder1Minutes, showDuringDayOption = mIsAllDayEvent) {
mReminder1Minutes = if (it == -1 || it == 0) it else it / 60
checkReminderTexts()
}
}
private fun showReminder2Dialog() {
showPickSecondsDialogHelper(mReminder2Minutes, showDuringDayOption = mIsAllDayEvent) {
mReminder2Minutes = if (it == -1 || it == 0) it else it / 60
checkReminderTexts()
}
}
private fun showReminder3Dialog() {
showPickSecondsDialogHelper(mReminder3Minutes, showDuringDayOption = mIsAllDayEvent) {
mReminder3Minutes = if (it == -1 || it == 0) it else it / 60
checkReminderTexts()
}
}
private fun showRepeatIntervalDialog() {
showEventRepeatIntervalDialog(mRepeatInterval) {
setRepeatInterval(it)
}
}
private fun setRepeatInterval(interval: Int) {
mRepeatInterval = interval
updateRepetitionText()
checkRepeatTexts(interval)
when {
mRepeatInterval.isXWeeklyRepetition() -> setRepeatRule(Math.pow(2.0, (mEventStartDateTime.dayOfWeek - 1).toDouble()).toInt())
mRepeatInterval.isXMonthlyRepetition() -> setRepeatRule(REPEAT_SAME_DAY)
mRepeatInterval.isXYearlyRepetition() -> setRepeatRule(REPEAT_SAME_DAY)
}
}
private fun checkRepeatTexts(limit: Int) {
event_repetition_limit_holder.beGoneIf(limit == 0)
checkRepetitionLimitText()
event_repetition_rule_holder.beVisibleIf(mRepeatInterval.isXWeeklyRepetition() || mRepeatInterval.isXMonthlyRepetition() || mRepeatInterval.isXYearlyRepetition())
checkRepetitionRuleText()
}
private fun showRepetitionTypePicker() {
hideKeyboard()
RepeatLimitTypePickerDialog(this, mRepeatLimit, mEventStartDateTime.seconds()) {
setRepeatLimit(it)
}
}
private fun setRepeatLimit(limit: Long) {
mRepeatLimit = limit
checkRepetitionLimitText()
}
private fun checkRepetitionLimitText() {
event_repetition_limit.text = when {
mRepeatLimit == 0L -> {
event_repetition_limit_label.text = getString(R.string.repeat)
resources.getString(R.string.forever)
}
mRepeatLimit > 0 -> {
event_repetition_limit_label.text = getString(R.string.repeat_till)
val repeatLimitDateTime = Formatter.getDateTimeFromTS(mRepeatLimit)
Formatter.getFullDate(this, repeatLimitDateTime)
}
else -> {
event_repetition_limit_label.text = getString(R.string.repeat)
"${-mRepeatLimit} ${getString(R.string.times)}"
}
}
}
private fun showRepetitionRuleDialog() {
hideKeyboard()
when {
mRepeatInterval.isXWeeklyRepetition() -> RepeatRuleWeeklyDialog(this, mRepeatRule) {
setRepeatRule(it)
}
mRepeatInterval.isXMonthlyRepetition() -> {
val items = getAvailableMonthlyRepetitionRules()
RadioGroupDialog(this, items, mRepeatRule) {
setRepeatRule(it as Int)
}
}
mRepeatInterval.isXYearlyRepetition() -> {
val items = getAvailableYearlyRepetitionRules()
RadioGroupDialog(this, items, mRepeatRule) {
setRepeatRule(it as Int)
}
}
}
}
private fun getAvailableMonthlyRepetitionRules(): ArrayList<RadioItem> {
val items = arrayListOf(RadioItem(REPEAT_SAME_DAY, getString(R.string.repeat_on_the_same_day_monthly)))
items.add(RadioItem(REPEAT_ORDER_WEEKDAY, getRepeatXthDayString(true, REPEAT_ORDER_WEEKDAY)))
if (isLastWeekDayOfMonth()) {
items.add(RadioItem(REPEAT_ORDER_WEEKDAY_USE_LAST, getRepeatXthDayString(true, REPEAT_ORDER_WEEKDAY_USE_LAST)))
}
if (isLastDayOfTheMonth()) {
items.add(RadioItem(REPEAT_LAST_DAY, getString(R.string.repeat_on_the_last_day_monthly)))
}
return items
}
private fun getAvailableYearlyRepetitionRules(): ArrayList<RadioItem> {
val items = arrayListOf(RadioItem(REPEAT_SAME_DAY, getString(R.string.repeat_on_the_same_day_yearly)))
items.add(RadioItem(REPEAT_ORDER_WEEKDAY, getRepeatXthDayInMonthString(true, REPEAT_ORDER_WEEKDAY)))
if (isLastWeekDayOfMonth()) {
items.add(RadioItem(REPEAT_ORDER_WEEKDAY_USE_LAST, getRepeatXthDayInMonthString(true, REPEAT_ORDER_WEEKDAY_USE_LAST)))
}
return items
}
private fun isLastDayOfTheMonth() = mEventStartDateTime.dayOfMonth == mEventStartDateTime.dayOfMonth().withMaximumValue().dayOfMonth
private fun isLastWeekDayOfMonth() = mEventStartDateTime.monthOfYear != mEventStartDateTime.plusDays(7).monthOfYear
private fun getRepeatXthDayString(includeBase: Boolean, repeatRule: Int): String {
val dayOfWeek = mEventStartDateTime.dayOfWeek
val base = getBaseString(dayOfWeek)
val order = getOrderString(repeatRule)
val dayString = getDayString(dayOfWeek)
return if (includeBase) {
"$base $order $dayString"
} else {
val everyString = getString(if (isMaleGender(mEventStartDateTime.dayOfWeek)) R.string.every_m else R.string.every_f)
"$everyString $order $dayString"
}
}
private fun getBaseString(day: Int): String {
return getString(
if (isMaleGender(day)) {
R.string.repeat_every_m
} else {
R.string.repeat_every_f
}
)
}
private fun isMaleGender(day: Int) = day == 1 || day == 2 || day == 4 || day == 5
private fun getOrderString(repeatRule: Int): String {
val dayOfMonth = mEventStartDateTime.dayOfMonth
var order = (dayOfMonth - 1) / 7 + 1
if (isLastWeekDayOfMonth() && repeatRule == REPEAT_ORDER_WEEKDAY_USE_LAST) {
order = -1
}
val isMale = isMaleGender(mEventStartDateTime.dayOfWeek)
return getString(
when (order) {
1 -> if (isMale) R.string.first_m else R.string.first_f
2 -> if (isMale) R.string.second_m else R.string.second_f
3 -> if (isMale) R.string.third_m else R.string.third_f
4 -> if (isMale) R.string.fourth_m else R.string.fourth_f
5 -> if (isMale) R.string.fifth_m else R.string.fifth_f
else -> if (isMale) R.string.last_m else R.string.last_f
}
)
}
private fun getDayString(day: Int): String {
return getString(
when (day) {
1 -> R.string.monday_alt
2 -> R.string.tuesday_alt
3 -> R.string.wednesday_alt
4 -> R.string.thursday_alt
5 -> R.string.friday_alt
6 -> R.string.saturday_alt
else -> R.string.sunday_alt
}
)
}
private fun getRepeatXthDayInMonthString(includeBase: Boolean, repeatRule: Int): String {
val weekDayString = getRepeatXthDayString(includeBase, repeatRule)
val monthString = resources.getStringArray(R.array.in_months)[mEventStartDateTime.monthOfYear - 1]
return "$weekDayString $monthString"
}
private fun setRepeatRule(rule: Int) {
mRepeatRule = rule
checkRepetitionRuleText()
if (rule == 0) {
setRepeatInterval(0)
}
}
private fun checkRepetitionRuleText() {
when {
mRepeatInterval.isXWeeklyRepetition() -> {
event_repetition_rule.text = if (mRepeatRule == EVERY_DAY_BIT) getString(R.string.every_day) else getSelectedDaysString(mRepeatRule)
}
mRepeatInterval.isXMonthlyRepetition() -> {
val repeatString = if (mRepeatRule == REPEAT_ORDER_WEEKDAY_USE_LAST || mRepeatRule == REPEAT_ORDER_WEEKDAY)
R.string.repeat else R.string.repeat_on
event_repetition_rule_label.text = getString(repeatString)
event_repetition_rule.text = getMonthlyRepetitionRuleText()
}
mRepeatInterval.isXYearlyRepetition() -> {
val repeatString = if (mRepeatRule == REPEAT_ORDER_WEEKDAY_USE_LAST || mRepeatRule == REPEAT_ORDER_WEEKDAY)
R.string.repeat else R.string.repeat_on
event_repetition_rule_label.text = getString(repeatString)
event_repetition_rule.text = getYearlyRepetitionRuleText()
}
}
}
private fun getMonthlyRepetitionRuleText() = when (mRepeatRule) {
REPEAT_SAME_DAY -> getString(R.string.the_same_day)
REPEAT_LAST_DAY -> getString(R.string.the_last_day)
else -> getRepeatXthDayString(false, mRepeatRule)
}
private fun getYearlyRepetitionRuleText() = when (mRepeatRule) {
REPEAT_SAME_DAY -> getString(R.string.the_same_day)
else -> getRepeatXthDayInMonthString(false, mRepeatRule)
}
private fun showEventTypeDialog() {
hideKeyboard()
SelectEventTypeDialog(this, mEventTypeId, false, true, false, true) {
mEventTypeId = it.id!!
updateEventType()
}
}
private fun checkReminderTexts() {
updateReminder1Text()
updateReminder2Text()
updateReminder3Text()
updateReminderTypeImages()
}
private fun updateReminder1Text() {
event_reminder_1.text = getFormattedMinutes(mReminder1Minutes)
}
private fun updateReminder2Text() {
event_reminder_2.apply {
beGoneIf(event_reminder_2.isGone() && mReminder1Minutes == REMINDER_OFF)
if (mReminder2Minutes == REMINDER_OFF) {
text = resources.getString(R.string.add_another_reminder)
alpha = 0.4f
} else {
text = getFormattedMinutes(mReminder2Minutes)
alpha = 1f
}
}
}
private fun updateReminder3Text() {
event_reminder_3.apply {
beGoneIf(event_reminder_3.isGone() && (mReminder2Minutes == REMINDER_OFF || mReminder1Minutes == REMINDER_OFF))
if (mReminder3Minutes == REMINDER_OFF) {
text = resources.getString(R.string.add_another_reminder)
alpha = 0.4f
} else {
text = getFormattedMinutes(mReminder3Minutes)
alpha = 1f
}
}
}
private fun showReminderTypePicker(currentValue: Int, callback: (Int) -> Unit) {
val items = arrayListOf(
RadioItem(REMINDER_NOTIFICATION, getString(R.string.notification)),
RadioItem(REMINDER_EMAIL, getString(R.string.email))
)
RadioGroupDialog(this, items, currentValue) {
callback(it as Int)
}
}
private fun showAvailabilityPicker(currentValue: Int, callback: (Int) -> Unit) {
val items = arrayListOf(
RadioItem(Attendees.AVAILABILITY_BUSY, getString(R.string.status_busy)),
RadioItem(Attendees.AVAILABILITY_FREE, getString(R.string.status_free))
)
RadioGroupDialog(this, items, currentValue) {
callback(it as Int)
}
}
private fun updateReminderTypeImages() {
updateReminderTypeImage(event_reminder_1_type, Reminder(mReminder1Minutes, mReminder1Type))
updateReminderTypeImage(event_reminder_2_type, Reminder(mReminder2Minutes, mReminder2Type))
updateReminderTypeImage(event_reminder_3_type, Reminder(mReminder3Minutes, mReminder3Type))
}
private fun updateCalDAVVisibility() {
val isSyncedEvent = mEventCalendarId != STORED_LOCALLY_ONLY
event_attendees_image.beVisibleIf(isSyncedEvent)
event_attendees_holder.beVisibleIf(isSyncedEvent)
event_attendees_divider.beVisibleIf(isSyncedEvent)
event_availability_divider.beVisibleIf(isSyncedEvent)
event_availability_image.beVisibleIf(isSyncedEvent)
event_availability.beVisibleIf(isSyncedEvent)
}
private fun updateReminderTypeImage(view: ImageView, reminder: Reminder) {
view.beVisibleIf(reminder.minutes != REMINDER_OFF && mEventCalendarId != STORED_LOCALLY_ONLY)
val drawable = if (reminder.type == REMINDER_NOTIFICATION) R.drawable.ic_bell_vector else R.drawable.ic_mail_vector
val icon = resources.getColoredDrawableWithColor(drawable, getProperTextColor())
view.setImageDrawable(icon)
}
private fun updateAvailabilityImage() {
val drawable = if (mAvailability == Attendees.AVAILABILITY_FREE) R.drawable.ic_event_available_vector else R.drawable.ic_event_busy_vector
val icon = resources.getColoredDrawableWithColor(drawable, getProperTextColor())
event_availability_image.setImageDrawable(icon)
}
private fun updateAvailabilityText() {
event_availability.text = if (mAvailability == Attendees.AVAILABILITY_FREE) getString(R.string.status_free) else getString(R.string.status_busy)
}
private fun updateRepetitionText() {
event_repetition.text = getRepetitionText(mRepeatInterval)
}
private fun updateEventType() {
ensureBackgroundThread {
val eventType = eventTypesDB.getEventTypeWithId(mEventTypeId)
if (eventType != null) {
runOnUiThread {
event_type.text = eventType.title
event_type_color.setFillWithStroke(eventType.color, getProperBackgroundColor())
}
}
}
}
private fun updateCalDAVCalendar() {
if (config.caldavSync) {
event_caldav_calendar_image.beVisible()
event_caldav_calendar_holder.beVisible()
event_caldav_calendar_divider.beVisible()
val calendars = calDAVHelper.getCalDAVCalendars("", true).filter {
it.canWrite() && config.getSyncedCalendarIdsAsList().contains(it.id)
}
updateCurrentCalendarInfo(if (mEventCalendarId == STORED_LOCALLY_ONLY) null else getCalendarWithId(calendars, getCalendarId()))
event_caldav_calendar_holder.setOnClickListener {
hideKeyboard()
SelectEventCalendarDialog(this, calendars, mEventCalendarId) {
if (mEventCalendarId != STORED_LOCALLY_ONLY && it == STORED_LOCALLY_ONLY) {
mEventTypeId = config.lastUsedLocalEventTypeId
updateEventType()
}
mWasCalendarChanged = true
mEventCalendarId = it
config.lastUsedCaldavCalendarId = it
updateCurrentCalendarInfo(getCalendarWithId(calendars, it))
updateReminderTypeImages()
updateCalDAVVisibility()
updateAvailabilityText()
updateAvailabilityImage()
}
}
} else {
updateCurrentCalendarInfo(null)
}
}
private fun getCalendarId() = if (mEvent.source == SOURCE_SIMPLE_CALENDAR) config.lastUsedCaldavCalendarId else mEvent.getCalDAVCalendarId()
private fun getCalendarWithId(calendars: List<CalDAVCalendar>, calendarId: Int) = calendars.firstOrNull { it.id == calendarId }
private fun updateCurrentCalendarInfo(currentCalendar: CalDAVCalendar?) {
event_type_image.beVisibleIf(currentCalendar == null)
event_type_holder.beVisibleIf(currentCalendar == null)
event_caldav_calendar_divider.beVisibleIf(currentCalendar == null)
event_caldav_calendar_email.beGoneIf(currentCalendar == null)
event_caldav_calendar_color.beGoneIf(currentCalendar == null)
if (currentCalendar == null) {
mEventCalendarId = STORED_LOCALLY_ONLY
val mediumMargin = resources.getDimension(R.dimen.medium_margin).toInt()
event_caldav_calendar_name.apply {
text = getString(R.string.store_locally_only)
setPadding(paddingLeft, paddingTop, paddingRight, mediumMargin)
}
event_caldav_calendar_holder.apply {
setPadding(paddingLeft, mediumMargin, paddingRight, mediumMargin)
}
} else {
event_caldav_calendar_email.text = currentCalendar.accountName
ensureBackgroundThread {
val calendarColor = eventsHelper.getEventTypeWithCalDAVCalendarId(currentCalendar.id)?.color ?: currentCalendar.color
runOnUiThread {
event_caldav_calendar_color.setFillWithStroke(calendarColor, getProperBackgroundColor())
event_caldav_calendar_name.apply {
text = currentCalendar.displayName
setPadding(paddingLeft, paddingTop, paddingRight, resources.getDimension(R.dimen.tiny_margin).toInt())
}
event_caldav_calendar_holder.apply {
setPadding(paddingLeft, 0, paddingRight, 0)
}
}
}
}
}
private fun resetTime() {
if (mEventEndDateTime.isBefore(mEventStartDateTime) &&
mEventStartDateTime.dayOfMonth() == mEventEndDateTime.dayOfMonth() &&
mEventStartDateTime.monthOfYear() == mEventEndDateTime.monthOfYear()
) {
mEventEndDateTime =
mEventEndDateTime.withTime(mEventStartDateTime.hourOfDay, mEventStartDateTime.minuteOfHour, mEventStartDateTime.secondOfMinute, 0)
updateEndTimeText()
checkStartEndValidity()
}
}
private fun toggleAllDay(isAllDay: Boolean) {
hideKeyboard()
mIsAllDayEvent = isAllDay
event_start_time.beGoneIf(isAllDay)
event_end_time.beGoneIf(isAllDay)
updateTimeZoneText()
showOrHideTimeZone()
resetTime()
}
private fun showOrHideTimeZone() {
val allowChangingTimeZones = config.allowChangingTimeZones && !mIsAllDayEvent
event_time_zone_divider.beVisibleIf(allowChangingTimeZones)
event_time_zone_image.beVisibleIf(allowChangingTimeZones)
event_time_zone.beVisibleIf(allowChangingTimeZones)
}
private fun shareEvent() {
shareEvents(arrayListOf(mEvent.id!!))
}
private fun deleteEvent() {
if (mEvent.id == null) {
return
}
DeleteEventDialog(this, arrayListOf(mEvent.id!!), mEvent.repeatInterval > 0) {
ensureBackgroundThread {
when (it) {
DELETE_SELECTED_OCCURRENCE -> eventsHelper.addEventRepetitionException(mEvent.id!!, mEventOccurrenceTS, true)
DELETE_FUTURE_OCCURRENCES -> eventsHelper.addEventRepeatLimit(mEvent.id!!, mEventOccurrenceTS)
DELETE_ALL_OCCURRENCES -> eventsHelper.deleteEvent(mEvent.id!!, true)
}
runOnUiThread {
hideKeyboard()
finish()
}
}
}
}
private fun duplicateEvent() {
// the activity has the singleTask launchMode to avoid some glitches, so finish it before relaunching
hideKeyboard()
finish()
Intent(this, EventActivity::class.java).apply {
putExtra(EVENT_ID, mEvent.id)
putExtra(EVENT_OCCURRENCE_TS, mEventOccurrenceTS)
putExtra(IS_DUPLICATE_INTENT, true)
startActivity(this)
}
}
private fun saveCurrentEvent() {
if (config.wasAlarmWarningShown || (mReminder1Minutes == REMINDER_OFF && mReminder2Minutes == REMINDER_OFF && mReminder3Minutes == REMINDER_OFF)) {
ensureBackgroundThread {
saveEvent()
}
} else {
ReminderWarningDialog(this) {
config.wasAlarmWarningShown = true
ensureBackgroundThread {
saveEvent()
}
}
}
}
private fun saveEvent() {
val newTitle = event_title.value
if (newTitle.isEmpty()) {
toast(R.string.title_empty)
runOnUiThread {
event_title.requestFocus()
}
return
}
var newStartTS: Long
var newEndTS: Long
getStartEndTimes().apply {
newStartTS = first
newEndTS = second
}
if (newStartTS > newEndTS) {
toast(R.string.end_before_start)
return
}
val wasRepeatable = mEvent.repeatInterval > 0
val oldSource = mEvent.source
val newImportId = if (mEvent.id != null) {
mEvent.importId
} else {
UUID.randomUUID().toString().replace("-", "") + System.currentTimeMillis().toString()
}
val newEventType = if (!config.caldavSync || config.lastUsedCaldavCalendarId == 0 || mEventCalendarId == STORED_LOCALLY_ONLY) {
mEventTypeId
} else {
calDAVHelper.getCalDAVCalendars("", true).firstOrNull { it.id == mEventCalendarId }?.apply {
if (!canWrite()) {
runOnUiThread {
toast(R.string.insufficient_permissions)
}
return
}
}
eventsHelper.getEventTypeWithCalDAVCalendarId(mEventCalendarId)?.id ?: config.lastUsedLocalEventTypeId
}
val newSource = if (!config.caldavSync || mEventCalendarId == STORED_LOCALLY_ONLY) {
config.lastUsedLocalEventTypeId = newEventType
SOURCE_SIMPLE_CALENDAR
} else {
"$CALDAV-$mEventCalendarId"
}
val reminders = getReminders()
if (!event_all_day.isChecked) {
if ((reminders.getOrNull(2)?.minutes ?: 0) < -1) {
reminders.removeAt(2)
}
if ((reminders.getOrNull(1)?.minutes ?: 0) < -1) {
reminders.removeAt(1)
}
if ((reminders.getOrNull(0)?.minutes ?: 0) < -1) {
reminders.removeAt(0)
}
}
val reminder1 = reminders.getOrNull(0) ?: Reminder(REMINDER_OFF, REMINDER_NOTIFICATION)
val reminder2 = reminders.getOrNull(1) ?: Reminder(REMINDER_OFF, REMINDER_NOTIFICATION)
val reminder3 = reminders.getOrNull(2) ?: Reminder(REMINDER_OFF, REMINDER_NOTIFICATION)
mReminder1Type = if (mEventCalendarId == STORED_LOCALLY_ONLY) REMINDER_NOTIFICATION else reminder1.type
mReminder2Type = if (mEventCalendarId == STORED_LOCALLY_ONLY) REMINDER_NOTIFICATION else reminder2.type
mReminder3Type = if (mEventCalendarId == STORED_LOCALLY_ONLY) REMINDER_NOTIFICATION else reminder3.type
config.apply {
if (usePreviousEventReminders) {
lastEventReminderMinutes1 = reminder1.minutes
lastEventReminderMinutes2 = reminder2.minutes
lastEventReminderMinutes3 = reminder3.minutes
}
}
mEvent.apply {
startTS = newStartTS
endTS = newEndTS
title = newTitle
description = event_description.value
reminder1Minutes = reminder1.minutes
reminder2Minutes = reminder2.minutes
reminder3Minutes = reminder3.minutes
reminder1Type = mReminder1Type
reminder2Type = mReminder2Type
reminder3Type = mReminder3Type
repeatInterval = mRepeatInterval
importId = newImportId
timeZone = if (mIsAllDayEvent || timeZone.isEmpty()) DateTimeZone.getDefault().id else timeZone
flags = mEvent.flags.addBitIf(event_all_day.isChecked, FLAG_ALL_DAY)
repeatLimit = if (repeatInterval == 0) 0 else mRepeatLimit
repeatRule = mRepeatRule
attendees = if (mEventCalendarId == STORED_LOCALLY_ONLY) "" else getAllAttendees(true)
eventType = newEventType
lastUpdated = System.currentTimeMillis()
source = newSource
location = event_location.value
availability = mAvailability
}
// recreate the event if it was moved in a different CalDAV calendar
if (mEvent.id != null && oldSource != newSource && oldSource != SOURCE_IMPORTED_ICS) {
eventsHelper.deleteEvent(mEvent.id!!, true)
mEvent.id = null
}
if (mEvent.getReminders().isNotEmpty()) {
handleNotificationPermission { granted ->
if (granted) {
ensureBackgroundThread {
storeEvent(wasRepeatable)
}
} else {
toast(R.string.no_post_notifications_permissions)
}
}
} else {
storeEvent(wasRepeatable)
}
}
private fun storeEvent(wasRepeatable: Boolean) {
if (mEvent.id == null) {
eventsHelper.insertEvent(mEvent, addToCalDAV = true, showToasts = true) {
hideKeyboard()
if (DateTime.now().isAfter(mEventStartDateTime.millis)) {
if (mEvent.repeatInterval == 0 && mEvent.getReminders().any { it.type == REMINDER_NOTIFICATION }) {
notifyEvent(mEvent)
}
}
finish()
}
} else {
if (mRepeatInterval > 0 && wasRepeatable) {
runOnUiThread {
showEditRepeatingEventDialog()
}
} else {
hideKeyboard()
eventsHelper.updateEvent(mEvent, updateAtCalDAV = true, showToasts = true) {
finish()
}
}
}
}
private fun showEditRepeatingEventDialog() {
EditRepeatingEventDialog(this) {
hideKeyboard()
when (it) {
0 -> {
ensureBackgroundThread {
eventsHelper.addEventRepetitionException(mEvent.id!!, mEventOccurrenceTS, true)
mEvent.apply {
parentId = id!!.toLong()
id = null
repeatRule = 0
repeatInterval = 0
repeatLimit = 0
}
eventsHelper.insertEvent(mEvent, true, true) {
finish()
}
}
}
1 -> {
ensureBackgroundThread {
eventsHelper.addEventRepeatLimit(mEvent.id!!, mEventOccurrenceTS)
mEvent.apply {
id = null
}
eventsHelper.insertEvent(mEvent, addToCalDAV = true, showToasts = true) {
finish()
}
}
}
2 -> {
ensureBackgroundThread {
eventsHelper.addEventRepeatLimit(mEvent.id!!, mEventOccurrenceTS)
eventsHelper.updateEvent(mEvent, updateAtCalDAV = true, showToasts = true) {
finish()
}
}
}
}
}
}
private fun updateStartTexts() {
updateStartDateText()
updateStartTimeText()
}
private fun updateStartDateText() {
event_start_date.text = Formatter.getDate(this, mEventStartDateTime)
checkStartEndValidity()
}
private fun updateStartTimeText() {
event_start_time.text = Formatter.getTime(this, mEventStartDateTime)
checkStartEndValidity()
}
private fun updateEndTexts() {
updateEndDateText()
updateEndTimeText()
}
private fun updateEndDateText() {
event_end_date.text = Formatter.getDate(this, mEventEndDateTime)
checkStartEndValidity()
}
private fun updateEndTimeText() {
event_end_time.text = Formatter.getTime(this, mEventEndDateTime)
checkStartEndValidity()
}
private fun updateTimeZoneText() {
event_time_zone.text = mEvent.getTimeZoneString()
}
private fun checkStartEndValidity() {
val textColor = if (mEventStartDateTime.isAfter(mEventEndDateTime)) resources.getColor(R.color.red_text) else getProperTextColor()
event_end_date.setTextColor(textColor)
event_end_time.setTextColor(textColor)
}
private fun showOnMap() {
if (event_location.value.isEmpty()) {
toast(R.string.please_fill_location)
return
}
val pattern = Pattern.compile(LAT_LON_PATTERN)
val locationValue = event_location.value
val uri = if (pattern.matcher(locationValue).find()) {
val delimiter = if (locationValue.contains(';')) ";" else ","
val parts = locationValue.split(delimiter)
val latitude = parts.first()
val longitude = parts.last()
Uri.parse("geo:$latitude,$longitude")
} else {
val location = Uri.encode(locationValue)
Uri.parse("geo:0,0?q=$location")
}
val intent = Intent(Intent.ACTION_VIEW, uri)
launchActivityIntent(intent)
}
private fun setupStartDate() {
hideKeyboard()
val datepicker = DatePickerDialog(
this, getDatePickerDialogTheme(), startDateSetListener, mEventStartDateTime.year, mEventStartDateTime.monthOfYear - 1,
mEventStartDateTime.dayOfMonth
)
datepicker.datePicker.firstDayOfWeek = if (config.isSundayFirst) Calendar.SUNDAY else Calendar.MONDAY
datepicker.show()
}
private fun setupStartTime() {
hideKeyboard()
TimePickerDialog(
this,
getTimePickerDialogTheme(),
startTimeSetListener,
mEventStartDateTime.hourOfDay,
mEventStartDateTime.minuteOfHour,
config.use24HourFormat
).show()
}
private fun setupEndDate() {
hideKeyboard()
val datepicker = DatePickerDialog(
this, getDatePickerDialogTheme(), endDateSetListener, mEventEndDateTime.year, mEventEndDateTime.monthOfYear - 1,
mEventEndDateTime.dayOfMonth
)
datepicker.datePicker.firstDayOfWeek = if (config.isSundayFirst) Calendar.SUNDAY else Calendar.MONDAY
datepicker.show()
}
private fun setupEndTime() {
hideKeyboard()
TimePickerDialog(
this,
getTimePickerDialogTheme(),
endTimeSetListener,
mEventEndDateTime.hourOfDay,
mEventEndDateTime.minuteOfHour,
config.use24HourFormat
).show()
}
private val startDateSetListener = DatePickerDialog.OnDateSetListener { view, year, monthOfYear, dayOfMonth ->
dateSet(year, monthOfYear, dayOfMonth, true)
}
private val startTimeSetListener = TimePickerDialog.OnTimeSetListener { view, hourOfDay, minute ->
timeSet(hourOfDay, minute, true)
}
private val endDateSetListener = DatePickerDialog.OnDateSetListener { view, year, monthOfYear, dayOfMonth -> dateSet(year, monthOfYear, dayOfMonth, false) }
private val endTimeSetListener = TimePickerDialog.OnTimeSetListener { view, hourOfDay, minute -> timeSet(hourOfDay, minute, false) }
private fun dateSet(year: Int, month: Int, day: Int, isStart: Boolean) {
if (isStart) {
val diff = mEventEndDateTime.seconds() - mEventStartDateTime.seconds()
mEventStartDateTime = mEventStartDateTime.withDate(year, month + 1, day)
updateStartDateText()
checkRepeatRule()
mEventEndDateTime = mEventStartDateTime.plusSeconds(diff.toInt())
updateEndTexts()
} else {
mEventEndDateTime = mEventEndDateTime.withDate(year, month + 1, day)
updateEndDateText()
}
}
private fun timeSet(hours: Int, minutes: Int, isStart: Boolean) {
try {
if (isStart) {
val diff = mEventEndDateTime.seconds() - mEventStartDateTime.seconds()
mEventStartDateTime = mEventStartDateTime.withHourOfDay(hours).withMinuteOfHour(minutes)
updateStartTimeText()
mEventEndDateTime = mEventStartDateTime.plusSeconds(diff.toInt())
updateEndTexts()
} else {
mEventEndDateTime = mEventEndDateTime.withHourOfDay(hours).withMinuteOfHour(minutes)
updateEndTimeText()
}
} catch (e: Exception) {
timeSet(hours + 1, minutes, isStart)
return
}
}
private fun setupTimeZone() {
hideKeyboard()
Intent(this, SelectTimeZoneActivity::class.java).apply {
putExtra(CURRENT_TIME_ZONE, mEvent.getTimeZoneString())
startActivityForResult(this, SELECT_TIME_ZONE_INTENT)
}
}
private fun checkRepeatRule() {
if (mRepeatInterval.isXWeeklyRepetition()) {
val day = mRepeatRule
if (day == MONDAY_BIT || day == TUESDAY_BIT || day == WEDNESDAY_BIT || day == THURSDAY_BIT || day == FRIDAY_BIT || day == SATURDAY_BIT || day == SUNDAY_BIT) {
setRepeatRule(Math.pow(2.0, (mEventStartDateTime.dayOfWeek - 1).toDouble()).toInt())
}
} else if (mRepeatInterval.isXMonthlyRepetition() || mRepeatInterval.isXYearlyRepetition()) {
if (mRepeatRule == REPEAT_LAST_DAY && !isLastDayOfTheMonth()) {
mRepeatRule = REPEAT_SAME_DAY
}
checkRepetitionRuleText()
}
}
private fun fillAvailableContacts() {
mAvailableContacts = getEmails()
val names = getNames()
mAvailableContacts.forEach {
val contactId = it.contactId
val contact = names.firstOrNull { it.contactId == contactId }
val name = contact?.name
if (name != null) {
it.name = name
}
val photoUri = contact?.photoUri
if (photoUri != null) {
it.photoUri = photoUri
}
}
}
private fun updateAttendees() {
val currentCalendar = calDAVHelper.getCalDAVCalendars("", true).firstOrNull { it.id == mEventCalendarId }
mAttendees.forEach {
it.isMe = it.email == currentCalendar?.accountName
}
mAttendees.sortWith(compareBy<Attendee>
{ it.isMe }.thenBy
{ it.status == Attendees.ATTENDEE_STATUS_ACCEPTED }.thenBy
{ it.status == Attendees.ATTENDEE_STATUS_DECLINED }.thenBy
{ it.status == Attendees.ATTENDEE_STATUS_TENTATIVE }.thenBy
{ it.status })
mAttendees.reverse()
runOnUiThread {
mAttendees.forEach {
val attendee = it
val deviceContact = mAvailableContacts.firstOrNull { it.email.isNotEmpty() && it.email == attendee.email && it.photoUri.isNotEmpty() }
if (deviceContact != null) {
attendee.photoUri = deviceContact.photoUri
}
addAttendee(attendee)
}
addAttendee()
val imageHeight = event_repetition_image.height
if (imageHeight > 0) {
event_attendees_image.layoutParams.height = imageHeight
} else {
event_repetition_image.onGlobalLayout {
event_attendees_image.layoutParams.height = event_repetition_image.height
}
}
}
}
private fun addAttendee(attendee: Attendee? = null) {
val attendeeHolder = layoutInflater.inflate(R.layout.item_attendee, event_attendees_holder, false) as RelativeLayout
val autoCompleteView = attendeeHolder.event_attendee
val selectedAttendeeHolder = attendeeHolder.event_contact_attendee
val selectedAttendeeDismiss = attendeeHolder.event_contact_dismiss
mAttendeeAutoCompleteViews.add(autoCompleteView)
autoCompleteView.onTextChangeListener {
if (mWasContactsPermissionChecked) {
checkNewAttendeeField()
} else {
handlePermission(PERMISSION_READ_CONTACTS) {
checkNewAttendeeField()
mWasContactsPermissionChecked = true
}
}
}
event_attendees_holder.addView(attendeeHolder)
val textColor = getProperTextColor()
autoCompleteView.setColors(textColor, getProperPrimaryColor(), getProperBackgroundColor())
selectedAttendeeHolder.event_contact_name.setColors(textColor, getProperPrimaryColor(), getProperBackgroundColor())
selectedAttendeeHolder.event_contact_me_status.setColors(textColor, getProperPrimaryColor(), getProperBackgroundColor())
selectedAttendeeDismiss.applyColorFilter(textColor)
selectedAttendeeDismiss.setOnClickListener {
attendeeHolder.beGone()
mSelectedContacts = mSelectedContacts.filter { it.toString() != selectedAttendeeDismiss.tag }.toMutableList() as ArrayList<Attendee>
}
val adapter = AutoCompleteTextViewAdapter(this, mAvailableContacts)
autoCompleteView.setAdapter(adapter)
autoCompleteView.imeOptions = EditorInfo.IME_ACTION_NEXT
autoCompleteView.setOnItemClickListener { parent, view, position, id ->
val currAttendees = (autoCompleteView.adapter as AutoCompleteTextViewAdapter).resultList
val selectedAttendee = currAttendees[position]
addSelectedAttendee(selectedAttendee, autoCompleteView, selectedAttendeeHolder)
}
if (attendee != null) {
addSelectedAttendee(attendee, autoCompleteView, selectedAttendeeHolder)
}
}
private fun addSelectedAttendee(attendee: Attendee, autoCompleteView: MyAutoCompleteTextView, selectedAttendeeHolder: RelativeLayout) {
mSelectedContacts.add(attendee)
autoCompleteView.beGone()
autoCompleteView.focusSearch(View.FOCUS_DOWN)?.requestFocus()
selectedAttendeeHolder.apply {
beVisible()
val attendeeStatusBackground = resources.getDrawable(R.drawable.attendee_status_circular_background)
(attendeeStatusBackground as LayerDrawable).findDrawableByLayerId(R.id.attendee_status_circular_background)
.applyColorFilter(getProperBackgroundColor())
event_contact_status_image.apply {
background = attendeeStatusBackground
setImageDrawable(getAttendeeStatusImage(attendee))
beVisibleIf(attendee.showStatusImage())
}
event_contact_name.text = if (attendee.isMe) getString(R.string.my_status) else attendee.getPublicName()
if (attendee.isMe) {
(event_contact_name.layoutParams as RelativeLayout.LayoutParams).addRule(RelativeLayout.START_OF, event_contact_me_status.id)
}
val placeholder = BitmapDrawable(resources, SimpleContactsHelper(context).getContactLetterIcon(event_contact_name.value))
event_contact_image.apply {
attendee.updateImage(this@EventActivity, this, placeholder)
beVisible()
}
event_contact_dismiss.apply {
tag = attendee.toString()
beGoneIf(attendee.isMe)
}
if (attendee.isMe) {
updateAttendeeMe(this, attendee)
}
event_contact_me_status.apply {
beVisibleIf(attendee.isMe)
}
if (attendee.isMe) {
event_contact_attendee.setOnClickListener {
val items = arrayListOf(
RadioItem(Attendees.ATTENDEE_STATUS_ACCEPTED, getString(R.string.going)),
RadioItem(Attendees.ATTENDEE_STATUS_DECLINED, getString(R.string.not_going)),
RadioItem(Attendees.ATTENDEE_STATUS_TENTATIVE, getString(R.string.maybe_going))
)
RadioGroupDialog(this@EventActivity, items, attendee.status) {
attendee.status = it as Int
updateAttendeeMe(this, attendee)
}
}
}
}
}
private fun getAttendeeStatusImage(attendee: Attendee): Drawable {
return resources.getDrawable(
when (attendee.status) {
Attendees.ATTENDEE_STATUS_ACCEPTED -> R.drawable.ic_check_green
Attendees.ATTENDEE_STATUS_DECLINED -> R.drawable.ic_cross_red
else -> R.drawable.ic_question_yellow
}
)
}
private fun updateAttendeeMe(holder: RelativeLayout, attendee: Attendee) {
holder.apply {
event_contact_me_status.text = getString(
when (attendee.status) {
Attendees.ATTENDEE_STATUS_ACCEPTED -> R.string.going
Attendees.ATTENDEE_STATUS_DECLINED -> R.string.not_going
Attendees.ATTENDEE_STATUS_TENTATIVE -> R.string.maybe_going
else -> R.string.invited
}
)
event_contact_status_image.apply {
beVisibleIf(attendee.showStatusImage())
setImageDrawable(getAttendeeStatusImage(attendee))
}
mAttendees.firstOrNull { it.isMe }?.status = attendee.status
}
}
private fun checkNewAttendeeField() {
if (mAttendeeAutoCompleteViews.none { it.isVisible() && it.value.isEmpty() }) {
addAttendee()
}
}
private fun getAllAttendees(isSavingEvent: Boolean): String {
var attendees = ArrayList<Attendee>()
mSelectedContacts.forEach {
attendees.add(it)
}
val customEmails = mAttendeeAutoCompleteViews.filter { it.isVisible() }.map { it.value }.filter { it.isNotEmpty() }.toMutableList() as ArrayList<String>
customEmails.mapTo(attendees) {
Attendee(0, "", it, Attendees.ATTENDEE_STATUS_INVITED, "", false, Attendees.RELATIONSHIP_NONE)
}
attendees = attendees.distinctBy { it.email }.toMutableList() as ArrayList<Attendee>
if (mEvent.id == null && isSavingEvent && attendees.isNotEmpty()) {
val currentCalendar = calDAVHelper.getCalDAVCalendars("", true).firstOrNull { it.id == mEventCalendarId }
mAvailableContacts.firstOrNull { it.email == currentCalendar?.accountName }?.apply {
attendees = attendees.filter { it.email != currentCalendar?.accountName }.toMutableList() as ArrayList<Attendee>
status = Attendees.ATTENDEE_STATUS_ACCEPTED
relationship = Attendees.RELATIONSHIP_ORGANIZER
attendees.add(this)
}
}
return Gson().toJson(attendees)
}
private fun getNames(): List<Attendee> {
val contacts = ArrayList<Attendee>()
val uri = Data.CONTENT_URI
val projection = arrayOf(
Data.CONTACT_ID,
StructuredName.PREFIX,
StructuredName.GIVEN_NAME,
StructuredName.MIDDLE_NAME,
StructuredName.FAMILY_NAME,
StructuredName.SUFFIX,
StructuredName.PHOTO_THUMBNAIL_URI
)
val selection = "${Data.MIMETYPE} = ?"
val selectionArgs = arrayOf(StructuredName.CONTENT_ITEM_TYPE)
queryCursor(uri, projection, selection, selectionArgs) { cursor ->
val id = cursor.getIntValue(Data.CONTACT_ID)
val prefix = cursor.getStringValue(StructuredName.PREFIX) ?: ""
val firstName = cursor.getStringValue(StructuredName.GIVEN_NAME) ?: ""
val middleName = cursor.getStringValue(StructuredName.MIDDLE_NAME) ?: ""
val surname = cursor.getStringValue(StructuredName.FAMILY_NAME) ?: ""
val suffix = cursor.getStringValue(StructuredName.SUFFIX) ?: ""
val photoUri = cursor.getStringValue(StructuredName.PHOTO_THUMBNAIL_URI) ?: ""
val names = arrayListOf(prefix, firstName, middleName, surname, suffix).filter { it.trim().isNotEmpty() }
val fullName = TextUtils.join(" ", names).trim()
if (fullName.isNotEmpty() || photoUri.isNotEmpty()) {
val contact = Attendee(id, fullName, "", Attendees.ATTENDEE_STATUS_NONE, photoUri, false, Attendees.RELATIONSHIP_NONE)
contacts.add(contact)
}
}
return contacts
}
private fun getEmails(): ArrayList<Attendee> {
val contacts = ArrayList<Attendee>()
val uri = CommonDataKinds.Email.CONTENT_URI
val projection = arrayOf(
Data.CONTACT_ID,
CommonDataKinds.Email.DATA
)
queryCursor(uri, projection) { cursor ->
val id = cursor.getIntValue(Data.CONTACT_ID)
val email = cursor.getStringValue(CommonDataKinds.Email.DATA) ?: return@queryCursor
val contact = Attendee(id, "", email, Attendees.ATTENDEE_STATUS_NONE, "", false, Attendees.RELATIONSHIP_NONE)
contacts.add(contact)
}
return contacts
}
private fun updateIconColors() {
event_show_on_map.applyColorFilter(getProperPrimaryColor())
val textColor = getProperTextColor()
arrayOf(
event_time_image, event_time_zone_image, event_repetition_image, event_reminder_image, event_type_image, event_caldav_calendar_image,
event_reminder_1_type, event_reminder_2_type, event_reminder_3_type, event_attendees_image, event_availability_image
).forEach {
it.applyColorFilter(textColor)
}
}
private fun updateActionBarTitle() {
event_toolbar.title = if (mIsNewEvent) {
getString(R.string.new_event)
} else {
getString(R.string.edit_event)
}
}
}
| gpl-3.0 | 982ac5be84f2e1e5c41a03fb8186d814 | 38.694205 | 170 | 0.615939 | 4.797656 | false | false | false | false |
GunoH/intellij-community | platform/lang-impl/src/com/intellij/ide/navbar/ide/NavBarVmItem.kt | 2 | 1207 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ide.navbar.ide
import com.intellij.ide.navbar.NavBarItem
import com.intellij.ide.navbar.NavBarItemPresentation
import com.intellij.ide.navbar.vm.NavBarPopupItem
import com.intellij.model.Pointer
internal class NavBarVmItem(
val pointer: Pointer<out NavBarItem>,
override val presentation: NavBarItemPresentation,
val isModuleContentRoot: Boolean,
itemClass: Class<NavBarItem>,
) : NavBarPopupItem {
// Synthetic string field for fast equality heuristics
// Used to match element's direct child in the navbar with the same child in its popup
private val texts = itemClass.canonicalName + "$" +
presentation.text.replace("$", "$$") + "$" +
presentation.popupText?.replace("$", "$$")
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as NavBarVmItem
return texts == other.texts
}
override fun hashCode(): Int {
return texts.hashCode()
}
override fun toString(): String {
return texts
}
}
| apache-2.0 | 2936e9d262b0b809c91bb2c875d68e91 | 32.527778 | 120 | 0.706711 | 4.405109 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/code-insight/line-markers/testData/recursive/extensionReceiver.kt | 2 | 580 | fun Any.foo(other: Any) {
<lineMarker text="Recursive call">foo</lineMarker>(1)
"".<lineMarker text="Recursive call">foo</lineMarker>(1)
this.<lineMarker text="Recursive call">foo</lineMarker>(1)
<lineMarker text="Recursive call">foo(1).foo</lineMarker>(2)
with(other) {
<lineMarker text="Recursive call">foo</lineMarker>(other)
this.<lineMarker text="Recursive call">foo</lineMarker>(other)
<lineMarker text="Recursive call">foo</lineMarker>(this@foo)
this@foo.<lineMarker text="Recursive call">foo</lineMarker>(other)
}
} | apache-2.0 | eb443d45ef729134270fe6556143bdb9 | 43.692308 | 74 | 0.674138 | 4.055944 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/SetterBackingFieldAssignmentInspection.kt | 2 | 4334 | // 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.inspections
import com.intellij.codeInspection.*
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElementVisitor
import com.intellij.psi.PsiWhiteSpace
import org.jetbrains.kotlin.descriptors.PropertyDescriptor
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType
import org.jetbrains.kotlin.psi.psiUtil.siblings
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall
class SetterBackingFieldAssignmentInspection : AbstractKotlinInspection(), CleanupLocalInspectionTool {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession): PsiElementVisitor =
propertyAccessorVisitor(fun(accessor) {
if (!accessor.isSetter) return
val bodyExpression = accessor.bodyBlockExpression ?: return
val property = accessor.property
val propertyContext = property.analyze()
val propertyDescriptor = propertyContext[BindingContext.DECLARATION_TO_DESCRIPTOR, property] as? PropertyDescriptor ?: return
if (propertyContext[BindingContext.BACKING_FIELD_REQUIRED, propertyDescriptor] == false) return
val accessorContext by lazy { accessor.analyze() }
val parameter = accessor.valueParameters.singleOrNull()
if (bodyExpression.anyDescendantOfType<KtExpression> {
when (it) {
is KtBinaryExpression ->
it.left.isBackingFieldReference(property) && it.operationToken in assignmentOperators
is KtUnaryExpression ->
it.baseExpression.isBackingFieldReference(property) && it.operationToken in incrementAndDecrementOperators
is KtCallExpression -> {
it.valueArguments.any { arg ->
val argumentResultingDescriptor = arg.getArgumentExpression()
.getResolvedCall(accessorContext)
?.resultingDescriptor
argumentResultingDescriptor != null && argumentResultingDescriptor == accessorContext[BindingContext.VALUE_PARAMETER, parameter]
}
}
else -> false
}
}) return
holder.registerProblem(
accessor,
KotlinBundle.message("existing.backing.field.is.not.assigned.by.the.setter"),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
AssignBackingFieldFix()
)
})
private fun KtExpression?.isBackingFieldReference(property: KtProperty) = with(SuspiciousVarPropertyInspection) {
this@isBackingFieldReference != null && isBackingFieldReference(property)
}
}
private val assignmentOperators = listOf(KtTokens.EQ, KtTokens.PLUSEQ, KtTokens.MINUSEQ, KtTokens.MULTEQ, KtTokens.DIVEQ, KtTokens.PERCEQ)
private val incrementAndDecrementOperators = listOf(KtTokens.PLUSPLUS, KtTokens.MINUSMINUS)
private class AssignBackingFieldFix : LocalQuickFix {
override fun getName() = KotlinBundle.message("assign.backing.field.fix.text")
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val setter = descriptor.psiElement as? KtPropertyAccessor ?: return
val parameter = setter.valueParameters.firstOrNull() ?: return
val bodyExpression = setter.bodyBlockExpression ?: return
bodyExpression.lBrace
?.siblings(withItself = false)
?.takeWhile { it != bodyExpression.rBrace }
?.singleOrNull { it is PsiWhiteSpace }
?.also { it.delete() }
bodyExpression.addBefore(KtPsiFactory(setter).createExpression("field = ${parameter.name}"), bodyExpression.rBrace)
}
} | apache-2.0 | e4f52b4517e862b568e0ae53abd17c21 | 50 | 160 | 0.679972 | 5.740397 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/gradle/gradle-tooling/src/org/jetbrains/kotlin/idea/gradleTooling/arguments/CompilerArgumentsCachingManager.kt | 2 | 2679 | // 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.gradleTooling.arguments
import org.jetbrains.kotlin.idea.projectModel.CompilerArgumentsCacheMapper
import org.jetbrains.kotlin.idea.projectModel.KotlinCachedCompilerArgument
import java.io.File
object CompilerArgumentsCachingManager {
@Suppress("UNCHECKED_CAST")
internal fun <TArg> cacheCompilerArgument(
argument: TArg,
mapper: CompilerArgumentsCacheMapper
): KotlinCachedCompilerArgument<*> =
when {
argument == null -> KotlinCachedEmptyCompilerArgument
argument is String -> REGULAR_ARGUMENT_CACHING_STRATEGY.cacheArgument(argument, mapper)
argument is Boolean -> BOOLEAN_ARGUMENT_CACHING_STRATEGY.cacheArgument(argument, mapper)
argument is Array<*> -> MULTIPLE_ARGUMENT_CACHING_STRATEGY.cacheArgument(argument as Array<String>, mapper)
else -> error("Unknown argument received" + argument.let { ": ${it::class.java.name}" })
}
private interface CompilerArgumentCachingStrategy<TArg, TCached> {
fun cacheArgument(argument: TArg, mapper: CompilerArgumentsCacheMapper): TCached
}
private val BOOLEAN_ARGUMENT_CACHING_STRATEGY = object : CompilerArgumentCachingStrategy<Boolean, KotlinCachedBooleanCompilerArgument> {
override fun cacheArgument(argument: Boolean, mapper: CompilerArgumentsCacheMapper): KotlinCachedBooleanCompilerArgument {
val argStr = argument.toString()
val id = mapper.cacheArgument(argStr)
return KotlinCachedBooleanCompilerArgument(id)
}
}
private val REGULAR_ARGUMENT_CACHING_STRATEGY = object : CompilerArgumentCachingStrategy<String, KotlinCachedRegularCompilerArgument> {
override fun cacheArgument(argument: String, mapper: CompilerArgumentsCacheMapper): KotlinCachedRegularCompilerArgument {
val id = mapper.cacheArgument(argument)
return KotlinCachedRegularCompilerArgument(id)
}
}
private val MULTIPLE_ARGUMENT_CACHING_STRATEGY =
object : CompilerArgumentCachingStrategy<Array<String>, KotlinCachedMultipleCompilerArgument> {
override fun cacheArgument(
argument: Array<String>,
mapper: CompilerArgumentsCacheMapper
): KotlinCachedMultipleCompilerArgument {
val cachedArguments = argument.map { cacheCompilerArgument(it, mapper) }
return KotlinCachedMultipleCompilerArgument(cachedArguments)
}
}
}
| apache-2.0 | e3100ff0425c377b2cdf80c9a93a8210 | 50.519231 | 158 | 0.723778 | 5.212062 | false | false | false | false |
mglukhikh/intellij-community | uast/uast-java/src/org/jetbrains/uast/java/expressions/JavaUAnnotationCallExpression.kt | 2 | 1952 | /*
* Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
*/
package org.jetbrains.uast.java.expressions
import com.intellij.psi.PsiAnnotation
import com.intellij.psi.PsiType
import org.jetbrains.uast.*
import org.jetbrains.uast.java.JavaAbstractUExpression
import org.jetbrains.uast.java.JavaConverter
import org.jetbrains.uast.java.JavaUAnnotation
import org.jetbrains.uast.java.lz
import org.jetbrains.uast.visitor.UastVisitor
class JavaUAnnotationCallExpression(
override val psi: PsiAnnotation,
givenParent: UElement?
) : JavaAbstractUExpression(givenParent), UCallExpressionEx {
val uAnnotation by lz {
JavaUAnnotation(psi, this)
}
override val returnType: PsiType?
get() = uAnnotation.qualifiedName?.let { PsiType.getTypeByName(it, psi.project, psi.resolveScope) }
override val kind: UastCallKind
get() = UastCallKind.CONSTRUCTOR_CALL
override val methodName: String?
get() = null
override val receiver: UExpression?
get() = null
override val receiverType: PsiType?
get() = null
override val methodIdentifier: UIdentifier?
get() = null
override val classReference by lz {
psi.nameReferenceElement?.let { ref ->
JavaConverter.convertReference(ref, this, null) as? UReferenceExpression
}
}
override val valueArgumentCount: Int
get() = psi.parameterList.attributes.size
override val valueArguments by lz {
uAnnotation.attributeValues
}
override fun getArgumentForParameter(i: Int): UExpression? = valueArguments.getOrNull(i)
override fun accept(visitor: UastVisitor) {
visitor.visitCallExpression(this)
uAnnotation.accept(visitor)
visitor.afterVisitCallExpression(this)
}
override val typeArgumentCount = 0
override val typeArguments: List<PsiType> = emptyList()
override fun resolve() = uAnnotation.resolve()?.constructors?.firstOrNull()
}
| apache-2.0 | d065fc7a5f7be4e9ed71d507efe1ab45 | 28.134328 | 140 | 0.758197 | 4.58216 | false | false | false | false |
sybila/terminal-components | src/main/java/com/github/sybila/main.kt | 1 | 4482 | package com.github.sybila
import com.github.sybila.checker.CheckerStats
import com.github.sybila.checker.solver.SolverStats
import com.github.sybila.ode.generator.AbstractOdeFragment
import com.github.sybila.ode.generator.rect.RectangleOdeModel
import com.github.sybila.ode.model.OdeModel
import com.github.sybila.ode.model.Parser
import com.github.sybila.ode.model.computeApproximation
import com.google.gson.Gson
import org.kohsuke.args4j.CmdLineException
import org.kohsuke.args4j.CmdLineParser
import java.io.Closeable
internal abstract class Algorithm<T: Any>(
protected val config: Config,
protected val allStates: ExplicitOdeFragment<T>,
protected val odeModel: OdeModel
) : Closeable {
abstract fun computeComponents(): ResultSet
}
fun main(args: Array<String>) {
Config().apply {
try {
val parser = CmdLineParser(this)
parser.parseArgument(*args)
if (this.help) {
parser.printUsage(System.err)
System.err.println()
return
}
} catch (e: CmdLineException) {
// if there's a problem in the command line,
// you'll get this exception. this will report
// an error message.
System.err.println(e.message)
System.err.println("terminal-components [options...]")
// print the list of available options (with fresh defaults)
CmdLineParser(Config()).printUsage(System.err)
System.err.println()
return
}
}.use { config ->
val log = config.logStream
log?.println("Loading model and computing approximation...")
SolverStats.reset(log)
CheckerStats.reset(log)
val modelFile = config.model ?: error("Missing model file.")
val odeModel = Parser().parse(modelFile).computeApproximation(
fast = config.fastApproximation, cutToRange = config.cutToRange
)
log?.println("Computing transition system...")
val result = odeModel.run {
val isRectangular = variables.all {
it.equation.map { it.paramIndex }.filter { it >= 0 }.toSet().size <= 1
}
when {
!isRectangular -> error("Multiple parameters in one equation detected. This situation is not supported.")
else -> {
log?.println("Using generic rectangular solver.")
RectangleOdeModel(this, !config.disableSelfLoops)
.makeExplicit(config).also {
log?.println("Start component analysis...")
}.runAnalysis(odeModel, config)
}
}
}
log?.println("Attractor analysis finished, printing results...")
log?.println("Found attractor counts: ${result.results.map { it.formula }}")
SolverStats.printGlobal()
CheckerStats.printGlobal()
val json = Gson()
config.resultStream?.println(json.toJson(result))
}
}
private fun <T: Any> AbstractOdeFragment<T>.makeExplicit(
config: Config
): ExplicitOdeFragment<T> {
val step = (stateCount / 100).coerceAtLeast(100)
val successors = Array(stateCount) { s ->
if (s % step == 0) config.logStream?.println("Successor progress: $s/$stateCount")
s.successors(true).asSequence().toList()
}
val predecessors = Array(stateCount) { s ->
if (s % step == 0) config.logStream?.println("Predecessor progress: $s/$stateCount")
s.predecessors(true).asSequence().toList()
}
val pivotChooser: (ExplicitOdeFragment<T>) -> PivotChooser<T> = if (config.disableHeuristic) {
{ fragment -> NaivePivotChooser(fragment) }
} else {
{ fragment -> StructureAndCardinalityPivotChooser(fragment) }
}
return ExplicitOdeFragment(this.solver, stateCount, pivotChooser, successors, predecessors)
}
private fun <T: Any> ExplicitOdeFragment<T>.runAnalysis(odeModel: OdeModel, config: Config): ResultSet {
val algorithm = if (config.algorithm == Config.AlgorithmType.LOCAL) {
LocalAlgorithm(config, this, odeModel)
} else {
DistAlgorithm(config, this, odeModel)
}
val start = System.currentTimeMillis()
return algorithm.use {
it.computeComponents().also { config.logStream?.println("Search elapsed: ${System.currentTimeMillis() - start}ms") }
}
} | gpl-3.0 | 5c28ad9058bd21c81efbadbf7d61b93b | 36.049587 | 124 | 0.629407 | 4.437624 | false | true | false | false |
fkorotkov/k8s-kotlin-dsl | DSLs/kubernetes/dsl/src/test/kotlin/com/fkorotkov/kubernetes/SimpleCompilationTest.kt | 1 | 1094 | package com.fkorotkov.kubernetes
import io.fabric8.kubernetes.api.model.IntOrString
import org.junit.Test
import kotlin.test.assertEquals
class SimpleCompilationTest {
@Test
fun testService() {
val serviceName = "test"
val myService = newService {
metadata {
name = serviceName
labels = mapOf(
"app" to serviceName,
"tier" to "backend"
)
}
spec {
type = "NodePort"
ports = listOf(
newServicePort {
name = "http"
port = 8080
targetPort = IntOrString(8080)
},
newServicePort {
name = "grcp"
port = 8239
targetPort = IntOrString(8239)
}
)
selector = mapOf(
"app" to serviceName,
"tier" to "backend"
)
}
}
assertEquals(serviceName, myService.metadata.name)
assertEquals("NodePort", myService.spec.type)
myService.apply {
metadata {
name = "foo"
}
}
assertEquals("foo", myService.metadata.name)
}
} | mit | 87107bee527b2ff7fa1915e3a8a0af6d | 21.346939 | 54 | 0.540219 | 4.358566 | false | true | false | false |
sksamuel/ktest | kotest-assertions/kotest-assertions-shared/src/commonMain/kotlin/io/kotest/assertions/MultiAssertionError.kt | 1 | 1001 | package io.kotest.assertions
import io.kotest.mpp.stacktraces
/**
* An error that bundles multiple other [Throwable]s together.
*/
class MultiAssertionError(errors: List<Throwable>) : AssertionError(createMessage(errors)) {
companion object {
internal fun createMessage(errors: List<Throwable>) = buildString {
append("\nThe following ")
if (errors.size == 1) {
append("assertion")
} else {
append(errors.size).append(" assertions")
}
append(" failed:\n")
for ((i, err) in errors.withIndex()) {
append(i + 1).append(") ").append(err.message).append("\n")
stacktraces.throwableLocation(err)?.let {
append("\tat ").append(it).append("\n")
}
}
}
}
}
fun multiAssertionError(errors: List<Throwable>): Throwable {
val message = MultiAssertionError.createMessage(errors)
return failure(message, errors.firstOrNull { it.cause != null })
}
| mit | dde4f2162ba3111ceea82943370d4607 | 29.333333 | 92 | 0.607393 | 4.352174 | false | true | false | false |
h0tk3y/better-parse | src/commonMain/kotlin/com/github/h0tk3y/betterParse/parser/Parser.kt | 1 | 3967 | package com.github.h0tk3y.betterParse.parser
import com.github.h0tk3y.betterParse.lexer.Token
import com.github.h0tk3y.betterParse.lexer.TokenMatch
import com.github.h0tk3y.betterParse.lexer.TokenMatchesSequence
/** A common interface for parsers that can try to consume a part or the whole [TokenMatch] sequence and return one of
* possible [ParseResult], either [Parsed] or [ErrorResult] */
public interface Parser<out T> {
public fun tryParse(tokens: TokenMatchesSequence, fromPosition: Int): ParseResult<T>
}
public object EmptyParser : Parser<Unit> {
override fun tryParse(tokens: TokenMatchesSequence, fromPosition: Int): ParseResult<Unit> = ParsedValue(Unit, fromPosition)
}
public fun <T> Parser<T>.tryParseToEnd(tokens: TokenMatchesSequence, position: Int): ParseResult<T> {
val result = tryParse(tokens, position)
return when (result) {
is ErrorResult -> result
is Parsed -> tokens.getNotIgnored(result.nextPosition)?.let {
UnparsedRemainder(it)
} ?: result
}
}
public fun <T> Parser<T>.parse(tokens: TokenMatchesSequence): T = tryParse(tokens, 0).toParsedOrThrow().value
public fun <T> Parser<T>.parseToEnd(tokens: TokenMatchesSequence): T = tryParseToEnd(tokens, 0).toParsedOrThrow().value
/** Represents a result of input sequence parsing by a [Parser] that tried to parse [T]. */
public sealed class ParseResult<out T>
/** Represents a successful parsing result of a [Parser] that produced [value]
* and left input starting with [nextPosition] unprocessed. */
public abstract class Parsed<out T> : ParseResult<T>() {
public abstract val value: T
public abstract val nextPosition: Int
override fun toString(): String = "Parsed($value)"
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || this::class != other::class) return false
other as Parsed<*>
if (value != other.value) return false
if (nextPosition != other.nextPosition) return false
return true
}
override fun hashCode(): Int {
var result = value?.hashCode() ?: 0
result = 31 * result + nextPosition
return result
}
}
internal class ParsedValue<out T>(override val value: T, override val nextPosition : Int) : Parsed<T>()
/** Represents a parse error of a [Parser] that could not successfully parse an input sequence. */
public abstract class ErrorResult : ParseResult<Nothing>() {
override fun toString(): String = "ErrorResult"
}
/** A [startsWith] token was found where the end of the input sequence was expected during
* [tryParseToEnd] or [parseToEnd]. */
public data class UnparsedRemainder(val startsWith: TokenMatch) : ErrorResult()
/** A token was [found] where another type of token was [expected]. */
public data class MismatchedToken(val expected: Token, val found: TokenMatch) : ErrorResult()
/** A lexer could not match the input sequence with any token known to it. Contains [tokenMismatch] with special type */
public data class NoMatchingToken(val tokenMismatch: TokenMatch) : ErrorResult()
/** An end of the input sequence was encountered where a token was [expected]. */
public data class UnexpectedEof(val expected: Token) : ErrorResult()
/** A parser tried several alternatives but all resulted into [errors]. */
public data class AlternativesFailure(val errors: List<ErrorResult>) : ErrorResult()
/** Thrown when a [Parser] is forced to parse a sequence with [parseToEnd] or [parse] and fails with an [ErrorResult]. */
public class ParseException(@Suppress("CanBeParameter") public val errorResult: ErrorResult)
: Exception("Could not parse input: $errorResult")
/** Throws [ParseException] if the receiver [ParseResult] is a [ErrorResult]. Returns the [Parsed] result otherwise. */
public fun <T> ParseResult<T>.toParsedOrThrow(): Parsed<T> = when (this) {
is Parsed -> this
is ErrorResult -> throw ParseException(this)
} | apache-2.0 | 89d15aeadae226f0e76cc194908ae931 | 41.666667 | 127 | 0.721452 | 4.220213 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.