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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
robinverduijn/gradle | subprojects/kotlin-dsl/src/integTest/kotlin/org/gradle/kotlin/dsl/integration/LocationAwareScriptEvaluationIntegrationTest.kt | 1 | 4970 | package org.gradle.kotlin.dsl.integration
import org.gradle.kotlin.dsl.fixtures.AbstractKotlinIntegrationTest
import org.gradle.kotlin.dsl.fixtures.containsMultiLineString
import org.junit.Assert.assertThat
import org.junit.Test
class LocationAwareScriptEvaluationIntegrationTest : AbstractKotlinIntegrationTest() {
private
val boom = """throw InternalError("BOOM!")"""
@Test
fun `location of exception thrown from build script is reported`() {
withSettings("""include("a")""")
val script = withBuildScriptIn("a", boom)
assertFailingBuildOutputOf("help") {
"""
* Where:
Build file '${script.canonicalPath}' line: 1
"""
}
}
@Test
fun `location of exception thrown from applied script is reported`() {
withBuildScript("""apply(from = "other.gradle.kts")""")
val script = withFile("other.gradle.kts", boom)
assertFailingBuildOutputOf("help") {
"""
* Where:
Script '${script.canonicalPath}' line: 1
"""
}
}
@Test
fun `location of exception thrown from applied script with same filename is reported`() {
withBuildScript("""apply(from = "other/build.gradle.kts")""")
val script = withFile("other/build.gradle.kts", boom)
assertFailingBuildOutputOf("help") {
"""
* Where:
Script '${script.canonicalPath}' line: 1
"""
}
}
@Test
fun `location of exception thrown from buildscript block is reported`() {
val script = withBuildScript("buildscript { $boom }")
assertFailingBuildOutputOf("help") {
"""
* Where:
Build file '${script.canonicalPath}' line: 1
"""
}
}
@Test
fun `location of exception thrown from plugins block is reported`() {
val script = withBuildScript("plugins { $boom }")
assertFailingBuildOutputOf("help") {
"""
* Where:
Build file '${script.canonicalPath}' line: 1
"""
}
}
@Test
fun `location of exception thrown from settings script is reported`() {
val script = withSettings(boom)
assertFailingBuildOutputOf("help") {
"""
* Where:
Settings file '${script.canonicalPath}' line: 1
"""
}
}
@Test
fun `location of exception thrown from initialization script is reported`() {
val script = withFile("my.init.gradle.kts", boom)
assertFailingBuildOutputOf("help", "-I", script.absolutePath) {
"""
* Where:
Initialization script '${script.canonicalPath}' line: 1
"""
}
}
@Test
fun `location of missing script application is reported`() {
withBuildScript("""apply(from = "present.gradle.kts")""")
val present = withFile("present.gradle.kts", """apply(from = "absent.gradle.kts")""")
assertFailingBuildOutputOf("help") {
"""
* Where:
Script '${present.canonicalPath}' line: 1
* What went wrong:
Could not read script '${existing("absent.gradle.kts").canonicalPath}' as it does not exist.
"""
}
}
@Test
fun `location of exception thrown by kotlin script applied from groovy script is reported`() {
withFile("build.gradle", "apply from: 'other.gradle.kts'")
val script = withFile("other.gradle.kts", """
println("In Kotlin Script")
$boom
""")
assertFailingBuildOutputOf("help") {
"""
* Where:
Script '${script.canonicalPath}' line: 3
"""
}
}
/**
* This is a caveat.
* The Groovy DSL provider relies on exceptions being analyzed up the stack.
* See [org.gradle.initialization.DefaultExceptionAnalyser.transform], note the comments.
* The Kotlin DSL provider handles this in isolation,
* thus hiding the location of exceptions thrown by groovy scripts applied from kotlin scripts.
*
* This test exercises the current behavior.
*/
@Test
fun `location of exception thrown by groovy script applied from kotlin script shadowed by the kotlin location`() {
val kotlinScript = withBuildScript("""apply(from = "other.gradle")""")
withFile("other.gradle", """
println("In Groovy Script")
throw new InternalError("BOOM!")
""")
assertFailingBuildOutputOf("help") {
"""
* Where:
Build file '${kotlinScript.canonicalPath}' line: 1
"""
}
}
private
fun assertFailingBuildOutputOf(vararg arguments: String, string: () -> String) =
assertThat(buildAndFail(*arguments).error, containsMultiLineString(string()))
}
| apache-2.0 | e93a8605cf9d26b1617713f5310de9d3 | 27.895349 | 118 | 0.57505 | 5.025278 | false | true | false | false |
mozilla-mobile/focus-android | app/src/androidTest/java/org/mozilla/focus/activity/ErrorPagesTest.kt | 1 | 1916 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.focus.activity
import androidx.test.internal.runner.junit4.AndroidJUnit4ClassRunner
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.mozilla.focus.R
import org.mozilla.focus.activity.robots.searchScreen
import org.mozilla.focus.helpers.FeatureSettingsHelper
import org.mozilla.focus.helpers.MainActivityFirstrunTestRule
import org.mozilla.focus.helpers.TestHelper.getStringResource
import org.mozilla.focus.helpers.TestHelper.setNetworkEnabled
// This tests verify invalid URL and no network connection error pages
@RunWith(AndroidJUnit4ClassRunner::class)
class ErrorPagesTest {
private val featureSettingsHelper = FeatureSettingsHelper()
@get: Rule
val mActivityTestRule = MainActivityFirstrunTestRule(showFirstRun = false)
@Before
fun setUp() {
featureSettingsHelper.setCfrForTrackingProtectionEnabled(false)
}
@After
fun tearDown() {
featureSettingsHelper.resetAllFeatureFlags()
}
@Test
fun badURLCheckTest() {
val badURl = "bad.url"
searchScreen {
}.loadPage(badURl) {
verifyPageContent(getStringResource(R.string.mozac_browser_errorpages_unknown_host_title))
verifyPageContent("Try Again")
}
}
@Test
fun noNetworkConnectionErrorPageTest() {
val pageUrl = "mozilla.org"
setNetworkEnabled(false)
searchScreen {
}.loadPage(pageUrl) {
verifyPageContent(getStringResource(R.string.mozac_browser_errorpages_unknown_host_title))
verifyPageContent("Try Again")
setNetworkEnabled(true)
}
}
}
| mpl-2.0 | 98d279cf24270bb3e59236aec45069cb | 30.933333 | 102 | 0.72547 | 4.4662 | false | true | false | false |
f-droid/fdroidclient | libs/database/src/main/java/org/fdroid/database/Version.kt | 1 | 7973 | package org.fdroid.database
import androidx.core.os.LocaleListCompat
import androidx.room.DatabaseView
import androidx.room.Embedded
import androidx.room.Entity
import androidx.room.ForeignKey
import androidx.room.Relation
import org.fdroid.LocaleChooser.getBestLocale
import org.fdroid.database.VersionedStringType.PERMISSION
import org.fdroid.database.VersionedStringType.PERMISSION_SDK_23
import org.fdroid.index.v2.ANTI_FEATURE_KNOWN_VULNERABILITY
import org.fdroid.index.v2.FileV1
import org.fdroid.index.v2.FileV2
import org.fdroid.index.v2.LocalizedTextV2
import org.fdroid.index.v2.ManifestV2
import org.fdroid.index.v2.PackageManifest
import org.fdroid.index.v2.PackageVersion
import org.fdroid.index.v2.PackageVersionV2
import org.fdroid.index.v2.PermissionV2
import org.fdroid.index.v2.SignerV2
import org.fdroid.index.v2.UsesSdkV2
/**
* A database table entity representing the version of an [App]
* identified by its [versionCode] and [signer].
* This holds the data of [PackageVersionV2].
*/
@Entity(
tableName = Version.TABLE,
primaryKeys = ["repoId", "packageName", "versionId"],
foreignKeys = [ForeignKey(
entity = AppMetadata::class,
parentColumns = ["repoId", "packageName"],
childColumns = ["repoId", "packageName"],
onDelete = ForeignKey.CASCADE,
)],
)
internal data class Version(
val repoId: Long,
val packageName: String,
val versionId: String,
val added: Long,
@Embedded(prefix = "file_") val file: FileV1,
@Embedded(prefix = "src_") val src: FileV2? = null,
@Embedded(prefix = "manifest_") val manifest: AppManifest,
override val releaseChannels: List<String>? = emptyList(),
val antiFeatures: Map<String, LocalizedTextV2>? = null,
val whatsNew: LocalizedTextV2? = null,
val isCompatible: Boolean,
) : PackageVersion {
internal companion object {
const val TABLE = "Version"
}
override val versionCode: Long get() = manifest.versionCode
override val signer: SignerV2? get() = manifest.signer
override val packageManifest: PackageManifest get() = manifest
override val hasKnownVulnerability: Boolean
get() = antiFeatures?.contains(ANTI_FEATURE_KNOWN_VULNERABILITY) == true
internal fun toAppVersion(versionedStrings: List<VersionedString>): AppVersion = AppVersion(
version = this,
versionedStrings = versionedStrings,
)
}
internal fun PackageVersionV2.toVersion(
repoId: Long,
packageName: String,
versionId: String,
isCompatible: Boolean,
) = Version(
repoId = repoId,
packageName = packageName,
versionId = versionId,
added = added,
file = file,
src = src,
manifest = manifest.toManifest(),
releaseChannels = releaseChannels,
antiFeatures = antiFeatures,
whatsNew = whatsNew,
isCompatible = isCompatible,
)
/**
* A version of an [App] identified by [AppManifest.versionCode] and [AppManifest.signer].
*/
public data class AppVersion internal constructor(
@Embedded internal val version: Version,
@Relation(
parentColumn = "versionId",
entityColumn = "versionId",
)
internal val versionedStrings: List<VersionedString>?,
) {
public val repoId: Long get() = version.repoId
public val packageName: String get() = version.packageName
public val added: Long get() = version.added
public val isCompatible: Boolean get() = version.isCompatible
public val manifest: AppManifest get() = version.manifest
public val file: FileV1 get() = version.file
public val src: FileV2? get() = version.src
public val usesPermission: List<PermissionV2>
get() = versionedStrings?.getPermissions(version) ?: emptyList()
public val usesPermissionSdk23: List<PermissionV2>
get() = versionedStrings?.getPermissionsSdk23(version) ?: emptyList()
public val featureNames: List<String> get() = version.manifest.features ?: emptyList()
public val nativeCode: List<String> get() = version.manifest.nativecode ?: emptyList()
public val releaseChannels: List<String> get() = version.releaseChannels ?: emptyList()
public val antiFeatureKeys: List<String>
get() = version.antiFeatures?.map { it.key } ?: emptyList()
public fun getWhatsNew(localeList: LocaleListCompat): String? =
version.whatsNew.getBestLocale(localeList)
public fun getAntiFeatureReason(antiFeatureKey: String, localeList: LocaleListCompat): String? {
return version.antiFeatures?.get(antiFeatureKey)?.getBestLocale(localeList)
}
}
/**
* The manifest information of an [AppVersion].
*/
public data class AppManifest(
public val versionName: String,
public val versionCode: Long,
@Embedded(prefix = "usesSdk_") public val usesSdk: UsesSdkV2? = null,
public override val maxSdkVersion: Int? = null,
@Embedded(prefix = "signer_") public val signer: SignerV2? = null,
public override val nativecode: List<String>? = emptyList(),
public val features: List<String>? = emptyList(),
) : PackageManifest {
public override val minSdkVersion: Int? get() = usesSdk?.minSdkVersion
public override val featureNames: List<String>? get() = features
}
internal fun ManifestV2.toManifest() = AppManifest(
versionName = versionName,
versionCode = versionCode,
usesSdk = usesSdk,
maxSdkVersion = maxSdkVersion,
signer = signer,
nativecode = nativecode,
features = features.map { it.name },
)
@DatabaseView(viewName = HighestVersion.TABLE,
value = """SELECT repoId, packageName, antiFeatures FROM ${Version.TABLE}
GROUP BY repoId, packageName HAVING MAX(manifest_versionCode)""")
internal class HighestVersion(
val repoId: Long,
val packageName: String,
val antiFeatures: Map<String, LocalizedTextV2>? = null,
) {
internal companion object {
const val TABLE = "HighestVersion"
}
}
internal enum class VersionedStringType {
PERMISSION,
PERMISSION_SDK_23,
}
@Entity(
tableName = VersionedString.TABLE,
primaryKeys = ["repoId", "packageName", "versionId", "type", "name"],
foreignKeys = [ForeignKey(
entity = Version::class,
parentColumns = ["repoId", "packageName", "versionId"],
childColumns = ["repoId", "packageName", "versionId"],
onDelete = ForeignKey.CASCADE,
)],
)
internal data class VersionedString(
val repoId: Long,
val packageName: String,
val versionId: String,
val type: VersionedStringType,
val name: String,
val version: Int? = null,
) {
internal companion object {
const val TABLE = "VersionedString"
}
}
internal fun List<PermissionV2>.toVersionedString(
version: Version,
type: VersionedStringType,
) = map { permission ->
VersionedString(
repoId = version.repoId,
packageName = version.packageName,
versionId = version.versionId,
type = type,
name = permission.name,
version = permission.maxSdkVersion,
)
}
internal fun ManifestV2.getVersionedStrings(version: Version): List<VersionedString> {
return usesPermission.toVersionedString(version, PERMISSION) +
usesPermissionSdk23.toVersionedString(version, PERMISSION_SDK_23)
}
internal fun List<VersionedString>.getPermissions(version: Version) = mapNotNull { v ->
v.map(version, PERMISSION) {
PermissionV2(
name = v.name,
maxSdkVersion = v.version,
)
}
}
internal fun List<VersionedString>.getPermissionsSdk23(version: Version) = mapNotNull { v ->
v.map(version, PERMISSION_SDK_23) {
PermissionV2(
name = v.name,
maxSdkVersion = v.version,
)
}
}
private fun <T> VersionedString.map(
v: Version,
wantedType: VersionedStringType,
factory: () -> T,
): T? {
return if (repoId != v.repoId || packageName != v.packageName || versionId != v.versionId ||
type != wantedType
) null
else factory()
}
| gpl-3.0 | 21e0d914216cc81d5aa042470bc154b1 | 32.783898 | 100 | 0.697981 | 4.137519 | false | false | false | false |
toastkidjp/Jitte | app/src/main/java/jp/toastkid/yobidashi/barcode/BarcodeReaderFragment.kt | 1 | 10202 | /*
* Copyright (c) 2019 toastkidjp.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompany this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html.
*/
package jp.toastkid.yobidashi.barcode
import android.Manifest
import android.annotation.SuppressLint
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.Rect
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 androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.LayoutRes
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.google.zxing.ResultPoint
import com.journeyapps.barcodescanner.BarcodeCallback
import com.journeyapps.barcodescanner.BarcodeResult
import com.journeyapps.barcodescanner.SourceData
import com.journeyapps.barcodescanner.camera.PreviewCallback
import jp.toastkid.lib.ContentViewModel
import jp.toastkid.lib.intent.ShareIntentFactory
import jp.toastkid.lib.preference.PreferenceApplier
import jp.toastkid.lib.storage.ExternalFileAssignment
import jp.toastkid.lib.view.DraggableTouchListener
import jp.toastkid.lib.window.WindowRectCalculatorCompat
import jp.toastkid.search.SearchCategory
import jp.toastkid.yobidashi.R
import jp.toastkid.yobidashi.databinding.FragmentBarcodeReaderBinding
import jp.toastkid.yobidashi.libs.clip.Clipboard
import jp.toastkid.yobidashi.search.SearchAction
import timber.log.Timber
import java.io.FileOutputStream
/**
* Barcode reader function fragment.
*
* @author toastkidjp
*/
class BarcodeReaderFragment : Fragment() {
/**
* Data Binding object.
*/
private var binding: FragmentBarcodeReaderBinding? = null
private var viewModel: BarcodeReaderResultPopupViewModel? = null
/**
* Preferences wrapper.
*/
private lateinit var preferenceApplier: PreferenceApplier
/**
* For showing barcode reader result.
*/
private lateinit var resultPopup: BarcodeReaderResultPopup
private var contentViewModel: ContentViewModel? = null
private val cameraPermissionRequestLauncher =
registerForActivityResult(ActivityResultContracts.RequestPermission()) {
if (it) {
startDecode()
return@registerForActivityResult
}
contentViewModel?.snackShort(R.string.message_requires_permission_camera)
parentFragmentManager.popBackStack()
}
private val storagePermissionRequestLauncher =
registerForActivityResult(ActivityResultContracts.RequestPermission()) {
if (it) {
invokeRequest()
return@registerForActivityResult
}
contentViewModel?.snackShort(R.string.message_requires_permission_storage)
}
/**
* Required permission for this fragment(and function).
*/
private val permission = Manifest.permission.CAMERA
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = DataBindingUtil.inflate(inflater, LAYOUT_ID, container, false)
val context = binding?.root?.context ?: return binding?.root
resultPopup = BarcodeReaderResultPopup(context)
return binding?.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
preferenceApplier = PreferenceApplier(view.context)
binding?.fragment = this
if (isNotGranted()) {
cameraPermissionRequestLauncher.launch(permission)
}
viewModel = ViewModelProvider(this).get(BarcodeReaderResultPopupViewModel::class.java)
viewModel?.also {
val viewLifecycleOwner = viewLifecycleOwner
it.clip.observe(viewLifecycleOwner, Observer { event ->
val text = event?.getContentIfNotHandled() ?: return@Observer
clip(text)
})
it.share.observe(viewLifecycleOwner, Observer { event ->
val text = event?.getContentIfNotHandled() ?: return@Observer
startActivity(ShareIntentFactory()(text))
})
it.open.observe(viewLifecycleOwner, Observer { event ->
val text = event?.getContentIfNotHandled() ?: return@Observer
val activity = activity ?: return@Observer
SearchAction(
activity,
preferenceApplier.getDefaultSearchEngine()
?: SearchCategory.getDefaultCategoryName(),
text
).invoke()
})
}
resultPopup.setViewModel(viewModel)
contentViewModel = activity?.let { ViewModelProvider(it).get(ContentViewModel::class.java) }
initializeFab()
setHasOptionsMenu(true)
if (isNotGranted()) {
return
}
startDecode()
}
/**
* Return is granted required permission.
*
* @return If is granted camera permission, return true
*/
private fun isNotGranted() =
activity?.checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
inflater.inflate(R.menu.camera, menu)
}
/**
* Invoke click menu action.
*
* @param item [MenuItem]
* @return This function always return true
*/
override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) {
R.id.reset_camera_fab_position -> {
binding?.camera?.also {
it.translationX = 0f
it.translationY = 0f
preferenceApplier.clearCameraFabPosition()
}
true
}
else -> super.onOptionsItemSelected(item)
}
@SuppressLint("ClickableViewAccessibility")
private fun initializeFab() {
val draggableTouchListener = DraggableTouchListener()
draggableTouchListener.setCallback(object : DraggableTouchListener.OnNewPosition {
override fun onNewPosition(x: Float, y: Float) {
preferenceApplier.setNewCameraFabPosition(x, y)
}
})
draggableTouchListener.setOnClick(object : DraggableTouchListener.OnClick {
override fun onClick() {
camera()
}
})
binding?.camera?.setOnTouchListener(draggableTouchListener)
binding?.camera?.also {
val position = preferenceApplier.cameraFabPosition() ?: return@also
it.animate()
.x(position.first)
.y(position.second)
.setDuration(10)
.start()
}
}
/**
* Start decode.
*/
private fun startDecode() {
binding?.barcodeView?.decodeContinuous(object : BarcodeCallback {
override fun barcodeResult(barcodeResult: BarcodeResult) {
val text = barcodeResult.text
if (text == resultPopup.currentText()) {
return
}
showResult(text)
}
override fun possibleResultPoints(list: List<ResultPoint>) = Unit
})
}
/**
* Copy result text to clipboard.
*
* @param text Result text
*/
private fun clip(text: String) {
binding?.root?.let { snackbarParent ->
Clipboard.clip(snackbarParent.context, text)
}
}
private fun camera() {
storagePermissionRequestLauncher.launch(Manifest.permission.WRITE_EXTERNAL_STORAGE)
}
private fun invokeRequest() {
val barcodeView = binding?.barcodeView ?: return
barcodeView.barcodeView?.cameraInstance?.requestPreview(object : PreviewCallback {
override fun onPreview(sourceData: SourceData?) {
val context = context ?: return
val output = ExternalFileAssignment()(
context,
"shoot_${System.currentTimeMillis()}.png"
)
sourceData?.cropRect = getRect()
val fileOutputStream = FileOutputStream(output)
sourceData?.bitmap?.compress(
Bitmap.CompressFormat.PNG,
100,
fileOutputStream
)
fileOutputStream.close()
contentViewModel?.snackShort("Camera saved: ${output.absolutePath}")
}
private fun getRect(): Rect? {
return WindowRectCalculatorCompat().invoke(activity)
}
override fun onPreviewError(e: Exception?) {
Timber.e(e)
}
})
}
/**
* Show result with snackbar.
*
* @param text [String]
*/
private fun showResult(text: String) {
binding?.root?.let { resultPopup.show(it, text) }
}
override fun onResume() {
super.onResume()
binding?.barcodeView?.resume()
val colorPair = preferenceApplier.colorPair()
resultPopup.onResume(colorPair)
colorPair.applyReverseTo(binding?.camera)
}
override fun onPause() {
super.onPause()
binding?.barcodeView?.pause()
resultPopup.hide()
}
override fun onDetach() {
storagePermissionRequestLauncher.unregister()
cameraPermissionRequestLauncher.unregister()
super.onDetach()
}
companion object {
/**
* Layout ID.
*/
@LayoutRes
private const val LAYOUT_ID = R.layout.fragment_barcode_reader
}
} | epl-1.0 | 8458531da0ba24ed24fbafad619df2da | 30.588235 | 100 | 0.633405 | 5.383641 | false | false | false | false |
ModerateFish/component | framework/src/main/java/com/thornbirds/frameworkext/component/route/RouteComponentController.kt | 1 | 2579 | package com.thornbirds.frameworkext.component.route
import android.util.Log
import com.thornbirds.component.ComponentController
import com.thornbirds.component.IEventController
import com.thornbirds.component.utils.DebugUtils
/**
* Created by yangli on 2017/11/19.
*/
internal typealias RouterController = RouteComponentController<IPageRouter<*>>
internal typealias PageEntry = IPageEntry<RouterController>
internal typealias PageCreator = IPageCreator<PageEntry>
abstract class RouteComponentController<T : IRouter<*>>(
eventController: IEventController?
) : ComponentController(eventController), IRouterController {
abstract val router: T?
abstract val parentRouter: T?
abstract fun exitRouter(): Boolean
var state = STATE_IDLE
private set
protected abstract fun onCreate()
protected abstract fun onStart()
protected abstract fun onStop()
protected abstract fun onDestroy()
protected abstract fun onBackPressed(): Boolean
fun performCreate() {
if (state == STATE_CREATED) {
return
}
if (state == STATE_IDLE) {
state = STATE_CREATED
if (DebugUtils.DEBUG) {
Log.d(TAG, "onCreate")
}
onCreate()
}
}
fun performStart() {
if (state == STATE_STARTED) {
return
}
if (state == STATE_CREATED || state == STATE_STOPPED) {
state = STATE_STARTED
if (DebugUtils.DEBUG) {
Log.d(TAG, "onStart")
}
onStart()
}
}
fun performStop() {
if (state == STATE_STOPPED) {
return
}
if (state == STATE_STARTED) {
state = STATE_STOPPED
if (DebugUtils.DEBUG) {
Log.d(TAG, "onStop")
}
onStop()
}
}
fun performDestroy() {
if (state == STATE_DESTROYED) {
return
}
if (DebugUtils.DEBUG) {
Log.d(TAG, "onDestroy")
}
state = STATE_DESTROYED
super.release()
onDestroy()
}
fun performBackPressed(): Boolean {
if (state == STATE_DESTROYED) {
return false
}
if (DebugUtils.DEBUG) {
Log.d(TAG, "onBackPressed")
}
return onBackPressed()
}
companion object {
const val STATE_IDLE = 0
const val STATE_CREATED = 1
const val STATE_STARTED = 2
const val STATE_STOPPED = 3
const val STATE_DESTROYED = 4
}
} | apache-2.0 | 5cd5f423d8c00b1b5e51aa5bcb2a8a25 | 24.544554 | 78 | 0.572315 | 4.740809 | false | false | false | false |
Kotlin/dokka | plugins/base/src/main/kotlin/transformers/documentables/KotlinArrayDocumentableReplacerTransformer.kt | 1 | 3221 | package org.jetbrains.dokka.base.transformers.documentables
import org.jetbrains.dokka.Platform
import org.jetbrains.dokka.links.DRI
import org.jetbrains.dokka.model.*
import org.jetbrains.dokka.plugability.DokkaContext
class KotlinArrayDocumentableReplacerTransformer(context: DokkaContext):
DocumentableReplacerTransformer(context) {
private fun Documentable.isJVM() =
sourceSets.any{ it.analysisPlatform == Platform.jvm }
override fun processGenericTypeConstructor(genericTypeConstructor: GenericTypeConstructor): AnyWithChanges<GenericTypeConstructor> =
genericTypeConstructor.takeIf { genericTypeConstructor.dri == DRI("kotlin", "Array") }
?.let {
with(it.projections.firstOrNull() as? Variance<Bound>) {
with(this?.inner as? GenericTypeConstructor) {
when (this?.dri) {
DRI("kotlin", "Int") ->
AnyWithChanges(
GenericTypeConstructor(DRI("kotlin", "IntArray"), emptyList()),
true)
DRI("kotlin", "Boolean") ->
AnyWithChanges(
GenericTypeConstructor(DRI("kotlin", "BooleanArray"), emptyList()),
true)
DRI("kotlin", "Float") ->
AnyWithChanges(
GenericTypeConstructor(DRI("kotlin", "FloatArray"), emptyList()),
true)
DRI("kotlin", "Double") ->
AnyWithChanges(
GenericTypeConstructor(DRI("kotlin", "DoubleArray"), emptyList()),
true)
DRI("kotlin", "Long") ->
AnyWithChanges(
GenericTypeConstructor(DRI("kotlin", "LongArray"), emptyList()),
true)
DRI("kotlin", "Short") ->
AnyWithChanges(
GenericTypeConstructor(DRI("kotlin", "ShortArray"), emptyList()),
true)
DRI("kotlin", "Char") ->
AnyWithChanges(
GenericTypeConstructor(DRI("kotlin", "CharArray"), emptyList()),
true)
DRI("kotlin", "Byte") ->
AnyWithChanges(
GenericTypeConstructor(DRI("kotlin", "ByteArray"), emptyList()),
true)
else -> null
}
}
}
}
?: super.processGenericTypeConstructor(genericTypeConstructor)
override fun processModule(module: DModule): AnyWithChanges<DModule> =
if(module.isJVM())
super.processModule(module)
else AnyWithChanges(module)
} | apache-2.0 | 3441cd828f9ba8436aef8f7c163f764a | 50.142857 | 136 | 0.458864 | 6.613963 | false | false | false | false |
vsch/idea-multimarkdown | src/main/java/com/vladsch/md/nav/editor/resources/SwingHtmlCssProvider.kt | 1 | 836 | // Copyright (c) 2015-2020 Vladimir Schneider <[email protected]> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.vladsch.md.nav.editor.resources
import com.vladsch.md.nav.MdBundle
import com.vladsch.md.nav.editor.text.TextHtmlPanelProvider
import com.vladsch.md.nav.editor.util.HtmlCssResource
import com.vladsch.md.nav.editor.util.HtmlCssResourceProvider
object SwingHtmlCssProvider : HtmlCssResourceProvider() {
val NAME = MdBundle.message("editor.swing.html.css.provider.name")
val ID = "com.vladsch.md.nav.editor.swing.html.css"
override val HAS_PARENT = false
override val INFO = Info(ID, NAME)
override val COMPATIBILITY = TextHtmlPanelProvider.COMPATIBILITY
override val cssResource: HtmlCssResource = SwingHtmlCssResource
}
| apache-2.0 | eb3c3dbe8d2cfec90bc3f99b1b302307 | 48.176471 | 177 | 0.79067 | 3.782805 | false | false | false | false |
wuseal/JsonToKotlinClass | src/test/kotlin/wu/seal/jsontokotlin/DataClassGeneratorByJSONObjectTest.kt | 1 | 6628 | package wu.seal.jsontokotlin
import com.google.gson.Gson
import com.google.gson.JsonObject
import com.winterbe.expekt.should
import org.junit.Test
import org.junit.Before
import wu.seal.jsontokotlin.model.classscodestruct.GenericListClass
import wu.seal.jsontokotlin.model.classscodestruct.KotlinClass
import wu.seal.jsontokotlin.model.classscodestruct.DataClass
import wu.seal.jsontokotlin.test.TestConfig
import wu.seal.jsontokotlin.utils.classgenerator.DataClassGeneratorByJSONObject
class DataClassGeneratorByJSONObjectTest {
val json ="""
{
"glossary":{
"title":"example glossary",
"GlossDiv":{
"title":"S",
"GlossList":{
"GlossEntry":{
"ID":"SGML",
"SortAs":"SGML",
"GlossTerm":"Standard Generalized Markup Language",
"Acronym":"SGML",
"Abbrev":"ISO 8879:1986",
"GlossDef":{
"para":"A meta-markup language, used to create markup languages such as DocBook.",
"GlossSeeAlso":[
"GML",
"XML"
]
},
"GlossSee":"markup"
}
}
}
}
}
""".trimIndent()
@Before
fun before() {
TestConfig.setToTestInitState()
}
@Test
fun generate() {
val jsonObject = Gson().fromJson(json,JsonObject::class.java)
val dataClass = DataClassGeneratorByJSONObject("Test", jsonObject).generate()
dataClass.name.should.be.equal("Test")
val p1 = dataClass.properties[0]
p1.name.should.be.equal("glossary")
p1.type.should.be.equal("Glossary")
p1.typeObject.should.not.`null`
val p1RefDataClass = p1.typeObject as DataClass
p1RefDataClass.name.should.be.equal("Glossary")
val p1p1 = p1RefDataClass.properties[0]
p1p1.name.should.be.equal("title")
p1p1.type.should.be.equal(KotlinClass.STRING.name)
p1p1.originJsonValue.should.be.equal("example glossary")
val p1p2 = p1RefDataClass.properties[1]
p1p2.name.should.be.equal("GlossDiv")
p1p2.type.should.be.equal("GlossDiv")
p1p2.typeObject.should.not.`null`
val p1p2RefDataClass = p1p2.typeObject as DataClass
p1p2RefDataClass.name.should.be.equal("GlossDiv")
p1p2RefDataClass.properties.size.should.be.equal(2)
val p1p2p1 = p1p2RefDataClass.properties[0]
p1p2p1.name.should.be.equal("title")
p1p2p1.originJsonValue.should.be.equal("S")
p1p2p1.type.should.be.equal(KotlinClass.STRING.name)
p1p2p1.typeObject.should.equal(KotlinClass.STRING)
val p1p2p2 = p1p2RefDataClass.properties[1]
p1p2p2.name.should.be.equal("GlossList")
p1p2p2.type.should.be.equal("GlossList")
p1p2p2.typeObject.should.not.`null`
val p1p2p2RefDataClass = p1p2p2.typeObject as DataClass
p1p2p2RefDataClass.name.should.be.equal("GlossList")
p1p2p2RefDataClass.properties.size.should.be.equal(1)
val p1p2p2p1 = p1p2p2RefDataClass.properties[0]
p1p2p2p1.typeObject.should.not.`null`
p1p2p2p1.name.should.be.equal("GlossEntry")
p1p2p2p1.type.should.be.equal("GlossEntry")
p1p2p2p1.originJsonValue.should.be.empty
val p1p2p2p1RefDataClass = p1p2p2p1.typeObject as DataClass
p1p2p2p1RefDataClass.properties.size.should.be.equal(7)
val glossEntryP1 = p1p2p2p1RefDataClass.properties[0]
glossEntryP1.name.should.be.equal("ID")
glossEntryP1.originJsonValue.should.be.equal("SGML")
glossEntryP1.type.should.be.equal(KotlinClass.STRING.name)
glossEntryP1.typeObject.should.equal(KotlinClass.STRING)
val glossEntryP2 = p1p2p2p1RefDataClass.properties[1]
glossEntryP2.name.should.be.equal("SortAs")
glossEntryP2.originJsonValue.should.be.equal("SGML")
glossEntryP2.type.should.be.equal(KotlinClass.STRING.name)
glossEntryP2.typeObject.should.be.equal(KotlinClass.STRING)
val glossEntryP3 = p1p2p2p1RefDataClass.properties[2]
glossEntryP3.name.should.be.equal("GlossTerm")
glossEntryP3.originJsonValue.should.be.equal("Standard Generalized Markup Language")
glossEntryP3.type.should.be.equal(KotlinClass.STRING.name)
glossEntryP3.typeObject.should.equal(KotlinClass.STRING)
val glossEntryP4 = p1p2p2p1RefDataClass.properties[3]
glossEntryP4.name.should.be.equal("Acronym")
glossEntryP4.originJsonValue.should.be.equal("SGML")
glossEntryP4.type.should.be.equal(KotlinClass.STRING.name)
glossEntryP4.typeObject.should.be.equal(KotlinClass.STRING)
val glossEntryP5 = p1p2p2p1RefDataClass.properties[4]
glossEntryP5.name.should.be.equal("Abbrev")
glossEntryP5.originJsonValue.should.be.equal("ISO 8879:1986")
glossEntryP5.type.should.be.equal(KotlinClass.STRING.name)
glossEntryP5.typeObject.should.be.equal(KotlinClass.STRING)
val glossEntryP7 = p1p2p2p1RefDataClass.properties[6]
glossEntryP7.name.should.be.equal("GlossSee")
glossEntryP7.originJsonValue.should.be.equal("markup")
glossEntryP7.type.should.be.equal(KotlinClass.STRING.name)
glossEntryP7.typeObject.should.be.equal(KotlinClass.STRING)
val glossEntryP6 = p1p2p2p1RefDataClass.properties[5]
glossEntryP6.name.should.be.equal("GlossDef")
glossEntryP6.type.should.be.equal("GlossDef")
glossEntryP6.typeObject.should.be.not.`null`
glossEntryP6.originJsonValue.should.be.empty
val glossDefDataClass = glossEntryP6.typeObject as DataClass
glossDefDataClass.name.should.be.equal("GlossDef")
glossDefDataClass.properties.size.should.be.equal(2)
val glossDefP1 = glossDefDataClass.properties[0]
glossDefP1.name.should.be.equal("para")
glossDefP1.originJsonValue.should.be.equal("A meta-markup language, used to create markup languages such as DocBook.")
glossDefP1.type.should.be.equal(KotlinClass.STRING.name)
glossDefP1.typeObject.should.equal(KotlinClass.STRING)
val glossDefP2 = glossDefDataClass.properties[1]
glossDefP2.name.should.be.equal("GlossSeeAlso")
glossDefP2.type.should.be.equal(GenericListClass(KotlinClass.STRING).name)
glossDefP2.originJsonValue.should.be.empty
glossDefP2.typeObject.should.be.equal(GenericListClass(KotlinClass.STRING))
}
} | gpl-3.0 | 5a59f7c46531b637cde1ad88175079ba | 42.045455 | 126 | 0.676976 | 3.32898 | false | true | false | false |
http4k/http4k | http4k-contract/src/main/kotlin/org/http4k/contract/security/ApiKeySecurity.kt | 1 | 1255 | package org.http4k.contract.security
import org.http4k.core.Filter
import org.http4k.core.Method
import org.http4k.core.Request
import org.http4k.core.Response
import org.http4k.core.Status.Companion.UNAUTHORIZED
import org.http4k.lens.Lens
import org.http4k.lens.LensFailure
/**
* Checks the presence of the named Api Key parameter. Filter returns 401 if Api-Key is not found in request.
*
* Default implementation of ApiKey. Includes an option to NOT authorise OPTIONS requests, which is
* currently not enabled for OpenAPI.
*/
class ApiKeySecurity<out T>(val param: Lens<Request, T>,
validateKey: (T) -> Boolean,
authorizeOptionsRequests: Boolean = true,
val name: String = "api_key") : Security {
override val filter = Filter { next ->
{
if (!authorizeOptionsRequests && it.method == Method.OPTIONS) {
next(it)
} else {
val keyValid = try {
validateKey(param(it))
} catch (e: LensFailure) {
false
}
if (keyValid) next(it) else Response(UNAUTHORIZED)
}
}
}
companion object
}
| apache-2.0 | 654b4e2c08cef79f7fadeadda8e2f32a | 32.918919 | 109 | 0.594422 | 4.327586 | false | false | false | false |
orbit/orbit | src/orbit-client-spring-plugin/src/test/kotlin/orbit/client/plugin/spring/SpringAddressableConstructorTest.kt | 1 | 1548 | /*
Copyright (C) 2015 - 2020 Electronic Arts Inc. All rights reserved.
This file is part of the Orbit Project <https://www.orbit.cloud>.
See license in LICENSE.
*/
package orbit.client.plugin.spring
import kotlinx.coroutines.runBlocking
import orbit.client.OrbitClient
import orbit.client.OrbitClientConfig
import orbit.client.actor.createProxy
import orbit.client.plugin.spring.actor.SpringTestActor
import orbit.client.plugin.spring.misc.SpringConfig
import orbit.server.OrbitServer
import orbit.server.OrbitServerConfig
import org.junit.Test
import org.springframework.context.annotation.AnnotationConfigApplicationContext
import kotlin.test.assertTrue
class SpringAddressableConstructorTest {
@Test
fun `test spring actor injection`() {
val ctx = AnnotationConfigApplicationContext()
ctx.register(SpringConfig::class.java)
ctx.refresh()
val server = OrbitServer(OrbitServerConfig())
val client = OrbitClient(OrbitClientConfig(
addressableConstructor = SpringAddressableConstructor.Config(ctx),
packages = listOf("orbit.client.plugin.spring.actor")
))
runBlocking {
server.start().join()
client.start().join()
val actor = client.actorFactory.createProxy<SpringTestActor>()
val result1 = actor.getCallCount().await()
val result2 = actor.getCallCount().await()
assertTrue(result2 > result1)
client.stop().join()
server.stop().join()
}
}
} | bsd-3-clause | 9b9a79463e7d4557d02578c51f65c90e | 31.270833 | 80 | 0.702842 | 4.579882 | false | true | false | false |
blackbbc/Tucao | app/src/main/kotlin/me/sweetll/tucao/business/download/fragment/DownloadingFragment.kt | 1 | 5420 | package me.sweetll.tucao.business.download.fragment
import androidx.databinding.DataBindingUtil
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemLongClickListener
import me.sweetll.tucao.R
import me.sweetll.tucao.base.BaseFragment
import me.sweetll.tucao.business.download.DownloadActivity
import me.sweetll.tucao.business.download.adapter.DownloadingVideoAdapter
import me.sweetll.tucao.business.download.event.RefreshDownloadingVideoEvent
import me.sweetll.tucao.model.json.Part
import me.sweetll.tucao.model.json.Video
import me.sweetll.tucao.databinding.FragmentDownloadingBinding
import me.sweetll.tucao.extension.DownloadHelpers
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
class DownloadingFragment: BaseFragment(), DownloadActivity.ContextMenuCallback {
lateinit var binding: FragmentDownloadingBinding
val videoAdapter: DownloadingVideoAdapter by lazy {
DownloadingVideoAdapter(activity as DownloadActivity, DownloadHelpers.loadDownloadingVideos())
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_downloading, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setupRecyclerView()
}
fun setupRecyclerView() {
binding.videoRecycler.layoutManager = LinearLayoutManager(activity)
binding.videoRecycler.adapter = videoAdapter
binding.videoRecycler.recycledViewPool.setMaxRecycledViews(DownloadingVideoAdapter.TYPE_PART, 0)
binding.videoRecycler.recycledViewPool.setMaxRecycledViews(DownloadingVideoAdapter.TYPE_VIDEO, 0)
binding.videoRecycler.addOnItemTouchListener(object: OnItemLongClickListener() {
override fun onSimpleItemLongClick(helper: BaseQuickAdapter<*, *>, view: View, position: Int) {
if ((activity as DownloadActivity).currentActionMode != null) {
return
}
(activity as DownloadActivity).openContextMenu(this@DownloadingFragment, false)
videoAdapter.data.forEach {
when (it) {
is Video -> {
it.checkable = true
it.checked = false
it.subItems.forEach {
it.checkable = true
it.checked = false
}
}
is Part -> {
it.checkable = true
it.checked = false
}
}
}
videoAdapter.notifyDataSetChanged()
}
})
}
override fun onStart() {
super.onStart()
EventBus.getDefault().register(this)
}
override fun onStop() {
super.onStop()
EventBus.getDefault().unregister(this)
}
@Subscribe(threadMode = ThreadMode.MAIN)
fun onRefreshEvent(event: RefreshDownloadingVideoEvent) {
videoAdapter.setNewData(DownloadHelpers.loadDownloadingVideos())
}
override fun onDestroyContextMenu() {
videoAdapter.data.forEach {
when (it) {
is Video -> {
it.checkable = false
it.subItems.forEach { it.checkable = false }
}
is Part -> it.checkable = false
}
}
videoAdapter.notifyDataSetChanged()
}
override fun onClickDelete() {
DownloadHelpers.cancelDownload(
videoAdapter.data.flatMap {
when (it) {
is Video -> it.subItems
else -> listOf(it as Part)
}
}.distinctBy(Part::vid).filter(Part::checked)
)
}
override fun onClickPickAll(): Boolean {
if (videoAdapter.data.all {
when (it) {
is Video -> it.checked
is Part -> it.checked
else -> false
}
}) {
// 取消全选
videoAdapter.data.forEach {
when (it) {
is Video -> {
it.checked = false
it.subItems.forEach { it.checked = false }
}
is Part -> it.checked = false
}
}
videoAdapter.notifyDataSetChanged()
return false
} else {
// 全选
videoAdapter.data.forEach {
when (it) {
is Video -> {
it.checked = true
it.subItems.forEach { it.checked = true }
}
is Part -> it.checked = true
}
}
videoAdapter.notifyDataSetChanged()
return true
}
}
}
| mit | fdce4819101529cff63e9e18f02e6962 | 35.540541 | 116 | 0.577108 | 5.440644 | false | false | false | false |
msebire/intellij-community | platform/configuration-store-impl/src/ApplicationStoreImpl.kt | 1 | 4191 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.configurationStore
import com.intellij.configurationStore.schemeManager.ROOT_CONFIG
import com.intellij.openapi.application.Application
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.application.appSystemDir
import com.intellij.openapi.components.*
import com.intellij.openapi.components.impl.stores.FileStorageCoreUtil
import com.intellij.openapi.diagnostic.runAndLogException
import com.intellij.openapi.util.NamedJDOMExternalizable
import com.intellij.util.io.systemIndependentPath
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch
import org.jetbrains.jps.model.serialization.JpsGlobalLoader
private class ApplicationPathMacroManager : PathMacroManager(null)
const val APP_CONFIG = "\$APP_CONFIG$"
class ApplicationStoreImpl(private val application: Application, pathMacroManager: PathMacroManager? = null) : ComponentStoreWithExtraComponents() {
override val storageManager = ApplicationStorageManager(application, pathMacroManager)
// number of app components require some state, so, we load default state in test mode
override val loadPolicy: StateLoadPolicy
get() = if (application.isUnitTestMode) StateLoadPolicy.LOAD_ONLY_DEFAULT else StateLoadPolicy.LOAD
override fun setPath(path: String) {
// app config must be first, because collapseMacros collapse from fist to last, so, at first we must replace APP_CONFIG because it overlaps ROOT_CONFIG value
storageManager.addMacro(APP_CONFIG, "$path/${PathManager.OPTIONS_DIRECTORY}")
storageManager.addMacro(ROOT_CONFIG, path)
storageManager.addMacro(StoragePathMacros.CACHE_FILE, appSystemDir.resolve("workspace").resolve("app.xml").systemIndependentPath)
}
override suspend fun doSave(result: SaveResult, isForceSavingAllSettings: Boolean) {
val saveSessionManager = saveSettingsSavingComponentsAndCommitComponents(result, isForceSavingAllSettings)
// todo can we store default project in parallel to regular saving? for now only flush on disk is async, but not component committing
coroutineScope {
launch {
saveSessionManager.save().appendTo(result)
}
launch {
// here, because no Project (and so, ProjectStoreImpl) on Welcome Screen
val r = serviceIfCreated<DefaultProjectExportableAndSaveTrigger>()?.save(isForceSavingAllSettings) ?: return@launch
// ignore
r.isChanged = false
r.appendTo(result)
}
}
}
override fun toString() = "app"
}
class ApplicationStorageManager(application: Application?, pathMacroManager: PathMacroManager? = null)
: StateStorageManagerImpl("application", pathMacroManager?.createTrackingSubstitutor(), application) {
override fun getOldStorageSpec(component: Any, componentName: String, operation: StateStorageOperation): String? {
return when (component) {
is NamedJDOMExternalizable -> "${component.externalFileName}${FileStorageCoreUtil.DEFAULT_EXT}"
else -> PathManager.DEFAULT_OPTIONS_FILE
}
}
override fun getMacroSubstitutor(fileSpec: String): PathMacroSubstitutor? {
return when (fileSpec) {
JpsGlobalLoader.PathVariablesSerializer.STORAGE_FILE_NAME -> null
else -> super.getMacroSubstitutor(fileSpec)
}
}
override val isUseXmlProlog: Boolean
get() = false
override val isUseVfsForWrite: Boolean
get() = false
override fun providerDataStateChanged(storage: FileBasedStorage, writer: DataWriter?, type: DataStateChanged) {
// IDEA-144052 When "Settings repository" is enabled changes in 'Path Variables' aren't saved to default path.macros.xml file causing errors in build process
if (storage.fileSpec == "path.macros.xml") {
LOG.runAndLogException {
writer.writeTo(storage.file)
}
}
}
override fun normalizeFileSpec(fileSpec: String) = removeMacroIfStartsWith(super.normalizeFileSpec(fileSpec), APP_CONFIG)
override fun expandMacros(path: String) = if (path[0] == '$') super.expandMacros(path) else "${expandMacro(APP_CONFIG)}/$path"
} | apache-2.0 | eccca4aca9f1481b7580ab0baa7d6803 | 45.577778 | 161 | 0.771892 | 4.97153 | false | true | false | false |
icanit/mangafeed | app/src/main/java/eu/kanade/tachiyomi/ui/reader/ReaderPresenter.kt | 1 | 15541 | package eu.kanade.tachiyomi.ui.reader
import android.os.Bundle
import android.util.Pair
import eu.kanade.tachiyomi.data.cache.ChapterCache
import eu.kanade.tachiyomi.data.database.DatabaseHelper
import eu.kanade.tachiyomi.data.database.models.Chapter
import eu.kanade.tachiyomi.data.database.models.Manga
import eu.kanade.tachiyomi.data.database.models.MangaSync
import eu.kanade.tachiyomi.data.download.DownloadManager
import eu.kanade.tachiyomi.data.download.model.Download
import eu.kanade.tachiyomi.data.mangasync.MangaSyncManager
import eu.kanade.tachiyomi.data.mangasync.UpdateMangaSyncService
import eu.kanade.tachiyomi.data.preference.PreferencesHelper
import eu.kanade.tachiyomi.data.source.SourceManager
import eu.kanade.tachiyomi.data.source.base.Source
import eu.kanade.tachiyomi.data.source.model.Page
import eu.kanade.tachiyomi.event.ReaderEvent
import eu.kanade.tachiyomi.ui.base.presenter.BasePresenter
import eu.kanade.tachiyomi.util.SharedData
import rx.Observable
import rx.Subscription
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import rx.subjects.PublishSubject
import timber.log.Timber
import java.io.File
import javax.inject.Inject
class ReaderPresenter : BasePresenter<ReaderActivity>() {
@Inject lateinit var prefs: PreferencesHelper
@Inject lateinit var db: DatabaseHelper
@Inject lateinit var downloadManager: DownloadManager
@Inject lateinit var syncManager: MangaSyncManager
@Inject lateinit var sourceManager: SourceManager
@Inject lateinit var chapterCache: ChapterCache
lateinit var manga: Manga
private set
lateinit var chapter: Chapter
private set
lateinit var source: Source
private set
var requestedPage: Int = 0
var currentPage: Page? = null
private var nextChapter: Chapter? = null
private var previousChapter: Chapter? = null
private var mangaSyncList: List<MangaSync>? = null
private val retryPageSubject by lazy { PublishSubject.create<Page>() }
private val pageInitializerSubject by lazy { PublishSubject.create<Chapter>() }
val isSeamlessMode by lazy { prefs.seamlessMode() }
private var appenderSubscription: Subscription? = null
private val GET_PAGE_LIST = 1
private val GET_ADJACENT_CHAPTERS = 2
private val GET_MANGA_SYNC = 3
private val PRELOAD_NEXT_CHAPTER = 4
private val MANGA_KEY = "manga_key"
private val CHAPTER_KEY = "chapter_key"
private val PAGE_KEY = "page_key"
override fun onCreate(savedState: Bundle?) {
super.onCreate(savedState)
if (savedState == null) {
val event = SharedData.remove(ReaderEvent::class.java) ?: return
manga = event.manga
chapter = event.chapter
} else {
manga = savedState.getSerializable(MANGA_KEY) as Manga
chapter = savedState.getSerializable(CHAPTER_KEY) as Chapter
requestedPage = savedState.getInt(PAGE_KEY)
}
source = sourceManager.get(manga.source)!!
initializeSubjects()
startableLatestCache(GET_ADJACENT_CHAPTERS,
{ getAdjacentChaptersObservable() },
{ view, pair -> view.onAdjacentChapters(pair.first, pair.second) })
startable(PRELOAD_NEXT_CHAPTER,
{ getPreloadNextChapterObservable() },
{ },
{ error -> Timber.e("Error preloading chapter") })
restartable(GET_MANGA_SYNC,
{ getMangaSyncObservable().subscribe() })
restartableLatestCache(GET_PAGE_LIST,
{ getPageListObservable(chapter) },
{ view, chapter -> view.onChapterReady(manga, this.chapter, currentPage) },
{ view, error -> view.onChapterError(error) })
if (savedState == null) {
loadChapter(chapter)
if (prefs.autoUpdateMangaSync()) {
start(GET_MANGA_SYNC)
}
}
}
override fun onSave(state: Bundle) {
onChapterLeft()
state.putSerializable(MANGA_KEY, manga)
state.putSerializable(CHAPTER_KEY, chapter)
state.putSerializable(PAGE_KEY, currentPage?.pageNumber ?: 0)
super.onSave(state)
}
private fun initializeSubjects() {
// Listen for pages initialization events
add(pageInitializerSubject.observeOn(Schedulers.io())
.concatMap { ch ->
val observable: Observable<Page>
if (ch.isDownloaded) {
val chapterDir = downloadManager.getAbsoluteChapterDirectory(source, manga, ch)
observable = Observable.from(ch.pages)
.flatMap { downloadManager.getDownloadedImage(it, chapterDir) }
} else {
observable = source.getAllImageUrlsFromPageList(ch.pages)
.flatMap({ source.getCachedImage(it) }, 2)
.doOnCompleted { source.savePageList(ch.url, ch.pages) }
}
observable.doOnCompleted {
if (!isSeamlessMode && chapter === ch) {
preloadNextChapter()
}
}
}.subscribe())
// Listen por retry events
add(retryPageSubject.observeOn(Schedulers.io())
.flatMap { page ->
if (page.imageUrl == null)
source.getImageUrlFromPage(page)
else
Observable.just<Page>(page)
}
.flatMap { source.getCachedImage(it) }
.subscribe())
}
// Returns the page list of a chapter
private fun getPageListObservable(chapter: Chapter): Observable<Chapter> {
val observable: Observable<List<Page>> = if (chapter.isDownloaded)
// Fetch the page list from disk
Observable.just(downloadManager.getSavedPageList(source, manga, chapter)!!)
else
// Fetch the page list from cache or fallback to network
source.getCachedPageListOrPullFromNetwork(chapter.url)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
return observable.map { pages ->
for (page in pages) {
page.chapter = chapter
}
chapter.pages = pages
if (requestedPage >= -1 || currentPage == null) {
if (requestedPage == -1) {
currentPage = pages[pages.size - 1]
} else {
currentPage = pages[requestedPage]
}
}
requestedPage = -2
pageInitializerSubject.onNext(chapter)
chapter
}
}
private fun getAdjacentChaptersObservable(): Observable<Pair<Chapter, Chapter>> {
return Observable.zip(
db.getPreviousChapter(chapter).asRxObservable().take(1),
db.getNextChapter(chapter).asRxObservable().take(1),
{ a, b -> Pair.create(a, b) })
.doOnNext { pair ->
previousChapter = pair.first
nextChapter = pair.second
}
.observeOn(AndroidSchedulers.mainThread())
}
// Preload the first pages of the next chapter. Only for non seamless mode
private fun getPreloadNextChapterObservable(): Observable<Page> {
return source.getCachedPageListOrPullFromNetwork(nextChapter!!.url)
.flatMap { pages ->
nextChapter!!.pages = pages
val pagesToPreload = Math.min(pages.size, 5)
Observable.from(pages).take(pagesToPreload)
}
// Preload up to 5 images
.concatMap { page ->
if (page.imageUrl == null)
source.getImageUrlFromPage(page)
else
Observable.just<Page>(page)
}
// Download the first image
.concatMap { page ->
if (page.pageNumber == 0)
source.getCachedImage(page)
else
Observable.just<Page>(page)
}
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnCompleted { stopPreloadingNextChapter() }
}
private fun getMangaSyncObservable(): Observable<List<MangaSync>> {
return db.getMangasSync(manga).asRxObservable()
.take(1)
.doOnNext { mangaSyncList = it }
}
// Loads the given chapter
private fun loadChapter(chapter: Chapter, requestedPage: Int = 0) {
if (isSeamlessMode) {
if (appenderSubscription != null)
remove(appenderSubscription)
} else {
stopPreloadingNextChapter()
}
this.chapter = chapter
chapter.status = if (isChapterDownloaded(chapter)) Download.DOWNLOADED else Download.NOT_DOWNLOADED
// If the chapter is partially read, set the starting page to the last the user read
if (!chapter.read && chapter.last_page_read != 0)
this.requestedPage = chapter.last_page_read
else
this.requestedPage = requestedPage
// Reset next and previous chapter. They have to be fetched again
nextChapter = null
previousChapter = null
start(GET_PAGE_LIST)
start(GET_ADJACENT_CHAPTERS)
}
fun setActiveChapter(chapter: Chapter) {
onChapterLeft()
this.chapter = chapter
nextChapter = null
previousChapter = null
start(GET_ADJACENT_CHAPTERS)
}
fun appendNextChapter() {
if (nextChapter == null)
return
if (appenderSubscription != null)
remove(appenderSubscription)
nextChapter?.let {
if (appenderSubscription != null)
remove(appenderSubscription)
it.status = if (isChapterDownloaded(it)) Download.DOWNLOADED else Download.NOT_DOWNLOADED
appenderSubscription = getPageListObservable(it).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.compose(deliverLatestCache<Chapter>())
.subscribe(split({ view, chapter ->
view.onAppendChapter(chapter)
}, { view, error ->
view.onChapterAppendError()
}))
add(appenderSubscription)
}
}
// Check whether the given chapter is downloaded
fun isChapterDownloaded(chapter: Chapter): Boolean {
return downloadManager.isChapterDownloaded(source, manga, chapter)
}
fun retryPage(page: Page?) {
if (page != null) {
page.status = Page.QUEUE
if (page.imagePath != null) {
val file = File(page.imagePath)
chapterCache.removeFileFromCache(file.name)
}
retryPageSubject.onNext(page)
}
}
// Called before loading another chapter or leaving the reader. It allows to do operations
// over the chapter read like saving progress
fun onChapterLeft() {
val pages = chapter.pages ?: return
// Get the last page read
var activePageNumber = chapter.last_page_read
// Just in case, avoid out of index exceptions
if (activePageNumber >= pages.size) {
activePageNumber = pages.size - 1
}
val activePage = pages[activePageNumber]
// Cache current page list progress for online chapters to allow a faster reopen
if (!chapter.isDownloaded) {
source.savePageList(chapter.url, pages)
}
// Save current progress of the chapter. Mark as read if the chapter is finished
if (activePage.isLastPage) {
chapter.read = true
// Check if remove after read is selected by user
if (prefs.removeAfterRead()) {
if (prefs.removeAfterReadPrevious() ) {
if (previousChapter != null) {
deleteChapter(previousChapter!!, manga)
}
} else {
deleteChapter(chapter, manga)
}
}
}
db.insertChapter(chapter).asRxObservable().subscribe()
}
/**
* Delete selected chapter
* @param chapter chapter that is selected
* *
* @param manga manga that belongs to chapter
*/
fun deleteChapter(chapter: Chapter, manga: Manga) {
val source = sourceManager.get(manga.source)!!
downloadManager.deleteChapter(source, manga, chapter)
}
// If the current chapter has been read, we check with this one
// If not, we check if the previous chapter has been read
// We know the chapter we have to check, but we don't know yet if an update is required.
// This boolean is used to return 0 if no update is required
fun getMangaSyncChapterToUpdate(): Int {
if (chapter.pages == null || mangaSyncList == null || mangaSyncList!!.isEmpty())
return 0
var lastChapterReadLocal = 0
if (chapter.read)
lastChapterReadLocal = Math.floor(chapter.chapter_number.toDouble()).toInt()
else if (previousChapter != null && previousChapter!!.read)
lastChapterReadLocal = Math.floor(previousChapter!!.chapter_number.toDouble()).toInt()
var hasToUpdate = false
for (mangaSync in mangaSyncList!!) {
if (lastChapterReadLocal > mangaSync.last_chapter_read) {
mangaSync.last_chapter_read = lastChapterReadLocal
mangaSync.update = true
hasToUpdate = true
}
}
return if (hasToUpdate) lastChapterReadLocal else 0
}
fun updateMangaSyncLastChapterRead() {
for (mangaSync in mangaSyncList!!) {
val service = syncManager.getService(mangaSync.sync_id)
if (service.isLogged && mangaSync.update) {
UpdateMangaSyncService.start(context, mangaSync)
}
}
}
fun loadNextChapter(): Boolean {
nextChapter?.let {
onChapterLeft()
loadChapter(it, 0)
return true
}
return false
}
fun loadPreviousChapter(): Boolean {
previousChapter?.let {
onChapterLeft()
loadChapter(it, 0)
return true
}
return false
}
fun hasNextChapter(): Boolean {
return nextChapter != null
}
fun hasPreviousChapter(): Boolean {
return previousChapter != null
}
private fun preloadNextChapter() {
if (hasNextChapter() && !isChapterDownloaded(nextChapter!!)) {
start(PRELOAD_NEXT_CHAPTER)
}
}
private fun stopPreloadingNextChapter() {
if (!isUnsubscribed(PRELOAD_NEXT_CHAPTER)) {
stop(PRELOAD_NEXT_CHAPTER)
if (nextChapter!!.pages != null)
source.savePageList(nextChapter!!.url, nextChapter!!.pages)
}
}
fun updateMangaViewer(viewer: Int) {
manga.viewer = viewer
db.insertManga(manga).executeAsBlocking()
}
}
| apache-2.0 | e0985bc4168cf5b2373cb446527ac6bb | 35.058005 | 107 | 0.59417 | 4.9955 | false | false | false | false |
infinum/android_dbinspector | dbinspector/src/main/kotlin/com/infinum/dbinspector/domain/shared/models/parameters/ContentParameters.kt | 1 | 671 | package com.infinum.dbinspector.domain.shared.models.parameters
import com.infinum.dbinspector.domain.Domain
import com.infinum.dbinspector.domain.connection.models.DatabaseConnection
import com.infinum.dbinspector.domain.shared.base.PageParameters
import com.infinum.dbinspector.domain.shared.models.Sort
internal data class ContentParameters(
val databasePath: String = "",
val connection: DatabaseConnection? = null,
val statement: String,
val sort: SortParameters = SortParameters(Sort.ASCENDING),
val pageSize: Int = Domain.Constants.Limits.PAGE_SIZE,
override var page: Int? = Domain.Constants.Limits.INITIAL_PAGE
) : PageParameters(page)
| apache-2.0 | bb3f2f71b6da1f6a7dbd079901a5c5c2 | 43.733333 | 74 | 0.797317 | 4.301282 | false | false | false | false |
thiago-soliveira/android-kotlin-dagger-poc | DaggerPoc/app/src/main/java/dagger/poc/android/data/model/Answer.kt | 1 | 596 | package dagger.poc.android.data.model
import android.arch.persistence.room.ColumnInfo
import android.arch.persistence.room.Entity
import android.arch.persistence.room.ForeignKey
import android.arch.persistence.room.PrimaryKey
/**
* Created by Thiago on 6/26/2017.
*/
@Entity(foreignKeys = arrayOf(
ForeignKey(entity = User::class,
parentColumns = arrayOf("id"),
childColumns = arrayOf("author_id")))
)
data class Answer constructor(@ColumnInfo(name = "author_id") var authorId: Long = 0) {
@PrimaryKey(autoGenerate = true)
var id: Long = 0
} | mit | feca2c4e24674539afb1464dfe88a618 | 26.136364 | 87 | 0.701342 | 3.94702 | false | false | false | false |
debop/debop4k | debop4k-science/src/main/kotlin/debop4k/science/gis/coords/UtmZonex.kt | 1 | 7696 | /*
* Copyright (c) 2016. Sunghyouk Bae <[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.
*
*/
@file:JvmName("UtmZonex")
package debop4k.science.gis.coords
import debop4k.core.loggerOf
import org.eclipse.collections.impl.factory.Lists
import java.util.concurrent.*
private val log = loggerOf("UtmZonex")
/** UTM Zone의 경도 크기 (6 degree) */
const val UTM_LONGITUDE_SIZE = 6
/** UTM Zone의 위도 크기 (8 degree) */
const val UTM_LATITUDE_SIZE = 8
/** UTM Zone 의 최소 Longitude Zone 값 ( 1 ) */
const val UTM_LONGITUDE_MIN = 1
/** UTM Zone 의 최대 Longitude Zone 값 ( 60 ) */
const val UTM_LONGITUDE_MAX = 60
/**
* UTM Zone 의 위도를 구분한 '구역 코드 - 시작 위도'
*/
val UtmLatitudes: Map<Char, Double> by lazy {
linkedMapOf('C' to -80.0,
'D' to -72.0,
'E' to -64.0,
'F' to -56.0,
'G' to -48.0,
'H' to -40.0,
'J' to -32.0,
'K' to -24.0,
'L' to -16.0,
'M' to -8.0,
'N' to 0.0,
'P' to 8.0,
'Q' to 16.0,
'R' to 24.0,
'S' to 32.0,
'T' to 40.0,
'U' to 48.0,
'V' to 56.0,
'W' to 64.0,
'X' to 72.0)
}
/**
* UTM Zone 의 영역과 영역을 위경도 좌표로 표현한 BondingBox 의 맵
*/
val UtmZoneBoundingBoxes: Map<UtmZone, BoundingBox> by lazy {
val map = ConcurrentSkipListMap<UtmZone, BoundingBox>()
for (lon in UTM_LONGITUDE_MIN..UTM_LONGITUDE_MAX) {
for (lat in UtmLatitudes.keys) {
val zone = UtmZone(lon, lat)
val longitude = lon.toLongitudeByUtm() //getLongitudeByUtm(lon)
val latitude = lat.toLatitudeByUtm() //getLatitudeByUtm(lat)
val bbox = BoundingBox.of(longitude,
latitude + UTM_LATITUDE_SIZE,
longitude + UTM_LONGITUDE_SIZE,
latitude)
map.put(zone, bbox)
}
}
map
}
/** UTM 문자열 (예: 51N) 을 파싱하여, UtmZone 인스턴스를 만듭니다 */
fun utmZoneOf(utmZoneStr: String?): UtmZone {
if (utmZoneStr.isNullOrBlank() || utmZoneStr?.length != 3) {
throw IllegalArgumentException("UtmZone 형식이 아닙니다. utmZoneStr=$utmZoneStr")
}
val longitudeZone = utmZoneStr.substring(0, 2).toInt()
val latitudeZone = utmZoneStr.substring(2, 3).toUpperCase().first()
return UtmZone(longitudeZone, latitudeZone)
}
fun utmZoneOf(longitudeZone: Int, latitudeZone: Char): UtmZone {
return UtmZone(longitudeZone, latitudeZone.toUpperCase())
}
/** 해당 Location 이 속한 [UtmZone] 인스턴스를 만듭니다 */
@JvmOverloads
fun utmZoneOf(longitude: Double = 0.0, latitude: Double = 0.0): UtmZone {
return UtmZone(longitude.toUtmLongitude(), latitude.toUtmLatitude())
}
/** 해당 [GeoLocation] 이 속한 [UtmZone] 인스턴스를 만듭니다 */
fun utmZoneOf(location: GeoLocation): UtmZone {
return utmZoneOf(location.longitude, location.latitude)
}
fun UtmZone.toGeoLocation(): GeoLocation {
val lon = longitudeZone.toLongitudeByUtm()
val lat = latitudeZone.toLatitudeByUtm()
return GeoLocation(lat + UTM_LATITUDE_SIZE, lon)
}
val Char.isUtmLatitude: Boolean get() = UtmLatitudes.keys.contains(this.toUpperCase())
fun Int.toLongitudeByUtm(): Double {
return (this - 31) * UTM_LONGITUDE_SIZE.toDouble()
}
@Deprecated("use toLongitudeByUtm()", ReplaceWith("utmLongitude.toLongitudeByUtm()"))
fun getLongitudeByUtm(utmLongitude: Int): Double {
return utmLongitude.toLongitudeByUtm()
}
fun Char.toLatitudeByUtm(): Double {
return UtmLatitudes[this.toUpperCase()]!!
}
@Deprecated("use toLatitudeByUtm", ReplaceWith("utmLatitude.toLatitudeByUtm()"))
fun getLatitudeByUtm(utmLatitude: Char): Double {
return utmLatitude.toLatitudeByUtm()
}
/**
* 경도가 속한 UTM Longitude Zone을 구한다.
* @return UTM Longitude Zone
*/
fun Double.toUtmLongitude(): Int {
return (this / UTM_LONGITUDE_SIZE + 31).toInt()
}
/**
* 경도가 속한 UTM Longitude Zone을 구한다.
* @param longitude 경도
* @return UTM Longitude Zone
*/
@Deprecated("use toUtmLongitude", ReplaceWith("longitude.toUtmLongitude()"))
fun getUtmLongitude(longitude: Double): Int {
return longitude.toUtmLongitude()
}
/**
* 지정한 위도가 속한 UTM Latitude Zone 을 구합니다.
* @return UTM Latitude Zone (예 : 'S', 'T')
*/
fun Double.toUtmLatitude(): Char {
val latitudes = Lists.mutable.withAll<Char>(UtmLatitudes.keys)
latitudes.sortThis { c1, c2 -> -c1!!.compareTo(c2!!) }
for (c in latitudes) {
val utm = UtmLatitudes[c] ?: Double.NaN
if (utm != Double.NaN && utm <= this) {
return c
}
}
throw RuntimeException("해당 UTM Zone Latitude 를 찾지 못했습니다. latitude=$this")
}
/**
* 지정한 위도가 속한 UTM Latitude Zone 을 구합니다.
* @return UTM Latitude Zone (예 : 'S', 'T')
*/
@Deprecated("use toUtmLatitude", ReplaceWith("latitude.toUtmLatitude()"))
fun getUtmLatitude(latitude: Double): Char {
return latitude.toUtmLatitude()
}
/**
* UTM Zone에 해당하는 영역을 위경도 좌표로 표현한 Bounding Box 을 반환합니다.
* @return UTM Zone 영역을 위경도 좌표로 표현한 Bounding Box
*/
fun UtmZone.boundingBox(): BoundingBox {
return UtmZoneBoundingBoxes[this] ?: throw RuntimeException("Not found bounding box. utm=$this")
}
/**
* UTM Zone에 해당하는 영역을 위경도 좌표로 표현한 Bounding Box 을 반환합니다.
* @param utm UtmZone
* @return UTM Zone 영역을 위경도 좌표로 표현한 Bounding Box
*/
@Deprecated("use boundingBox", ReplaceWith("utm.boundingBox()"))
fun getBoundingBox(utm: UtmZone): BoundingBox {
return utm.boundingBox()
}
/**
* UTM Zone 의 특정 Cell의 Bounding Box 를 계산합니다.
* @param size Cell 의 크기 (경위도의 단위)
* @param row Cell 의 row index (0부터 시작)
* @param col Cell의 column index (0부터 시작)
* @return UtmZone의 특정 cell의 Bounding Box를 구합니다.
*/
@JvmOverloads
fun UtmZone.cellBbox(size: Double, row: Int = 0, col: Int = 0): BoundingBox {
log.trace("utm={}, size={}, row={}, col={}", this, size, row, col)
val utmBbox = this.boundingBox()
val left = utmBbox.left + size * col.toDouble()
val top = utmBbox.top - size * row.toDouble()
val right = left + size
val bottom = top - size
val cellBbox = BoundingBox.of(left, top, right, bottom)
log.trace("utm bbox={}, size={}, row={}, col={}, cell bbox={}", utmBbox, size, row, col, cellBbox)
return cellBbox
}
/**
* UTM Zone 의 특정 Cell의 Bounding Box 를 계산합니다.
* @param utm UTM Zone
* @param size Cell 의 크기 (경위도의 단위)
* @param row Cell 의 row index (0부터 시작)
* @param col Cell의 column index (0부터 시작)
* @return UtmZone의 특정 cell의 Bounding Box를 구합니다.
*/
@JvmOverloads
@Deprecated("use cellBox", ReplaceWith("utm.cellBbox(size, row, col)"))
fun getCellBoundingBox(utm: UtmZone, size: Double, row: Int = 0, col: Int = 0): BoundingBox {
return utm.cellBbox(size, row, col)
} | apache-2.0 | b244b700bfbd7f66189cf22fdb4e80c3 | 28.381743 | 100 | 0.655932 | 3.014049 | false | false | false | false |
yangdd1205/spring-boot | spring-boot-project/spring-boot/src/test/kotlin/org/springframework/boot/context/properties/KotlinConfigurationPropertiesBeanRegistrarTests.kt | 11 | 2350 | package org.springframework.boot.context.properties
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.support.DefaultListableBeanFactory
import org.springframework.beans.factory.support.GenericBeanDefinition
import org.springframework.core.type.AnnotationMetadata
import org.springframework.core.type.classreading.SimpleMetadataReaderFactory
/**
* Tests for `ConfigurationPropertiesBeanRegistrar`.
*
* @author Stephane Nicoll
*/
@Suppress("unused")
class KotlinConfigurationPropertiesBeanRegistrarTests {
private val beanFactory = DefaultListableBeanFactory()
private val registrar = ConfigurationPropertiesBeanRegistrar(beanFactory)
@Test
fun `type with default constructor should register generic bean definition`() {
this.registrar.register(FooProperties::class.java)
val beanDefinition = this.beanFactory.getBeanDefinition(
"foo-org.springframework.boot.context.properties.KotlinConfigurationPropertiesBeanRegistrarTests\$FooProperties")
assertThat(beanDefinition).isExactlyInstanceOf(GenericBeanDefinition::class.java)
}
@Test
fun `type with primary constructor and no autowired should register configuration properties bean definition`() {
this.registrar.register(BarProperties::class.java)
val beanDefinition = this.beanFactory.getBeanDefinition(
"bar-org.springframework.boot.context.properties.KotlinConfigurationPropertiesBeanRegistrarTests\$BarProperties")
assertThat(beanDefinition).isExactlyInstanceOf(
ConfigurationPropertiesValueObjectBeanDefinition::class.java)
}
@Test
fun `type with no primary constructor should register generic bean definition`() {
this.registrar.register(BingProperties::class.java)
val beanDefinition = this.beanFactory.getBeanDefinition(
"bing-org.springframework.boot.context.properties.KotlinConfigurationPropertiesBeanRegistrarTests\$BingProperties")
assertThat(beanDefinition).isExactlyInstanceOf(GenericBeanDefinition::class.java)
}
@ConfigurationProperties(prefix = "foo")
class FooProperties
@ConstructorBinding
@ConfigurationProperties(prefix = "bar")
class BarProperties(val name: String?, val counter: Int = 42)
@ConfigurationProperties(prefix = "bing")
class BingProperties {
constructor()
constructor(@Suppress("UNUSED_PARAMETER") foo: String)
}
}
| mit | 37feba7288e10c1446c0ae76ff8ecaf6 | 36.301587 | 119 | 0.822553 | 4.484733 | false | true | false | false |
didi/DoraemonKit | Android/dokit-ft/src/main/java/com/didichuxing/doraemonkit/kit/filemanager/sqlite/bean/TableFieldInfo.kt | 1 | 368 | package com.didichuxing.doraemonkit.kit.filemanager.sqlite.bean
/**
* ================================================
* 作 者:jint(金台)
* 版 本:1.0
* 创建日期:2020/6/28-15:06
* 描 述:
* 修订历史:
* ================================================
*/
data class TableFieldInfo(var title: String, var isPrimary: Boolean) | apache-2.0 | 03194c0ea0199638e8f4a35f21f6f5df | 25.916667 | 68 | 0.450311 | 3.879518 | false | false | false | false |
nemerosa/ontrack | ontrack-extension-bitbucket-cloud/src/test/java/net/nemerosa/ontrack/extension/bitbucket/cloud/BitbucketCloudTestUtils.kt | 1 | 2670 | package net.nemerosa.ontrack.extension.bitbucket.cloud
import net.nemerosa.ontrack.extension.bitbucket.cloud.configuration.BitbucketCloudConfiguration
import net.nemerosa.ontrack.extension.git.GitExtensionFeature
import net.nemerosa.ontrack.extension.scm.SCMExtensionFeature
import net.nemerosa.ontrack.extension.stale.StaleExtensionFeature
import net.nemerosa.ontrack.test.TestUtils.uid
import net.nemerosa.ontrack.test.getEnv
import net.nemerosa.ontrack.test.getOptionalEnv
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.condition.EnabledIf
class BitbucketCloudTestEnv(
val workspace: String,
val user: String,
val token: String,
val expectedProject: String,
val expectedRepository: String,
)
val bitbucketCloudExtensionFeature: BitbucketCloudExtensionFeature by lazy {
BitbucketCloudExtensionFeature(GitExtensionFeature(SCMExtensionFeature(), StaleExtensionFeature()))
}
val bitbucketCloudTestEnv: BitbucketCloudTestEnv by lazy {
BitbucketCloudTestEnv(
workspace = getEnv("ontrack.test.extension.bitbucket.cloud.workspace"),
user = getEnv("ontrack.test.extension.bitbucket.cloud.user"),
token = getEnv("ontrack.test.extension.bitbucket.cloud.token"),
expectedProject = getEnv("ontrack.test.extension.bitbucket.cloud.expected.project"),
expectedRepository = getEnv("ontrack.test.extension.bitbucket.cloud.expected.repository"),
)
}
/**
* Creates a real configuration for Bitbucket Cloud, suitable for system tests.
*/
fun bitbucketCloudTestConfigReal(name: String = uid("C")) = bitbucketCloudTestEnv.run {
BitbucketCloudConfiguration(
name = name,
workspace = workspace,
user = user,
password = token,
)
}
fun bitbucketCloudTestConfigMock(
name: String = uid("C"),
workspace: String = "my-workspace",
) =
BitbucketCloudConfiguration(
name = name,
workspace = workspace,
user = "user",
password = "token",
)
/**
* Annotation to use on tests relying on an external Bitbucket Cloud repository.
*/
@Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.RUNTIME)
@Test
@EnabledIf("net.nemerosa.ontrack.extension.bitbucket.cloud.TestOnBitbucketCloudCondition#isTestOnBitbucketCloudEnabled")
annotation class TestOnBitbucketCloud
/**
* Testing if the environment is set for testing against Bitbucket Cloud
*/
class TestOnBitbucketCloudCondition {
companion object {
@JvmStatic
fun isTestOnBitbucketCloudEnabled(): Boolean =
!getOptionalEnv("ontrack.test.extension.bitbucket.cloud.workspace").isNullOrBlank()
}
}
| mit | 4112b84540806f24ea50ad325a5c46c6 | 33.230769 | 120 | 0.756554 | 4.611399 | false | true | false | false |
bailuk/AAT | aat-gtk/src/main/kotlin/ch/bailu/aat_gtk/view/toplevel/list/FileList.kt | 1 | 3274 | package ch.bailu.aat_gtk.view.toplevel.list
import ch.bailu.aat_gtk.app.GtkAppContext
import ch.bailu.aat_gtk.view.UiController
import ch.bailu.aat_gtk.view.menu.provider.SolidOverlaySelectorMenu
import ch.bailu.aat_gtk.view.solid.SolidDirectoryQueryComboView
import ch.bailu.aat_gtk.view.toplevel.list.menu.FileContextMenu
import ch.bailu.aat_lib.description.AverageSpeedDescription
import ch.bailu.aat_lib.description.DateDescription
import ch.bailu.aat_lib.description.DistanceDescription
import ch.bailu.aat_lib.description.TimeDescription
import ch.bailu.aat_lib.logger.AppLog
import ch.bailu.aat_lib.preferences.SolidDirectoryQuery
import ch.bailu.aat_lib.preferences.StorageInterface
import ch.bailu.aat_lib.preferences.map.SolidOverlayFileList
import ch.bailu.aat_lib.service.directory.IteratorSimple
import ch.bailu.foc.FocFactory
import ch.bailu.gtk.GTK
import ch.bailu.gtk.bridge.ListIndex
import ch.bailu.gtk.gtk.*
class FileList(
application: Application,
storage: StorageInterface,
focFactory: FocFactory,
uiController: UiController
) {
private val descriptions = arrayOf(
DateDescription(),
DistanceDescription(GtkAppContext.storage),
AverageSpeedDescription(GtkAppContext.storage),
TimeDescription())
val vbox = Box(Orientation.VERTICAL, 12)
private val listIndex = ListIndex()
private val iteratorSimple = IteratorSimple(GtkAppContext)
private val items = HashMap<ListItem, FileListItem>()
private val overlayMenu = SolidOverlaySelectorMenu(SolidOverlayFileList(storage,focFactory))
private var logCounter = 0
private fun log() {
logCounter++
if (logCounter > 30) {
AppLog.d(this, "Refs (items): ${items.size}")
logCounter = 0
}
}
init {
try {
listIndex.size = iteratorSimple.count
val factory = SignalListItemFactory()
factory.onSetup { item: ListItem ->
items[item] = FileListItem(item, FileContextMenu(overlayMenu, iteratorSimple, uiController, application), descriptions)
log()
}
factory.onBind { item: ListItem ->
val index = ListIndex.toIndex(item)
iteratorSimple.moveToPosition(index)
items[item]?.bind(iteratorSimple.info, index)
}
factory.onTeardown { item: ListItem->
items.remove(item)
log()
}
val list = ListView(listIndex.inSelectionModel(), factory)
list.onActivate {
iteratorSimple.moveToPosition(it)
uiController.load(iteratorSimple.info)
}
iteratorSimple.setOnCursorChangedListener {
if (listIndex.size != iteratorSimple.count) {
listIndex.size = iteratorSimple.count
}
}
val scrolled = ScrolledWindow()
scrolled.child = list
scrolled.hexpand = GTK.TRUE
scrolled.vexpand = GTK.TRUE
vbox.append(SolidDirectoryQueryComboView(storage, focFactory).combo)
vbox.append(scrolled)
} catch (e: Exception) {
AppLog.e(this, e)
}
}
}
| gpl-3.0 | 69e425833f42e2014520efd1bfe43d1d | 32.070707 | 135 | 0.658216 | 4.394631 | false | false | false | false |
liceoArzignano/app_bold | app/src/main/kotlin/it/liceoarzignano/bold/marks/Mark.kt | 1 | 563 | package it.liceoarzignano.bold.marks
import it.liceoarzignano.bold.database.DBItem
class Mark : DBItem {
var subject = ""
var value = 0
var date = 0L
var description = ""
var isFirstQuarter = false
constructor()
constructor(id: Long, subject: String, value: Int, date: Long,
description: String, firstQuarter: Boolean) {
this.id = id
this.subject = subject
this.value = value
this.date = date
this.description = description
this.isFirstQuarter = firstQuarter
}
}
| lgpl-3.0 | 210ce04c24f937b301fcd64498401226 | 23.478261 | 66 | 0.625222 | 4.265152 | false | false | false | false |
bailuk/AAT | aat-gtk/src/main/kotlin/ch/bailu/aat_gtk/search/RestNominatim.kt | 1 | 811 | package ch.bailu.aat_gtk.search
import ch.bailu.aat_gtk.app.GtkAppContext
import ch.bailu.aat_gtk.config.Strings
import ch.bailu.aat_gtk.lib.rest.RestClient
import ch.bailu.aat_lib.util.fs.AppDirectory
import java.io.File
class RestNominatim {
val restClient = RestClient(getJsonFile("search"), Strings.appIdName,"{\"result\":","}")
fun search(search: String, observer: (RestClient)->Unit) {
val url = "https://nominatim.openstreetmap.org/search"
this.restClient.download("${url}?city=${search}&format=json", observer)
}
private fun getJsonFile(name: String): File {
val dir = AppDirectory.getDataDirectory(
GtkAppContext.dataDirectory,
AppDirectory.DIR_NOMINATIM)
dir.mkdirs()
return File(dir.child(name).toString())
}
}
| gpl-3.0 | f27751693d3be8d74c17858ad01c3b75 | 31.44 | 92 | 0.688039 | 3.620536 | false | false | false | false |
ReactiveSocket/reactivesocket-tck | rsocket-tck-core/src/main/kotlin/io/rsocket/tck/frame/shared/RawFrame.kt | 1 | 915 | package io.rsocket.tck.frame.shared
import io.netty.buffer.*
import io.rsocket.tck.frame.*
import strikt.api.*
import strikt.assertions.*
data class RawFrame(
val header: FrameHeader<UntypedFlags>,
val type: FrameType,
val buffer: ByteBuf
)
fun ByteBuf.frame(): RawFrame = preview {
val streamId = readInt()
val typeAndFlags = readShort().toInt() and 0xFFFF
val flags = typeAndFlags and FrameHeader.FLAGS_MASK
val frameType = FrameType.fromEncodedType(typeAndFlags shr FrameHeader.TYPE_SHIFT)
RawFrame(
header = FrameHeader(
streamId = streamId,
flags = UntypedFlags(flags)
),
type = frameType,
buffer = slice()
)
}
inline fun <T> RawFrame.typed(type: FrameType, block: ByteBuf.() -> T): T {
expectThat([email protected])
.describedAs("frame type")
.isEqualTo(type)
return buffer.preview(block)
}
| apache-2.0 | 2e0462b1bbfd02c012e2fb012de0ffff | 25.911765 | 86 | 0.663388 | 3.910256 | false | false | false | false |
openHPI/android-app | app/src/main/java/de/xikolo/utils/extensions/DateExtensions.kt | 1 | 3350 | @file:JvmName("DateUtil")
package de.xikolo.utils.extensions
import android.content.Context
import android.util.Log
import de.xikolo.R
import de.xikolo.config.Config
import de.xikolo.models.Course
import java.text.DateFormat
import java.text.ParseException
import java.text.SimpleDateFormat
import java.time.Year
import java.util.*
import java.util.concurrent.TimeUnit
private const val TAG = "DateExtensions"
private const val XIKOLO_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS"
fun <T : Date> T.isBetween(from: Date?, to: Date?): Boolean {
if (from == null && to == null) {
return false
}
if (from == null) {
if (this.before(to)) {
return true
}
}
if (to == null) {
if (this.after(from)) {
return true
}
}
return from != null && to != null && this.after(from) && this.before(to)
}
val <T : Date?> T.isPast: Boolean
get() {
return this != null && Date().after(this)
}
val <T : Date?> T.isFuture: Boolean
get() {
return this != null && Date().before(this)
}
val <T : String?> T.asDate: Date?
get() {
val dateFm = SimpleDateFormat(XIKOLO_DATE_FORMAT, Locale.getDefault())
var parsedDate: Date? = null
try {
if (this != null) {
parsedDate = dateFm.parse(this)
}
} catch (e: ParseException) {
if (Config.DEBUG)
Log.w(TAG, "Failed parsing $this", e)
parsedDate = null
}
return parsedDate
}
val <T : Date> T.formattedString: String
get() {
val dateFm = SimpleDateFormat(XIKOLO_DATE_FORMAT, Locale.getDefault())
return dateFm.format(this)
}
val <T : Date> T.localString: String
get() {
val dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, Locale.getDefault())
dateFormat.timeZone = Calendar.getInstance().timeZone
return dateFormat.format(this)!!
}
val <T : Date> T.utcString: String
get() {
val dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, Locale.getDefault())
dateFormat.timeZone = TimeZone.getTimeZone("UTC")
return dateFormat.format(this)
}
fun <T : Date> T.timeLeftUntilString(context: Context): String {
val millis = this.time - Date().time
val days = TimeUnit.MILLISECONDS.toDays(millis)
val hours = TimeUnit.MILLISECONDS.toHours(millis - TimeUnit.DAYS.toMillis(days))
val minutes = TimeUnit.MILLISECONDS.toMinutes(millis - TimeUnit.DAYS.toMillis(days) - TimeUnit.HOURS.toMillis(hours))
return String.format(Locale.getDefault(), context.getString(R.string.time_left_format),
days,
hours,
minutes
)
}
val <T : Date> T.midnight: Date
get() {
val c = Calendar.getInstance()
c.time = this
c.set(Calendar.HOUR_OF_DAY, 24)
c.set(Calendar.MINUTE, 0)
c.set(Calendar.SECOND, 0)
return c.time
}
val <T : Date> T.sevenDaysAhead: Date
get() {
val c = Calendar.getInstance()
c.time = this.midnight
c.add(Calendar.DAY_OF_YEAR, 7)
return c.time
}
val <T : Date> T.calendarYear: Int
get() {
val c = Calendar.getInstance()
c.time = this
return c.get(Calendar.YEAR)
}
| bsd-3-clause | e5c38120996db0cc447ecadf029b7ff3 | 26.916667 | 121 | 0.612239 | 3.709856 | false | false | false | false |
gameofbombs/kt-postgresql-async | db-async-common/src/main/kotlin/com/github/mauricio/async/db/column/DateEncoderDecoder.kt | 2 | 1558 | /*
* Copyright 2013 Maurício Linhares
*
* Maurício Linhares licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.github.mauricio.async.db.column
import java.time.LocalDate
import java.time.format.DateTimeFormatter
import com.github.mauricio.async.db.exceptions.DateEncoderNotAvailableException
import java.time.temporal.TemporalAccessor
object DateEncoderDecoder : ColumnEncoderDecoder {
private val ZeroedDate = "0000-00-00"
private val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd")
override fun decode(value: String): LocalDate? =
if (ZeroedDate == value) {
null
} else {
LocalDate.from(this.formatter.parse(value))
}
override fun encode(value: Any): String =
when (value) {
is java.sql.Date -> this.formatter.format(value.toLocalDate())
is TemporalAccessor -> this.formatter.format(value)
else -> throw DateEncoderNotAvailableException(value)
}
}
| apache-2.0 | a2f71ab4f6cf0edcdc173fb4a178e930 | 34.363636 | 79 | 0.694087 | 4.445714 | false | false | false | false |
MimiReader/mimi-reader | mimi-app/src/main/java/com/emogoth/android/phone/mimi/db/models/RefreshQueue.kt | 1 | 1264 | package com.emogoth.android.phone.mimi.db.models
import androidx.room.*
import com.emogoth.android.phone.mimi.db.MimiDatabase
@Entity(tableName = MimiDatabase.REFRESH_QUEUE_TABLE,
indices = [Index(RefreshQueue.ID, unique = true),
Index(RefreshQueue.HISTORY_ID, unique = true)],
foreignKeys = [ForeignKey(
entity = History::class,
parentColumns = [History.ID],
childColumns = [RefreshQueue.HISTORY_ID],
onDelete = ForeignKey.CASCADE)])
data class RefreshQueue(
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = RefreshQueue.ID)
val id: Int? = null,
@ColumnInfo(name = RefreshQueue.HISTORY_ID)
val historyId: Int? = null,
@ColumnInfo(name = RefreshQueue.THREAD_SIZE)
val threadSize: Int = 0,
@ColumnInfo(name = RefreshQueue.REPLY_COUNT)
val unread: Int = 0,
@ColumnInfo(name = RefreshQueue.LAST_REFRESH)
val lastRefresh: Long = 0L
) {
companion object {
const val ID = "id"
const val HISTORY_ID = "history_id"
const val THREAD_SIZE = "thread_size"
const val REPLY_COUNT = "reply_count"
const val LAST_REFRESH = "last_refresh"
}
} | apache-2.0 | dd4370665f960ad713346b2911264792 | 31.435897 | 59 | 0.616297 | 4.199336 | false | false | false | false |
kiruto/kotlin-android-mahjong | app/src/main/java/dev/yuriel/mahjan/texture/AnimatedFontBlock.kt | 1 | 4913 | /*
* The MIT License (MIT)
*
* Copyright (c) 2016 yuriel<[email protected]>
*
* 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 dev.yuriel.mahjan.texture
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.graphics.g2d.Batch
import com.badlogic.gdx.graphics.g2d.BitmapFont
import com.badlogic.gdx.graphics.g2d.GlyphLayout
import com.badlogic.gdx.graphics.g2d.SpriteBatch
/**
* Created by yuriel on 8/12/16.
*/
open class AnimatedFontBlock(private var batch: Batch? = null) {
var font: BitmapFont? = null
private set
var painter: Painter? = null
private set
var width: Float = 0F
var height: Float = 0F
val layout: GlyphLayout = GlyphLayout()
fun load(fileName: String, imageName: String): Painter {
font = BitmapFont(Gdx.files.internal(fileName), Gdx.files.internal(imageName), false)
if (null == batch) {
batch = SpriteBatch()
}
painter = Painter()
layout.setText(font, "")
return painter!!
}
fun draw() {
painter?.draw()
}
fun draw(batch: Batch) {
painter?.draw(batch)
}
fun getCenterOriginToText(x: Float, y: Float, width: Float, height: Float): Pair<Float, Float> {
var resultX = x
var resultY = y
resultX += (width - this.width) / 2F
resultY -= (height - this.height) / 2F
return Pair(resultX, resultY)
}
inner class Painter internal constructor(){
private var color: Color = Color(0F, 0F, 0F, 0F)
private var x: Float = 0F
private var y: Float = 0F
private var scaleX: Float = 1F
private var scaleY: Float = 1F
private var text: String = ""
private var frame: Int = 0
private var colorGetter: ((Int) -> Color)? = null
private var scaleGetter: ((Int) -> Pair<Float, Float>)? = null
private var originGetter: ((Int) -> Pair<Float, Float>)? = null
fun color(c: Color): Painter {
color = c
return this
}
fun color(r: Float, g: Float, b: Float, a: Float): Painter {
color = Color(r, g, b, a)
return this
}
fun color(f: (i: Int) -> Color): Painter {
colorGetter = f
return this
}
fun scale(x: Float, y: Float): Painter {
scaleX = x
scaleY = y
return this
}
fun scale(f: (i: Int) -> Pair<Float, Float>): Painter {
scaleGetter = f
return this
}
fun text(t: String): Painter {
text = t
layout.setText(font, text)
width = layout.width
height =layout.height
return this
}
fun origin(x: Float, y: Float): Painter {
this.x = x
this.y = y
return this
}
fun origin(f: (i: Int) -> Pair<Float, Float>): Painter {
originGetter = f
return this
}
internal fun draw() {
batch?.begin()
draw(batch)
batch?.end()
}
internal fun draw(batch: Batch?) {
if (frame == Int.MAX_VALUE) frame = 0
font?.color = colorGetter?.invoke(frame)?: color
val scale: Pair<Float, Float>? = scaleGetter?.invoke(frame)
font?.data?.scaleX = scale?.first?: scaleX
font?.data?.scaleY = scale?.second?: scaleY
if (null != scale) {
width = layout.width * scale.first
height = layout.height * scale.second
}
val origin: Pair<Float, Float>? = originGetter?.invoke(frame)
x = origin?.first?: x
y = origin?.second?: y
font?.draw(batch, text, x, y)
frame ++
}
}
} | mit | c074aebf58be75b16b346ff7e7d58942 | 30.5 | 100 | 0.585386 | 4.184838 | false | false | false | false |
ojacquemart/spring-kotlin-euro-bets | src/main/kotlin/org/ojacquemart/eurobets/firebase/management/game/StartGameTask.kt | 2 | 1944 | package org.ojacquemart.eurobets.firebase.management.game
import org.ojacquemart.eurobets.firebase.Collections
import org.ojacquemart.eurobets.firebase.config.FirebaseRef
import org.ojacquemart.eurobets.firebase.config.SchedulingSettings
import org.ojacquemart.eurobets.firebase.support.Settings
import org.ojacquemart.eurobets.firebase.rx.RxFirebase
import org.ojacquemart.eurobets.lang.loggerFor
import org.springframework.scheduling.TaskScheduler
import org.springframework.scheduling.support.CronTrigger
import org.springframework.stereotype.Component
import rx.Observable
import java.util.concurrent.ScheduledFuture
import javax.annotation.PostConstruct
@Component
open class StartGameTask(val schedulingConfig: SchedulingSettings,
val ref: FirebaseRef,
val taskScheduler: TaskScheduler) {
private val log = loggerFor<StartGameTask>()
var scheduled: ScheduledFuture<*>? = null
@PostConstruct
fun checkStart() {
val obsSettings: Observable<Settings> = RxFirebase.observe(ref.firebase.child(Collections.settings))
.map { ds -> ds.getValue(Settings::class.java) }
obsSettings.subscribe { settings ->
handleStartedFlag(settings)
}
}
private fun handleStartedFlag(settings: Settings) {
log.info("Game started status: ${settings.started}")
when (settings.started) {
true -> if (scheduled != null) {
log.debug("Game is started. Cancel the scheduled task.")
scheduled!!.cancel(true);
}
false -> {
log.info("Game is not started. Set up the scheduled with cron=${schedulingConfig.cronStarted}")
val updater = SettingsUpdater(ref)
scheduled = taskScheduler.schedule(StartGameCheckRunnable(settings, updater), CronTrigger(schedulingConfig.cronStarted))
}
}
}
}
| unlicense | 1dee23ce0b52eabe6bd12a41392dafae | 37.88 | 136 | 0.696502 | 4.835821 | false | true | false | false |
edvin/tornadofx | src/main/java/tornadofx/Charts.kt | 1 | 5046 | package tornadofx
import javafx.collections.ObservableList
import javafx.event.EventTarget
import javafx.scene.chart.*
/**
* Create a PieChart with optional title data and add to the parent pane. The optional op will be performed on the new instance.
*/
fun EventTarget.piechart(title: String? = null, data: ObservableList<PieChart.Data>? = null, op: PieChart.() -> Unit = {}): PieChart {
val chart = if (data != null) PieChart(data) else PieChart()
chart.title = title
return opcr(this, chart, op)
}
/**
* Add and create a PieChart.Data entry. The optional op will be performed on the data instance,
* a good place to add event handlers to the PieChart.Data.node for example.
*
* @return The new Data entry
*/
fun PieChart.data(name: String, value: Double, op: PieChart.Data.() -> Unit = {}) = PieChart.Data(name, value).apply {
data.add(this)
op(this)
}
/**
* Add and create multiple PieChart.Data entries from the given map.
*/
fun PieChart.data(value: Map<String, Double>) = value.forEach { data(it.key, it.value) }
/**
* Create a LineChart with optional title, axis and add to the parent pane. The optional op will be performed on the new instance.
*/
fun <X, Y> EventTarget.linechart(title: String? = null, x: Axis<X>, y: Axis<Y>, op: LineChart<X, Y>.() -> Unit = {}) =
LineChart<X, Y>(x, y).attachTo(this, op) { it.title = title }
/**
* Create an AreaChart with optional title, axis and add to the parent pane. The optional op will be performed on the new instance.
*/
fun <X, Y> EventTarget.areachart(title: String? = null, x: Axis<X>, y: Axis<Y>, op: AreaChart<X, Y>.() -> Unit = {}) =
AreaChart<X,Y>(x, y).attachTo(this, op){ it.title = title }
/**
* Create a BubbleChart with optional title, axis and add to the parent pane. The optional op will be performed on the new instance.
*/
fun <X, Y> EventTarget.bubblechart(title: String? = null, x: Axis<X>, y: Axis<Y>, op: BubbleChart<X, Y>.() -> Unit = {}) =
BubbleChart<X, Y>(x, y).attachTo(this,op){ it.title = title }
/**
* Create a ScatterChart with optional title, axis and add to the parent pane. The optional op will be performed on the new instance.
*/
fun <X, Y> EventTarget.scatterchart(title: String? = null, x: Axis<X>, y: Axis<Y>, op: ScatterChart<X, Y>.() -> Unit = {}) =
ScatterChart(x, y).attachTo(this,op){ it.title = title }
/**
* Create a BarChart with optional title, axis and add to the parent pane. The optional op will be performed on the new instance.
*/
fun <X, Y> EventTarget.barchart(title: String? = null, x: Axis<X>, y: Axis<Y>, op: BarChart<X, Y>.() -> Unit = {}) =
BarChart<X, Y>(x, y).attachTo(this, op){ it.title = title }
/**
* Create a BarChart with optional title, axis and add to the parent pane. The optional op will be performed on the new instance.
*/
fun <X, Y> EventTarget.stackedbarchart(title: String? = null, x: Axis<X>, y: Axis<Y>, op: StackedBarChart<X, Y>.() -> Unit = {}) =
StackedBarChart<X, Y>(x, y).attachTo(this, op) { it.title = title }
/**
* Add a new XYChart.Series with the given name to the given Chart. Optionally specify a list data for the new series or
* add data with the optional op that will be performed on the created series object.
*/
fun <X, Y, ChartType : XYChart<X, Y>> ChartType.series(
name: String,
elements: ObservableList<XYChart.Data<X, Y>>? = null,
op: (XYChart.Series<X, Y>).() -> Unit = {}
) = XYChart.Series<X, Y>().also {
it.name = name
elements?.let (it::setData)
op(it)
data.add(it)
}
/**
* Add and create a XYChart.Data entry with x, y and optional extra value. The optional op will be performed on the data instance,
* a good place to add event handlers to the Data.node for example.
*
* @return The new Data entry
*/
fun <X, Y> XYChart.Series<X, Y>.data(x: X, y: Y, extra: Any? = null, op: (XYChart.Data<X, Y>).() -> Unit = {}) = XYChart.Data<X, Y>(x, y).apply {
if (extra != null) extraValue = extra
data.add(this)
op(this)
}
/**
* Helper class for the multiseries support
*/
class MultiSeries<X, Y>(val series: List<XYChart.Series<X, Y>>, val chart: XYChart<X, Y>) {
fun data(x: X, vararg y: Y) = y.forEachIndexed { index, value -> series[index].data(x, value) }
}
/**
* Add multiple series XYChart.Series with data in one go. Specify a list of names for the series
* and then add values in the op. Example:
*
* multiseries("Portfolio 1", "Portfolio 2") {
* data(1, 23, 10)
* data(2, 14, 5)
* data(3, 15, 8)
* ...
* }
*
*/
fun <X, Y, ChartType : XYChart<X, Y>> ChartType.multiseries(vararg names: String, op: (MultiSeries<X, Y>).() -> Unit = {}): MultiSeries<X, Y> {
val series = names.map { XYChart.Series<X, Y>().apply { name = it } }
val multiSeries = MultiSeries(series, this).also(op)
data.addAll(series)
return multiSeries
}
operator fun <X, Y> XYChart.Data<X, Y>.component1(): X = xValue;
operator fun <X, Y> XYChart.Data<X, Y>.component2(): Y = yValue;
| apache-2.0 | 76271318c59cf4c0a03127a9a6b110b3 | 40.02439 | 145 | 0.65002 | 3.251289 | false | false | false | false |
AndroidX/androidx | glance/glance-appwidget/integration-tests/demos/src/main/java/androidx/glance/appwidget/demos/CompoundButtonAppWidget.kt | 3 | 10146 | /*
* 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.glance.appwidget.demos
import android.content.Context
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.booleanPreferencesKey
import androidx.glance.GlanceId
import androidx.glance.GlanceModifier
import androidx.glance.action.ActionParameters
import androidx.glance.action.actionParametersOf
import androidx.glance.appwidget.CheckBox
import androidx.glance.appwidget.checkBoxColors
import androidx.glance.appwidget.GlanceAppWidget
import androidx.glance.appwidget.GlanceAppWidgetReceiver
import androidx.glance.appwidget.RadioButton
import androidx.glance.appwidget.radioButtonColors
import androidx.glance.appwidget.SizeMode
import androidx.glance.appwidget.Switch
import androidx.glance.appwidget.switchColors
import androidx.glance.appwidget.selectableGroup
import androidx.glance.appwidget.action.ActionCallback
import androidx.glance.appwidget.action.ToggleableStateKey
import androidx.glance.appwidget.action.actionRunCallback
import androidx.glance.appwidget.appWidgetBackground
import androidx.glance.appwidget.cornerRadius
import androidx.glance.appwidget.state.updateAppWidgetState
import androidx.glance.background
import androidx.glance.color.ColorProvider
import androidx.glance.currentState
import androidx.glance.layout.Alignment
import androidx.glance.layout.Column
import androidx.glance.layout.Row
import androidx.glance.layout.fillMaxSize
import androidx.glance.layout.fillMaxWidth
import androidx.glance.layout.padding
import androidx.glance.layout.height
import androidx.glance.text.FontStyle
import androidx.glance.text.FontWeight
import androidx.glance.text.TextStyle
class CompoundButtonAppWidget : GlanceAppWidget() {
override val sizeMode: SizeMode = SizeMode.Exact
enum class Buttons {
CHECK_1, CHECK_2, CHECK_3, SWITCH_1, SWITCH_2, RADIO_1, RADIO_2, RADIO_3;
val prefsKey = booleanPreferencesKey(name)
}
enum class Radios {
RADIO_1, RADIO_2, RADIO_3;
val prefsKey = booleanPreferencesKey(name)
}
@Composable
override fun Content() {
Column(
modifier = GlanceModifier.fillMaxSize().background(Color.LightGray)
.padding(R.dimen.external_padding).cornerRadius(R.dimen.corner_radius)
.appWidgetBackground(),
verticalAlignment = Alignment.Vertical.CenterVertically,
horizontalAlignment = Alignment.Horizontal.CenterHorizontally
) {
val textStyle = TextStyle(
color = ColorProvider(day = Color.Red, night = Color.Cyan),
fontSize = 16.sp,
fontWeight = FontWeight.Bold,
fontStyle = FontStyle.Italic
)
val fillModifier = GlanceModifier.fillMaxWidth()
val prefs = currentState<Preferences>()
val checkbox1Checked = prefs[Buttons.CHECK_1.prefsKey] ?: false
val checkbox2Checked = prefs[Buttons.CHECK_2.prefsKey] ?: false
val checkbox3Checked = prefs[Buttons.CHECK_3.prefsKey] ?: false
val switch1Checked = prefs[Buttons.SWITCH_1.prefsKey] ?: false
val switch2Checked = prefs[Buttons.SWITCH_2.prefsKey] ?: false
val radio1Checked = prefs[Buttons.RADIO_1.prefsKey] ?: false
val radio2Checked = prefs[Buttons.RADIO_2.prefsKey] ?: false
val radio3Checked = prefs[Buttons.RADIO_3.prefsKey] ?: false
CheckBox(
checked = checkbox1Checked,
onCheckedChange = actionRunCallback<ToggleAction>(
actionParametersOf(EventTargetKey to Buttons.CHECK_1.name)
),
text = "Checkbox 1",
modifier = GlanceModifier.height(56.dp).padding(bottom = 24.dp),
)
CheckBox(
checked = checkbox2Checked,
onCheckedChange = actionRunCallback<ToggleAction>(
actionParametersOf(EventTargetKey to Buttons.CHECK_2.name)
),
text = "Checkbox 2",
style = textStyle,
modifier = fillModifier,
colors = checkBoxColors(
checkedColor = ColorProvider(day = Color.Red, night = Color.Cyan),
uncheckedColor = ColorProvider(day = Color.Green, night = Color.Magenta)
)
)
CheckBox(
checked = checkbox3Checked,
onCheckedChange = actionRunCallback<ToggleAction>(
actionParametersOf(EventTargetKey to Buttons.CHECK_3.name)
),
text = "Checkbox 3",
)
Switch(
checked = switch1Checked,
onCheckedChange = actionRunCallback<ToggleAction>(
actionParametersOf(EventTargetKey to Buttons.SWITCH_1.name)
),
text = "Switch 1",
colors = switchColors(
checkedThumbColor = ColorProvider(day = Color.Red, night = Color.Cyan),
uncheckedThumbColor = ColorProvider(day = Color.Green, night = Color.Magenta),
checkedTrackColor = ColorProvider(day = Color.Blue, night = Color.Yellow),
uncheckedTrackColor = ColorProvider(day = Color.Magenta, night = Color.Green)
),
)
Switch(
checked = switch2Checked,
onCheckedChange = actionRunCallback<ToggleAction>(
actionParametersOf(EventTargetKey to Buttons.SWITCH_2.name)
),
text = "Switch 2",
style = textStyle,
modifier = fillModifier
)
Column(modifier = fillModifier.selectableGroup()) {
RadioButton(
checked = radio1Checked,
onClick = actionRunCallback<RadioAction>(
actionParametersOf(EventTargetKey to Radios.RADIO_1.name)
),
text = "Radio 1",
colors = radioButtonColors(
checkedColor = ColorProvider(day = Color.Red, night = Color.Cyan),
uncheckedColor = ColorProvider(day = Color.Green, night = Color.Magenta)
),
)
RadioButton(
checked = radio2Checked,
onClick = actionRunCallback<RadioAction>(
actionParametersOf(EventTargetKey to Radios.RADIO_2.name)
),
text = "Radio 2",
colors = radioButtonColors(
checkedColor = ColorProvider(day = Color.Cyan, night = Color.Yellow),
uncheckedColor = ColorProvider(day = Color.Red, night = Color.Blue)
),
)
RadioButton(
checked = radio3Checked,
onClick = actionRunCallback<RadioAction>(
actionParametersOf(EventTargetKey to Radios.RADIO_3.name)
),
text = "Radio 3",
)
}
Row(modifier = fillModifier.selectableGroup()) {
RadioButton(
checked = radio1Checked,
onClick = null,
text = "Radio 1",
)
RadioButton(
checked = radio2Checked,
onClick = null,
text = "Radio 2",
)
RadioButton(
checked = radio3Checked,
onClick = null,
text = "Radio 3",
)
}
}
}
}
class ToggleAction : ActionCallback {
override suspend fun onAction(
context: Context,
glanceId: GlanceId,
parameters: ActionParameters,
) {
val target = requireNotNull(parameters[EventTargetKey]) {
"Add event target to parameters in order to update the view state."
}.let { CompoundButtonAppWidget.Buttons.valueOf(it) }
val checked = requireNotNull(parameters[ToggleableStateKey]) {
"This action should only be called in response to toggleable events"
}
updateAppWidgetState(context, glanceId) { state ->
state[target.prefsKey] = checked
}
CompoundButtonAppWidget().update(context, glanceId)
}
}
private val EventTargetKey = ActionParameters.Key<String>("EventTarget")
class RadioAction : ActionCallback {
override suspend fun onAction(
context: Context,
glanceId: GlanceId,
parameters: ActionParameters,
) {
val target = requireNotNull(parameters[EventTargetKey]) {
"Add event target to parameters in order to update the view state."
}.let { CompoundButtonAppWidget.Radios.valueOf(it) }
updateAppWidgetState(context, glanceId) { state ->
CompoundButtonAppWidget.Radios.values().forEach { state[it.prefsKey] = it == target }
}
CompoundButtonAppWidget().update(context, glanceId)
}
}
class CompoundButtonAppWidgetReceiver : GlanceAppWidgetReceiver() {
override val glanceAppWidget = CompoundButtonAppWidget()
}
| apache-2.0 | 37af8e71f8709ce6bc6aaffc7bc46063 | 40.581967 | 98 | 0.617879 | 5.168619 | false | false | false | false |
AndroidX/androidx | privacysandbox/tools/tools-core/src/main/java/androidx/privacysandbox/tools/core/generator/BinderCodeConverter.kt | 3 | 6863 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.privacysandbox.tools.core.generator
import androidx.privacysandbox.tools.core.model.AnnotatedInterface
import androidx.privacysandbox.tools.core.model.ParsedApi
import androidx.privacysandbox.tools.core.model.Type
import androidx.privacysandbox.tools.core.model.Types
import com.squareup.kotlinpoet.ClassName
import com.squareup.kotlinpoet.CodeBlock
import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy
import com.squareup.kotlinpoet.TypeName
/** Utility to generate [CodeBlock]s that convert values to/from their binder equivalent. */
abstract class BinderCodeConverter(private val api: ParsedApi) {
/**
* Generate a block that converts the given expression from the binder representation to its
* model equivalent.
*
* @param type the type of the resulting expression. Can reference a primitive on annotated
* interface/value.
* @param expression the expression to be converted.
* @return a [CodeBlock] containing the generated code to perform the conversion.
*/
fun convertToModelCode(type: Type, expression: String): CodeBlock {
require(type != Types.unit) { "Cannot convert Unit." }
val value = api.valueMap[type]
if (value != null) {
return CodeBlock.of("%M(%L)", value.fromParcelableNameSpec(), expression)
}
val callback = api.callbackMap[type]
if (callback != null) {
return CodeBlock.of("%T(%L)", callback.clientProxyNameSpec(), expression)
}
val sandboxInterface = api.interfaceMap[type]
if (sandboxInterface != null) {
return convertToInterfaceModelCode(sandboxInterface, expression)
}
if (type.qualifiedName == List::class.qualifiedName) {
val convertToModelCodeBlock = convertToModelCode(type.typeParameters[0], "it")
return CodeBlock.of(
"%L%L.toList()",
expression,
// Only convert the list elements if necessary.
if (convertToModelCodeBlock == CodeBlock.of("it"))
CodeBlock.of("")
else
CodeBlock.of(".map { %L }", convertToModelCodeBlock)
)
}
if (type == Types.short) {
return CodeBlock.of("%L.toShort()", expression)
}
return CodeBlock.of(expression)
}
protected abstract fun convertToInterfaceModelCode(
annotatedInterface: AnnotatedInterface,
expression: String
): CodeBlock
/**
* Generate a block that converts the given expression from the model representation to its
* binder equivalent.
*
* @param type the type of the given expression. Can reference a primitive on annotated
* interface/value.
* @param expression the expression to be converted.
* @return a [CodeBlock] containing the generated code to perform the conversion.
*/
fun convertToBinderCode(type: Type, expression: String): CodeBlock {
require(type != Types.unit) { "Cannot convert to Unit." }
val value = api.valueMap[type]
if (value != null) {
return CodeBlock.of("%M(%L)", value.toParcelableNameSpec(), expression)
}
val callback = api.callbackMap[type]
if (callback != null) {
return CodeBlock.of("%T(%L)", callback.stubDelegateNameSpec(), expression)
}
val sandboxInterface = api.interfaceMap[type]
if (sandboxInterface != null) {
return convertToInterfaceBinderCode(sandboxInterface, expression)
}
if (type.qualifiedName == List::class.qualifiedName) {
val convertToBinderCodeBlock = convertToBinderCode(type.typeParameters[0], "it")
return CodeBlock.of(
"%L%L.%L()",
expression,
// Only convert the list elements if necessary.
if (convertToBinderCodeBlock == CodeBlock.of("it"))
CodeBlock.of("")
else
CodeBlock.of(".map { %L }", convertToBinderCodeBlock),
toBinderList(type.typeParameters[0])
)
}
if (type == Types.short) {
return CodeBlock.of("%L.toInt()", expression)
}
return CodeBlock.of(expression)
}
private fun toBinderList(type: Type) = when (type) {
Types.boolean -> "toBooleanArray"
Types.int -> "toIntArray"
Types.long -> "toLongArray"
Types.short -> "toIntArray"
Types.float -> "toFloatArray"
Types.double -> "toDoubleArray"
Types.char -> "toCharArray"
else -> "toTypedArray"
}
protected abstract fun convertToInterfaceBinderCode(
annotatedInterface: AnnotatedInterface,
expression: String
): CodeBlock
/** Convert the given model type declaration to its binder equivalent. */
fun convertToBinderType(type: Type): TypeName {
val value = api.valueMap[type]
if (value != null) {
return value.parcelableNameSpec()
}
val callback = api.callbackMap[type]
if (callback != null) {
return callback.aidlType().innerType.poetTypeName()
}
val sandboxInterface = api.interfaceMap[type]
if (sandboxInterface != null) {
return sandboxInterface.aidlType().innerType.poetTypeName()
}
if (type.qualifiedName == List::class.qualifiedName)
return convertToBinderListType(type)
return type.poetTypeName()
}
private fun convertToBinderListType(type: Type): TypeName =
when (type.typeParameters[0]) {
Types.boolean -> ClassName("kotlin", "BooleanArray")
Types.int -> ClassName("kotlin", "IntArray")
Types.long -> ClassName("kotlin", "LongArray")
Types.short -> ClassName("kotlin", "IntArray")
Types.float -> ClassName("kotlin", "FloatArray")
Types.double -> ClassName("kotlin", "DoubleArray")
Types.char -> ClassName("kotlin", "CharArray")
else -> ClassName("kotlin", "Array")
.parameterizedBy(convertToBinderType(type.typeParameters[0]))
}
} | apache-2.0 | bd6dbc8ef2a90496f35ccbfb51d0ec79 | 40.6 | 96 | 0.634854 | 4.826301 | false | false | false | false |
deeplearning4j/deeplearning4j | nd4j/samediff-import/samediff-import-tensorflow/src/main/kotlin/org/nd4j/samediff/frameworkimport/tensorflow/rule/attribute/TensorflowNDArrayToIntAttributeValue.kt | 1 | 5009 | /*
* ******************************************************************************
* *
* *
* * This program and the accompanying materials are made available under the
* * terms of the Apache License, Version 2.0 which is available at
* * https://www.apache.org/licenses/LICENSE-2.0.
* *
* * See the NOTICE file distributed with this work for additional
* * information regarding copyright ownership.
* * 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.
* *
* * SPDX-License-Identifier: Apache-2.0
* *****************************************************************************
*/
package org.nd4j.samediff.frameworkimport.tensorflow.rule.attribute
import org.nd4j.ir.OpNamespace
import org.nd4j.samediff.frameworkimport.argDescriptorType
import org.nd4j.samediff.frameworkimport.findOp
import org.nd4j.samediff.frameworkimport.ir.IRAttribute
import org.nd4j.samediff.frameworkimport.isNd4jTensorName
import org.nd4j.samediff.frameworkimport.isOutputFrameworkAttributeName
import org.nd4j.samediff.frameworkimport.opdefs.OpDescriptorLoaderHolder
import org.nd4j.samediff.frameworkimport.process.MappingProcess
import org.nd4j.samediff.frameworkimport.rule.MappingRule
import org.nd4j.samediff.frameworkimport.rule.attribute.AttributeValueType
import org.nd4j.samediff.frameworkimport.rule.attribute.NDArrayToIntAttributeValue
import org.nd4j.samediff.frameworkimport.tensorflow.ir.TensorflowIRAttr
import org.nd4j.samediff.frameworkimport.tensorflow.ir.isTensorflowAttributeName
import org.nd4j.samediff.frameworkimport.tensorflow.ir.isTensorflowTensorName
import org.nd4j.samediff.frameworkimport.tensorflow.ir.tensorflowAttributeValueTypeFor
import org.tensorflow.framework.*
@MappingRule("tensorflow","ndarraytointattributevalue","attribute")
class TensorflowNDArrayToIntAttributeValue(mappingNamesToPerform: Map<String, String>) : NDArrayToIntAttributeValue<GraphDef, OpDef, NodeDef, OpDef.AttrDef, AttrValue, TensorProto, DataType>(mappingNamesToPerform = mappingNamesToPerform,transformerArgs = emptyMap()) {
override fun createIRAttribute(name: String, attrDef: OpDef.AttrDef, attributeValueType: AttrValue): IRAttribute<OpDef.AttrDef, AttrValue, TensorProto, DataType> {
return TensorflowIRAttr(attrDef, attributeValueType)
}
override fun convertAttributesReverse(allInputArguments: List<OpNamespace.ArgDescriptor>, inputArgumentsToProcess: List<OpNamespace.ArgDescriptor>): List<IRAttribute<OpDef.AttrDef, AttrValue, TensorProto, DataType>> {
TODO("Not yet implemented")
}
override fun isInputFrameworkTensorName(name: String, mappingProcess: MappingProcess<GraphDef, OpDef, NodeDef, TensorProto, OpDef.AttrDef, AttrValue, DataType>): Boolean {
val opDef = OpDescriptorLoaderHolder.listForFramework<OpDef>("tensorflow")[mappingProcess.inputFrameworkOpName()]!!
return isTensorflowTensorName(name, opDef)
}
override fun isNd4jTensorName(name: String, mappingProcess: MappingProcess<GraphDef, OpDef, NodeDef, TensorProto, OpDef.AttrDef, AttrValue, DataType>): Boolean {
val nd4jOpDescriptor = OpDescriptorLoaderHolder.nd4jOpDescriptor.findOp(mappingProcess.opName())
return isNd4jTensorName(name,nd4jOpDescriptor)
}
override fun isInputFrameworkAttributeName(name: String, mappingProcess: MappingProcess<GraphDef, OpDef, NodeDef, TensorProto, OpDef.AttrDef, AttrValue, DataType>): Boolean {
val opDef = OpDescriptorLoaderHolder.listForFramework<OpDef>("tensorflow")[mappingProcess.inputFrameworkOpName()]!!
return isTensorflowAttributeName(name, opDef)
}
override fun isOutputFrameworkAttributeName(name: String, mappingProcess: MappingProcess<GraphDef, OpDef, NodeDef, TensorProto, OpDef.AttrDef, AttrValue, DataType>): Boolean {
val nd4jOpDescriptor = OpDescriptorLoaderHolder.nd4jOpDescriptor.findOp(mappingProcess.opName())
return isOutputFrameworkAttributeName(name,nd4jOpDescriptor)
}
override fun argDescriptorType(name: String, mappingProcess: MappingProcess<GraphDef, OpDef, NodeDef, TensorProto, OpDef.AttrDef, AttrValue, DataType>): OpNamespace.ArgDescriptor.ArgType {
val nd4jOpDescriptor = OpDescriptorLoaderHolder.nd4jOpDescriptor.findOp(mappingProcess.opName())
return argDescriptorType(name,nd4jOpDescriptor)
}
override fun attributeValueTypeFor(name: String, mappingProcess: MappingProcess<GraphDef, OpDef, NodeDef, TensorProto, OpDef.AttrDef, AttrValue, DataType>): AttributeValueType {
val opDef = OpDescriptorLoaderHolder.listForFramework<OpDef>("tensorflow")[mappingProcess.inputFrameworkOpName()]!!
return tensorflowAttributeValueTypeFor(attributeName = name, opDef = opDef)
}
} | apache-2.0 | 5f33f0d11897edae98645aa51e2a4c03 | 60.851852 | 268 | 0.771811 | 5.019038 | false | false | false | false |
Undin/intellij-rust | toml/src/main/kotlin/org/rust/toml/crates/local/CratesLocalIndexService.kt | 2 | 2676 | /*
* 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.intellij.openapi.components.service
import com.intellij.openapi.components.serviceIfCreated
import io.github.z4kn4fein.semver.Version
import io.github.z4kn4fein.semver.toVersionOrNull
import org.jetbrains.annotations.TestOnly
import org.rust.stdext.RsResult
import java.nio.file.Path
interface CratesLocalIndexService {
/**
* @return [CargoRegistryCrate] if there is a crate with such [crateName], and `null` if it is not.
*/
fun getCrate(crateName: String): RsResult<CargoRegistryCrate?, Error>
/**
* @return list of crate names in the index.
*/
fun getAllCrateNames(): RsResult<List<String>, Error>
sealed class Error {
object Updating : Error() {
override fun toString(): String =
"CratesLocalIndexService.Error.Updating(Index is being updated)"
}
object NotYetLoaded : Error() {
override fun toString(): String =
"CratesLocalIndexService.Error.NotYetLoaded(The index is not yet loaded)"
}
object Disposed : Error() {
override fun toString(): String =
"CratesLocalIndexService.Error.Disposed(The service has been disposed)"
}
sealed class InternalError : Error() {
data class NoCargoIndex(val path: Path) : InternalError()
data class RepoReadError(val path: Path, val message: String) : InternalError()
data class PersistentHashMapInitError(val path: Path, val message: String) : InternalError()
data class PersistentHashMapWriteError(val message: String) : InternalError()
data class PersistentHashMapReadError(val message: String) : InternalError()
}
}
companion object {
fun getInstance(): CratesLocalIndexService = service()
fun getInstanceIfCreated(): CratesLocalIndexService? = serviceIfCreated()
}
}
data class CargoRegistryCrate(val versions: List<CargoRegistryCrateVersion>) {
val sortedVersions: List<CargoRegistryCrateVersion>
get() = versions.sortedBy { it.semanticVersion }
companion object {
@TestOnly
fun of(vararg versions: String): CargoRegistryCrate =
CargoRegistryCrate(versions.map {
CargoRegistryCrateVersion(it, false, emptyList())
})
}
}
data class CargoRegistryCrateVersion(
val version: String,
val isYanked: Boolean,
val features: List<String>
) {
val semanticVersion: Version? get() = version.toVersionOrNull()
}
| mit | f93ec96b263d8059fe5626942bc32bc7 | 33.753247 | 104 | 0.676009 | 4.489933 | false | false | false | false |
TeamWizardry/LibrarianLib | modules/facade/src/main/kotlin/com/teamwizardry/librarianlib/facade/pastry/layers/dropdown/PastryDropdown.kt | 1 | 3371 | package com.teamwizardry.librarianlib.facade.pastry.layers.dropdown
import com.teamwizardry.librarianlib.etcetera.eventbus.CancelableEvent
import com.teamwizardry.librarianlib.etcetera.eventbus.Hook
import com.teamwizardry.librarianlib.facade.layer.GuiLayer
import com.teamwizardry.librarianlib.facade.layer.GuiLayerEvents
import com.teamwizardry.librarianlib.facade.layers.SpriteLayer
import com.teamwizardry.librarianlib.facade.pastry.Pastry
import com.teamwizardry.librarianlib.facade.pastry.PastryTexture
import com.teamwizardry.librarianlib.facade.pastry.layers.PastryActivatedControl
import com.teamwizardry.librarianlib.facade.layer.supporting.ScreenSpace
import com.teamwizardry.librarianlib.core.util.rect
import com.teamwizardry.librarianlib.core.util.vec
import java.util.function.Consumer
public class PastryDropdown<T> constructor(
posX: Int, posY: Int,
width: Int,
callback: Consumer<T>?
): PastryActivatedControl(posX, posY, width, Pastry.lineHeight) {
public val items: MutableList<PastryDropdownItem<T>> = mutableListOf()
public var selected: PastryDropdownItem<T>? = null
private set
private val sprite = SpriteLayer(PastryTexture.dropdown, 0, 0, widthi, heighti)
private var menu: DropdownMenu<T>? = null
internal var buttonContents: GuiLayer? = null
init {
if (callback != null)
this.BUS.hook<SelectEvent<T>> {
callback.accept(it.value)
}
this.add(sprite)
}
public fun selectIndex(index: Int) {
val newItem = items[index]
if (selected === newItem) return
if (newItem.decoration) {
selected = null
buttonContents?.also { remove(it) }
buttonContents = null
} else {
selected = newItem
buttonContents?.also { remove(it) }
buttonContents = newItem.createLayer().also { add(it) }
}
if (!newItem.decoration)
BUS.fire(SelectEvent(newItem.value))
}
public fun select(value: T) {
val index = items.indexOfFirst {
!it.decoration && it.value == value
}
if (index == -1)
throw IllegalArgumentException("Could not find dropdown item with value of $value")
selectIndex(index)
}
private fun openMenu(mouseActivated: Boolean) {
val menu = DropdownMenu(this, mouseActivated)
this.menu = menu
root.add(menu)
menu.initialMousePos = convertPointTo(mousePos, ScreenSpace)
menu.pos = this.convertPointTo(vec(0, 0), root)
selected?.also { menu.scrollTo(it) }
}
internal fun menuClosed() {
}
override fun activate() {
openMenu(false)
}
@Hook
private fun removeFromParent(e: GuiLayerEvents.RemoveFromParentEvent) {
menu?.also {
it.parent?.remove(it)
}
}
@Hook
private fun mouseDown(e: GuiLayerEvents.MouseDown) {
if (this.mouseOver) {
openMenu(true)
}
}
override fun layoutChildren() {
sprite.size = this.size
buttonContents?.frame = rect(2, 2, width - 10, height - 4)
}
public fun sizeToFit() {
this.width = items.map { it.createLayer().width + 15 }.maxOrNull() ?: this.width
}
public class SelectEvent<T>(public val value: T): CancelableEvent()
} | lgpl-3.0 | bc6991620040be5c3f1b2a3c573ff423 | 31.423077 | 95 | 0.661228 | 4.256313 | false | false | false | false |
devromik/black-and-white | sources/src/main/kotlin/net/devromik/bw/x/PairXResult.kt | 1 | 2497 | package net.devromik.bw.x
import net.devromik.bw.*
import net.devromik.bw.Color.*
import net.devromik.tree.TreeNode
import java.lang.Math.max
/**
* @author Shulnyaev Roman
*/
class PairXResult<D>(
val root: TreeNode<D>,
val top: XResult<D>,
val childPos: Int = 0) : XResult<D> {
val child = root.childAt(childPos)
val subtreeSize = top.subtreeSize() + 1
val topMaxWhiteMap = top.maxWhiteMap()
val maxWhiteMap: FixedRootColorMaxWhiteMap
// ****************************** //
init {
maxWhiteMap = FixedRootColorMaxWhiteMap(subtreeSize)
for (black in (0..subtreeSize)) {
// BLACK
maxWhiteMap[BLACK, black] = max(
topMaxWhiteMap[BLACK, black - 1],
topMaxWhiteMap[BLACK, black])
// WHITE
var topMaxWhite = topMaxWhiteMap[WHITE, black]
maxWhiteMap[WHITE, black] = if (topMaxWhite != INVALID_MAX_WHITE) topMaxWhite + 1 else INVALID_MAX_WHITE
// GRAY
topMaxWhite = topMaxWhiteMap[GRAY, black]
maxWhiteMap[GRAY, black] = max(
topMaxWhiteMap[GRAY, black - 1],
if (topMaxWhite != INVALID_MAX_WHITE) topMaxWhite + 1 else INVALID_MAX_WHITE)
}
}
// ****************************** //
override fun maxWhiteMap() = maxWhiteMap
override fun color(coloring: Coloring<D>, rootColor: Color, black: Int, maxWhite: Int) {
coloring.color(root, rootColor)
// BLACK
if (rootColor == BLACK) {
if (topMaxWhiteMap[BLACK, black - 1] > topMaxWhiteMap[BLACK, black]) {
top.color(coloring, BLACK, black - 1, maxWhite)
coloring.color(child, BLACK)
}
else {
top.color(coloring, BLACK, black, maxWhite)
coloring.color(child, GRAY)
}
}
// WHITE
else if (rootColor == WHITE) {
top.color(coloring, WHITE, black, maxWhite - 1)
coloring.color(child, WHITE)
}
// GRAY
else {
if (topMaxWhiteMap[GRAY, black - 1] > topMaxWhiteMap[GRAY, black]) {
top.color(coloring, GRAY, black - 1, maxWhite)
coloring.color(child, BLACK)
}
else {
top.color(coloring, GRAY, black, maxWhite - 1)
coloring.color(child, WHITE)
}
}
}
override fun subtreeSize() = subtreeSize
} | mit | 13a8565b13222a14922b3dcf9d64c4a2 | 29.839506 | 116 | 0.542251 | 4.168614 | false | false | false | false |
veyndan/reddit-client | app/src/main/java/com/veyndan/paper/reddit/SubredditFilterFragment.kt | 2 | 969 | package com.veyndan.paper.reddit
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.veyndan.paper.reddit.api.reddit.Reddit
import com.veyndan.paper.reddit.databinding.FragmentSubredditFilterBinding
class SubredditFilterFragment : Fragment(), Filter {
private lateinit var binding: FragmentSubredditFilterBinding
companion object {
@JvmStatic
fun newInstance(): SubredditFilterFragment = SubredditFilterFragment()
}
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
binding = FragmentSubredditFilterBinding.inflate(inflater, container, false)
return binding.root
}
override fun requestFilter(): Reddit.Filter = Reddit.Filter(
nodeDepth = 0,
subredditName = binding.filterFormSubreddit.text.toString())
}
| mit | 98a2a3f04c10f57974f5fbe54305b12c | 31.3 | 117 | 0.757482 | 4.773399 | false | false | false | false |
fcostaa/kotlin-microservice | app/src/test/kotlin/com/felipecosta/microservice/app/movies/frontcontroller/UpdateMovieFrontCommandTest.kt | 1 | 1416 | package com.felipecosta.microservice.app.movies.frontcontroller
import com.felipecosta.microservice.app.NotImplementedRequest
import com.felipecosta.microservice.app.core.domain.MoviesRepository
import com.felipecosta.microservice.app.core.domain.entity.Movie
import com.felipecosta.microservice.server.Request
import com.felipecosta.microservice.server.Response
import io.mockk.*
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.TestInstance
import kotlin.test.assertEquals
@TestInstance(value = TestInstance.Lifecycle.PER_CLASS)
class UpdateMovieFrontCommandTest {
private val mockMoviesRepository = mockk<MoviesRepository>()
private val frontCommand = UpdateMovieFrontCommand(mockMoviesRepository)
@BeforeEach
fun setUp() {
clearAllMocks()
}
@Test
fun givenJsonBodyThenAssertResponseWithUpdatedMovie() {
frontCommand.init(object : Request by NotImplementedRequest() {
override val body: String = """{"name":"New movie"}"""
override val routeParams = mapOf(":id" to "1")
})
every { mockMoviesRepository.find(1) } returns Movie("Old movie", 1)
every { mockMoviesRepository.update(Movie("New movie", 1)) } just Runs
frontCommand.process()
assertEquals(Response("""{"response":{"name":"New movie","id":1}}""", 200), frontCommand.response)
}
} | mit | 9c0c0cdff38df59cca93a93c8039c454 | 34.425 | 106 | 0.737994 | 4.509554 | false | true | false | false |
Tvede-dk/CommonsenseAndroidKotlin | widgets/src/main/kotlin/com/commonsense/android/kotlin/views/input/selection/SingleSelectionHandler.kt | 1 | 7019 | package com.commonsense.android.kotlin.views.input.selection
import com.commonsense.android.kotlin.base.*
import com.commonsense.android.kotlin.base.extensions.*
/**
* Handles a group of ToggleableViews , such that you can select at max 1 of them
* and any other selection will change that selection.
* This is very similar to the concept of a Radiobutton group,
* except we provide a value on each selection in the callback,
* thus removing all kinds of worries about which view is selected and
* extracting / calculating a value from that
* it can also be configured to allow deselection, by calling the allowDeselection.
*/
class SingleSelectionHandler<T>(callback: FunctionUnit<T>) :
BaseSelectionHandler<T, T, ToggleableView<T>?>(callback) {
/**
* The one we should interact with, it handles the set-ting correctly.
*/
override var selection: ToggleableView<T>? = null
set(value) {
//deselect previous one if any
field?.deselect()
//set newly selected (if any) and at the same time call the callback notifying about any
// selection changes.
field = value.parseTo(this::toggleCallbackToCallback)
}
// /**
// * The views we are working on, akk the once that can be selected and deselected (only 1 selected at a time).
// *
// * Consideration: should this be a Set, but will that cause any issues ?
// *
// *
// */
// private val viewsToWorkOn = mutableListOf<ToggleableView<T>>()
// /**
// *Simple guard against callback hell / massacre
// */
// private var innerDisableSelectionChanged = false
/**
* The one we should interact with, it handles the setting correctly.
*/
// private var selected: ToggleableView<T>? = null
// set(value) {
// //deselect previous one if any
// field?.deselect()
// //set newly selected (if any) and at the same time call the callback notifying about any
// // selection changes.
// field = value.parseTo(this::toggleCallbackToCallback)
// }
/**
* Notifies the callback about a selection change, if any callback are registered.
*/
private fun toggleCallbackToCallback(toggleView: ToggleableView<T>) =
callback.invoke(toggleView.value)
/**
* Whenever we are allowed to de / un select all (the user)
* this can / will happen on start; and if the last selected view gets removed.
*/
private var isAllowedToUnselectedAll: Boolean = false
/**
* A callback that gets called every time we deselect an item (so no selection exists)
* this allows you to deselect all views.
* this is mostly a special case, as the regular callback does not allow "null" as a value,
* but this is actually that case.
*/
fun allowDeselection(onDeselection: EmptyFunction) {
onDeselectCallback = onDeselection
isAllowedToUnselectedAll = true
}
/**
* Holding the on deselection callback if any.
*/
private var onDeselectCallback: EmptyFunction? = null
// /**
// * Controls iff we allow the user to un-select the current selected.
// *
// */
// private fun onSelectionChanged(view: ToggleableView<T>, selection: Boolean) = updateSelection {
// when {
// selection && selected != view -> selected = view
// //if not allowed to deselect, make the "deselected" view selected again :)
// selected == view && !selection && !isAllowedToUnselectedAll -> selected?.select()
// //if allowed, then nothing is selected.
// selected == view && !selection && isAllowedToUnselectedAll -> {
// selected = null
// onDeselectCallback?.invoke()
// }
// }
// }
/**
* Changes the selection to the given value;
* so if the value is 42, and the 3 view in this contains that value, then that view is selected
* however it requires the value to be equatable. either though reference (pointer)
* or by implementing equal.
* It will run though all views,
* so if there are multiple views with the same value (which is an error) it will select the last one.
*
* This is O(n) where n is the number of views.
*/
fun setSelectedValue(selectedValue: T?) = updateSelection {
//find the view with the value and select it.
viewsToWorkOn.forEach {
it.checked = it.value == selectedValue
if (it.checked) {
selection = it
}
}
}
// /**
// * Updates the internal selection of this view, via a guard, to avoid any kind of callback hell.
// * It performs the action inside of the "guard"
// * (where changing selection will not cause an infinite loop effect).
// */
// private inline fun updateSelection(crossinline action: EmptyFunction) {
// if (innerDisableSelectionChanged) {
// return
// }
// innerDisableSelectionChanged = true
// action()
// innerDisableSelectionChanged = false
// }
// /**
// * Adds the given toggleable view to the list of views that we can select between.
// */
// operator fun plusAssign(selectionToAdd: ToggleableView<T>) {
// addView(selectionToAdd)
// }
//
// /**
// * De attaches the given view from the views we are working on
// */
// operator fun minusAssign(selectionToRemove: ToggleableView<T>) {
// removeView(selectionToRemove)
// }
//
// /**
// * De attaches the given view from the views we are working on
// */
// fun removeView(view: ToggleableView<T>) = updateSelection {
// view.deselect()
// view.clearOnSelectionChanged()
// if (selected == view) {
// selected = null
// }
// viewsToWorkOn.remove(view)
// }
//
// /**
// * Adds the given toggleable view to the list of views that we can select between.
// */
// fun addView(view: ToggleableView<T>) = updateSelection {
// view.deselect()
// view.setOnSelectionChanged(this::onSelectionChanged)
// viewsToWorkOn.add(view)
// }
override fun handleSelectionChanged(view: ToggleableView<T>, selectedValue: Boolean) {
when {
selectedValue && selection != view -> selection = view
//if not allowed to deselect, make the "deselected" view selected again :)
selection == view && !selectedValue && !isAllowedToUnselectedAll -> selection?.select()
//if allowed, then nothing is selected.
selection == view && !selectedValue && isAllowedToUnselectedAll -> {
selection = null
onDeselectCallback?.invoke()
}
}
}
override fun isSelected(view: ToggleableView<T>): Boolean = selection == view
override fun removeSelected() {
selection = null
}
} | mit | 1b6d232bb230489fac2a5f114b6c2e4f | 35.185567 | 115 | 0.620886 | 4.359627 | false | false | false | false |
hastebrot/protokola | src/main/kotlin/protokola/observable/dolphinObservable.kt | 1 | 5795 | package protokola.observable
import protokola.Message
import protokola.demo
import protokola.property.get
import protokola.property.push
import protokola.property.set
import protokola.property.splice
import kotlin.reflect.KClass
import kotlin.reflect.KMutableProperty1
// we need a plain object with mutable fields.
data class Person(var firstName: String? = null,
var lastName: String? = null)
data class FishShop(var fishes: MutableList<String?>? = mutableListOf())
fun main(args: Array<String>) {
demo("bind changes") {
// wrap a plain object into a bean to make it an explicit observable object.
val bean = Bean(Person())
// val bean = Bean(Person::class)
// bind fields of the plain object into observable values.
bean.property(Person::lastName)
.bind { println(it.payload) }
bean.property(Person::firstName)
.bind { println(it.payload) }
bean.property(Person::lastName).emitInitialChange()
bean.property(Person::firstName).emitInitialChange()
// change a property value.
bean.property(Person::lastName).set("Feuerstein")
bean.property(Person::firstName).set("Herbert")
// change another property value.
bean.property(Person::lastName).set("Schmidt")
bean.property(Person::firstName).set("Harald")
bean.removeProperty(Person::lastName)
bean.removeProperty(Person::firstName)
}
demo("bind splices") {
val bean = Bean(FishShop())
bean.property(FishShop::fishes)
.bind { println(it.payload) }
bean.property(FishShop::fishes).emitInitialSplice()
bean.property(FishShop::fishes)
.push("angel", "clown", "mandarin", "surgeon")
bean.property(FishShop::fishes)
.splice(1, 2, "foo", "bar")
bean.property(FishShop::fishes)
.push("baz", "quux")
}
}
// a bean serves as a wrapper for a plain object, that provides access to observable values.
class Bean<T : Any>(private val instance: T) {
private val properties = mutableMapOf<KMutableProperty1<T, *>, Property<T, *>>()
constructor(type: KClass<T>) : this(type.java.newInstance()!!)
fun <R : Any?> property(property: KMutableProperty1<T, R?>): Property<T, R> =
if (property in properties) retrieveProperty(property)
else addProperty(property)
fun <R : Any?> removeProperty(property: KMutableProperty1<T, R?>) {
properties[property]!!.unbindAll()
properties.remove(property)
}
private fun <R : Any?> addProperty(property: KMutableProperty1<T, R?>) =
Property(instance, property)
.apply { properties[property] = this }
@Suppress("UNCHECKED_CAST")
private fun <R : Any?> retrieveProperty(property: KMutableProperty1<T, R?>) =
properties[property] as Property<T, R>
}
// allows bean creation with bean<Person>() instead of Bean(Person::class).
inline fun <reified T : Any> bean() = Bean(T::class)
fun <T: Any> bean(instance: T) = Bean(instance)
// a property allows to observe value changes via bindings.
class Property<T, R>(val instance: T,
val property: KMutableProperty1<T, R?>) {
private val handlers = mutableListOf<Handler<Message<*>>>()
fun bind(handler: Handler<Message<*>>): Binding {
handlers += handler
return {
handlers -= handler
}
}
fun unbindAll() {
handlers.clear()
}
fun emit(valueChange: ValueChange<R>) {
handlers.forEach { handler ->
handler(Message(valueChange))
}
}
fun <R : List<V?>, V> emit(valueSplice: ValueSplice<R, V>) {
handlers.forEach { handler ->
handler(Message(valueSplice))
}
}
fun emitInitialChange() {
val value = get() as R?
emit(ValueChange(value, null))
}
fun emitInitialSplice() {
val items = get() as List<Any?>?
emit(ValueSplice(items, 0, listOf(), items!!.size))
}
}
fun <T, R : Any?> Property<T, R>.get(): R? {
return get(instance, property)
}
fun <T, R : Any?> Property<T, R>.set(value: R?) {
val oldValue = get(instance, property)
set(instance, property, value)
emit(ValueChange(value, oldValue))
}
fun <T, R : MutableList<V?>, V> Property<T, R>.push(vararg addedItems: V?) {
val startIndex = get(instance, property)!!.size
push(instance, property, addedItems.toList())
val items = get(instance, property)
emit(ValueSplice(items, startIndex, listOf<V>(), addedItems.size))
}
//fun <T, R : MutableList<V?>, V> Property<T, R>.pop(): V? {
// val startIndex = get(instance, property)!!.size - 1
// val removedItem = pop(instance, property)
// val items = get(instance, property)
// emit(ValueSplice(items, startIndex, listOf(removedItem), 1))
// return removedItem
//}
fun <T, R : MutableList<V?>, V> Property<T, R>.splice(startIndex: Int,
removedCount: Int,
vararg addedItems: V?) {
val removedItems = splice(instance, property, startIndex, removedCount, addedItems.toList())
val items = get(instance, property)
emit(ValueSplice(items, startIndex, removedItems.toList(), addedItems.size))
}
typealias Binding = () -> Unit
typealias Handler<T> = (T) -> Unit
data class ValueChange<out R>(val value: R?,
val oldValue: R?)
data class ValueSplice<out R : List<V?>, out V>(val items: R?,
val startIndex: Int,
val removedItems: R,
val addedCount: Int)
| apache-2.0 | 5d144e9e93372a9a9257c2fda607033b | 31.016575 | 96 | 0.609318 | 4.055283 | false | false | false | false |
PoweRGbg/AndroidAPS | app/src/main/java/info/nightscout/androidaps/events/EventPreferenceChange.kt | 3 | 407 | package info.nightscout.androidaps.events
import info.nightscout.androidaps.MainApp
class EventPreferenceChange : Event {
private var changedKey: String? = null
constructor(key: String) {
changedKey = key
}
constructor(resourceID: Int) {
changedKey = MainApp.gs(resourceID)
}
fun isChanged(id: Int): Boolean {
return changedKey == MainApp.gs(id)
}
}
| agpl-3.0 | dc1b7fb65f7b99df976bc31db0274d7b | 20.421053 | 43 | 0.668305 | 4.239583 | false | false | false | false |
westnordost/osmagent | app/src/main/java/de/westnordost/streetcomplete/quests/religion/AddReligionToWaysideShrine.kt | 1 | 954 | package de.westnordost.streetcomplete.quests.religion
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.osm.SimpleOverpassQuestType
import de.westnordost.streetcomplete.data.osm.changes.StringMapChangesBuilder
import de.westnordost.streetcomplete.data.osm.download.OverpassMapDataDao
class AddReligionToWaysideShrine(o: OverpassMapDataDao) : SimpleOverpassQuestType<String>(o) {
override val tagFilters =
"nodes, ways, relations with historic=wayside_shrine and !religion and (access !~ private|no)"
override val commitMessage = "Add religion for wayside shrine"
override val icon = R.drawable.ic_quest_religion
override fun getTitle(tags: Map<String, String>) = R.string.quest_religion_for_wayside_shrine_title
override fun createForm() = AddReligionForm()
override fun applyAnswerTo(answer: String, changes: StringMapChangesBuilder) {
changes.add("religion", answer)
}
}
| gpl-3.0 | 32310edf5418e79854c8a9865815311d | 42.363636 | 103 | 0.785115 | 4.12987 | false | false | false | false |
GLodi/GitNav | app/src/main/java/giuliolodi/gitnav/ui/fileviewer/FileViewerPresenter.kt | 1 | 4350 | /*
* Copyright 2017 GLodi
*
* 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 giuliolodi.gitnav.ui.fileviewer
import android.util.Base64
import giuliolodi.gitnav.data.DataManager
import giuliolodi.gitnav.data.model.FileViewerIntent
import giuliolodi.gitnav.ui.base.BasePresenter
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.schedulers.Schedulers
import timber.log.Timber
import java.io.UnsupportedEncodingException
import javax.inject.Inject
/**
* Created by giulio on 22/07/2017.
*/
class FileViewerPresenter<V: FileViewerContract.View> : BasePresenter<V>, FileViewerContract.Presenter<V> {
private val TAG: String = "FileViewerPresenter"
private var mFileContent: String? = null
private var mFilename: String? = null
private var LOADING: Boolean = false
@Inject
constructor(mCompositeDisposable: CompositeDisposable, mDataManager: DataManager) : super(mCompositeDisposable, mDataManager)
override fun subscribe(fileViewerIntent: FileViewerIntent, isNetworkAvailable: Boolean) {
if (fileViewerIntent.repoOwner != null && fileViewerIntent.repoName != null && fileViewerIntent.fileName != null) {
getView().initRepoFileTitle(fileViewerIntent.fileName!!, fileViewerIntent.repoOwner + "/" + fileViewerIntent.repoName)
mFilename = fileViewerIntent.fileName
}
else if (fileViewerIntent.gistFileName != null && fileViewerIntent.gistContent != null) {
getView().initGistFileTitleContent(fileViewerIntent.gistFileName!!, fileViewerIntent.gistContent!!)
mFilename = fileViewerIntent.fileName
}
if (LOADING) getView().showLoading()
else if (mFileContent != null) showFile()
else {
if (isNetworkAvailable) {
getView().showLoading()
LOADING = true
if (fileViewerIntent.repoOwner != null && fileViewerIntent.repoName != null && fileViewerIntent.filePath != null) {
loadFile(fileViewerIntent)
}
}
else {
getView().showNoConnectionError()
getView().hideLoading()
LOADING = false
}
}
}
private fun loadFile(fileViewerIntent: FileViewerIntent) {
getCompositeDisposable().add(getDataManager().getContent(fileViewerIntent.repoOwner!!, fileViewerIntent.repoName!!, fileViewerIntent.filePath!!)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{ repoContent ->
var fileDecoded: String = ""
try {
fileDecoded = Base64.decode(repoContent[0].content, Base64.DEFAULT).toString(charset("UTF-8"))
mFileContent = fileDecoded
} catch (e: UnsupportedEncodingException) { e.printStackTrace() }
showFile()
getView().hideLoading()
LOADING = false
},
{ throwable ->
throwable?.localizedMessage?.let { getView().showError(it) }
getView().hideLoading()
Timber.e(throwable)
LOADING = false
}
))
}
private fun showFile() {
if (mFilename?.substring(mFilename?.indexOf('.')!!, mFilename?.length!!)?.equals(".md")!!) {
mFileContent?.let { getView().showMDFile(it) }
}
else {
mFileContent?.let { getView().showRepoFile(it) }
}
}
} | apache-2.0 | b6af7a7c65a6361317814d8052171e40 | 40.04717 | 152 | 0.613793 | 5.272727 | false | false | false | false |
MarkNKamau/JustJava-Android | app/src/main/java/com/marknkamau/justjava/utils/DateTime.kt | 1 | 2141 | package com.marknkamau.justjava.utils
import android.annotation.SuppressLint
import java.text.SimpleDateFormat
import java.util.*
/**
* A class to be used to easily handle dates.
* Months begin at 1
*/
data class DateTime(
var year: Int,
var month: Int,
var dayOfMonth: Int,
var hourOfDay: Int,
var minute: Int,
var second: Int = 0
) {
companion object {
/**
* Returns the current time as a DateTime object.
*/
val now: DateTime
get() = Date(System.currentTimeMillis()).toDateTime()
/**
* Converts a timestamp(in seconds) to a DateTime object
*/
fun fromTimestamp(timestamp: Long): DateTime = Date(timestamp * 1000).toDateTime()
}
/**
* Time in seconds.
*/
val timestamp: Long
get() {
val now = Calendar.getInstance()
now.set(this.year, this.month - 1, this.dayOfMonth, this.hourOfDay, this.minute, this.second)
return now.time.time / 1000L
}
/**
* Formats the dateTime as the given format
*/
@SuppressLint("SimpleDateFormat")
fun format(format: String): String {
val now = Calendar.getInstance()
now.set(this.year, this.month - 1, this.dayOfMonth, this.hourOfDay, this.minute, this.second)
return now.time.format(format)
}
@SuppressLint("SimpleDateFormat")
fun parse(format: String, source: String): DateTime? = SimpleDateFormat(format).parse(source)?.toDateTime()
}
/**
* Converts a java date to a DateTime object.
*/
fun Date.toDateTime(): DateTime {
val hourOfDay = this.format("H").toInt() // Format according to 24Hr from 0-23
val minute = this.format("m").toInt()
val year = this.format("yyyy").toInt()
val month = this.format("M").toInt()
val dayOfMonth = this.format("dd").toInt()
val second = this.format("s").toInt()
return DateTime(year, month, dayOfMonth, hourOfDay, minute, second)
}
/**
* Helper function to format dates.
*/
@SuppressLint("SimpleDateFormat")
fun Date.format(pattern: String): String = SimpleDateFormat(pattern).format(this)
| apache-2.0 | f54edd6429b90b9e576f243fc4f4fb3e | 27.546667 | 111 | 0.634283 | 4.125241 | false | false | false | false |
Mindera/skeletoid | base/src/main/java/com/mindera/skeletoid/logs/utils/ShareLogFilesUtils.kt | 1 | 5780 | package com.mindera.skeletoid.logs.utils
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.net.Uri
import androidx.core.content.FileProvider
import com.mindera.skeletoid.generic.AndroidUtils
import com.mindera.skeletoid.logs.LOG
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.IOException
import java.util.zip.ZipEntry
import java.util.zip.ZipOutputStream
/**
* A way to share log file easily
*
*
* Remember to add this to the Android Manifest of the App
*
*
* <provider android:authorities="${applicationId}" android:exported="false" android:grantUriPermissions="true">
* <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/fileprovider"></meta-data>
</provider> *
*
*
* and add the file fileprovider.xml to the resources with
*
*
*
* <paths>
* <files-path path="." name="logs"></files-path>
</paths> *
*/
object ShareLogFilesUtils {
private const val TAG = "ShareLogFilesUtils"
private const val FOLDER_LOGS = "logs"
private const val FILE_LOG_ZIP = "logs.zip"
/**
* Class to be able to share LogFileAppender generated files
*
* @param activity The activity
* @param intentChooserTitle Intent chooser title
* @param subjectTitle Subject title (for email)
* @param bodyText Body text
* @param emails Emails to add on to: field (for email)
* @param file Log file to be sent
*/
fun sendLogs(
activity: Activity,
intentChooserTitle: String,
subjectTitle: String,
bodyText: String,
emails: Array<String>?,
file: File,
fileUri: Uri? = null
) {
val intent = Intent(Intent.ACTION_SEND)
intent.putExtra(Intent.EXTRA_SUBJECT, subjectTitle)
// Add emails to show on to: field
if (!emails.isNullOrEmpty()) {
intent.putExtra(Intent.EXTRA_EMAIL, emails)
}
// Add additional information to the email
intent.putExtra(Intent.EXTRA_TEXT, bodyText)
val uri = fileUri
?: FileProvider.getUriForFile(
activity,
activity.packageName,
file
)
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
intent.putExtra(Intent.EXTRA_STREAM, uri)
intent.type = activity.contentResolver.getType(uri)
activity.startActivity(Intent.createChooser(intent, intentChooserTitle))
}
/**
* Class to be able to share compressed LogFileAppender generated files
*
* @param activity The activity
* @param intentChooserTitle Intent chooser title
* @param subjectTitle Subject title (for email)
* @param bodyText Body text
* @param emails Emails to add on to: field (for email)
*/
fun sendLogsEmail(
activity: Activity,
intentChooserTitle: String,
subjectTitle: String,
bodyText: String,
emails: Array<String>?,
fileUri: Uri? = null
) {
val output = File(getCompressedLogsPath(activity))
if (!zipLogFiles(getFileLogPath(activity) + File.separator, output.absolutePath) || !output.exists()) {
return
}
sendLogs(activity, intentChooserTitle, subjectTitle, bodyText, emails, output, fileUri)
}
/**
* Returns the path where the application logs are being stored.
*
* @param context Application context
* @return path The default path where the application logs are being stored
* @see AndroidUtils
*/
fun getFileLogPath(context: Context): String {
return AndroidUtils.getFileDirPath(context, "")
}
private fun getCompressedLogsPath(context: Context): String {
val path = getFileLogPath(context) + File.separator + FOLDER_LOGS
ensureFolderExists(path)
return path + File.separator + FILE_LOG_ZIP
}
private fun ensureFolderExists(path: String) {
File(path).mkdirs()
}
private fun zipLogFiles(source: String, output: String): Boolean {
var fos: FileOutputStream? = null
var zos: ZipOutputStream? = null
var fis: FileInputStream? = null
return try {
fos = FileOutputStream(output)
zos = ZipOutputStream(fos)
val srcFile = File(source)
val files = srcFile.listFiles()
LOG.d(TAG, "Compress directory: " + srcFile.name + " via zip.")
for (file in files) {
if (file.isDirectory) {
continue
}
LOG.d(TAG, "Adding file: " + file.name)
val buffer = ByteArray(1024)
fis = FileInputStream(file)
zos.putNextEntry(ZipEntry(file.name))
var length: Int
while (fis.read(buffer).also { length = it } > 0) {
zos.write(buffer, 0, length)
}
zos.closeEntry()
}
true
} catch (ex: IOException) {
LOG.e(TAG, "Unable to zip folder: " + ex.message)
false
} finally {
try {
fis?.close()
} catch (e: Exception) {
LOG.e(TAG, e, "Unable to close FileInputStream")
}
try {
fos?.close()
} catch (e: Exception) {
LOG.e(TAG, e, "Unable to close FileOutputStream")
}
try {
zos?.close()
} catch (e: Exception) {
LOG.e(TAG, e, "Unable to close ZipOutputStream")
}
}
}
} | mit | fff02aba7eb55600a3adbb65067a9a05 | 31.846591 | 114 | 0.59083 | 4.515625 | false | false | false | false |
Adventech/sabbath-school-android-2 | common/design-compose/src/main/kotlin/app/ss/design/compose/extensions/modifier/RecomposeHighlighter.kt | 1 | 5105 | /*
* Copyright 2022 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package app.ss.design.compose.extensions.modifier
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.Stable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.composed
import androidx.compose.ui.draw.drawWithCache
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.drawscope.Fill
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.graphics.lerp
import androidx.compose.ui.platform.debugInspectorInfo
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.delay
import kotlin.math.min
/**
* A [Modifier] that draws a border around elements that are recomposing. The border increases in
* size and interpolates from red to green as more recompositions occur before a timeout.
*/
@Stable
fun Modifier.recomposeHighlighter(): Modifier = this.then(recomposeModifier)
// Use a single instance + @Stable to ensure that recompositions can enable skipping optimizations
// Modifier.composed will still remember unique data per call site.
private val recomposeModifier =
Modifier.composed(inspectorInfo = debugInspectorInfo { name = "recomposeHighlighter" }) {
// The total number of compositions that have occurred. We're not using a State<> here be
// able to read/write the value without invalidating (which would cause infinite
// recomposition).
val totalCompositions = remember { arrayOf(0L) }
totalCompositions[0]++
// The value of totalCompositions at the last timeout.
val totalCompositionsAtLastTimeout = remember { mutableStateOf(0L) }
// Start the timeout, and reset everytime there's a recomposition. (Using totalCompositions
// as the key is really just to cause the timer to restart every composition).
LaunchedEffect(totalCompositions[0]) {
delay(3000)
totalCompositionsAtLastTimeout.value = totalCompositions[0]
}
Modifier.drawWithCache {
onDrawWithContent {
// Draw actual content.
drawContent()
// Below is to draw the highlight, if necessary. A lot of the logic is copied from
// Modifier.border
val numCompositionsSinceTimeout =
totalCompositions[0] - totalCompositionsAtLastTimeout.value
val hasValidBorderParams = size.minDimension > 0f
if (!hasValidBorderParams || numCompositionsSinceTimeout <= 0) {
return@onDrawWithContent
}
val (color, strokeWidthPx) =
when (numCompositionsSinceTimeout) {
// We need at least one composition to draw, so draw the smallest border
// color in blue.
1L -> Color.Blue to 1f
// 2 compositions is _probably_ okay.
2L -> Color.Green to 2.dp.toPx()
// 3 or more compositions before timeout may indicate an issue. lerp the
// color from yellow to red, and continually increase the border size.
else -> {
lerp(
Color.Yellow.copy(alpha = 0.8f),
Color.Red.copy(alpha = 0.5f),
min(1f, (numCompositionsSinceTimeout - 1).toFloat() / 100f)
) to numCompositionsSinceTimeout.toInt().dp.toPx()
}
}
val halfStroke = strokeWidthPx / 2
val topLeft = Offset(halfStroke, halfStroke)
val borderSize = Size(size.width - strokeWidthPx, size.height - strokeWidthPx)
val fillArea = (strokeWidthPx * 2) > size.minDimension
val rectTopLeft = if (fillArea) Offset.Zero else topLeft
val size = if (fillArea) size else borderSize
val style = if (fillArea) Fill else Stroke(strokeWidthPx)
drawRect(
brush = SolidColor(color),
topLeft = rectTopLeft,
size = size,
style = style
)
}
}
}
| mit | c46c9445831e41b662ac78b19e68a00f | 44.176991 | 99 | 0.634476 | 4.985352 | false | false | false | false |
Maccimo/intellij-community | plugins/kotlin/fir-fe10-binding/src/org/jetbrains/kotlin/idea/fir/fe10/binding/ResolvedCallWrappers.kt | 2 | 11079 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.fir.fe10.binding
import org.jetbrains.kotlin.analysis.api.symbols.KtFunctionLikeSymbol
import org.jetbrains.kotlin.analysis.api.symbols.KtVariableLikeSymbol
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.descriptors.TypeParameterDescriptor
import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor
import org.jetbrains.kotlin.fir.declarations.FirValueParameter
import org.jetbrains.kotlin.fir.expressions.*
import org.jetbrains.kotlin.fir.expressions.impl.FirNoReceiverExpression
import org.jetbrains.kotlin.fir.realPsi
import org.jetbrains.kotlin.fir.references.FirErrorNamedReference
import org.jetbrains.kotlin.fir.references.FirResolvedNamedReference
import org.jetbrains.kotlin.fir.resolvedSymbol
import org.jetbrains.kotlin.fir.symbols.SymbolInternals
import org.jetbrains.kotlin.fir.symbols.impl.*
import org.jetbrains.kotlin.fir.types.FirTypeProjectionWithVariance
import org.jetbrains.kotlin.idea.fir.fe10.FE10BindingContext
import org.jetbrains.kotlin.idea.fir.fe10.FirWeakReference
import org.jetbrains.kotlin.idea.fir.fe10.toDeclarationDescriptor
import org.jetbrains.kotlin.idea.fir.fe10.toKotlinType
import org.jetbrains.kotlin.psi.Call
import org.jetbrains.kotlin.psi.ValueArgument
import org.jetbrains.kotlin.resolve.calls.model.*
import org.jetbrains.kotlin.resolve.calls.results.ResolutionStatus
import org.jetbrains.kotlin.resolve.calls.tasks.ExplicitReceiverKind
import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue
import org.jetbrains.kotlin.types.KotlinType
internal abstract class Fe10WrapperResolvedCall<C: Fe10WrapperCall<F>, F: FirQualifiedAccessExpression>(
private val call: C,
) : ResolvedCall<CallableDescriptor> {
protected val context: FE10BindingContext get() = call.context
protected val firAccessExpression: FirWeakReference<F> get() = call.firAccessExpression
override fun getCall(): Call = call
override fun getExtensionReceiver(): ReceiverValue? {
if (firAccessExpression.getFir().extensionReceiver === FirNoReceiverExpression) return null
return firAccessExpression.getFir().extensionReceiver.toExpressionReceiverValue(context)
}
override fun getDispatchReceiver(): ReceiverValue? {
if (firAccessExpression.getFir().dispatchReceiver === FirNoReceiverExpression) return null
return firAccessExpression.getFir().dispatchReceiver.toExpressionReceiverValue(context)
}
override fun getExplicitReceiverKind(): ExplicitReceiverKind {
if (firAccessExpression.getFir().explicitReceiver === null) return ExplicitReceiverKind.NO_EXPLICIT_RECEIVER
if (firAccessExpression.getFir().explicitReceiver === firAccessExpression.getFir().extensionReceiver) return ExplicitReceiverKind.EXTENSION_RECEIVER
return ExplicitReceiverKind.DISPATCH_RECEIVER
}
override fun getContextReceivers(): List<ReceiverValue> = context.implementationPlanned()
override fun getDataFlowInfoForArguments(): DataFlowInfoForArguments = context.noImplementation()
override fun getSmartCastDispatchReceiverType(): KotlinType? = context.noImplementation()
}
internal class FunctionFe10WrapperResolvedCall(call: FunctionFe10WrapperCall) :
Fe10WrapperResolvedCall<FunctionFe10WrapperCall, FirFunctionCall>(call) {
@OptIn(SymbolInternals::class)
private val ktFunctionSymbol: KtFunctionLikeSymbol = firAccessExpression.withFir {
when (val calleeReference = it.calleeReference) {
is FirResolvedNamedReference -> context.ktAnalysisSessionFacade.buildSymbol(calleeReference.resolvedSymbol.fir) as KtFunctionLikeSymbol
// TODO: NPE in case of empty candidate
is FirErrorNamedReference -> context.ktAnalysisSessionFacade.buildSymbol(calleeReference.candidateSymbol!!.fir) as KtFunctionLikeSymbol
else -> context.noImplementation("calleeReferenceType: ${calleeReference::class.java}")
}
}
private val _typeArguments: Map<TypeParameterDescriptor, KotlinType> by lazy(LazyThreadSafetyMode.PUBLICATION) {
if (firAccessExpression.getFir().typeArguments.isEmpty()) return@lazy emptyMap()
val typeArguments = linkedMapOf<TypeParameterDescriptor, KotlinType>()
for ((index, parameter) in candidateDescriptor.typeParameters.withIndex()) {
val firTypeProjectionWithVariance = firAccessExpression.getFir().typeArguments[index] as FirTypeProjectionWithVariance
val kotlinType = context.ktAnalysisSessionFacade.buildKtType(firTypeProjectionWithVariance.typeRef).toKotlinType(context)
typeArguments[parameter] = kotlinType
}
typeArguments
}
private val arguments: Map<ValueParameterDescriptor, ResolvedValueArgument> by lazy(LazyThreadSafetyMode.PUBLICATION) {
val firArguments = firAccessExpression.withFir { it.argumentMapping } ?: context.implementationPostponed()
val firParameterToResolvedValueArgument = hashMapOf<FirValueParameter, ResolvedValueArgument>()
val allArguments = call.valueArguments + call.functionLiteralArguments
var argumentIndex = 0
for ((firExpression, firValueParameter) in firArguments.entries) {
if (firExpression is FirVarargArgumentsExpression) {
val varargArguments = mutableListOf<ValueArgument>()
for (subExpression in firExpression.arguments) {
val currentArgument = allArguments[argumentIndex]; argumentIndex++
check(currentArgument.getArgumentExpression() === subExpression.realPsi) {
"Different psi: ${currentArgument.getArgumentExpression()} !== ${subExpression.realPsi}"
}
varargArguments.add(currentArgument)
}
firParameterToResolvedValueArgument[firValueParameter] = VarargValueArgument(varargArguments)
} else {
val currentArgument = allArguments[argumentIndex]; argumentIndex++
check(currentArgument.getArgumentExpression() === firExpression.realPsi) {
"Different psi: ${currentArgument.getArgumentExpression()} !== ${firExpression.realPsi}"
}
firParameterToResolvedValueArgument[firValueParameter] = ExpressionValueArgument(currentArgument)
}
}
val arguments = linkedMapOf<ValueParameterDescriptor, ResolvedValueArgument>()
for ((parameterIndex, parameter) in ktFunctionSymbol.valueParameters.withIndex()) {
val resolvedValueArgument = context.ktAnalysisSessionFacade.withFir(parameter) { it: FirValueParameter ->
firParameterToResolvedValueArgument[it]
} ?: DefaultValueArgument.DEFAULT
arguments[candidateDescriptor.valueParameters[parameterIndex]] = resolvedValueArgument
}
arguments
}
override fun getStatus(): ResolutionStatus =
if (firAccessExpression.getFir().calleeReference is FirResolvedNamedReference) ResolutionStatus.SUCCESS else ResolutionStatus.OTHER_ERROR
override fun getCandidateDescriptor(): CallableDescriptor {
return ktFunctionSymbol.toDeclarationDescriptor(context)
}
// type arguments should be substituted
override fun getResultingDescriptor(): CallableDescriptor = context.incorrectImplementation { candidateDescriptor }
override fun getValueArguments(): Map<ValueParameterDescriptor, ResolvedValueArgument> = arguments
override fun getValueArgumentsByIndex(): List<ResolvedValueArgument> = valueArguments.values.toList()
override fun getArgumentMapping(valueArgument: ValueArgument): ArgumentMapping {
val firArguments = firAccessExpression.withFir { it.argumentMapping } ?: context.implementationPostponed()
val argumentExpression = valueArgument.getArgumentExpression() ?: context.implementationPostponed()
fun FirExpression.isMyArgument() = realPsi === valueArgument || realPsi === argumentExpression
var targetFirParameter: FirValueParameter? = null
outer@ for ((firExpression, firValueParameter) in firArguments.entries) {
if (firExpression is FirVarargArgumentsExpression) {
for (subExpression in firExpression.arguments)
if (subExpression.isMyArgument()) {
targetFirParameter = firValueParameter
break@outer
}
} else if (firExpression.isMyArgument()) {
targetFirParameter = firValueParameter
break@outer
}
}
if (targetFirParameter == null) return ArgumentUnmapped
val parameterIndex = ktFunctionSymbol.valueParameters.indexOfFirst {
context.ktAnalysisSessionFacade.withFir(it) { parameter: FirValueParameter -> parameter === targetFirParameter }
}
if (parameterIndex == -1) error("Fir parameter not found :(")
val parameterDescriptor = candidateDescriptor.valueParameters[parameterIndex]
val argumentMatch = ArgumentMatchImpl(parameterDescriptor)
context.incorrectImplementation {
// I'm not sure, when we should have not success status
argumentMatch.recordMatchStatus(ArgumentMatchStatus.SUCCESS)
}
return argumentMatch
}
override fun getTypeArguments(): Map<TypeParameterDescriptor, KotlinType> = _typeArguments
}
internal class VariableFe10WrapperResolvedCall(call: VariableFe10WrapperCall) :
Fe10WrapperResolvedCall<VariableFe10WrapperCall, FirPropertyAccessExpression>(call) {
@OptIn(SymbolInternals::class)
private val ktVariableSymbol: KtVariableLikeSymbol = firAccessExpression.withFir {
val resolvedSymbol = it.calleeReference.resolvedSymbol
check(resolvedSymbol is FirVariableSymbol) {
"Expected FirVariableSymbol, but get: $resolvedSymbol"
}
context.ktAnalysisSessionFacade.buildSymbol(resolvedSymbol.fir) as KtVariableLikeSymbol
}
override fun getStatus(): ResolutionStatus = context.incorrectImplementation { ResolutionStatus.SUCCESS }
override fun getCandidateDescriptor(): CallableDescriptor = ktVariableSymbol.toDeclarationDescriptor(context) as CallableDescriptor
// type arguments should be substituted
override fun getResultingDescriptor(): CallableDescriptor = context.incorrectImplementation { candidateDescriptor }
override fun getValueArguments(): Map<ValueParameterDescriptor, ResolvedValueArgument> = emptyMap()
override fun getValueArgumentsByIndex(): List<ResolvedValueArgument> = emptyList()
override fun getArgumentMapping(valueArgument: ValueArgument): ArgumentMapping =
error("Variable call has no arguments. fir: $firAccessExpression, valueArgument = $valueArgument")
override fun getTypeArguments(): Map<TypeParameterDescriptor, KotlinType> = emptyMap()
} | apache-2.0 | 47e09f2c757dc00515a072bed3a1a500 | 52.786408 | 156 | 0.751422 | 5.56454 | false | false | false | false |
nicopico-dev/HappyBirthday | app/src/main/java/fr/nicopico/happybirthday/ui/home/ContactAdapter.kt | 1 | 2525 | /*
* Copyright 2016 Nicolas Picon <[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 fr.nicopico.happybirthday.ui.home
import android.content.Context
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import fr.nicopico.happybirthday.R
import fr.nicopico.happybirthday.domain.model.Contact
import kotlinx.android.synthetic.main.item_contact.view.*
class ContactAdapter(context: Context) : RecyclerView.Adapter<ContactAdapter.ViewHolder>() {
private val inflater: LayoutInflater
init {
inflater = LayoutInflater.from(context)
}
var data: List<Contact>? = null
set(value) {
field = value
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ViewHolder {
return inflater.inflate(R.layout.item_contact, parent, false).let(::ViewHolder)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bind(data!![position])
}
override fun getItemCount(): Int = data?.size ?: 0
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
fun bind(contact: Contact) {
itemView.imgAvatar.setImageURI(contact.avatarThumbnail)
itemView.txtName.text = contact.displayName
with(itemView.txtInfos) {
val birthday = contact.birthday
visibility = View.VISIBLE
text = birthday.format("d MMMM,")
if (contact.canComputeAge()) {
val nextBirthdayDate = birthday.nextBirthdayDate()
val age = contact.getAge(nextBirthdayDate)
if (age != null) {
append(" $age ans")
}
}
val nextOccurrence = birthday.inDays()
append(" dans $nextOccurrence jours")
}
}
}
} | apache-2.0 | 47c8a6766d2f92f595f3664e72c55506 | 32.68 | 92 | 0.651881 | 4.624542 | false | false | false | false |
google/identity-credential | appholder/src/main/java/com/android/mdl/app/document/Document.kt | 1 | 1626 | package com.android.mdl.app.document
import android.graphics.Bitmap
import android.os.Parcelable
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import kotlinx.parcelize.Parcelize
import java.util.Calendar
@Parcelize
@Entity(tableName = "document")
data class Document(
@ColumnInfo(name = "doc_type") val docType: String,
@PrimaryKey @ColumnInfo(name = "identity_credential_name") val identityCredentialName: String,
@ColumnInfo(name = "user_visible_name") var userVisibleName: String, // Name displayed in UI, e.g. “P HIN”
@ColumnInfo(name = "user_visible_document_background") val userVisibleDocumentBackground: Bitmap?,
@ColumnInfo(name = "hardware_backed") val hardwareBacked: Boolean, // cf. blurb in IdentityCredentialStore docs
@ColumnInfo(name = "self_signed") val selfSigned: Boolean, // dummy credential in app created
@ColumnInfo(name = "user_authentication") val userAuthentication: Boolean, // uses user authentication
@ColumnInfo(name = "number_mso") var numberMso: Int,
@ColumnInfo(name = "max_use_mso") var maxUseMso: Int,
@ColumnInfo(name = "server_url") val serverUrl: String? = null,
@ColumnInfo(name = "provisioning_code") val provisioningCode: String? = null,
@ColumnInfo(name = "date_provisioned") val dateProvisioned: Calendar = Calendar.getInstance(),
@ColumnInfo(name = "date_check_for_update") var dateCheckForUpdate: Calendar? = null,
@ColumnInfo(name = "date_refresh_auth_keys") var dateRefreshAuthKeys: Calendar? = null,
@ColumnInfo(name = "card_art") var cardArt: Int = 0
) : Parcelable | apache-2.0 | 1e5925c1da8ea47920e6fc575fa25353 | 54.965517 | 115 | 0.74476 | 3.852732 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/accounts/login/jetpack/LoginNoSitesFragment.kt | 1 | 5775 | package org.wordpress.android.ui.accounts.login.jetpack
import android.content.Context
import android.os.Bundle
import android.view.View
import androidx.activity.OnBackPressedCallback
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import dagger.hilt.android.AndroidEntryPoint
import org.wordpress.android.R
import org.wordpress.android.WordPress
import org.wordpress.android.databinding.JetpackLoginEmptyViewBinding
import org.wordpress.android.login.LoginListener
import org.wordpress.android.login.util.AvatarHelper
import org.wordpress.android.login.util.AvatarHelper.AvatarRequestListener
import org.wordpress.android.ui.ActivityLauncher
import org.wordpress.android.ui.accounts.LoginNavigationEvents.ShowInstructions
import org.wordpress.android.ui.accounts.LoginNavigationEvents.ShowSignInForResultJetpackOnly
import org.wordpress.android.ui.accounts.login.jetpack.LoginNoSitesViewModel.State.NoUser
import org.wordpress.android.ui.accounts.login.jetpack.LoginNoSitesViewModel.State.ShowUser
import org.wordpress.android.ui.main.utils.MeGravatarLoader
import org.wordpress.android.ui.utils.UiHelpers
import javax.inject.Inject
@AndroidEntryPoint
class LoginNoSitesFragment : Fragment(R.layout.jetpack_login_empty_view) {
companion object {
const val TAG = "LoginNoSitesFragment"
fun newInstance(): LoginNoSitesFragment {
return LoginNoSitesFragment()
}
}
@Inject lateinit var meGravatarLoader: MeGravatarLoader
@Inject lateinit var uiHelpers: UiHelpers
private var loginListener: LoginListener? = null
private val viewModel: LoginNoSitesViewModel by viewModels()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initBackPressHandler()
with(JetpackLoginEmptyViewBinding.bind(view)) {
initContentViews()
initClickListeners()
initViewModel(savedInstanceState)
}
}
private fun JetpackLoginEmptyViewBinding.initContentViews() {
uiHelpers.setTextOrHide(loginErrorMessageTitle, R.string.login_no_jetpack_sites)
uiHelpers.setTextOrHide(loginErrorMessageText, R.string.login_no_jetpack_sites_error_message)
}
private fun JetpackLoginEmptyViewBinding.initClickListeners() {
bottomButtonsContainer.buttonPrimary.setOnClickListener { viewModel.onSeeInstructionsPressed() }
bottomButtonsContainer.buttonSecondary.setOnClickListener { viewModel.onTryAnotherAccountPressed() }
}
private fun JetpackLoginEmptyViewBinding.initViewModel(savedInstanceState: Bundle?) {
initObservers()
viewModel.start(
application = requireActivity().application as WordPress,
savedInstanceState = savedInstanceState
)
}
private fun JetpackLoginEmptyViewBinding.initObservers() {
viewModel.navigationEvents.observe(viewLifecycleOwner, { events ->
events.getContentIfNotHandled()?.let {
when (it) {
is ShowSignInForResultJetpackOnly -> showSignInForResultJetpackOnly()
is ShowInstructions -> showInstructions(it.url)
else -> { // no op
}
}
}
})
viewModel.uiModel.observe(viewLifecycleOwner, { uiModel ->
when (val state = uiModel.state) {
is ShowUser -> {
loadGravatar(state.accountAvatarUrl)
setUserName(state.userName)
setDisplayName(state.displayName)
userCardView.visibility = View.VISIBLE
}
is NoUser -> userCardView.visibility = View.GONE
}
})
}
private fun JetpackLoginEmptyViewBinding.loadGravatar(avatarUrl: String) {
AvatarHelper.loadAvatarFromUrl(
this@LoginNoSitesFragment,
meGravatarLoader.constructGravatarUrl(avatarUrl),
userContainer.imageAvatar,
object : AvatarRequestListener {
override fun onRequestFinished() {
// no op
}
})
}
private fun JetpackLoginEmptyViewBinding.setUserName(value: String) =
uiHelpers.setTextOrHide(userContainer.textUsername, value)
private fun JetpackLoginEmptyViewBinding.setDisplayName(value: String) =
uiHelpers.setTextOrHide(userContainer.textDisplayName, value)
private fun showSignInForResultJetpackOnly() {
ActivityLauncher.showSignInForResultJetpackOnly(requireActivity())
}
private fun showInstructions(url: String) {
ActivityLauncher.openUrlExternal(requireContext(), url)
}
override fun onSaveInstanceState(outState: Bundle) {
viewModel.writeToBundle(outState)
super.onSaveInstanceState(outState)
}
override fun onAttach(context: Context) {
super.onAttach(context)
// this will throw if parent activity doesn't implement the login listener interface
loginListener = context as? LoginListener
}
override fun onDetach() {
loginListener = null
super.onDetach()
}
override fun onResume() {
super.onResume()
viewModel.onFragmentResume()
}
private fun initBackPressHandler() {
requireActivity().onBackPressedDispatcher.addCallback(
viewLifecycleOwner,
object : OnBackPressedCallback(
true
) {
override fun handleOnBackPressed() {
viewModel.onBackPressed()
}
})
}
}
| gpl-2.0 | 87ed93d58a363f4094aaed847ca15519 | 36.745098 | 108 | 0.680693 | 5.312787 | false | false | false | false |
mdaniel/intellij-community | platform/lang-impl/src/com/intellij/find/impl/uiModel.kt | 1 | 2986 | // 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.find.impl
import com.intellij.ide.scratch.ScratchUtil
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.fileEditor.UniqueVFilePathBuilder
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.vfs.newvfs.VfsPresentationUtil
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.usages.TextChunk
import com.intellij.usages.UsageInfo2UsageAdapter
import com.intellij.usages.UsageInfoAdapter
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.Nls
import java.awt.Color
@ApiStatus.Internal
class FindPopupItem(
val usage: UsageInfoAdapter,
val presentation: UsagePresentation?,
) {
val path: String = usage.path
val line: Int = usage.line
val navigationOffset: Int = usage.navigationOffset
val presentableText: String?
get() = presentation?.text?.joinToString("")
fun withPresentation(presentation: UsagePresentation?): FindPopupItem {
return FindPopupItem(usage, presentation)
}
}
internal class SearchEverywhereItem(
val usage: UsageInfo2UsageAdapter,
val presentation: UsagePresentation,
) {
fun withPresentation(presentation: UsagePresentation): SearchEverywhereItem {
return SearchEverywhereItem(usage, presentation)
}
override fun equals(other: Any?): Boolean {
ApplicationManager.getApplication().assertIsNonDispatchThread()
if (this === other) return true
if (javaClass != other?.javaClass) return false
return usage.plainText == (other as SearchEverywhereItem).usage.plainText
}
override fun hashCode() = usage.plainText.hashCode()
}
@ApiStatus.Internal
class UsagePresentation(
val text: Array<out TextChunk>,
val backgroundColor: Color?,
val fileString: @Nls String,
)
internal fun usagePresentation(
project: Project,
scope: GlobalSearchScope,
usage: UsageInfoAdapter,
): UsagePresentation? {
return if (usage is UsageInfo2UsageAdapter) {
usagePresentation(project, scope, usage)
}
else {
null
}
}
internal fun usagePresentation(
project: Project,
scope: GlobalSearchScope,
usage: UsageInfo2UsageAdapter,
): UsagePresentation {
ApplicationManager.getApplication().assertIsNonDispatchThread()
val text: Array<TextChunk> = usage.presentation.text
return UsagePresentation(
text = text,
backgroundColor = VfsPresentationUtil.getFileBackgroundColor(project, usage.file),
fileString = getFilePath(project, scope, usage),
)
}
private fun getFilePath(project: Project, scope: GlobalSearchScope, usage: UsageInfo2UsageAdapter): @NlsSafe String {
val file = usage.file ?: return ""
return if (ScratchUtil.isScratch(file)) {
ScratchUtil.getRelativePath(project, file)
}
else {
UniqueVFilePathBuilder.getInstance().getUniqueVirtualFilePath(project, file, scope)
}
}
| apache-2.0 | 4617a5c4b1819cdeb2bfcd3dd59a96f2 | 28.86 | 120 | 0.777294 | 4.423704 | false | false | false | false |
mdaniel/intellij-community | platform/workspaceModel/storage/testEntities/testSrc/com/intellij/workspaceModel/storage/entities/test/api/WithNullsMultipleOpposite.kt | 1 | 3235 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.workspaceModel.storage.entities.test.api
import org.jetbrains.deft.annotations.Child
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
interface ParentWithNullsOppositeMultiple : WorkspaceEntity {
val parentData: String
//region generated code
//@formatter:off
@GeneratedCodeApiVersion(1)
interface Builder: ParentWithNullsOppositeMultiple, ModifiableWorkspaceEntity<ParentWithNullsOppositeMultiple>, ObjBuilder<ParentWithNullsOppositeMultiple> {
override var parentData: String
override var entitySource: EntitySource
}
companion object: Type<ParentWithNullsOppositeMultiple, Builder>() {
operator fun invoke(parentData: String, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): ParentWithNullsOppositeMultiple {
val builder = builder()
builder.parentData = parentData
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//@formatter:on
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: ParentWithNullsOppositeMultiple, modification: ParentWithNullsOppositeMultiple.Builder.() -> Unit) = modifyEntity(ParentWithNullsOppositeMultiple.Builder::class.java, entity, modification)
var ParentWithNullsOppositeMultiple.Builder.children: @Child List<ChildWithNullsOppositeMultiple>
by WorkspaceEntity.extension()
//endregion
interface ChildWithNullsOppositeMultiple : WorkspaceEntity {
val childData: String
val parentEntity: ParentWithNullsOppositeMultiple?
//region generated code
//@formatter:off
@GeneratedCodeApiVersion(1)
interface Builder: ChildWithNullsOppositeMultiple, ModifiableWorkspaceEntity<ChildWithNullsOppositeMultiple>, ObjBuilder<ChildWithNullsOppositeMultiple> {
override var childData: String
override var entitySource: EntitySource
override var parentEntity: ParentWithNullsOppositeMultiple?
}
companion object: Type<ChildWithNullsOppositeMultiple, Builder>() {
operator fun invoke(childData: String, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): ChildWithNullsOppositeMultiple {
val builder = builder()
builder.childData = childData
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//@formatter:on
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: ChildWithNullsOppositeMultiple, modification: ChildWithNullsOppositeMultiple.Builder.() -> Unit) = modifyEntity(ChildWithNullsOppositeMultiple.Builder::class.java, entity, modification)
//endregion
val ParentWithNullsOppositeMultiple.children: List<@Child ChildWithNullsOppositeMultiple>
by WorkspaceEntity.extension()
| apache-2.0 | dcbd03ad7ed552736f0baa925ce47d39 | 40.474359 | 234 | 0.786708 | 5.464527 | false | false | false | false |
ksmirenko/telegram-proger-bot | src/main/java/progerbot/TelegramApi.kt | 1 | 4061 | package progerbot
import com.google.appengine.api.urlfetch.*
import com.google.gson.Gson
import com.google.gson.JsonParser
import org.apache.http.entity.ContentType
import org.apache.http.entity.mime.MultipartEntityBuilder
import telegram.File
import java.io.BufferedReader
import java.io.ByteArrayOutputStream
import java.io.StringReader
import java.net.URL
import java.net.URLEncoder
import java.util.*
/**
* Performs all interaction with Telegram Bot API.
*/
public object TelegramApi {
private val CHARSET = "UTF-8"
private val IS_TOKEN_HARDCODED = false
/**
* URL of API with token.
*/
private val telegramApiUrl : String
private val telegramToken : String
init {
if (!IS_TOKEN_HARDCODED) {
// loading token from locally stored file
val prop = Properties()
val inputStreamToken = MainServlet::class.java.classLoader.getResourceAsStream("auth.properties")
prop.load(inputStreamToken)
telegramToken = prop.getProperty("json.telegramBotToken")
}
else {
telegramToken = "" // hardcoded token would be here
}
telegramApiUrl = "https://api.telegram.org/bot$telegramToken"
}
public fun sendText(chatId : String, text : String) : Boolean {
try {
Logger.println("Sending message: {$text}")
val resp = HttpRequests.simpleRequest(
"$telegramApiUrl/sendMessage",
HTTPMethod.POST,
"chat_id=$chatId&text=${URLEncoder.encode(text, CHARSET)}")
return resp.responseCode == 200
}
catch (e : Exception) {
if (e.message != null)
Logger.println(e.message!!)
return false
}
}
public fun sendImage(chatId : String, imageByteArray : ByteArray) : HTTPResponse {
// creating Telegram POST request
val telegramPost = HTTPRequest(URL("$telegramApiUrl/sendPhoto"), HTTPMethod.POST)
val entity = (MultipartEntityBuilder.create()
.addTextBody("chat_id", chatId)
.addBinaryBody("photo", imageByteArray, ContentType.MULTIPART_FORM_DATA, "image.png"))
.build()
val bos = ByteArrayOutputStream()
entity.writeTo(bos)
val body = bos.toByteArray()
// extract multipart boundary (body starts with --boundary\r\n)
var boundary = BufferedReader(StringReader(String(body))).readLine()
boundary = boundary.substring(2, boundary.length)
// adding multipart header and body
telegramPost.addHeader(HTTPHeader("Content-type", "multipart/form-data; boundary=" + boundary))
telegramPost.payload = body
// sending image back to user
return URLFetchServiceFactory.getURLFetchService().fetch(telegramPost)
}
public fun getFile(fileId : String) : File? {
try {
val codeRequestResponse : HTTPResponse = URLFetchServiceFactory.getURLFetchService().fetch(
URL("$telegramApiUrl/getFile?file_id=$fileId"))
if (codeRequestResponse.responseCode == 200) {
val jsonObject = JsonParser().parse(codeRequestResponse.content.toString(CHARSET)).asJsonObject
val file = Gson().fromJson(jsonObject.get("result"), telegram.File::class.java)
return file
}
else return null
}
catch (e : Exception) {
Logger.println(e)
return null
}
}
public fun getUpdates(offset : Int = 0) = HttpRequests.simpleRequest("$telegramApiUrl/getupdates",
HTTPMethod.GET,
"offset=${Integer.toString(offset)}&timeout=60"
)
/**
* Downloads a file from Telegram server.
*/
public fun downloadTextFile(filePath : String) : String =
URLFetchServiceFactory.getURLFetchService().fetch(
URL("https://api.telegram.org/file/bot$telegramToken/$filePath")
).content.toString(CHARSET)
} | apache-2.0 | 4a666500f5faab6a8bdfeeb1c3d821b8 | 36.962617 | 111 | 0.628417 | 4.689376 | false | false | false | false |
WhisperSystems/Signal-Android | app/src/main/java/org/thoughtcrime/securesms/components/settings/app/notifications/NotificationsSettingsFragment.kt | 2 | 14245 | package org.thoughtcrime.securesms.components.settings.app.notifications
import android.app.Activity
import android.content.Intent
import android.graphics.ColorFilter
import android.graphics.PorterDuff
import android.graphics.PorterDuffColorFilter
import android.media.RingtoneManager
import android.net.Uri
import android.provider.Settings
import android.text.TextUtils
import android.view.View
import androidx.annotation.RequiresApi
import androidx.core.content.ContextCompat
import androidx.lifecycle.ViewModelProviders
import androidx.preference.PreferenceManager
import org.thoughtcrime.securesms.R
import org.thoughtcrime.securesms.components.settings.DSLConfiguration
import org.thoughtcrime.securesms.components.settings.DSLSettingsAdapter
import org.thoughtcrime.securesms.components.settings.DSLSettingsFragment
import org.thoughtcrime.securesms.components.settings.DSLSettingsText
import org.thoughtcrime.securesms.components.settings.PreferenceModel
import org.thoughtcrime.securesms.components.settings.PreferenceViewHolder
import org.thoughtcrime.securesms.components.settings.RadioListPreference
import org.thoughtcrime.securesms.components.settings.RadioListPreferenceViewHolder
import org.thoughtcrime.securesms.components.settings.configure
import org.thoughtcrime.securesms.keyvalue.SignalStore
import org.thoughtcrime.securesms.notifications.NotificationChannels
import org.thoughtcrime.securesms.util.MappingAdapter
import org.thoughtcrime.securesms.util.RingtoneUtil
import org.thoughtcrime.securesms.util.ViewUtil
private const val MESSAGE_SOUND_SELECT: Int = 1
private const val CALL_RINGTONE_SELECT: Int = 2
class NotificationsSettingsFragment : DSLSettingsFragment(R.string.preferences__notifications) {
private val repeatAlertsValues by lazy { resources.getStringArray(R.array.pref_repeat_alerts_values) }
private val repeatAlertsLabels by lazy { resources.getStringArray(R.array.pref_repeat_alerts_entries) }
private val notificationPrivacyValues by lazy { resources.getStringArray(R.array.pref_notification_privacy_values) }
private val notificationPrivacyLabels by lazy { resources.getStringArray(R.array.pref_notification_privacy_entries) }
private val notificationPriorityValues by lazy { resources.getStringArray(R.array.pref_notification_priority_values) }
private val notificationPriorityLabels by lazy { resources.getStringArray(R.array.pref_notification_priority_entries) }
private val ledColorValues by lazy { resources.getStringArray(R.array.pref_led_color_values) }
private val ledColorLabels by lazy { resources.getStringArray(R.array.pref_led_color_entries) }
private val ledBlinkValues by lazy { resources.getStringArray(R.array.pref_led_blink_pattern_values) }
private val ledBlinkLabels by lazy { resources.getStringArray(R.array.pref_led_blink_pattern_entries) }
private lateinit var viewModel: NotificationsSettingsViewModel
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == MESSAGE_SOUND_SELECT && resultCode == Activity.RESULT_OK && data != null) {
val uri = data.getParcelableExtra<Uri>(RingtoneManager.EXTRA_RINGTONE_PICKED_URI)
viewModel.setMessageNotificationsSound(uri)
} else if (requestCode == CALL_RINGTONE_SELECT && resultCode == Activity.RESULT_OK && data != null) {
val uri = data.getParcelableExtra<Uri>(RingtoneManager.EXTRA_RINGTONE_PICKED_URI)
viewModel.setCallRingtone(uri)
}
}
override fun bindAdapter(adapter: DSLSettingsAdapter) {
adapter.registerFactory(
LedColorPreference::class.java,
MappingAdapter.LayoutFactory(::LedColorPreferenceViewHolder, R.layout.dsl_preference_item)
)
val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(requireContext())
val factory = NotificationsSettingsViewModel.Factory(sharedPreferences)
viewModel = ViewModelProviders.of(this, factory)[NotificationsSettingsViewModel::class.java]
viewModel.state.observe(viewLifecycleOwner) {
adapter.submitList(getConfiguration(it).toMappingModelList())
}
}
private fun getConfiguration(state: NotificationsSettingsState): DSLConfiguration {
return configure {
sectionHeaderPref(R.string.NotificationsSettingsFragment__messages)
switchPref(
title = DSLSettingsText.from(R.string.preferences__notifications),
isChecked = state.messageNotificationsState.notificationsEnabled,
onClick = {
viewModel.setMessageNotificationsEnabled(!state.messageNotificationsState.notificationsEnabled)
}
)
clickPref(
title = DSLSettingsText.from(R.string.preferences__sound),
summary = DSLSettingsText.from(getRingtoneSummary(state.messageNotificationsState.sound)),
isEnabled = state.messageNotificationsState.notificationsEnabled,
onClick = {
launchMessageSoundSelectionIntent()
}
)
switchPref(
title = DSLSettingsText.from(R.string.preferences__vibrate),
isChecked = state.messageNotificationsState.vibrateEnabled,
isEnabled = state.messageNotificationsState.notificationsEnabled,
onClick = {
viewModel.setMessageNotificationVibration(!state.messageNotificationsState.vibrateEnabled)
}
)
customPref(
LedColorPreference(
colorValues = ledColorValues,
radioListPreference = RadioListPreference(
title = DSLSettingsText.from(R.string.preferences__led_color),
listItems = ledColorLabels,
selected = ledColorValues.indexOf(state.messageNotificationsState.ledColor),
isEnabled = state.messageNotificationsState.notificationsEnabled,
onSelected = {
viewModel.setMessageNotificationLedColor(ledColorValues[it])
}
)
)
)
if (!NotificationChannels.supported()) {
radioListPref(
title = DSLSettingsText.from(R.string.preferences__pref_led_blink_title),
listItems = ledBlinkLabels,
selected = ledBlinkValues.indexOf(state.messageNotificationsState.ledBlink),
isEnabled = state.messageNotificationsState.notificationsEnabled,
onSelected = {
viewModel.setMessageNotificationLedBlink(ledBlinkValues[it])
}
)
}
switchPref(
title = DSLSettingsText.from(R.string.preferences_notifications__in_chat_sounds),
isChecked = state.messageNotificationsState.inChatSoundsEnabled,
isEnabled = state.messageNotificationsState.notificationsEnabled,
onClick = {
viewModel.setMessageNotificationInChatSoundsEnabled(!state.messageNotificationsState.inChatSoundsEnabled)
}
)
radioListPref(
title = DSLSettingsText.from(R.string.preferences__repeat_alerts),
listItems = repeatAlertsLabels,
selected = repeatAlertsValues.indexOf(state.messageNotificationsState.repeatAlerts.toString()),
isEnabled = state.messageNotificationsState.notificationsEnabled,
onSelected = {
viewModel.setMessageRepeatAlerts(repeatAlertsValues[it].toInt())
}
)
radioListPref(
title = DSLSettingsText.from(R.string.preferences_notifications__show),
listItems = notificationPrivacyLabels,
selected = notificationPrivacyValues.indexOf(state.messageNotificationsState.messagePrivacy),
isEnabled = state.messageNotificationsState.notificationsEnabled,
onSelected = {
viewModel.setMessageNotificationPrivacy(notificationPrivacyValues[it])
}
)
if (NotificationChannels.supported()) {
clickPref(
title = DSLSettingsText.from(R.string.preferences_notifications__priority),
isEnabled = state.messageNotificationsState.notificationsEnabled,
onClick = {
launchNotificationPriorityIntent()
}
)
} else {
radioListPref(
title = DSLSettingsText.from(R.string.preferences_notifications__priority),
listItems = notificationPriorityLabels,
selected = notificationPriorityValues.indexOf(state.messageNotificationsState.priority.toString()),
isEnabled = state.messageNotificationsState.notificationsEnabled,
onSelected = {
viewModel.setMessageNotificationPriority(notificationPriorityValues[it].toInt())
}
)
}
dividerPref()
sectionHeaderPref(R.string.NotificationsSettingsFragment__calls)
switchPref(
title = DSLSettingsText.from(R.string.preferences__notifications),
isChecked = state.callNotificationsState.notificationsEnabled,
onClick = {
viewModel.setCallNotificationsEnabled(!state.callNotificationsState.notificationsEnabled)
}
)
clickPref(
title = DSLSettingsText.from(R.string.preferences_notifications__ringtone),
summary = DSLSettingsText.from(getRingtoneSummary(state.callNotificationsState.ringtone)),
isEnabled = state.callNotificationsState.notificationsEnabled,
onClick = {
launchCallRingtoneSelectionIntent()
}
)
switchPref(
title = DSLSettingsText.from(R.string.preferences__vibrate),
isChecked = state.callNotificationsState.vibrateEnabled,
isEnabled = state.callNotificationsState.notificationsEnabled,
onClick = {
viewModel.setCallVibrateEnabled(!state.callNotificationsState.vibrateEnabled)
}
)
dividerPref()
sectionHeaderPref(R.string.NotificationsSettingsFragment__notify_when)
switchPref(
title = DSLSettingsText.from(R.string.NotificationsSettingsFragment__contact_joins_signal),
isChecked = state.notifyWhenContactJoinsSignal,
onClick = {
viewModel.setNotifyWhenContactJoinsSignal(!state.notifyWhenContactJoinsSignal)
}
)
}
}
private fun getRingtoneSummary(uri: Uri): String {
return if (TextUtils.isEmpty(uri.toString())) {
getString(R.string.preferences__silent)
} else {
val tone = RingtoneUtil.getRingtone(requireContext(), uri)
if (tone != null) {
tone.getTitle(requireContext()) ?: getString(R.string.NotificationsSettingsFragment__unknown_ringtone)
} else {
getString(R.string.preferences__default)
}
}
}
private fun launchMessageSoundSelectionIntent() {
val current = SignalStore.settings().messageNotificationSound
val intent = Intent(RingtoneManager.ACTION_RINGTONE_PICKER)
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_DEFAULT, true)
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_SILENT, true)
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, RingtoneManager.TYPE_NOTIFICATION)
intent.putExtra(
RingtoneManager.EXTRA_RINGTONE_DEFAULT_URI,
Settings.System.DEFAULT_NOTIFICATION_URI
)
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, current)
startActivityForResult(intent, MESSAGE_SOUND_SELECT)
}
@RequiresApi(26)
private fun launchNotificationPriorityIntent() {
val intent = Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS)
intent.putExtra(
Settings.EXTRA_CHANNEL_ID,
NotificationChannels.getMessagesChannel(requireContext())
)
intent.putExtra(Settings.EXTRA_APP_PACKAGE, requireContext().packageName)
startActivity(intent)
}
private fun launchCallRingtoneSelectionIntent() {
val current = SignalStore.settings().callRingtone
val intent = Intent(RingtoneManager.ACTION_RINGTONE_PICKER)
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_DEFAULT, true)
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_SILENT, true)
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, RingtoneManager.TYPE_RINGTONE)
intent.putExtra(
RingtoneManager.EXTRA_RINGTONE_DEFAULT_URI,
Settings.System.DEFAULT_RINGTONE_URI
)
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, current)
startActivityForResult(intent, CALL_RINGTONE_SELECT)
}
private class LedColorPreference(
val colorValues: Array<String>,
val radioListPreference: RadioListPreference
) : PreferenceModel<LedColorPreference>(
title = radioListPreference.title,
icon = radioListPreference.icon,
summary = radioListPreference.summary
) {
override fun areContentsTheSame(newItem: LedColorPreference): Boolean {
return super.areContentsTheSame(newItem) && radioListPreference.areContentsTheSame(newItem.radioListPreference)
}
}
private class LedColorPreferenceViewHolder(itemView: View) :
PreferenceViewHolder<LedColorPreference>(itemView) {
val radioListPreferenceViewHolder = RadioListPreferenceViewHolder(itemView)
override fun bind(model: LedColorPreference) {
super.bind(model)
radioListPreferenceViewHolder.bind(model.radioListPreference)
summaryView.visibility = View.GONE
val circleDrawable = requireNotNull(ContextCompat.getDrawable(context, R.drawable.circle_tintable))
circleDrawable.setBounds(0, 0, ViewUtil.dpToPx(20), ViewUtil.dpToPx(20))
circleDrawable.colorFilter = model.colorValues[model.radioListPreference.selected].toColorFilter()
if (ViewUtil.isLtr(itemView)) {
titleView.setCompoundDrawables(null, null, circleDrawable, null)
} else {
titleView.setCompoundDrawables(circleDrawable, null, null, null)
}
}
private fun String.toColorFilter(): ColorFilter {
val color = when (this) {
"green" -> ContextCompat.getColor(context, R.color.green_500)
"red" -> ContextCompat.getColor(context, R.color.red_500)
"blue" -> ContextCompat.getColor(context, R.color.blue_500)
"yellow" -> ContextCompat.getColor(context, R.color.yellow_500)
"cyan" -> ContextCompat.getColor(context, R.color.cyan_500)
"magenta" -> ContextCompat.getColor(context, R.color.pink_500)
"white" -> ContextCompat.getColor(context, R.color.white)
else -> ContextCompat.getColor(context, R.color.transparent)
}
return PorterDuffColorFilter(color, PorterDuff.Mode.SRC_IN)
}
}
}
| gpl-3.0 | d4df3e9aefefac474fb46bdc837d9141 | 41.27003 | 121 | 0.742296 | 4.95306 | false | false | false | false |
elpassion/cloud-timer-android | app/src/main/java/pl/elpassion/cloudtimer/timerslist/ThumbTimer.kt | 1 | 737 | package pl.elpassion.cloudtimer.timerslist
import android.widget.TextView
import com.triggertrap.seekarc.SeekArc
import pl.elpassion.cloudtimer.TimeConverter
class ThumbTimer(val textField: TextView, val arcCounter: SeekArc) {
private var arcValue = -1
var time: Long = 0L
set(time) {
textField.text = TimeConverter.formatShortFromMilliToMinutes(time)
if (arcValue != TimeConverter.getMinutes(time).toInt()) {
arcCounter.progress = TimeConverter.getMinutes(time).toInt() + 1
arcValue = TimeConverter.getMinutes(time).toInt() + 1
}
}
fun setOnClickListener(listener : () -> Unit) {
textField.setOnClickListener{ listener }
}
} | apache-2.0 | 8eae02a42c153e339365a0f8d2767764 | 32.545455 | 80 | 0.670285 | 4.284884 | false | false | false | false |
mobilesolutionworks/works-controller-android | library/src/main/kotlin/com/mobilesolutionworks/android/app/controller/WorksMainScheduler.kt | 1 | 2176 | package com.mobilesolutionworks.android.app.controller
import android.os.Handler
import android.os.Looper
import java.util.*
/**
* Created by yunarta on 8/3/17.
*/
internal class WorksMainScheduler {
private val mHandler = Handler(Looper.getMainLooper())
private val mObservable = object : Observable() {
public override fun setChanged() {
super.setChanged()
}
}
private var mIsPaused = true
fun resume() {
mIsPaused = false
mObservable.setChanged()
mObservable.notifyObservers()
mObservable.deleteObservers()
}
fun pause() {
mIsPaused = true
}
fun release() {
mObservable.deleteObservers()
}
/**
* Run the specified runnable after the host enter resumed state.
*
* This method will solve many problem like Fragment transaction problems,
* or background updates that need to be notified to host.
*/
fun runWhenUiIsReady(runnable: Runnable) {
if (mIsPaused) {
mObservable.addObserver { _, _ -> runOnMainThread(runnable) }
} else {
runOnMainThread(runnable)
}
}
/**
* Run the specified runnable immediately if the caller is currently on main thread,
* or it will be executed when the queue on main thread is available.
*
* This execution does not guarantee the UI is ready, if you want to run something only when
* the UI is ready use [.runWhenUiIsReady] instead.
*
* @param runnable runnable to run.
*/
fun runOnMainThread(runnable: Runnable) {
if (Looper.getMainLooper().thread === Thread.currentThread()) {
runnable.run()
} else {
mHandler.post(runnable)
}
}
/**
* Run the specified runnable delayed on main thread.
*
* This execution does not guarantee the UI is ready, if you want to run something only when
* the UI is ready use [.runWhenUiIsReady] instead.
*
* @param runnable runnable to run.
*/
fun runOnMainThreadDelayed(runnable: Runnable, delay: Long) {
mHandler.postDelayed(runnable, delay)
}
}
| apache-2.0 | ebc3adb796e17cdb24abad1128320d30 | 26.2 | 96 | 0.627757 | 4.659529 | false | false | false | false |
JavaEden/Orchid-Core | plugins/OrchidKSS/src/main/kotlin/com/eden/orchid/kss/pages/KssPage.kt | 2 | 1595 | package com.eden.orchid.kss.pages
import com.eden.common.util.EdenUtils
import com.eden.orchid.api.OrchidContext
import com.eden.orchid.api.options.annotations.Archetype
import com.eden.orchid.api.options.annotations.Description
import com.eden.orchid.api.options.archetypes.ConfigArchetype
import com.eden.orchid.api.render.RenderService
import com.eden.orchid.api.theme.pages.OrchidPage
import com.eden.orchid.kss.KssGenerator
import com.eden.orchid.kss.parser.StyleguideSection
@Archetype(value = ConfigArchetype::class, key = "${KssGenerator.GENERATOR_KEY}.styleguidePages")
@Description(value = "A page for a section in your styleguide.", name = "KSS")
class KssPage(
context: OrchidContext,
val styleguideSection: StyleguideSection
) : OrchidPage(
KssSectionResource(context, styleguideSection),
RenderService.RenderMode.TEMPLATE,
"styleguide",
"Styleguide - ${styleguideSection.name}"
) {
var parent: KssPage? = null
var children: MutableList<KssPage> = ArrayList()
var stylesheet: String? = null
get() {
if (!EdenUtils.isEmpty(styleguideSection.stylesheet))
return styleguideSection.stylesheet
else if (!EdenUtils.isEmpty(field))
return field
else
return ""
}
override fun getTitle(): String {
return "Section " + styleguideSection.styleGuideReference + " - " + styleguideSection.name
}
fun hasStylesheet(): Boolean {
return !EdenUtils.isEmpty(styleguideSection.stylesheet) || !EdenUtils.isEmpty(stylesheet)
}
}
| mit | 5d7a7fc56a287810713d67083874a7ec | 33.673913 | 98 | 0.71348 | 4.230769 | false | false | false | false |
GunoH/intellij-community | platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/FileEditorManagerImpl.kt | 1 | 77630 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:Suppress("OVERRIDE_DEPRECATION", "ReplaceGetOrSet", "LeakingThis")
package com.intellij.openapi.fileEditor.impl
import com.intellij.ProjectTopics
import com.intellij.codeInsight.intention.preview.IntentionPreviewUtils
import com.intellij.codeWithMe.ClientId
import com.intellij.codeWithMe.ClientId.Companion.current
import com.intellij.codeWithMe.ClientId.Companion.isCurrentlyUnderLocalId
import com.intellij.codeWithMe.ClientId.Companion.isLocal
import com.intellij.codeWithMe.ClientId.Companion.localId
import com.intellij.codeWithMe.ClientId.Companion.withClientId
import com.intellij.diagnostic.PluginException
import com.intellij.ide.IdeBundle
import com.intellij.ide.IdeEventQueue
import com.intellij.ide.actions.MaximizeEditorInSplitAction.Companion.getSplittersToMaximize
import com.intellij.ide.actions.SplitAction
import com.intellij.ide.impl.ProjectUtil.getActiveProject
import com.intellij.ide.lightEdit.LightEdit
import com.intellij.ide.plugins.PluginManager
import com.intellij.ide.ui.UISettings
import com.intellij.ide.ui.UISettingsListener
import com.intellij.injected.editor.VirtualFileWindow
import com.intellij.lang.LangBundle
import com.intellij.notebook.editor.BackedVirtualFile
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.IdeActions
import com.intellij.openapi.application.*
import com.intellij.openapi.client.ClientKind
import com.intellij.openapi.client.ClientSessionsManager.Companion.getProjectSession
import com.intellij.openapi.command.CommandProcessor
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.State
import com.intellij.openapi.components.Storage
import com.intellij.openapi.components.StoragePathMacros
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.ScrollType
import com.intellij.openapi.editor.event.EditorFactoryEvent
import com.intellij.openapi.editor.event.EditorFactoryListener
import com.intellij.openapi.editor.ex.EditorEx
import com.intellij.openapi.editor.ex.FocusChangeListener
import com.intellij.openapi.extensions.ExtensionNotApplicableException
import com.intellij.openapi.extensions.ExtensionPointListener
import com.intellij.openapi.extensions.PluginDescriptor
import com.intellij.openapi.fileEditor.*
import com.intellij.openapi.fileEditor.FileEditorComposite.Companion.EMPTY
import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx
import com.intellij.openapi.fileEditor.ex.FileEditorProviderManager
import com.intellij.openapi.fileEditor.ex.FileEditorWithProvider
import com.intellij.openapi.fileEditor.ex.IdeDocumentHistory
import com.intellij.openapi.fileEditor.impl.EditorComposite.Companion.retrofit
import com.intellij.openapi.fileEditor.impl.FileEditorProviderManagerImpl.Companion.getInstanceImpl
import com.intellij.openapi.fileEditor.impl.text.TextEditorProvider
import com.intellij.openapi.fileTypes.FileTypeEvent
import com.intellij.openapi.fileTypes.FileTypeListener
import com.intellij.openapi.fileTypes.FileTypeManager
import com.intellij.openapi.keymap.KeymapManager
import com.intellij.openapi.options.advanced.AdvancedSettings.Companion.getBoolean
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.PossiblyDumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectCloseListener
import com.intellij.openapi.roots.AdditionalLibraryRootsListener
import com.intellij.openapi.roots.ModuleRootEvent
import com.intellij.openapi.roots.ModuleRootListener
import com.intellij.openapi.ui.Splitter
import com.intellij.openapi.util.*
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.vcs.FileStatus
import com.intellij.openapi.vcs.FileStatusListener
import com.intellij.openapi.vcs.FileStatusManager
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.openapi.vfs.newvfs.BulkFileListener
import com.intellij.openapi.vfs.newvfs.events.VFileDeleteEvent
import com.intellij.openapi.vfs.newvfs.events.VFileEvent
import com.intellij.openapi.vfs.newvfs.events.VFileMoveEvent
import com.intellij.openapi.vfs.newvfs.events.VFilePropertyChangeEvent
import com.intellij.openapi.wm.IdeFocusManager
import com.intellij.pom.Navigatable
import com.intellij.reference.SoftReference
import com.intellij.ui.ComponentUtil
import com.intellij.ui.ExperimentalUI
import com.intellij.ui.docking.DockContainer
import com.intellij.ui.docking.DockManager
import com.intellij.ui.docking.impl.DockManagerImpl
import com.intellij.ui.tabs.impl.JBTabsImpl
import com.intellij.util.*
import com.intellij.util.concurrency.AppExecutorUtil
import com.intellij.util.concurrency.annotations.RequiresEdt
import com.intellij.util.concurrency.annotations.RequiresReadLock
import com.intellij.util.containers.SmartHashSet
import com.intellij.util.messages.impl.MessageListenerList
import com.intellij.util.ui.EdtInvocationManager
import com.intellij.util.ui.UIUtil
import com.intellij.util.ui.update.MergingUpdateQueue
import com.intellij.util.ui.update.Update
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.jdom.Element
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.Contract
import org.jetbrains.annotations.Nls
import java.awt.AWTEvent
import java.awt.Color
import java.awt.Component
import java.awt.KeyboardFocusManager
import java.awt.event.InputEvent
import java.awt.event.KeyEvent
import java.awt.event.MouseEvent
import java.beans.PropertyChangeEvent
import java.beans.PropertyChangeListener
import java.lang.ref.Reference
import java.lang.ref.WeakReference
import java.util.*
import java.util.concurrent.Callable
import java.util.concurrent.CancellationException
import java.util.concurrent.CompletableFuture
import java.util.concurrent.CopyOnWriteArrayList
import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.atomic.LongAdder
import java.util.function.Consumer
import java.util.function.Supplier
import javax.swing.JComponent
import javax.swing.JTabbedPane
import javax.swing.KeyStroke
import javax.swing.SwingUtilities
@State(name = "FileEditorManager", storages = [
Storage(StoragePathMacros.PRODUCT_WORKSPACE_FILE),
Storage(value = StoragePathMacros.WORKSPACE_FILE, deprecated = true),
])
open class FileEditorManagerImpl(private val project: Project) : FileEditorManagerEx(), PersistentStateComponent<Element?>, Disposable {
enum class OpenMode {
NEW_WINDOW, RIGHT_SPLIT, DEFAULT
}
val mainSplitters: EditorsSplitters
private val dockable: DockableEditorTabbedContainer
private val selectionHistory = ArrayList<Pair<VirtualFile, EditorWindow>>()
private var lastSelectedComposite: Reference<EditorComposite?>? = WeakReference<EditorComposite?>(null)
private val queue = MergingUpdateQueue("FileEditorManagerUpdateQueue", 50, true, MergingUpdateQueue.ANY_COMPONENT, this)
private var fileToUpdateTitle: SoftReference<VirtualFile?>? = null
private val updateFileTitleAlarm = SingleAlarm(Runnable {
val file = SoftReference.deref(fileToUpdateTitle)
if (file == null || !file.isValid) {
return@Runnable
}
fileToUpdateTitle = null
for (each in getAllSplitters()) {
each.updateFileName(file)
}
}, 50, this, Alarm.ThreadToUse.SWING_THREAD, ModalityState.NON_MODAL)
private val busyObject = SimpleBusyObject()
/**
* Removes invalid myEditor and updates "modified" status.
*/
private val editorPropertyChangeListener = MyEditorPropertyChangeListener()
private var contentFactory: DockableEditorContainerFactory? = null
private val openedComposites = CopyOnWriteArrayList<EditorComposite>()
private val listenerList = MessageListenerList(project.messageBus, FileEditorManagerListener.FILE_EDITOR_MANAGER)
init {
queue.setTrackUiActivity(true)
val connection = project.messageBus.connect(this)
connection.subscribe(DumbService.DUMB_MODE, object : DumbService.DumbModeListener {
override fun exitDumbMode() {
// can happen under write action, so postpone to avoid deadlock on FileEditorProviderManager.getProviders()
ApplicationManager.getApplication().invokeLater({ dumbModeFinished(project) }, project.disposed)
}
})
connection.subscribe(ProjectCloseListener.TOPIC, object : ProjectCloseListener {
override fun projectClosing(project: Project) {
if ([email protected] === project) {
// Dispose created editors. We do not use closeEditor method because
// it fires event and changes history.
closeAllFiles()
}
}
})
closeFilesOnFileEditorRemoval()
mainSplitters = EditorsSplitters(this)
dockable = DockableEditorTabbedContainer(mainSplitters, false)
// prepare for toolwindow manager
mainSplitters.isFocusable = false
}
companion object {
private val LOG = logger<FileEditorManagerImpl>()
@JvmField
protected val DUMB_AWARE = Key.create<Boolean>("DUMB_AWARE")
@JvmField
val NOTHING_WAS_OPENED_ON_START = Key.create<Boolean>("NOTHING_WAS_OPENED_ON_START")
@JvmField
val CLOSING_TO_REOPEN = Key.create<Boolean>("CLOSING_TO_REOPEN")
/**
* Works on VirtualFile objects, and allows to disable the Preview Tab functionality for certain files.
* If a virtual file has this key set to TRUE, the corresponding editor will always be opened in a regular tab.
*/
@JvmField
val FORBID_PREVIEW_TAB = Key.create<Boolean>("FORBID_PREVIEW_TAB")
@JvmField
val OPEN_IN_PREVIEW_TAB = Key.create<Boolean>("OPEN_IN_PREVIEW_TAB")
/**
* Works on FileEditor objects, allows to force opening other editor tabs in the main window.
* If the currently selected file editor has this key set to TRUE, new editors will be opened in the main splitters.
*/
val SINGLETON_EDITOR_IN_WINDOW = Key.create<Boolean>("OPEN_OTHER_TABS_IN_MAIN_WINDOW")
const val FILE_EDITOR_MANAGER = "FileEditorManager"
const val EDITOR_OPEN_INACTIVE_SPLITTER = "editor.open.inactive.splitter"
private val openFileSetModificationCount = AtomicInteger()
@JvmField
val OPEN_FILE_SET_MODIFICATION_COUNT = ModificationTracker { openFileSetModificationCount.get().toLong() }
private fun registerEditor(editor: EditorEx, project: Project) {
editor.addFocusListener(object : FocusChangeListener {
private var managerRef: WeakReference<FileEditorManagerImpl?>? = null
override fun focusGained(editor1: Editor) {
if (!Registry.`is`("editor.maximize.on.focus.gained.if.collapsed.in.split", false)) {
return
}
var manager = if (managerRef == null) null else managerRef!!.get()
if (manager == null) {
val fileEditorManager = getInstance(project)
if (fileEditorManager is FileEditorManagerImpl) {
manager = fileEditorManager
managerRef = WeakReference(manager)
}
else {
return
}
}
var component: Component? = editor1.component
while (component != null && component !== manager.mainSplitters) {
val parent: Component = component.parent
if (parent is Splitter) {
if (parent.firstComponent === component &&
(parent.proportion == parent.getMinProportion(true) ||
parent.proportion == parent.minimumProportion) || parent.proportion == parent.getMinProportion(false) ||
parent.proportion == parent.maximumProportion) {
val pairs = getSplittersToMaximize(project, editor1.component)
for ((s, second) in pairs) {
s.proportion = if (second) s.maximumProportion else s.minimumProportion
}
break
}
}
component = parent
}
}
}, project)
}
fun isDumbAware(editor: FileEditor): Boolean {
return java.lang.Boolean.TRUE == editor.getUserData(DUMB_AWARE) &&
(editor !is PossiblyDumbAware || (editor as PossiblyDumbAware).isDumbAware)
}
private fun isFileOpenInWindow(file: VirtualFile, window: EditorWindow): Boolean {
val shouldFileBeSelected = UISettings.getInstance().editorTabPlacement == UISettings.TABS_NONE
return if (shouldFileBeSelected) file == window.selectedFile else window.isFileOpen(file)
}
@JvmStatic
fun getOpenMode(event: AWTEvent): OpenMode {
if (event is MouseEvent) {
val isMouseClick = event.getID() == MouseEvent.MOUSE_CLICKED || event.getID() == MouseEvent.MOUSE_PRESSED || event.getID() == MouseEvent.MOUSE_RELEASED
val modifiers = event.modifiersEx
if (modifiers == InputEvent.SHIFT_DOWN_MASK && isMouseClick) {
return OpenMode.NEW_WINDOW
}
}
else if (event is KeyEvent) {
val keymapManager = KeymapManager.getInstance()
if (keymapManager != null) {
@Suppress("DEPRECATION")
val strings = keymapManager.activeKeymap.getActionIds(KeyStroke.getKeyStroke(event.keyCode, event.modifiers))
if (strings.contains(IdeActions.ACTION_OPEN_IN_NEW_WINDOW)) {
return OpenMode.NEW_WINDOW
}
if (strings.contains(IdeActions.ACTION_OPEN_IN_RIGHT_SPLIT)) {
return OpenMode.RIGHT_SPLIT
}
}
}
return OpenMode.DEFAULT
}
@JvmStatic
fun forbidSplitFor(file: VirtualFile): Boolean {
return java.lang.Boolean.TRUE == file.getUserData(SplitAction.FORBID_TAB_SPLIT)
}
private fun assertDispatchThread() {
ApplicationManager.getApplication().assertIsDispatchThread()
}
internal fun getOriginalFile(file: VirtualFile): VirtualFile {
return BackedVirtualFile.getOriginFileIfBacked(if (file is VirtualFileWindow) file.delegate else file)
}
fun runBulkTabChange(splitters: EditorsSplitters, task: Runnable) {
if (!ApplicationManager.getApplication().isDispatchThread) {
task.run()
}
else {
splitters.insideChange++
try {
task.run()
}
finally {
splitters.insideChange--
if (!splitters.isInsideChange) {
splitters.validate()
for (window in splitters.getWindows()) {
(window.tabbedPane.tabs as JBTabsImpl).revalidateAndRepaint()
}
}
}
}
}
}
override fun getDockContainer(): DockContainer? = dockable
internal class MyEditorFactoryListener : EditorFactoryListener {
init {
if (ApplicationManager.getApplication().isHeadlessEnvironment) {
throw ExtensionNotApplicableException.create()
}
}
override fun editorCreated(event: EditorFactoryEvent) {
val editor = event.editor as? EditorEx ?: return
val project = editor.project
if (project == null || project.isDisposed) {
return
}
registerEditor(editor, project)
}
}
private fun closeFilesOnFileEditorRemoval() {
FileEditorProvider.EP_FILE_EDITOR_PROVIDER.addExtensionPointListener(object : ExtensionPointListener<FileEditorProvider> {
override fun extensionRemoved(extension: FileEditorProvider, pluginDescriptor: PluginDescriptor) {
for (editor in openedComposites) {
for (provider in editor.allProviders) {
if (provider == extension) {
closeFile(editor.file)
break
}
}
}
}
}, this)
}
override fun dispose() {
fileToUpdateTitle = null
Disposer.dispose(dockable)
}
private fun dumbModeFinished(project: Project) {
for (file in openedFiles) {
val composites = getAllComposites(file)
val existingProviders = composites.flatMap(EditorComposite::allProviders)
val existingIds = existingProviders.mapTo(HashSet()) { it.editorTypeId }
val newProviders = FileEditorProviderManager.getInstance().getProviderList(project, file)
val toOpen = newProviders.filter { !existingIds.contains(it.editorTypeId) }
// need to open additional non dumb-aware editors
for (composite in composites) {
for (provider in toOpen) {
composite.addEditor(provider.createEditor(project, file), provider)
}
}
updateFileBackgroundColor(file)
}
// update for non-dumb-aware EditorTabTitleProviders
updateFileName(null)
}
@RequiresEdt
fun initDockableContentFactory() {
if (contentFactory != null) {
return
}
contentFactory = DockableEditorContainerFactory(this)
DockManager.getInstance(project).register(DockableEditorContainerFactory.TYPE, contentFactory!!, this)
}
//-------------------------------------------------------------------------------
override fun getComponent(): JComponent = mainSplitters
fun getAllSplitters(): Set<EditorsSplitters> {
val all = LinkedHashSet<EditorsSplitters>()
all.add(mainSplitters)
for (container in DockManager.getInstance(project).containers) {
if (container is DockableEditorTabbedContainer) {
all.add(container.splitters)
}
}
return Collections.unmodifiableSet(all)
}
private fun getActiveSplittersAsync(): CompletableFuture<EditorsSplitters?> {
val result = CompletableFuture<EditorsSplitters?>()
val fm = IdeFocusManager.getInstance(project)
TransactionGuard.getInstance().assertWriteSafeContext(ModalityState.defaultModalityState())
fm.doWhenFocusSettlesDown({
if (project.isDisposed) {
result.complete(null)
return@doWhenFocusSettlesDown
}
val focusOwner = fm.focusOwner
val container = DockManager.getInstance(project).getContainerFor(focusOwner) { obj ->
DockableEditorTabbedContainer::class.java.isInstance(obj)
}
if (container is DockableEditorTabbedContainer) {
result.complete(container.splitters)
}
else {
result.complete(mainSplitters)
}
}, ModalityState.defaultModalityState())
return result
}
private val activeSplittersSync: EditorsSplitters
get() {
assertDispatchThread()
if (Registry.`is`("ide.navigate.to.recently.focused.editor", false)) {
val splitters = getAllSplitters().toMutableList()
if (!splitters.isEmpty()) {
splitters.sortWith(Comparator { o1, o2 ->
o2.lastFocusGainedTime.compareTo(o1.lastFocusGainedTime)
})
return splitters[0]
}
}
val fm = IdeFocusManager.getInstance(project)
var focusOwner = fm.focusOwner
?: KeyboardFocusManager.getCurrentKeyboardFocusManager().focusOwner
?: fm.getLastFocusedFor(fm.lastFocusedIdeWindow)
var container = DockManager.getInstance(project).getContainerFor(focusOwner) { obj -> obj is DockableEditorTabbedContainer }
if (container == null) {
focusOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager().activeWindow
container = DockManager.getInstance(project).getContainerFor(focusOwner) { obj -> obj is DockableEditorTabbedContainer }
}
return if (container is DockableEditorTabbedContainer) {
container.splitters
}
else mainSplitters
}
@RequiresReadLock
override fun getPreferredFocusedComponent(): JComponent? {
val window = splitters.currentWindow
if (window != null) {
val composite = window.selectedComposite
if (composite != null) {
return composite.preferredFocusedComponent
}
}
return null
}
//-------------------------------------------------------
/**
* @return color of the `file` which corresponds to the
* file's status
*/
fun getFileColor(file: VirtualFile): Color {
val fileStatusManager = FileStatusManager.getInstance(project) ?: return UIUtil.getLabelForeground()
return fileStatusManager.getStatus(file).color ?: UIUtil.getLabelForeground()
}
open fun isProblem(file: VirtualFile): Boolean = false
open fun getFileTooltipText(file: VirtualFile, window: EditorWindow): @NlsContexts.Tooltip String {
var prefix = ""
val composite = window.getComposite(file)
if (composite != null && composite.isPreview) {
prefix = LangBundle.message("preview.editor.tab.tooltip.text") + " "
}
val availableProviders = DumbService.getDumbAwareExtensions(project, EditorTabTitleProvider.EP_NAME)
for (provider in availableProviders) {
val text = provider.getEditorTabTooltipText(project, file)
if (text != null) {
return prefix + text
}
}
return prefix + FileUtil.getLocationRelativeToUserHome(file.presentableUrl)
}
override fun updateFilePresentation(file: VirtualFile) {
if (!isFileOpen(file)) {
return
}
updateFileName(file)
queueUpdateFile(file)
}
/**
* Updates tab color for the specified `file`. The `file`
* should be opened in the myEditor, otherwise the method throws an assertion.
*/
override fun updateFileColor(file: VirtualFile) {
for (each in getAllSplitters()) {
each.updateFileColor(file)
}
}
private fun updateFileBackgroundColor(file: VirtualFile) {
if (ExperimentalUI.isNewUI()) {
return
}
for (each in getAllSplitters()) {
each.updateFileBackgroundColorAsync(file)
}
}
/**
* Reset the preview tab flag if an internal document change is made.
*/
private fun resetPreviewFlag(file: VirtualFile) {
if (!FileDocumentManager.getInstance().isFileModified(file)) {
return
}
for (splitter in getAllSplitters()) {
for (c in splitter.getAllComposites(file)) {
if (c.isPreview) {
c.isPreview = false
}
}
splitter.updateFileColor(file)
}
}
/**
* Updates tab icon for the specified `file`. The `file`
* should be opened in the myEditor, otherwise the method throws an assertion.
*/
/**
* Updates tab icon for the specified `file`. The `file`
* should be opened in the myEditor, otherwise the method throws an assertion.
*/
protected fun updateFileIcon(file: VirtualFile, immediately: Boolean = false) {
for (each in getAllSplitters()) {
if (immediately) {
each.updateFileIconImmediately(file, IconUtil.computeFileIcon(file, Iconable.ICON_FLAG_READ_STATUS, project))
}
else {
each.updateFileIcon(file)
}
}
}
/**
* Updates tab title and tab tool tip for the specified `file`
*/
fun updateFileName(file: VirtualFile?) {
// Queue here is to prevent title flickering when tab is being closed and two events arriving: with component==null and component==next focused tab
// only the last event makes sense to handle
updateFileTitleAlarm.cancelAndRequest()
fileToUpdateTitle = SoftReference(file)
}
private fun updateFrameTitle() {
getActiveSplittersAsync().thenAccept { it?.updateFileName(null) }
}
@Suppress("removal")
override fun getFile(editor: FileEditor): VirtualFile? {
val editorComposite = getComposite(editor)
val tabFile = editorComposite?.file
val editorFile = editor.file
if (editorFile != tabFile) {
if (editorFile == null) {
LOG.warn("${editor.javaClass.name}.getFile() shall not return null")
}
else if (tabFile == null) {
//todo DaemonCodeAnalyzerImpl#getSelectedEditors calls it for any Editor
//LOG.warn(editor.getClass().getName() + ".getFile() shall be used, fileEditor is not opened in a tab.");
}
else {
LOG.warn("fileEditor.getFile=$editorFile != fileEditorManager.getFile=$tabFile, fileEditor.class=${editor.javaClass.name}")
}
}
return tabFile
}
override fun unsplitWindow() {
activeSplittersSync.currentWindow?.unsplit(true)
}
override fun unsplitAllWindow() {
activeSplittersSync.currentWindow?.unsplitAll()
}
override fun getWindowSplitCount(): Int = activeSplittersSync.splitCount
override fun hasSplitOrUndockedWindows(): Boolean {
val splitters = getAllSplitters()
return if (splitters.size > 1) true else windowSplitCount > 1
}
override fun getWindows(): Array<EditorWindow> {
val windows = ArrayList<EditorWindow>()
for (each in getAllSplitters()) {
windows.addAll(each.getWindows())
}
return windows.toTypedArray()
}
override fun getNextWindow(window: EditorWindow): EditorWindow? {
val windows = splitters.getOrderedWindows()
for (i in windows.indices) {
if (windows[i] == window) {
return windows.get((i + 1) % windows.size)
}
}
LOG.error("Not window found")
return null
}
override fun getPrevWindow(window: EditorWindow): EditorWindow? {
val windows = splitters.getOrderedWindows()
for (i in windows.indices) {
if (windows[i] == window) {
return windows.get((i + windows.size - 1) % windows.size)
}
}
LOG.error("Not window found")
return null
}
override fun createSplitter(orientation: Int, window: EditorWindow?) {
// window was available from action event, for example when invoked from the tab menu of an editor that is not the 'current'
if (window != null) {
window.split(orientation = orientation, forceSplit = true, virtualFile = null, focusNew = false)
}
else {
splitters.currentWindow?.split(orientation = orientation, forceSplit = true, virtualFile = null, focusNew = false)
}
}
override fun changeSplitterOrientation() {
splitters.currentWindow?.changeOrientation()
}
override fun isInSplitter(): Boolean {
val currentWindow = splitters.currentWindow
return currentWindow != null && currentWindow.inSplitter()
}
override fun hasOpenedFile(): Boolean = splitters.currentWindow?.selectedComposite != null
override fun getCurrentFile(): VirtualFile? {
if (!isCurrentlyUnderLocalId) {
return clientFileEditorManager?.getSelectedFile()
}
return activeSplittersSync.currentFile
}
override fun getActiveWindow(): CompletableFuture<EditorWindow?> = getActiveSplittersAsync().thenApply { it?.currentWindow }
override fun getCurrentWindow(): EditorWindow? {
if (!isCurrentlyUnderLocalId) {
return null
}
if (!ApplicationManager.getApplication().isDispatchThread) {
LOG.warn("Requesting getCurrentWindow() on BGT, returning null", Throwable())
return null
}
return activeSplittersSync.currentWindow
}
override fun setCurrentWindow(window: EditorWindow?) {
if (isCurrentlyUnderLocalId) {
activeSplittersSync.setCurrentWindow(window = window, requestFocus = true)
}
}
fun closeFile(file: VirtualFile, window: EditorWindow, transferFocus: Boolean) {
assertDispatchThread()
openFileSetModificationCount.incrementAndGet()
CommandProcessor.getInstance().executeCommand(project, {
if (window.isFileOpen(file)) {
window.closeFile(file = file, disposeIfNeeded = true, transferFocus = transferFocus)
}
}, IdeBundle.message("command.close.active.editor"), null)
removeSelectionRecord(file, window)
}
override fun closeFile(file: VirtualFile, window: EditorWindow) {
closeFile(file, window, true)
}
//============================= EditorManager methods ================================
override fun closeFile(file: VirtualFile) {
closeFile(file = file, moveFocus = true, closeAllCopies = false)
}
@RequiresEdt
fun closeFile(file: VirtualFile, moveFocus: Boolean, closeAllCopies: Boolean) {
if (!closeAllCopies) {
if (isCurrentlyUnderLocalId) {
CommandProcessor.getInstance().executeCommand(project, {
openFileSetModificationCount.incrementAndGet()
val activeSplitters = activeSplittersSync
runBulkTabChange(activeSplitters) { activeSplitters.closeFile(file, moveFocus) }
}, "", null)
}
else {
clientFileEditorManager?.closeFile(file, false)
}
}
else {
withClientId(localId).use {
CommandProcessor.getInstance().executeCommand(project, {
openFileSetModificationCount.incrementAndGet()
for (each in getAllSplitters()) {
runBulkTabChange(each) { each.closeFile(file = file, moveFocus = moveFocus) }
}
}, "", null)
}
for (manager in allClientFileEditorManagers) {
manager.closeFile(file = file, closeAllCopies = true)
}
}
}
private val allClientFileEditorManagers: List<ClientFileEditorManager>
get() = project.getServices(ClientFileEditorManager::class.java, ClientKind.REMOTE)
override fun isFileOpenWithRemotes(file: VirtualFile): Boolean {
return isFileOpen(file) || allClientFileEditorManagers.any { it.isFileOpen(file) }
}
//-------------------------------------- Open File ----------------------------------------
override fun openFileWithProviders(file: VirtualFile,
focusEditor: Boolean,
searchForSplitter: Boolean): Pair<Array<FileEditor>, Array<FileEditorProvider>> {
val openOptions = FileEditorOpenOptions(requestFocus = focusEditor, reuseOpen = searchForSplitter)
return openFileWithProviders(file = file, suggestedWindow = null, options = openOptions).retrofit()
}
override fun openFileWithProviders(file: VirtualFile,
focusEditor: Boolean,
window: EditorWindow): Pair<Array<FileEditor>, Array<FileEditorProvider>> {
return openFileWithProviders(file, window, FileEditorOpenOptions(requestFocus = focusEditor)).retrofit()
}
override fun openFileWithProviders(file: VirtualFile,
suggestedWindow: EditorWindow?,
options: FileEditorOpenOptions): FileEditorComposite {
var window = suggestedWindow
require(file.isValid) { "file is not valid: $file" }
assertDispatchThread()
if (window != null && window.isDisposed) {
window = null
}
if (window == null) {
val mode = getOpenMode(IdeEventQueue.getInstance().trueCurrentEvent)
if (mode == OpenMode.NEW_WINDOW) {
if (forbidSplitFor(file)) {
closeFile(file)
}
return (DockManager.getInstance(project) as DockManagerImpl).createNewDockContainerFor(file, this)
}
if (mode == OpenMode.RIGHT_SPLIT) {
val result = openInRightSplit(file)
if (result != null) {
return result
}
}
}
var windowToOpenIn = window
if (windowToOpenIn == null && (options.reuseOpen || !getBoolean(EDITOR_OPEN_INACTIVE_SPLITTER))) {
windowToOpenIn = findWindowInAllSplitters(file)
}
if (windowToOpenIn == null) {
windowToOpenIn = getOrCreateCurrentWindow(file)
}
return openFileImpl2(windowToOpenIn, file, options)
}
private fun findWindowInAllSplitters(file: VirtualFile): EditorWindow? {
val activeCurrentWindow = activeSplittersSync.currentWindow
if (activeCurrentWindow != null && isFileOpenInWindow(file, activeCurrentWindow)) {
return activeCurrentWindow
}
for (splitters in getAllSplitters()) {
for (window in splitters.getWindows()) {
if (isFileOpenInWindow(file, window)) {
return if (getBoolean(EDITOR_OPEN_INACTIVE_SPLITTER)) window else activeCurrentWindow
// return a window from here so that we don't look for it again in getOrCreateCurrentWindow
}
}
}
return null
}
private fun getOrCreateCurrentWindow(file: VirtualFile): EditorWindow {
val uiSettings = UISettings.getInstance()
val useMainWindow = uiSettings.openTabsInMainWindow || SINGLETON_EDITOR_IN_WINDOW.get(selectedEditor, false)
val splitters = if (useMainWindow) mainSplitters else splitters
val currentWindow = splitters.currentWindow
if (currentWindow == null || uiSettings.editorTabPlacement != UISettings.TABS_NONE) {
return splitters.getOrCreateCurrentWindow(file)
}
else {
return currentWindow
}
}
fun openFileInNewWindow(file: VirtualFile): Pair<Array<FileEditor>, Array<FileEditorProvider>> {
if (forbidSplitFor(file)) {
closeFile(file)
}
return (DockManager.getInstance(project) as DockManagerImpl).createNewDockContainerFor(file, this).retrofit()
}
private fun openInRightSplit(file: VirtualFile): FileEditorComposite? {
val active = splitters
val window = active.currentWindow
if (window == null || window.inSplitter() && file == window.selectedFile && file == ArrayUtil.getLastElement(window.files)) {
// already in right splitter
return null
}
val split = active.openInRightSplit(file) ?: return null
var result: FileEditorComposite? = null
CommandProcessor.getInstance().executeCommand(project, {
val editorsWithProviders = split.composites.flatMap(EditorComposite::allEditorsWithProviders).toList()
val allEditors = editorsWithProviders.map { it.fileEditor }
val allProviders = editorsWithProviders.map { it.provider }
result = object : FileEditorComposite {
override val isPreview: Boolean
get() = false
override val allEditors: List<FileEditor>
get() = allEditors
override val allProviders: List<FileEditorProvider>
get() = allProviders
}
}, "", null)
return result
}
@Suppress("DeprecatedCallableAddReplaceWith")
@Deprecated("Use public API.")
fun openFileImpl2(window: EditorWindow,
file: VirtualFile,
focusEditor: Boolean): Pair<Array<FileEditor>, Array<FileEditorProvider>> {
return openFileImpl2(window = window, file = file, options = FileEditorOpenOptions(requestFocus = focusEditor)).retrofit()
}
open fun openFileImpl2(window: EditorWindow,
file: VirtualFile,
options: FileEditorOpenOptions): FileEditorComposite {
if (forbidSplitFor(file) && !window.isFileOpen(file)) {
closeFile(file)
}
val result = Ref<FileEditorComposite>()
CommandProcessor.getInstance().executeCommand(project, { result.set(openFileImpl4(window, file, null, options)) }, "", null)
return result.get()
}
/**
* @param file to be opened. Unlike openFile method, file can be
* invalid. For example, all file where invalidate, and they are being
* removed one by one. If we have removed one invalid file, then another
* invalid file become selected. That's why we do not require that
* passed file is valid.
* @param entry map between FileEditorProvider and FileEditorState. If this parameter
*/
fun openFileImpl3(window: EditorWindow,
file: VirtualFile,
focusEditor: Boolean,
entry: HistoryEntry?): FileEditorComposite {
return openFileImpl4(window = window, _file = file, entry = entry, options = FileEditorOpenOptions(requestFocus = focusEditor))
}
protected val clientFileEditorManager: ClientFileEditorManager?
get() {
val clientId = current
LOG.assertTrue(!clientId.isLocal, "Trying to get ClientFileEditorManager for local ClientId")
return getProjectSession(project, clientId)?.getService(ClientFileEditorManager::class.java)
}
/**
* This method can be invoked from background thread. Of course, UI for returned editors should be accessed from EDT in any case.
*/
internal fun openFileImpl4(window: EditorWindow,
@Suppress("LocalVariableName") _file: VirtualFile,
entry: HistoryEntry?,
options: FileEditorOpenOptions): FileEditorComposite {
assert(ApplicationManager.getApplication().isDispatchThread ||
!ApplicationManager.getApplication().isReadAccessAllowed) { "must not attempt opening files under read action" }
if (!isCurrentlyUnderLocalId) {
val clientManager = clientFileEditorManager ?: return EMPTY
val result = clientManager.openFile(file = _file, forceCreate = false)
val allEditors = result.map { it.fileEditor }
val allProviders = result.map { it.provider }
return object : FileEditorComposite {
override val isPreview: Boolean
get() = options.usePreviewTab
override val allEditors: List<FileEditor>
get() = allEditors
override val allProviders: List<FileEditorProvider>
get() = allProviders
}
}
val file = getOriginalFile(_file)
val compositeRef = Ref<FileEditorComposite>()
if (!options.isReopeningOnStartup) {
EdtInvocationManager.invokeAndWaitIfNeeded { compositeRef.set(window.getComposite(file)) }
}
val newProviders: List<FileEditorProvider>?
val builders: Array<AsyncFileEditorProvider.Builder?>?
if (compositeRef.isNull) {
if (!canOpenFile(file)) {
return EMPTY
}
// File is not opened yet. In this case we have to create editors
// and select the created EditorComposite.
newProviders = FileEditorProviderManager.getInstance().getProviderList(project, file)
builders = arrayOfNulls(newProviders.size)
for (i in newProviders.indices) {
try {
val provider = newProviders[i]
builders[i] = ReadAction.compute<AsyncFileEditorProvider.Builder?, RuntimeException> {
if (project.isDisposed || !file.isValid) {
return@compute null
}
LOG.assertTrue(provider.accept(project, file), "Provider $provider doesn't accept file $file")
if (provider is AsyncFileEditorProvider) provider.createEditorAsync(project, file) else null
}
}
catch (e: ProcessCanceledException) {
throw e
}
catch (e: Exception) {
LOG.error(e)
}
catch (e: AssertionError) {
LOG.error(e)
}
}
}
else {
newProviders = null
builders = null
}
ApplicationManager.getApplication().invokeAndWait {
if (project.isDisposed || !file.isValid) {
return@invokeAndWait
}
runBulkTabChange(window.owner) {
compositeRef.set(openFileImpl4Edt(window = window,
file = file,
entry = entry,
options = options,
newProviders = newProviders,
builders = builders?.asList() ?: emptyList()))
}
}
return compositeRef.get()
}
private fun openFileImpl4Edt(window: EditorWindow,
file: VirtualFile,
entry: HistoryEntry?,
options: FileEditorOpenOptions,
newProviders: List<FileEditorProvider>?,
builders: List<AsyncFileEditorProvider.Builder?>): FileEditorComposite {
@Suppress("NAME_SHADOWING")
var options = options
(TransactionGuard.getInstance() as TransactionGuardImpl).assertWriteActionAllowed()
LOG.assertTrue(file.isValid, "Invalid file: $file")
if (options.requestFocus) {
val activeProject = getActiveProject()
if (activeProject != null && activeProject != project) {
// allow focus switching only within a project
options = options.clone().withRequestFocus(false)
}
}
if (entry != null && entry.isPreview) {
options = options.clone().withUsePreviewTab()
}
return doOpenInEdtImpl(window = window, file = file, entry = entry, options = options, newProviders = newProviders, builders = builders)
}
private fun doOpenInEdtImpl(window: EditorWindow,
file: VirtualFile,
entry: HistoryEntry?,
options: FileEditorOpenOptions,
newProviders: List<FileEditorProvider>?,
builders: List<AsyncFileEditorProvider.Builder?>): FileEditorComposite {
var composite = window.getComposite(file)
val newEditor = composite == null
if (newEditor) {
LOG.assertTrue(newProviders != null)
composite = createComposite(file, newProviders!!, builders) ?: return EMPTY
project.messageBus.syncPublisher(FileEditorManagerListener.Before.FILE_EDITOR_MANAGER).beforeFileOpened(this, file)
openedComposites.add(composite)
}
val editorsWithProviders = composite!!.allEditorsWithProviders
window.setComposite(composite, options)
for (editorWithProvider in editorsWithProviders) {
restoreEditorState(file = file,
editorWithProvider = editorWithProvider,
entry = entry,
newEditor = newEditor,
exactState = options.isExactState)
}
// restore selected editor
val provider = if (entry == null) getInstanceImpl().getSelectedFileEditorProvider(composite)
else entry.selectedProvider
if (provider != null) {
composite.setSelectedEditor(provider.editorTypeId)
}
// notify editors about selection changes
val splitters = window.owner
splitters.setCurrentWindow(window, options.requestFocus)
splitters.afterFileOpen(file)
addSelectionRecord(file, window)
val selectedEditor = composite.selectedEditor
selectedEditor.selectNotify()
// transfer focus into editor
if (options.requestFocus && !ApplicationManager.getApplication().isUnitTestMode) {
val focusRunnable = Runnable {
if (splitters.currentWindow != window || window.selectedComposite !== composite) {
// While the editor was loading asynchronously, the user switched to another editor.
// Don't steal focus.
return@Runnable
}
val windowAncestor = SwingUtilities.getWindowAncestor(window.panel)
if (windowAncestor != null && windowAncestor == KeyboardFocusManager.getCurrentKeyboardFocusManager().focusedWindow) {
composite.preferredFocusedComponent?.requestFocus()
}
}
if (selectedEditor is TextEditor) {
runWhenLoaded(selectedEditor.editor, focusRunnable)
}
else {
focusRunnable.run()
}
IdeFocusManager.getInstance(project).toFront(splitters)
}
if (newEditor) {
openFileSetModificationCount.incrementAndGet()
}
//[jeka] this is a hack to support back-forward navigation
// previously here was incorrect call to fireSelectionChanged() with a side-effect
val ideDocumentHistory = IdeDocumentHistory.getInstance(project)
(ideDocumentHistory as IdeDocumentHistoryImpl).onSelectionChanged()
// update frame and tab title
updateFileName(file)
// make back/forward work
ideDocumentHistory.includeCurrentCommandAsNavigation()
if (options.pin != null) {
window.setFilePinned(file, options.pin!!)
}
if (newEditor) {
val messageBus = project.messageBus
messageBus.syncPublisher(FileOpenedSyncListener.TOPIC).fileOpenedSync(this, file, editorsWithProviders)
@Suppress("DEPRECATION")
messageBus.syncPublisher(FileEditorManagerListener.FILE_EDITOR_MANAGER).fileOpenedSync(this, file, editorsWithProviders)
notifyPublisher {
if (isFileOpen(file)) {
project.messageBus.syncPublisher(FileEditorManagerListener.FILE_EDITOR_MANAGER).fileOpened(this, file)
}
}
}
return composite
}
protected open fun createComposite(file: VirtualFile,
providers: List<FileEditorProvider>,
builders: List<AsyncFileEditorProvider.Builder?>): EditorComposite? {
val editorsWithProviders = ArrayList<FileEditorWithProvider>(providers.size)
for (i in providers.indices) {
try {
val provider = providers[i]
val builder = if (builders.isEmpty()) null else builders[i]
val editor = if (builder == null) provider.createEditor(project, file) else builder.build()
if (!editor.isValid) {
val pluginDescriptor = PluginManager.getPluginByClass(provider.javaClass)
LOG.error(PluginException("Invalid editor created by provider ${provider.javaClass.name}", pluginDescriptor?.pluginId))
continue
}
editorsWithProviders.add(FileEditorWithProvider(editor, provider))
}
catch (e: ProcessCanceledException) {
throw e
}
catch (e: Exception) {
LOG.error(e)
}
catch (e: AssertionError) {
LOG.error(e)
}
}
return createComposite(file, editorsWithProviders)
}
protected fun createComposite(file: VirtualFile,
editorsWithProviders: List<FileEditorWithProvider>): EditorComposite? {
for (editorWithProvider in editorsWithProviders) {
val editor = editorWithProvider.fileEditor
editor.addPropertyChangeListener(editorPropertyChangeListener)
editor.putUserData(DUMB_AWARE, DumbService.isDumbAware(editorWithProvider.provider))
}
return createCompositeInstance(file, editorsWithProviders)
}
@Contract("_, _ -> new")
protected fun createCompositeInstance(file: VirtualFile,
editorsWithProviders: List<FileEditorWithProvider>): EditorComposite? {
if (!isCurrentlyUnderLocalId) {
return clientFileEditorManager?.createComposite(file, editorsWithProviders)
}
// the only place this class in created, won't be needed when we get rid of EditorWithProviderComposite usages
@Suppress("DEPRECATION")
return EditorWithProviderComposite(file, editorsWithProviders, this)
}
private fun restoreEditorState(file: VirtualFile,
editorWithProvider: FileEditorWithProvider,
entry: HistoryEntry?,
newEditor: Boolean,
exactState: Boolean) {
var state: FileEditorState? = null
val provider = editorWithProvider.provider
if (entry != null) {
state = entry.getState(provider)
}
if (state == null && newEditor) {
// We have to try to get state from the history only in case
// if editor is not opened. Otherwise, history entry might have a state
// out of sync with the current editor state.
state = EditorHistoryManager.getInstance(project).getState(file, provider)
}
if (state != null) {
val editor = editorWithProvider.fileEditor
if (isDumbAware(editor)) {
editor.setState(state, exactState)
}
else {
DumbService.getInstance(project).runWhenSmart { editor.setState(state, exactState) }
}
}
}
override fun notifyPublisher(runnable: Runnable) {
val done = CompletableFuture<Any>()
busyObject.execute {
IdeFocusManager.getInstance(project).doWhenFocusSettlesDown(ExpirableRunnable.forProject(project) {
runnable.run()
done.complete(null)
}, ModalityState.current())
done
}
}
override fun setSelectedEditor(file: VirtualFile, fileEditorProviderId: String) {
if (!isCurrentlyUnderLocalId) {
clientFileEditorManager?.setSelectedEditor(file, fileEditorProviderId)
return
}
val composite = getComposite(file) ?: return
composite.setSelectedEditor(fileEditorProviderId)
// todo move to setSelectedEditor()?
composite.selectedEditor.selectNotify()
}
fun newEditorComposite(file: VirtualFile): EditorComposite? {
if (!canOpenFile(file)) {
return null
}
val providers = FileEditorProviderManager.getInstance().getProviderList(project, file)
val newComposite = createComposite(file = file, providers = providers, builders = emptyList()) ?: return null
val editorHistoryManager = EditorHistoryManager.getInstance(project)
for (editorWithProvider in newComposite.allEditorsWithProviders) {
val editor = editorWithProvider.fileEditor
val provider = editorWithProvider.provider
// restore myEditor state
val state = editorHistoryManager.getState(file, provider)
if (state != null) {
editor.setState(state)
}
}
return newComposite
}
override fun openFileEditor(descriptor: FileEditorNavigatable, focusEditor: Boolean): List<FileEditor> {
return openEditorImpl(descriptor = descriptor, focusEditor = focusEditor).first
}
/**
* @return the list of opened editors, and the one of them that was selected (if any)
*/
@RequiresEdt
private fun openEditorImpl(descriptor: FileEditorNavigatable, focusEditor: Boolean): Pair<List<FileEditor>, FileEditor> {
val realDescriptor: FileEditorNavigatable
if (descriptor is OpenFileDescriptor && descriptor.getFile() is VirtualFileWindow) {
val delegate = descriptor.getFile() as VirtualFileWindow
val hostOffset = delegate.documentWindow.injectedToHost(descriptor.offset)
val fixedDescriptor = OpenFileDescriptor(descriptor.project, delegate.delegate, hostOffset)
fixedDescriptor.isUseCurrentWindow = descriptor.isUseCurrentWindow()
fixedDescriptor.isUsePreviewTab = descriptor.isUsePreviewTab()
realDescriptor = fixedDescriptor
}
else {
realDescriptor = descriptor
}
val result = SmartList<FileEditor>()
var selectedEditor: FileEditor? = null
CommandProcessor.getInstance().executeCommand(project, {
val file = realDescriptor.file
val openOptions = FileEditorOpenOptions()
.withReuseOpen(!realDescriptor.isUseCurrentWindow)
.withUsePreviewTab(realDescriptor.isUsePreviewTab)
.withRequestFocus(focusEditor)
val editors = openFileWithProviders(file = file, suggestedWindow = null, options = openOptions).allEditors
result.addAll(editors)
var navigated = false
for (editor in editors) {
if (editor is NavigatableFileEditor && getSelectedEditor(realDescriptor.file) === editor) { // try to navigate opened editor
navigated = navigateAndSelectEditor(editor, realDescriptor)
if (navigated) {
selectedEditor = editor
break
}
}
}
if (!navigated) {
for (editor in editors) {
if (editor is NavigatableFileEditor && getSelectedEditor(realDescriptor.file) !== editor) { // try other editors
if (navigateAndSelectEditor(editor, realDescriptor)) {
selectedEditor = editor
break
}
}
}
}
}, "", null)
return Pair(result, selectedEditor)
}
private fun navigateAndSelectEditor(editor: NavigatableFileEditor, descriptor: Navigatable): Boolean {
if (editor.canNavigateTo(descriptor)) {
setSelectedEditor(editor)
editor.navigateTo(descriptor)
return true
}
return false
}
private fun setSelectedEditor(editor: FileEditor) {
(getComposite(editor) ?: return).setSelectedEditor(editor)
}
override fun getProject(): Project = project
override fun openTextEditor(descriptor: OpenFileDescriptor, focusEditor: Boolean): Editor? {
val editorsWithSelected = openEditorImpl(descriptor = descriptor, focusEditor = focusEditor)
val fileEditors = editorsWithSelected.first
val selectedEditor = editorsWithSelected.second
if (fileEditors.isEmpty()) {
return null
}
else if (fileEditors.size == 1) {
return (fileEditors.first() as? TextEditor)?.editor
}
val textEditors = fileEditors.mapNotNull { it as? TextEditor }
if (textEditors.isEmpty()) {
return null
}
var target = if (selectedEditor is TextEditor) selectedEditor else textEditors[0]
if (textEditors.size > 1) {
val editorsWithProviders = getComposite(target)!!.allEditorsWithProviders
val textProviderId = TextEditorProvider.getInstance().editorTypeId
for (editorWithProvider in editorsWithProviders) {
val editor = editorWithProvider.fileEditor
if (editor is TextEditor && editorWithProvider.provider.editorTypeId == textProviderId) {
target = editor
break
}
}
}
setSelectedEditor(target)
return target.editor
}
override fun getSelectedEditorWithRemotes(): Array<FileEditor> {
val result = ArrayList<FileEditor>()
result.addAll(selectedEditors)
for (m in allClientFileEditorManagers) {
result.addAll(m.getSelectedEditors())
}
return result.toTypedArray()
}
override fun getSelectedTextEditorWithRemotes(): Array<Editor> {
val result = ArrayList<Editor>()
for (e in selectedEditorWithRemotes) {
if (e is TextEditor) {
result.add(e.editor)
}
}
return result.toTypedArray()
}
override fun getSelectedTextEditor(): Editor? = getSelectedTextEditor(false)
fun getSelectedTextEditor(isLockFree: Boolean): Editor? {
if (!isCurrentlyUnderLocalId) {
val selectedEditor = (clientFileEditorManager ?: return null).getSelectedEditor()
return if (selectedEditor is TextEditor) selectedEditor.editor else null
}
val editor = IntentionPreviewUtils.getPreviewEditor()
if (editor != null) {
return editor
}
if (!isLockFree) {
assertDispatchThread()
}
val currentWindow = if (isLockFree) mainSplitters.currentWindow else splitters.currentWindow
if (currentWindow != null) {
val selectedEditor = currentWindow.selectedComposite
if (selectedEditor != null && selectedEditor.selectedEditor is TextEditor) {
return (selectedEditor.selectedEditor as TextEditor).editor
}
}
return null
}
override fun isFileOpen(file: VirtualFile): Boolean {
if (!isCurrentlyUnderLocalId) {
return (clientFileEditorManager ?: return false).isFileOpen(file)
}
return openedComposites.any { it.file == file }
}
override fun getOpenFiles(): Array<VirtualFile> = VfsUtilCore.toVirtualFileArray(openedFiles)
val openedFiles: List<VirtualFile>
get() {
if (!isCurrentlyUnderLocalId) {
return clientFileEditorManager?.getAllFiles() ?: emptyList()
}
val files = ArrayList<VirtualFile>()
for (composite in openedComposites) {
val file = composite.file
if (!files.contains(file)) {
files.add(file)
}
}
return files
}
override fun getOpenFilesWithRemotes(): List<VirtualFile> {
val result = openedFiles.toMutableList()
for (m in allClientFileEditorManagers) {
result.addAll(m.getAllFiles())
}
return result
}
override fun hasOpenFiles(): Boolean = !openedComposites.isEmpty()
override fun getSelectedFiles(): Array<VirtualFile> {
if (!isCurrentlyUnderLocalId) {
return (clientFileEditorManager ?: return VirtualFile.EMPTY_ARRAY).getSelectedFiles().toTypedArray()
}
val selectedFiles = LinkedHashSet<VirtualFile>()
val activeSplitters = splitters
selectedFiles.addAll(activeSplitters.selectedFiles)
for (each in getAllSplitters()) {
if (each !== activeSplitters) {
selectedFiles.addAll(each.selectedFiles)
}
}
return VfsUtilCore.toVirtualFileArray(selectedFiles)
}
override fun getSelectedEditors(): Array<FileEditor> {
if (!isCurrentlyUnderLocalId) {
return clientFileEditorManager?.getSelectedEditors()?.toTypedArray() ?: FileEditor.EMPTY_ARRAY
}
val selectedEditors = SmartHashSet<FileEditor>()
for (splitters in getAllSplitters()) {
splitters.addSelectedEditorsTo(selectedEditors)
}
return selectedEditors.toTypedArray()
}
override fun getSplitters(): EditorsSplitters {
return if (ApplicationManager.getApplication().isDispatchThread) activeSplittersSync else mainSplitters
}
override fun getSelectedEditor(): FileEditor? {
if (!isCurrentlyUnderLocalId) {
return clientFileEditorManager?.getSelectedEditor()
}
val window = splitters.currentWindow
if (window != null) {
val selected = window.selectedComposite
if (selected != null) {
return selected.selectedEditor
}
}
return super.getSelectedEditor()
}
override fun getSelectedEditor(file: VirtualFile): FileEditor? {
return getSelectedEditorWithProvider(file)?.fileEditor
}
@RequiresEdt
override fun getSelectedEditorWithProvider(file: VirtualFile): FileEditorWithProvider? {
val composite = getComposite(file)
return composite?.selectedWithProvider
}
@RequiresEdt
override fun getEditorsWithProviders(file: VirtualFile): Pair<Array<FileEditor>, Array<FileEditorProvider>> {
return retrofit(getComposite(file))
}
@RequiresEdt
override fun getEditors(file: VirtualFile): Array<FileEditor> = getComposite(file)?.allEditors?.toTypedArray() ?: FileEditor.EMPTY_ARRAY
override fun getAllEditors(file: VirtualFile): Array<FileEditor> {
val result = ArrayList<FileEditor>()
// reuse getAllComposites(file)? Are there cases some composites are not accessible via splitters?
for (composite in openedComposites) {
if (composite.file == file) {
result.addAll(composite.allEditors)
}
}
for (clientManager in allClientFileEditorManagers) {
result.addAll(clientManager.getEditors(file))
}
return result.toTypedArray()
}
@RequiresEdt
override fun getComposite(file: VirtualFile): EditorComposite? {
if (!isCurrentlyUnderLocalId) {
return clientFileEditorManager?.getComposite(file)
}
val editorWindow = splitters.currentWindow
if (editorWindow != null) {
val composite = editorWindow.getComposite(file)
if (composite != null) {
return composite
}
}
val originalFile = getOriginalFile(file)
return getAllSplitters()
.asSequence()
.map { each -> each.getAllComposites(originalFile).firstOrNull { it.file == originalFile } }
.firstOrNull { it != null }
}
fun getAllComposites(file: VirtualFile): List<EditorComposite> {
if (!isCurrentlyUnderLocalId) {
return clientFileEditorManager?.getAllComposites(file) ?: ArrayList()
}
val result = ArrayList<EditorComposite>()
for (each in getAllSplitters()) {
result.addAll(each.getAllComposites(file))
}
return result
}
override fun getAllEditors(): Array<FileEditor> {
val result = ArrayList<FileEditor>()
for (composite in openedComposites) {
result.addAll(composite.allEditors)
}
for (clientManager in allClientFileEditorManagers) {
result.addAll(clientManager.getAllEditors())
}
return result.toTypedArray()
}
@RequiresEdt
fun getTopComponents(editor: FileEditor): List<JComponent> {
return getComposite(editor)?.getTopComponents(editor) ?: emptyList()
}
@RequiresEdt
override fun addTopComponent(editor: FileEditor, component: JComponent) {
getComposite(editor)?.addTopComponent(editor, component)
}
@RequiresEdt
override fun removeTopComponent(editor: FileEditor, component: JComponent) {
getComposite(editor)?.removeTopComponent(editor, component)
}
@RequiresEdt
override fun addBottomComponent(editor: FileEditor, component: JComponent) {
getComposite(editor)?.addBottomComponent(editor, component)
}
@RequiresEdt
override fun removeBottomComponent(editor: FileEditor, component: JComponent) {
getComposite(editor)?.removeBottomComponent(editor, component)
}
override fun addFileEditorManagerListener(listener: FileEditorManagerListener) {
listenerList.add(listener)
}
override fun removeFileEditorManagerListener(listener: FileEditorManagerListener) {
listenerList.remove(listener)
}
@ApiStatus.Internal
@RequiresEdt
fun init(): EditorsSplitters {
FileStatusManager.getInstance(project)?.addFileStatusListener(MyFileStatusListener(), project)
val connection = project.messageBus.connect(this)
connection.subscribe(FileTypeManager.TOPIC, MyFileTypeListener())
if (!LightEdit.owns(project)) {
connection.subscribe(ProjectTopics.PROJECT_ROOTS, MyRootsListener())
connection.subscribe(AdditionalLibraryRootsListener.TOPIC, MyRootsListener())
}
// updates tabs names
connection.subscribe(VirtualFileManager.VFS_CHANGES, MyVirtualFileListener())
// extends/cuts number of opened tabs. Also updates location of tabs
connection.subscribe(UISettingsListener.TOPIC, MyUISettingsListener())
return mainSplitters
}
override fun getState(): Element? {
val state = Element("state")
mainSplitters.writeExternal(state)
return state
}
override fun loadState(state: Element) {
mainSplitters.readExternal(state)
}
open fun getComposite(editor: FileEditor): EditorComposite? {
for (splitters in getAllSplitters()) {
val editorsComposites = splitters.getAllComposites()
for (i in editorsComposites.indices.reversed()) {
val composite = editorsComposites[i]
if (composite.allEditors.contains(editor)) {
return composite
}
}
}
for (clientManager in allClientFileEditorManagers) {
val composite = clientManager.getComposite(editor)
if (composite != null) {
return composite
}
}
return null
}
@ApiStatus.Internal
fun fireSelectionChanged(newSelectedComposite: EditorComposite?) {
val composite = SoftReference.dereference(lastSelectedComposite)
val oldEditorWithProvider = composite?.selectedWithProvider
val newEditorWithProvider = newSelectedComposite?.selectedWithProvider
lastSelectedComposite = if (newSelectedComposite == null) null else WeakReference(newSelectedComposite)
if (oldEditorWithProvider == newEditorWithProvider) {
return
}
val event = FileEditorManagerEvent(this, oldEditorWithProvider, newEditorWithProvider)
val publisher = project.messageBus.syncPublisher(FileEditorManagerListener.FILE_EDITOR_MANAGER)
if (newEditorWithProvider != null) {
val component = newEditorWithProvider.fileEditor.component
val holder = ComponentUtil.getParentOfType(EditorWindowHolder::class.java as Class<out EditorWindowHolder?>, component as Component)
val file = newEditorWithProvider.fileEditor.file
if (holder != null && file != null) {
addSelectionRecord(file, holder.editorWindow)
}
}
notifyPublisher { publisher.selectionChanged(event) }
}
override fun isChanged(editor: EditorComposite): Boolean {
val fileStatusManager = FileStatusManager.getInstance(project) ?: return false
val status = fileStatusManager.getStatus(editor.file)
return status !== FileStatus.UNKNOWN && status !== FileStatus.NOT_CHANGED
}
internal fun disposeComposite(composite: EditorComposite) {
if (!isCurrentlyUnderLocalId) {
clientFileEditorManager?.removeComposite(composite)
return
}
openedComposites.remove(composite)
if (allEditors.isEmpty()) {
@Suppress("UsePropertyAccessSyntax")
setCurrentWindow(null)
}
if (composite == lastSelected) {
composite.selectedEditor.deselectNotify()
splitters.setCurrentWindow(null, false)
}
val editorsWithProviders = composite.allEditorsWithProviders
val selectedEditor = composite.selectedEditor
for (editorWithProvider in editorsWithProviders.asReversed()) {
val editor = editorWithProvider.fileEditor
val provider = editorWithProvider.provider
// we already notified the myEditor (when fire event)
if (selectedEditor == editor) {
editor.deselectNotify()
}
editor.removePropertyChangeListener(editorPropertyChangeListener)
provider.disposeEditor(editor)
}
Disposer.dispose(composite)
}
private val lastSelected: EditorComposite?
get() = activeSplittersSync.currentWindow?.selectedComposite
/**
* Closes deleted files. Closes file which are in the deleted directories.
*/
private inner class MyVirtualFileListener : BulkFileListener {
override fun before(events: List<VFileEvent>) {
for (event in events) {
if (event is VFileDeleteEvent) {
beforeFileDeletion(event)
}
}
}
override fun after(events: List<VFileEvent>) {
for (event in events) {
if (event is VFilePropertyChangeEvent) {
propertyChanged(event)
}
else if (event is VFileMoveEvent) {
fileMoved(event)
}
}
}
@RequiresEdt
private fun beforeFileDeletion(event: VFileDeleteEvent) {
val file = event.file
for (openedFile in openFilesWithRemotes.asReversed()) {
if (VfsUtilCore.isAncestor(file, openedFile, false)) {
closeFile(file = openedFile, moveFocus = true, closeAllCopies = true)
}
}
}
private fun propertyChanged(event: VFilePropertyChangeEvent) {
if (VirtualFile.PROP_NAME == event.propertyName) {
assertDispatchThread()
val file = event.file
if (isFileOpen(file)) {
updateFileName(file)
updateFileIcon(file) // file type can change after renaming
updateFileBackgroundColor(file)
}
}
else if (VirtualFile.PROP_WRITABLE == event.propertyName || VirtualFile.PROP_ENCODING == event.propertyName) {
updateIcon(event)
}
}
@RequiresEdt
private fun updateIcon(event: VFilePropertyChangeEvent) {
val file = event.file
if (isFileOpen(file)) {
updateFileIcon(file)
}
}
private fun fileMoved(e: VFileMoveEvent) {
val file = e.file
for (openFile in openedFiles) {
if (VfsUtilCore.isAncestor(file, openFile, false)) {
updateFileName(openFile)
updateFileBackgroundColor(openFile)
}
}
}
}
override fun isInsideChange(): Boolean = splitters.isInsideChange
private inner class MyEditorPropertyChangeListener : PropertyChangeListener {
@RequiresEdt
override fun propertyChange(e: PropertyChangeEvent) {
val propertyName = e.propertyName
if (FileEditor.PROP_MODIFIED == propertyName) {
val editor = e.source as FileEditor
val composite = getComposite(editor)
if (composite != null) {
updateFileIcon(composite.file)
}
}
else if (FileEditor.PROP_VALID == propertyName) {
val valid = e.newValue as Boolean
if (!valid) {
val composite = getComposite(e.source as FileEditor)
if (composite != null) {
closeFile(composite.file)
}
}
}
}
}
/**
* Gets events from VCS and updates color of myEditor tabs
*/
private inner class MyFileStatusListener : FileStatusListener {
// update color of all open files
@RequiresEdt
override fun fileStatusesChanged() {
LOG.debug("FileEditorManagerImpl.MyFileStatusListener.fileStatusesChanged()")
for (file in openedFiles.asReversed()) {
ApplicationManager.getApplication().invokeLater({
if (LOG.isDebugEnabled) {
LOG.debug("updating file status in tab for " + file.path)
}
updateFileStatus(file)
}, ModalityState.NON_MODAL, project.disposed)
}
}
// update color of the file (if necessary)
override fun fileStatusChanged(file: VirtualFile) {
assertDispatchThread()
if (isFileOpen(file)) {
updateFileStatus(file)
}
}
private fun updateFileStatus(file: VirtualFile) {
updateFileColor(file)
updateFileIcon(file)
}
}
/**
* Gets events from FileTypeManager and updates icons on tabs
*/
private inner class MyFileTypeListener : FileTypeListener {
@RequiresEdt
override fun fileTypesChanged(event: FileTypeEvent) {
for (file in openedFiles.asReversed()) {
updateFileIcon(file = file, immediately = true)
}
}
}
private inner class MyRootsListener : ModuleRootListener, AdditionalLibraryRootsListener {
override fun rootsChanged(event: ModuleRootEvent) {
changeHappened()
}
private fun changeHappened() {
AppUIExecutor
.onUiThread(ModalityState.any())
.expireWith(project)
.submit(Callable { windows.flatMap(EditorWindow::allComposites) })
.onSuccess(Consumer { allEditors ->
ReadAction
.nonBlocking(Callable { calcEditorReplacements(allEditors) })
.inSmartMode(project)
.finishOnUiThread(ModalityState.defaultModalityState(), Consumer(::replaceEditors))
.coalesceBy(this)
.submit(AppExecutorUtil.getAppExecutorService())
})
}
private fun calcEditorReplacements(composites: List<EditorComposite>): Map<EditorComposite, Pair<VirtualFile, Int>> {
val swappers = EditorFileSwapper.EP_NAME.extensionList
return composites.asSequence().mapNotNull { composite ->
if (composite.file.isValid) {
for (each in swappers) {
val fileAndOffset = each.getFileToSwapTo(project, composite)
if (fileAndOffset != null) {
return@mapNotNull composite to fileAndOffset
}
}
}
null
}.associate { it }
}
private fun replaceEditors(replacements: Map<EditorComposite, Pair<VirtualFile, Int>>) {
if (replacements.isEmpty()) {
return
}
for (eachWindow in windows) {
val selected = eachWindow.selectedComposite
val composites = eachWindow.allComposites
for (i in composites.indices) {
val composite = composites[i]
val file = composite.file
if (!file.isValid) {
continue
}
val newFilePair = replacements.get(composite) ?: continue
val newFile = newFilePair.first ?: continue
// already open
if (eachWindow.findFileIndex(newFile) != -1) continue
val openResult = openFileImpl2(window = eachWindow,
file = newFile,
options = FileEditorOpenOptions(index = i, requestFocus = composite === selected))
if (newFilePair.second != null) {
val openedEditor = EditorFileSwapper.findSinglePsiAwareEditor(openResult.allEditors)
if (openedEditor != null) {
openedEditor.editor.caretModel.moveToOffset(newFilePair.second!!)
openedEditor.editor.scrollingModel.scrollToCaret(ScrollType.CENTER)
}
}
closeFile(file, eachWindow)
}
}
}
override fun libraryRootsChanged(presentableLibraryName: @Nls String?,
oldRoots: Collection<VirtualFile>,
newRoots: Collection<VirtualFile>,
libraryNameForDebug: String) {
changeHappened()
}
}
/**
* Gets notifications from UISetting component to track changes of RECENT_FILES_LIMIT
* and EDITOR_TAB_LIMIT, etc. values.
*/
private inner class MyUISettingsListener : UISettingsListener {
@RequiresEdt
override fun uiSettingsChanged(uiSettings: UISettings) {
mainSplitters.revalidate()
for (each in getAllSplitters()) {
each.setTabsPlacement(uiSettings.editorTabPlacement)
each.trimToSize()
// Tab layout policy
if (uiSettings.scrollTabLayoutInEditor) {
each.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT)
}
else {
each.setTabLayoutPolicy(JTabbedPane.WRAP_TAB_LAYOUT)
}
}
// "Mark modified files with asterisk"
for (file in openedFiles.asReversed()) {
updateFileIcon(file)
updateFileName(file)
updateFileBackgroundColor(file)
}
// "Show full paths in window header"
updateFrameTitle()
}
}
@RequiresEdt
override fun closeAllFiles() {
CommandProcessor.getInstance().executeCommand(project, {
openFileSetModificationCount.incrementAndGet()
val splitters = splitters
runBulkTabChange(splitters, splitters::closeAllFiles)
}, "", null)
}
override fun getSiblings(file: VirtualFile): Collection<VirtualFile> = openedFiles
fun queueUpdateFile(file: VirtualFile) {
queue.queue(object : Update(file) {
override fun run() {
if (isFileOpen(file)) {
updateFileIcon(file)
updateFileColor(file)
updateFileBackgroundColor(file)
resetPreviewFlag(file)
}
}
})
}
override fun getSplittersFor(component: Component): EditorsSplitters {
val dockContainer = DockManager.getInstance(project).getContainerFor(component) { it is DockableEditorTabbedContainer }
return if (dockContainer is DockableEditorTabbedContainer) dockContainer.splitters else mainSplitters
}
fun getSelectionHistory(): List<Pair<VirtualFile, EditorWindow>> {
val copy = ArrayList<Pair<VirtualFile, EditorWindow>>()
for (pair in selectionHistory) {
if (pair.second!!.files.isEmpty()) {
val windows = pair.second!!.owner.getWindows()
if (windows.isNotEmpty() && windows[0].files.isNotEmpty()) {
val p = Pair(pair.first, windows[0])
if (!copy.contains(p)) {
copy.add(p)
}
}
}
else if (!copy.contains(pair)) {
copy.add(pair)
}
}
selectionHistory.clear()
selectionHistory.addAll(copy)
return selectionHistory
}
fun addSelectionRecord(file: VirtualFile, window: EditorWindow) {
val record = Pair(file, window)
selectionHistory.remove(record)
selectionHistory.add(0, record)
}
fun removeSelectionRecord(file: VirtualFile, window: EditorWindow) {
selectionHistory.remove(Pair(file, window))
updateFileName(file)
}
override fun getReady(requestor: Any): ActionCallback = busyObject.getReady(requestor)
override fun refreshIcons() {
val openedFiles = openedFiles
for (each in getAllSplitters()) {
for (file in openedFiles) {
each.updateFileIcon(file)
}
}
}
internal suspend fun openFileOnStartup(window: EditorWindow,
virtualFile: VirtualFile,
entry: HistoryEntry?,
options: FileEditorOpenOptions) {
assert(options.isReopeningOnStartup)
if (!ClientId.isCurrentlyUnderLocalId) {
(clientFileEditorManager ?: return).openFile(file = virtualFile, forceCreate = false)
return
}
val file = getOriginalFile(virtualFile)
val newProviders = FileEditorProviderManager.getInstance().getProvidersAsync(project, file)
if (!canOpenFile(file, newProviders)) {
return
}
// file is not opened yet - in this case we have to create editors and select the created EditorComposite.
val builders = ArrayList<AsyncFileEditorProvider.Builder?>(newProviders.size)
for (provider in newProviders) {
val builder = try {
readAction {
if (!file.isValid) {
return@readAction null
}
LOG.assertTrue(provider.accept(project, file), "Provider $provider doesn't accept file $file")
if (provider is AsyncFileEditorProvider) provider.createEditorAsync(project, file) else null
}
}
catch (e: ProcessCanceledException) {
throw e
}
catch (e: CancellationException) {
throw e
}
catch (e: Exception) {
LOG.error(e)
null
}
catch (e: AssertionError) {
LOG.error(e)
null
}
builders.add(builder)
}
withContext(Dispatchers.EDT) {
if (!file.isValid) {
return@withContext
}
val splitters = window.owner
splitters.insideChange++
try {
doOpenInEdtImpl(window = window, file = file, entry = entry, options = options, newProviders = newProviders, builders = builders)
}
finally {
splitters.insideChange--
}
}
}
}
private class SimpleBusyObject : BusyObject.Impl() {
private val busyCount = LongAdder()
override fun isReady(): Boolean = busyCount.sum() == 0L
fun execute(runnable: Supplier<CompletableFuture<*>>) {
busyCount.increment()
runnable.get().whenComplete { _, _ ->
busyCount.decrement()
if (isReady) {
onReady()
}
}
}
} | apache-2.0 | 69ecc1d2ccb154554da95bfe84d73613 | 36.557329 | 159 | 0.680484 | 4.93202 | false | false | false | false |
GunoH/intellij-community | platform/code-style-impl/src/com/intellij/formatting/LineCommentAddSpacePostFormatProcessor.kt | 2 | 3513 | // 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.formatting
import com.intellij.lang.Commenter
import com.intellij.lang.LanguageCommenters
import com.intellij.openapi.util.TextRange
import com.intellij.psi.*
import com.intellij.psi.codeStyle.CodeStyleSettings
import com.intellij.psi.codeStyle.LanguageCodeStyleProvider
import com.intellij.psi.impl.source.codeStyle.PostFormatProcessor
class LineCommentAddSpacePostFormatProcessor : PostFormatProcessor {
override fun processElement(source: PsiElement, settings: CodeStyleSettings) = source
.also { processText(it.containingFile, it.textRange, settings) }
override fun processText(source: PsiFile, rangeToReformat: TextRange, settings: CodeStyleSettings): TextRange {
val language = source.language
if (!settings.getCommonSettings(language).LINE_COMMENT_ADD_SPACE_ON_REFORMAT) {
return rangeToReformat // Option is disabled
}
val commenter = LanguageCommenters.INSTANCE.forLanguage(language) ?: return rangeToReformat
val languageCodeStyleSettingsProvider = LanguageCodeStyleProvider.findUsingBaseLanguage(language) ?: return rangeToReformat
val commentFinder = SingleLineCommentFinder(rangeToReformat, languageCodeStyleSettingsProvider, commenter)
source.accept(commentFinder)
val commentOffsets = commentFinder.commentOffsets
.filter { rangeToReformat.contains(it) }
.sorted()
.takeIf { it.isNotEmpty() }
?: return rangeToReformat // Nothing useful found
val documentManager = PsiDocumentManager.getInstance(source.project)
val document = documentManager.getDocument(source) ?: return rangeToReformat // Failed to get document
// Going backwards to protect earlier offsets from modifications in latter ones
commentOffsets.asReversed().forEach { document.insertString(it, " ") }
documentManager.commitDocument(document)
return rangeToReformat.grown(commentOffsets.size)
}
}
internal class SingleLineCommentFinder(val rangeToReformat: TextRange,
private val languageCodeStyleSettingsProvider: LanguageCodeStyleProvider,
commenter: Commenter) : PsiRecursiveElementVisitor() {
private val lineCommentPrefixes = commenter.lineCommentPrefixes.map { it.trim() }
val commentOffsets = arrayListOf<Int>()
override fun visitElement(element: PsiElement) {
if (element.textRange.intersects(rangeToReformat)) {
super.visitElement(element)
}
}
override fun visitComment(comment: PsiComment) {
val commentText = comment.text
val commentPrefixLength = lineCommentPrefixes
.find { commentText.startsWith(it) } // Find the line comment prefix
?.length // Not found -> not a line comment
?.takeUnless { commentText.length == it } // Empty comment, no need to add a trailing space
?: return
val commentContents = commentText.substring(commentPrefixLength)
if (!languageCodeStyleSettingsProvider.canInsertSpaceInLineComment(commentContents)) {
return
}
commentOffsets.add(comment.textRange.startOffset + commentPrefixLength)
}
}
| apache-2.0 | 422764d0b1576f04adbd8ed1e2bf60a6 | 42.37037 | 158 | 0.702818 | 5.290663 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/search/ideaExtensions/KotlinAnnotatedElementsSearcher.kt | 1 | 6766 | // 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.search.ideaExtensions
import com.intellij.openapi.diagnostic.Logger
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiModifierListOwner
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.search.LocalSearchScope
import com.intellij.psi.search.SearchScope
import com.intellij.psi.search.searches.AnnotatedElementsSearch
import com.intellij.psi.util.PsiUtilCore
import com.intellij.util.Processor
import com.intellij.util.QueryExecutor
import com.intellij.util.indexing.FileBasedIndex
import org.jetbrains.kotlin.asJava.ImpreciseResolveResult.NO_MATCH
import org.jetbrains.kotlin.asJava.ImpreciseResolveResult.UNSURE
import org.jetbrains.kotlin.asJava.LightClassUtil
import org.jetbrains.kotlin.asJava.toLightClass
import org.jetbrains.kotlin.asJava.toPsiParameters
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.search.PsiBasedClassResolver
import org.jetbrains.kotlin.idea.stubindex.KotlinAnnotationsIndex
import org.jetbrains.kotlin.idea.base.projectStructure.scope.KotlinSourceFilterScope
import com.intellij.openapi.application.runReadAction
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.collectDescendantsOfType
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
class KotlinAnnotatedElementsSearcher : QueryExecutor<PsiModifierListOwner, AnnotatedElementsSearch.Parameters> {
override fun execute(p: AnnotatedElementsSearch.Parameters, consumer: Processor<in PsiModifierListOwner>): Boolean {
return processAnnotatedMembers(p.annotationClass, p.scope) { declaration ->
when (declaration) {
is KtClassOrObject -> {
val lightClass = declaration.toLightClass()
consumer.process(lightClass)
}
is KtNamedFunction, is KtConstructor<*> -> {
val wrappedMethod = LightClassUtil.getLightClassMethod(declaration as KtFunction)
consumer.process(wrappedMethod)
}
is KtProperty -> {
val backingField = LightClassUtil.getLightClassBackingField(declaration)
if (backingField != null) {
return@processAnnotatedMembers consumer.process(backingField)
}
LightClassUtil.getLightClassPropertyMethods(declaration).all { consumer.process(it) }
}
is KtPropertyAccessor -> {
val method = LightClassUtil.getLightClassAccessorMethod(declaration)
return@processAnnotatedMembers consumer.process(method)
}
is KtParameter -> {
if (!declaration.toPsiParameters().all { consumer.process(it) }) return@processAnnotatedMembers false
LightClassUtil.getLightClassBackingField(declaration)?.let {
if (!consumer.process(it)) return@processAnnotatedMembers false
}
LightClassUtil.getLightClassPropertyMethods(declaration).all { consumer.process(it) }
}
else -> true
}
}
}
companion object {
private val LOG = Logger.getInstance("#com.intellij.psi.impl.search.AnnotatedMembersSearcher")
fun processAnnotatedMembers(
annClass: PsiClass,
useScope: SearchScope,
preFilter: (KtAnnotationEntry) -> Boolean = { true },
consumer: (KtDeclaration) -> Boolean
): Boolean {
assert(annClass.isAnnotationType) { "Annotation type should be passed to annotated members search" }
val psiBasedClassResolver = PsiBasedClassResolver.getInstance(annClass)
val annotationFQN = annClass.qualifiedName!!
val candidates = getKotlinAnnotationCandidates(annClass, useScope)
for (elt in candidates) {
if (notKtAnnotationEntry(elt)) continue
val result = runReadAction(fun(): Boolean {
if (elt !is KtAnnotationEntry) return true
if (!preFilter(elt)) return true
val declaration = elt.getStrictParentOfType<KtDeclaration>() ?: return true
val psiBasedResolveResult = elt.calleeExpression?.constructorReferenceExpression?.let { ref ->
psiBasedClassResolver.canBeTargetReference(ref)
}
if (psiBasedResolveResult == NO_MATCH) return true
if (psiBasedResolveResult == UNSURE) {
val context = elt.analyze(BodyResolveMode.PARTIAL)
val annotationDescriptor = context.get(BindingContext.ANNOTATION, elt) ?: return true
val fqName = annotationDescriptor.fqName ?: return true
if (fqName.asString() != annotationFQN) return true
}
if (!consumer(declaration)) return false
return true
})
if (!result) return false
}
return true
}
/* Return all elements annotated with given annotation name. Aliases don't work now. */
private fun getKotlinAnnotationCandidates(annClass: PsiClass, useScope: SearchScope): Collection<PsiElement> {
return runReadAction(fun(): Collection<PsiElement> {
if (useScope is GlobalSearchScope) {
val name = annClass.name ?: return emptyList()
val scope = KotlinSourceFilterScope.everything(useScope, annClass.project)
return KotlinAnnotationsIndex.get(name, annClass.project, scope)
}
return (useScope as LocalSearchScope).scope.flatMap { it.collectDescendantsOfType<KtAnnotationEntry>() }
})
}
private fun notKtAnnotationEntry(found: PsiElement): Boolean {
if (found is KtAnnotationEntry) return false
val faultyContainer = PsiUtilCore.getVirtualFile(found)
LOG.error("Non annotation in annotations list: $faultyContainer; element:$found")
if (faultyContainer != null && faultyContainer.isValid) {
FileBasedIndex.getInstance().requestReindex(faultyContainer)
}
return true
}
}
}
| apache-2.0 | 9d87b415ff4851dd8b26684f6423156c | 46.314685 | 158 | 0.655188 | 5.68094 | false | false | false | false |
AsamK/TextSecure | app/src/main/java/org/thoughtcrime/securesms/components/PlaybackSpeedToggleTextView.kt | 3 | 2826 | package org.thoughtcrime.securesms.components
import android.annotation.SuppressLint
import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.animation.DecelerateInterpolator
import androidx.appcompat.widget.AppCompatTextView
import org.thoughtcrime.securesms.R
class PlaybackSpeedToggleTextView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : AppCompatTextView(context, attrs, defStyleAttr) {
private val speeds: IntArray = context.resources.getIntArray(R.array.PlaybackSpeedToggleTextView__speeds)
private val labels: Array<String> = context.resources.getStringArray(R.array.PlaybackSpeedToggleTextView__speed_labels)
private var currentSpeedIndex = 0
private var requestedSpeed: Float? = null
var playbackSpeedListener: PlaybackSpeedListener? = null
init {
text = getCurrentLabel()
super.setOnClickListener {
currentSpeedIndex = getNextSpeedIndex()
text = getCurrentLabel()
requestedSpeed = getCurrentSpeed()
playbackSpeedListener?.onPlaybackSpeedChanged(getCurrentSpeed())
}
isClickable = false
}
@SuppressLint("ClickableViewAccessibility")
override fun onTouchEvent(event: MotionEvent?): Boolean {
if (isClickable) {
when (event?.action) {
MotionEvent.ACTION_DOWN -> zoomIn()
MotionEvent.ACTION_UP -> zoomOut()
MotionEvent.ACTION_CANCEL -> zoomOut()
}
}
return super.onTouchEvent(event)
}
fun clearRequestedSpeed() {
requestedSpeed = null
}
fun setCurrentSpeed(speed: Float) {
if (speed == getCurrentSpeed() || (requestedSpeed != null && requestedSpeed != speed)) {
if (requestedSpeed == speed) {
requestedSpeed = null
}
return
}
requestedSpeed = null
val outOf100 = (speed * 100).toInt()
val index = speeds.indexOf(outOf100)
if (index != -1) {
currentSpeedIndex = index
text = getCurrentLabel()
} else {
throw IllegalArgumentException("Invalid Speed $speed")
}
}
private fun getNextSpeedIndex(): Int = (currentSpeedIndex + 1) % speeds.size
private fun getCurrentSpeed(): Float = speeds[currentSpeedIndex] / 100f
private fun getCurrentLabel(): String = labels[currentSpeedIndex]
private fun zoomIn() {
animate()
.setInterpolator(DecelerateInterpolator())
.setDuration(150L)
.scaleX(1.2f)
.scaleY(1.2f)
}
private fun zoomOut() {
animate()
.setInterpolator(DecelerateInterpolator())
.setDuration(150L)
.scaleX(1f)
.scaleY(1f)
}
override fun setOnClickListener(l: OnClickListener?) {
throw UnsupportedOperationException()
}
interface PlaybackSpeedListener {
fun onPlaybackSpeedChanged(speed: Float)
}
}
| gpl-3.0 | 70ce19192935ea0118a193fac756743c | 25.914286 | 121 | 0.707006 | 4.610114 | false | false | false | false |
jk1/intellij-community | platform/platform-tests/testSrc/com/intellij/ui/layout/LayoutTestApp.kt | 3 | 3348 | // 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.ui.layout
import com.intellij.ide.ui.laf.IntelliJLaf
import com.intellij.ide.ui.laf.darcula.DarculaLaf
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.util.SystemInfoRt
import com.intellij.testFramework.runInEdtAndWait
import com.intellij.ui.components.dialog
import com.intellij.ui.layout.migLayout.*
import com.intellij.ui.layout.migLayout.patched.*
import com.intellij.util.io.write
import com.intellij.util.ui.UIUtil
import net.miginfocom.layout.AC
import net.miginfocom.layout.LayoutUtil
import java.awt.Dimension
import java.awt.GraphicsEnvironment
import java.awt.Point
import java.nio.file.Paths
import javax.swing.*
import javax.swing.plaf.metal.MetalLookAndFeel
object DarculaUiTestApp {
@JvmStatic
fun main(args: Array<String>) {
run(DarculaLaf())
}
}
object IntelliJUiTestApp {
@JvmStatic
fun main(args: Array<String>) {
run(IntelliJLaf())
}
}
private fun run(laf: LookAndFeel) {
val isDebugEnabled = true
// val isDebugEnabled = false
@Suppress("ConstantConditionIf")
if (isDebugEnabled) {
LayoutUtil.setGlobalDebugMillis(1000)
}
runInEdtAndWait {
UIManager.setLookAndFeel(MetalLookAndFeel())
UIManager.setLookAndFeel(laf)
// UIManager.setLookAndFeel(DarculaLaf())
// val panel = visualPaddingsPanelOnlyButton()
// val panel = visualPaddingsPanelOnlyComboBox()
// val panel = alignFieldsInTheNestedGrid()
// val panel = visualPaddingsPanelOnlyTextField()
// val panel = visualPaddingsPanelOnlyLabeledScrollPane()
// val panel = labelRowShouldNotGrow()
val panel = commentAndPanel()
// val panel = alignFieldsInTheNestedGrid()
// val panel = visualPaddingsPanel()
// val panel = withVerticalButtons()
// val panel = createLafTestPanel()
val dialog = dialog(
title = "",
panel = panel,
resizable = true,
okActionEnabled = false
) {
return@dialog null
}
panel.preferredSize = Dimension(350, 250)
if (panel.layout is MigLayout) {
Paths.get(System.getProperty("user.home"), "layout-dump.yml").write(serializeLayout(panel, isIncludeCellBounds = false))
}
moveToNotRetinaScreen(dialog)
dialog.show()
}
}
@Suppress("unused")
fun simplePanel() {
val panel = JPanel(MigLayout(createLayoutConstraints().insets("3px"), AC(), AC().align("baseline")))
panel.add(JLabel("text"))
val component = JTextField("text")
//val ff = component.getBaseline(40, 21)
panel.add(component)
}
private fun moveToNotRetinaScreen(dialog: DialogWrapper) {
val screenDevices = GraphicsEnvironment.getLocalGraphicsEnvironment().screenDevices
if (!SystemInfoRt.isMac || screenDevices == null || screenDevices.size <= 1) {
return
}
for (screenDevice in screenDevices) {
if (!UIUtil.isRetina(screenDevice)) {
val screenBounds = screenDevice.defaultConfiguration.bounds
dialog.setInitialLocationCallback {
val preferredSize = dialog.preferredSize
Point(screenBounds.x + ((screenBounds.width - preferredSize.width) / 2), (screenBounds.height - preferredSize.height) / 2)
}
break
}
}
} | apache-2.0 | 847e316268281c12e8a2bf1ed8a8e9a8 | 30.299065 | 140 | 0.714456 | 4.148699 | false | false | false | false |
chiclaim/android-sample | android-lib-retrofit/retrofit-sample/app/src/main/java/com/chiclaim/android/retrofit_sample/helper/CoroutineHelper.kt | 1 | 1615 | @file:JvmName("CoroutineHelper.kt")
package com.chiclaim.android.retrofit_sample.helper
import kotlinx.coroutines.*
import kotlin.coroutines.CoroutineContext
fun CoroutineScope.uiJob(timeout: Long = 0L, block: suspend CoroutineScope.() -> Unit) {
startJob(this, Dispatchers.Main, timeout, block)
}
fun startJob(
parentScope: CoroutineScope,
coroutineContext: CoroutineContext,
timeout: Long = 0L,
block: suspend CoroutineScope.() -> Unit
) {
parentScope.launch(coroutineContext) {
supervisorScope {
if (timeout > 0L) {
withTimeout(timeout) {
block()
}
} else {
block()
}
}
}
}
suspend fun <T> startTask(
coroutineContext: CoroutineContext,
timeout: Long = 0L,
block: suspend CoroutineScope.() -> T
): T {
return withContext(coroutineContext) {
return@withContext if (timeout > 0L) {
withTimeout(timeout) {
block()
}
} else {
block()
}
}
}
suspend fun <T> startTaskAsync(
parentScope: CoroutineScope,
coroutineContext: CoroutineContext = Dispatchers.Default,
timeout: Long = 0L,
block: suspend CoroutineScope.() -> T
): Deferred<T> {
return supervisorScope {
parentScope.async(coroutineContext) {
if (timeout > 0L) {
withTimeout(timeout) {
block()
}
} else {
block()
}
}
}
} | apache-2.0 | 733c11991612ba3fcc5f0cec8155fbf9 | 22.764706 | 88 | 0.539319 | 4.879154 | false | false | false | false |
Doctoror/ParticleConstellationsLiveWallpaper | app/src/main/java/com/doctoror/particleswallpaper/userprefs/data/SettingsModuleProvider.kt | 1 | 1811 | /*
* Copyright (C) 2018 Yaroslav Mytkalyk
*
* 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.doctoror.particleswallpaper.userprefs.data
import android.content.Context
import com.doctoror.particleswallpaper.engine.configurator.SceneConfigurator
import org.koin.dsl.module.module
fun provideModuleSettings() = module {
factory {
DefaultSceneSettings(
get<Context>().resources!!,
get<Context>().theme!!
)
}
single {
DeviceSettings(
prefsSource = {
get<Context>().getSharedPreferences(
PREFERENCES_NAME_DEVICE,
Context.MODE_PRIVATE
)
}
)
}
single {
OpenGlSettings(
prefsSource = {
get<Context>().getSharedPreferences(
PREFERENCES_NAME_OPENGL,
Context.MODE_PRIVATE
)
}
)
}
factory { SceneConfigurator(get()) }
single {
SceneSettings(
defaults = get(),
prefsSource = {
get<Context>().getSharedPreferences(
PREFERENCES_NAME_SCENE,
Context.MODE_PRIVATE
)
}
)
}
}
| apache-2.0 | 32a32862a161ba35d6f9507863cf7df1 | 26.439394 | 76 | 0.578134 | 5.072829 | false | false | false | false |
iSoron/uhabits | uhabits-android/src/androidTest/java/org/isoron/uhabits/widgets/CheckmarkWidgetTest.kt | 1 | 3216 | /*
* Copyright (C) 2016-2021 Álinson Santos Xavier <[email protected]>
*
* This file is part of Loop Habit Tracker.
*
* Loop Habit Tracker 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.
*
* Loop Habit Tracker 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 org.isoron.uhabits.widgets
import android.view.View
import android.widget.Button
import android.widget.FrameLayout
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.MediumTest
import org.hamcrest.CoreMatchers
import org.hamcrest.CoreMatchers.equalTo
import org.hamcrest.CoreMatchers.`is`
import org.hamcrest.MatcherAssert.assertThat
import org.isoron.uhabits.BaseViewTest
import org.isoron.uhabits.R
import org.isoron.uhabits.core.models.Entry
import org.isoron.uhabits.core.models.EntryList
import org.isoron.uhabits.core.models.Habit
import org.isoron.uhabits.core.models.Timestamp
import org.isoron.uhabits.core.utils.DateUtils.Companion.getTodayWithOffset
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
@MediumTest
class CheckmarkWidgetTest : BaseViewTest() {
private lateinit var habit: Habit
private lateinit var entries: EntryList
private lateinit var view: FrameLayout
private lateinit var today: Timestamp
override fun setUp() {
super.setUp()
setTheme(R.style.WidgetTheme)
today = getTodayWithOffset()
prefs.widgetOpacity = 255
prefs.isSkipEnabled = true
habit = fixtures.createVeryLongHabit()
entries = habit.computedEntries
val widget = CheckmarkWidget(targetContext, 0, habit)
view = convertToView(widget, 150, 200)
assertThat(entries.get(today).value, equalTo(Entry.YES_MANUAL))
}
@Test
@Throws(Exception::class)
fun testClick() {
val button = view.findViewById<View>(R.id.button) as Button
assertThat(
button,
`is`(CoreMatchers.not(CoreMatchers.nullValue()))
)
// A better test would be to capture the intent, but it doesn't seem
// possible to capture intents sent to BroadcastReceivers.
button.performClick()
sleep(1000)
assertThat(entries.get(today).value, equalTo(Entry.SKIP))
button.performClick()
sleep(1000)
assertThat(entries.get(today).value, equalTo(Entry.NO))
}
@Test
fun testIsInstalled() {
assertWidgetProviderIsInstalled(CheckmarkWidgetProvider::class.java)
}
@Test
@Throws(Exception::class)
fun testRender() {
assertRenders(view, PATH + "render.png")
}
companion object {
private const val PATH = "widgets/CheckmarkWidget/"
}
}
| gpl-3.0 | 6dad636118a1042480390057ead35646 | 33.202128 | 78 | 0.718507 | 4.29239 | false | true | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/jvm-debugger/test/test/org/jetbrains/kotlin/idea/debugger/test/KotlinDescriptorTestCaseWithStackFrames.kt | 5 | 7482 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.debugger.test
import com.intellij.debugger.engine.AsyncStackTraceProvider
import com.intellij.debugger.engine.JavaExecutionStack
import com.intellij.debugger.engine.JavaStackFrame
import com.intellij.debugger.engine.SuspendContextImpl
import com.intellij.debugger.engine.events.SuspendContextCommandImpl
import com.intellij.debugger.memory.utils.StackFrameItem
import com.intellij.execution.configurations.JavaParameters
import com.intellij.execution.process.ProcessOutputTypes
import com.intellij.openapi.application.ApplicationManager
import com.intellij.util.concurrency.Semaphore
import com.intellij.xdebugger.frame.XNamedValue
import com.intellij.xdebugger.frame.XStackFrame
import com.intellij.xdebugger.impl.frame.XDebuggerFramesList
import org.jetbrains.jps.model.library.JpsMavenRepositoryLibraryDescriptor
import org.jetbrains.kotlin.idea.debugger.coroutine.CoroutineAsyncStackTraceProvider
import org.jetbrains.kotlin.idea.debugger.coroutine.data.CoroutinePreflightFrame
import org.jetbrains.kotlin.idea.debugger.test.util.XDebuggerTestUtil
import org.jetbrains.kotlin.idea.debugger.test.util.iterator
import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull
import java.io.PrintWriter
import java.io.StringWriter
abstract class KotlinDescriptorTestCaseWithStackFrames : KotlinDescriptorTestCaseWithStepping() {
private companion object {
val ASYNC_STACKTRACE_EP_NAME = AsyncStackTraceProvider.EP.name
const val INDENT_FRAME = 1
const val INDENT_VARIABLES = 2
}
private val agentList = mutableListOf<JpsMavenRepositoryLibraryDescriptor>()
private fun out(frame: XStackFrame) {
out(INDENT_FRAME, frame.javaClass.simpleName + " FRAME:" + XDebuggerTestUtil.getFramePresentation(frame))
outVariables(frame)
}
private fun outVariables(stackFrame: XStackFrame) {
val variables = stackFrame.iterator().asSequence()
.filterIsInstance<XNamedValue>()
.map { it.name }
.sorted()
.toList()
out(INDENT_VARIABLES, "(${variables.joinToString()})")
}
private fun out(text: String) {
println(text, ProcessOutputTypes.SYSTEM)
}
private fun out(indent: Int, text: String) {
println("\t".repeat(indent) + text, ProcessOutputTypes.SYSTEM)
println(text)
}
private fun Throwable.stackTraceAsString(): String {
val writer = StringWriter()
printStackTrace(PrintWriter(writer))
return writer.toString()
}
private fun printStackFrame(frame: XStackFrame?) {
if (frame == null) {
return
} else if (frame is XDebuggerFramesList.ItemWithSeparatorAbove &&
frame.hasSeparatorAbove()) {
out(0, frame.captionAboveOf)
}
out(frame)
}
private fun printStackFrameItems(stackFrames: List<StackFrameItem>) {
for (frameItem in stackFrames) {
printStackFrame(frameItem.createFrame(debugProcess))
}
}
private fun AsyncStackTraceProvider.getAsyncStackTraceInSuspendContextCommand(suspendContext: SuspendContextImpl, frame: JavaStackFrame): List<StackFrameItem>? {
val semaphore = Semaphore(1)
var stackFrames: List<StackFrameItem>? = null
suspendContext.debugProcess.managerThread.schedule(object : SuspendContextCommandImpl(suspendContext) {
override fun contextAction(suspendContext: SuspendContextImpl) {
stackFrames = getAsyncStackTrace(frame, suspendContext)
semaphore.up()
}
override fun commandCancelled() = semaphore.up()
})
semaphore.waitFor(com.intellij.xdebugger.XDebuggerTestUtil.TIMEOUT_MS.toLong())
return stackFrames
}
private fun printStackTrace(asyncStackTraceProvider: AsyncStackTraceProvider?, suspendContext: SuspendContextImpl, executionStack: JavaExecutionStack) {
out("Thread stack trace:")
for (frame in XDebuggerTestUtil.collectFrames(executionStack)) {
if (frame !is JavaStackFrame) {
continue
}
out(frame)
if (frame is CoroutinePreflightFrame) {
val key = frame.coroutineInfoData.descriptor
out(0, "CoroutineInfo: ${key.id} ${key.name} ${key.state}")
}
val stackFrameItems = asyncStackTraceProvider?.getAsyncStackTraceInSuspendContextCommand(suspendContext, frame)
if (stackFrameItems != null) {
printStackFrameItems(stackFrameItems)
return
}
}
}
fun printStackTrace() {
val asyncStackTraceProvider = getAsyncStackTraceProvider()
doWhenXSessionPausedThenResume {
printContext(debugProcess.debuggerContext)
val suspendContext = debuggerSession.xDebugSession?.suspendContext as? SuspendContextImpl
val executionStack = suspendContext?.activeExecutionStack
if (suspendContext != null && executionStack != null) {
try {
printStackTrace(asyncStackTraceProvider, suspendContext, executionStack)
} catch (e: Throwable) {
val stackTrace = e.stackTraceAsString()
System.err.println("Exception occurred on calculating async stack traces: $stackTrace")
throw e
}
} else {
println("FrameProxy is 'null', can't calculate async stack trace", ProcessOutputTypes.SYSTEM)
}
}
}
private fun getAsyncStackTraceProvider(): CoroutineAsyncStackTraceProvider? {
val area = ApplicationManager.getApplication().extensionArea
if (!area.hasExtensionPoint(ASYNC_STACKTRACE_EP_NAME)) {
System.err.println("${ASYNC_STACKTRACE_EP_NAME} extension point is not found (probably old IDE version)")
return null
}
val extensionPoint = area.getExtensionPoint<Any>(ASYNC_STACKTRACE_EP_NAME)
val provider = extensionPoint.extensions.firstIsInstanceOrNull<CoroutineAsyncStackTraceProvider>()
if (provider == null) {
System.err.println("Kotlin coroutine async stack trace provider is not found")
}
return provider
}
override fun addMavenDependency(compilerFacility: DebuggerTestCompilerFacility, library: String) {
val regex = Regex(pattern = "$MAVEN_DEPENDENCY_REGEX(-javaagent)?")
val result = regex.matchEntire(library) ?: return
val (_, groupId: String, artifactId: String, version: String, agent: String) = result.groupValues
if ("-javaagent" == agent)
agentList.add(JpsMavenRepositoryLibraryDescriptor(groupId, artifactId, version, false))
addMavenDependency(compilerFacility, groupId, artifactId, version)
}
override fun createJavaParameters(mainClass: String?): JavaParameters {
val params = super.createJavaParameters(mainClass)
for (agent in agentList) {
val dependencies = loadDependencies(agent)
for (dependency in dependencies) {
params.vmParametersList.add("-javaagent:${dependency.file.presentableUrl}")
}
}
return params
}
}
| apache-2.0 | a5828b747637d7944200fc738788c041 | 42.248555 | 165 | 0.690323 | 5.217573 | false | true | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/j2k/old/src/org/jetbrains/kotlin/j2k/TypeVisitor.kt | 6 | 4387 | // 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
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.*
import com.intellij.psi.impl.source.PsiClassReferenceType
import org.jetbrains.kotlin.j2k.ast.*
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.resolve.jvm.JvmPrimitiveType
private val PRIMITIVE_TYPES_NAMES = JvmPrimitiveType.values().map { it.javaKeywordName }
class TypeVisitor(
private val converter: Converter,
private val topLevelType: PsiType,
private val topLevelTypeMutability: Mutability,
private val inAnnotationType: Boolean
) : PsiTypeVisitor<Type>() {
private val typeConverter: TypeConverter = converter.typeConverter
//TODO: support for all types
override fun visitType(type: PsiType) = ErrorType()
override fun visitPrimitiveType(primitiveType: PsiPrimitiveType): Type {
val name = primitiveType.canonicalText
return when {
name == "void" -> UnitType()
PRIMITIVE_TYPES_NAMES.contains(name) -> PrimitiveType(Identifier.withNoPrototype(StringUtil.capitalize(name)))
name == "null" -> NullType()
else -> PrimitiveType(Identifier.withNoPrototype(name))
}
}
override fun visitArrayType(arrayType: PsiArrayType): Type {
return ArrayType(typeConverter.convertType(arrayType.componentType, inAnnotationType = inAnnotationType), Nullability.Default, converter.settings)
}
override fun visitClassType(classType: PsiClassType): Type {
val mutability = if (classType === topLevelType) topLevelTypeMutability else Mutability.Default
val refElement = constructReferenceElement(classType, mutability)
return ClassType(refElement, Nullability.Default, converter.settings)
}
private fun constructReferenceElement(classType: PsiClassType, mutability: Mutability): ReferenceElement {
val typeArgs = convertTypeArgs(classType)
val psiClass = classType.resolve()
if (psiClass != null) {
val javaClassName = psiClass.qualifiedName
converter.convertToKotlinAnalogIdentifier(javaClassName, mutability)?.let {
return ReferenceElement(it, typeArgs).assignNoPrototype()
}
if (inAnnotationType && javaClassName == "java.lang.Class") {
val fqName = FqName("kotlin.reflect.KClass")
val identifier = Identifier.withNoPrototype(fqName.shortName().identifier, imports = listOf(fqName))
return ReferenceElement(identifier, typeArgs).assignNoPrototype()
}
}
if (classType is PsiClassReferenceType) {
return converter.convertCodeReferenceElement(classType.reference, hasExternalQualifier = false, typeArgsConverted = typeArgs)
}
return ReferenceElement(Identifier.withNoPrototype(classType.className ?: ""), typeArgs).assignNoPrototype()
}
private fun convertTypeArgs(classType: PsiClassType): List<Type> {
return if (classType.parameterCount == 0) {
createTypeArgsForRawTypeUsage(classType, Mutability.Default)
}
else {
typeConverter.convertTypes(classType.parameters)
}
}
private fun createTypeArgsForRawTypeUsage(classType: PsiClassType, mutability: Mutability): List<Type> {
if (classType is PsiClassReferenceType) {
val targetClass = classType.reference.resolve() as? PsiClass
if (targetClass != null) {
return targetClass.typeParameters.map { StarProjectionType().assignNoPrototype() }
}
}
return listOf()
}
override fun visitWildcardType(wildcardType: PsiWildcardType): Type {
return when {
wildcardType.isExtends -> OutProjectionType(typeConverter.convertType(wildcardType.extendsBound))
wildcardType.isSuper -> InProjectionType(typeConverter.convertType(wildcardType.superBound))
else -> StarProjectionType()
}
}
override fun visitEllipsisType(ellipsisType: PsiEllipsisType): Type {
return VarArgType(typeConverter.convertType(ellipsisType.componentType, inAnnotationType = inAnnotationType))
}
}
| apache-2.0 | f375ab704f5a8f380a8ff2edac595ca7 | 42.87 | 158 | 0.701618 | 5.266507 | false | false | false | false |
dkandalov/katas | kotlin/src/katas/kotlin/eightQueen/EightQueen16.kt | 1 | 2424 | package katas.kotlin.eightQueen
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.equalTo
import org.junit.Test
class EightQueen16 {
@Test fun `find all possible queen positions on a board from which they do no attack each other`() {
assertThat(findBoards(boardSize = 0).size, equalTo(1))
assertThat(findBoards(boardSize = 1).size, equalTo(1))
assertThat(findBoards(boardSize = 2).size, equalTo(0))
assertThat(findBoards(boardSize = 3).size, equalTo(0))
assertThat(findBoards(boardSize = 4), equalTo(listOf(
Board(listOf(Queen(2, 3), Queen(0, 2), Queen(3, 1), Queen(1, 0))),
Board(listOf(Queen(1, 3), Queen(3, 2), Queen(0, 1), Queen(2, 0)))
)))
assertThat(findBoards(boardSize = 5).size, equalTo(10))
assertThat(findBoards(boardSize = 6).size, equalTo(4))
assertThat(findBoards(boardSize = 7).size, equalTo(40))
assertThat(findBoards(boardSize = 8).size, equalTo(92))
assertThat(findBoards(boardSize = 9).size, equalTo(352))
assertThat(findBoards(boardSize = 10).size, equalTo(724))
}
@Test fun `both recursive and iterative functions should produce the same result`() {
(0..10).forEach { boardSize ->
assertThat(findBoards(boardSize), equalTo(findBoards_iterative(boardSize)))
}
}
}
private data class Queen(val x: Int, val y: Int) {
override fun toString() = "($x,$y)"
}
private data class Board(val queens: List<Queen> = emptyList()) {
fun add(queen: Queen) = if (isValidMove(queen)) Board(queens + queen) else null
private fun isValidMove(queen: Queen) =
queens.none { it.x == queen.x || it.y == queen.y } &&
queens.none { Math.abs(it.x - queen.x) == Math.abs(it.y - queen.y) }
}
private fun findBoards(boardSize: Int, y: Int = 0): List<Board> {
if (y == boardSize) return listOf(Board())
val boards = findBoards(boardSize, y + 1)
return 0.until(boardSize)
.map { x -> Queen(x, y) }
.flatMap { queen -> boards.mapNotNull { it.add(queen) } }
}
private fun findBoards_iterative(boardSize: Int): List<Board> {
var boards = listOf(Board())
0.until(boardSize).reversed().forEach { y ->
boards = 0.until(boardSize)
.map { x -> Queen(x, y) }
.flatMap { queen -> boards.mapNotNull { it.add(queen) } }
}
return boards
}
| unlicense | 45d4bf50aa4c8eefc5b1420cc2df2c2f | 39.4 | 104 | 0.633251 | 3.376045 | false | false | false | false |
securityfirst/Umbrella_android | app/src/main/java/org/secfirst/umbrella/feature/base/interactor/BaseInteractorImp.kt | 1 | 1587 | package org.secfirst.umbrella.feature.base.interactor
import org.secfirst.umbrella.data.database.content.ContentRepo
import org.secfirst.umbrella.data.network.ApiHelper
import org.secfirst.umbrella.data.preferences.AppPreferenceHelper
open class BaseInteractorImp() : BaseInteractor {
protected lateinit var apiHelper: ApiHelper
protected lateinit var preferenceHelper: AppPreferenceHelper
protected lateinit var contentRepo: ContentRepo
constructor(apiHelper: ApiHelper, preferenceHelper: AppPreferenceHelper, contentRepo: ContentRepo) : this() {
this.apiHelper = apiHelper
this.preferenceHelper = preferenceHelper
this.contentRepo = contentRepo
}
override suspend fun resetContent(): Boolean {
val res: Boolean = contentRepo.resetContent()
preferenceHelper.setLoggedIn(false)
preferenceHelper.setSkipPassword(false)
preferenceHelper.setMaskApp(false)
return res
}
override fun setDefaultLanguage(isoCountry: String) = preferenceHelper.setLanguage(isoCountry)
override fun getDefaultLanguage() = preferenceHelper.getLanguage()
override fun setSkipPassword(isSkip: Boolean) = preferenceHelper.setSkipPassword(isSkip)
override fun isSkippPassword(): Boolean = preferenceHelper.getSkipPassword()
override fun enablePasswordBanner(enableBanner: Boolean) = preferenceHelper.enablePasswordBanner(enableBanner)
override fun isUserLoggedIn() = preferenceHelper.isLoggedIn()
override fun setLoggedIn(isLogged: Boolean) = preferenceHelper.setLoggedIn(isLogged)
}
| gpl-3.0 | b182f4f1e645d70964e0475aff55bea5 | 37.707317 | 114 | 0.778198 | 5.237624 | false | false | false | false |
tateisu/SubwayTooter | app/src/main/java/jp/juggler/subwaytooter/actpost/ActPostAccount.kt | 1 | 3789 | package jp.juggler.subwaytooter.actpost
import jp.juggler.subwaytooter.ActPost
import jp.juggler.subwaytooter.App1
import jp.juggler.subwaytooter.R
import jp.juggler.subwaytooter.api.entity.TootVisibility
import jp.juggler.subwaytooter.dialog.pickAccount
import jp.juggler.subwaytooter.table.AcctColor
import jp.juggler.subwaytooter.table.SavedAccount
import jp.juggler.util.*
import org.jetbrains.anko.textColor
import kotlin.math.max
private val log = LogCategory("ActPostAccount")
fun ActPost.selectAccount(a: SavedAccount?) {
this.account = a
completionHelper.setInstance(a)
if (a == null) {
views.btnAccount.text = getString(R.string.not_selected)
views.btnAccount.setTextColor(attrColor(android.R.attr.textColorPrimary))
views.btnAccount.setBackgroundResource(R.drawable.btn_bg_transparent_round6dp)
} else {
// 先読みしてキャッシュを温める。この時点では取得結果を使わない
App1.custom_emoji_lister.tryGetList(a)
views.spLanguage.setSelection(max(0, languages.indexOfFirst { it.first == a.lang }))
val ac = AcctColor.load(a)
views.btnAccount.text = ac.nickname
if (AcctColor.hasColorBackground(ac)) {
views.btnAccount.background =
getAdaptiveRippleDrawableRound(this, ac.color_bg, ac.color_fg)
} else {
views.btnAccount.setBackgroundResource(R.drawable.btn_bg_transparent_round6dp)
}
views.btnAccount.textColor = ac.color_fg.notZero()
?: attrColor(android.R.attr.textColorPrimary)
}
updateTextCount()
updateFeaturedTags()
}
fun ActPost.canSwitchAccount(): Boolean {
val errStringId = when {
// 予約投稿の再編集はアカウント切り替えできない
scheduledStatus != null ->
R.string.cant_change_account_when_editing_scheduled_status
// 削除して再投稿はアカウント切り替えできない
states.redraftStatusId != null ->
R.string.cant_change_account_when_redraft
// 投稿の編集中はアカウント切り替えできない
states.editStatusId != null ->
R.string.cant_change_account_when_edit
// 添付ファイルがあったらはアカウント切り替えできない
attachmentList.isNotEmpty() ->
R.string.cant_change_account_when_attachment_specified
else -> null
} ?: return true
showToast(true, errStringId)
return false
}
fun ActPost.performAccountChooser() {
if (!canSwitchAccount()) return
if (isMultiWindowPost) {
accountList = SavedAccount.loadAccountList(this)
SavedAccount.sort(accountList)
}
launchMain {
pickAccount(
bAllowPseudo = false,
bAuto = false,
message = getString(R.string.choose_account)
)?.let { ai ->
// 別タンスのアカウントに変更したならならin_reply_toの変換が必要
if (states.inReplyToId != null && ai.apiHost != account?.apiHost) {
startReplyConversion(ai)
} else {
setAccountWithVisibilityConversion(ai)
}
}
}
}
internal fun ActPost.setAccountWithVisibilityConversion(a: SavedAccount) {
selectAccount(a)
try {
if (TootVisibility.isVisibilitySpoilRequired(states.visibility, a.visibility)) {
showToast(true, R.string.spoil_visibility_for_account)
states.visibility = a.visibility
}
} catch (ex: Throwable) {
log.trace(ex)
}
showVisibility()
showQuotedRenote()
updateTextCount()
}
| apache-2.0 | 03c1c2e3c03d963d88bf5246a47ad100 | 31.04717 | 92 | 0.644305 | 3.918345 | false | false | false | false |
opst-miyatay/LightCalendarView | library/src/main/kotlin/jp/co/recruit_mp/android/lightcalendarview/accent/DotAccent.kt | 2 | 1425 | /*
* Copyright (C) 2016 RECRUIT MARKETING PARTNERS CO., LTD.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jp.co.recruit_mp.android.lightcalendarview.accent
import android.graphics.Canvas
import android.graphics.Paint
/**
* Created by masayuki-recruit on 9/7/16.
*/
class DotAccent(var radius: Float, var color: Int? = null, key: Any = Any()) : Accent(key) {
override val width: Int
get() = (radius * 2).toInt()
override val height: Int
get() = (radius * 2).toInt()
override val marginLeftRight: Int
get() = (0.1 * radius).toInt()
override val marginTopBottom: Int
get() = (0.1 * radius).toInt()
override fun draw(canvas: Canvas, x: Float, y: Float, paint: Paint) {
val oldColor = paint.color
paint.color = this.color ?: paint.color
canvas.drawCircle(x, y, this.radius, paint)
paint.color = oldColor
}
}
| apache-2.0 | 6615fcc22873abb8b18f15e0a55402e2 | 32.928571 | 92 | 0.675088 | 3.759894 | false | false | false | false |
kaif-open/kaif-android | app/src/main/kotlin/io/kaif/mobile/view/HonorAdapter.kt | 1 | 1553 | package io.kaif.mobile.view
import android.support.v7.widget.RecyclerView
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import io.kaif.mobile.R
import org.jetbrains.anko.*
class HonorAdapter : RecyclerView.Adapter<HonorViewHolder>() {
private val honors = arrayOf("123", "456", "789", "123", "456", "789", "123", "456", "789", "123", "456", "789", "123", "456", "789", "123", "456", "789")
override fun getItemCount(): Int {
return honors.size
}
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): HonorViewHolder {
return HonorViewHolder(HonorView().createView(AnkoContext.create(parent!!.context, parent)))
}
override fun onBindViewHolder(holder: HonorViewHolder?, position: Int) {
holder!!.bind(honors[position])
}
}
class HonorView : AnkoComponent<ViewGroup> {
override fun createView(ui: AnkoContext<ViewGroup>): View {
return with(ui) {
linearLayout {
lparams(width = matchParent, height = dip(48))
orientation = LinearLayout.HORIZONTAL
textView {
id = R.id.title
textSize = 16f
}.lparams(width = matchParent, height = dip(48))
}
}
}
}
class HonorViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var title: TextView? = itemView.findViewById(R.id.title)
fun bind(data: String) {
title?.text = "hi $data"
}
}
| apache-2.0 | f0687a00f331347ec09bafdee1b10daf | 30.693878 | 158 | 0.632968 | 4.141333 | false | false | false | false |
paplorinc/intellij-community | platform/lang-impl/src/com/intellij/codeInsight/hint/ImplementationViewSession.kt | 2 | 3744 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInsight.hint
import com.intellij.codeInsight.documentation.DocumentationManager
import com.intellij.codeInsight.hint.PsiImplementationViewSession.getSelfAndImplementations
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiManager
import com.intellij.psi.presentation.java.SymbolPresentationUtil
import com.intellij.util.Processor
interface ImplementationViewSession : Disposable {
val factory: ImplementationViewSessionFactory
val project: Project
/**
* The list of implementations which could be found synchronously. Additional implementations can be obtained by calling
* [searchImplementationsInBackground].
*/
val implementationElements: List<ImplementationViewElement>
val file: VirtualFile?
val text: String?
val editor: Editor?
fun searchImplementationsInBackground(indicator: ProgressIndicator,
processor: Processor<PsiElement>): List<ImplementationViewElement>
fun elementRequiresIncludeSelf(): Boolean
fun needUpdateInBackground(): Boolean
}
interface ImplementationViewSessionFactory {
fun createSession(
dataContext: DataContext,
project: Project,
isSearchDeep: Boolean,
alwaysIncludeSelf: Boolean
): ImplementationViewSession?
fun createSessionForLookupElement(
project: Project,
editor: Editor?,
file: VirtualFile?,
lookupItemObject: Any?,
isSearchDeep: Boolean,
alwaysIncludeSelf: Boolean
): ImplementationViewSession?
companion object {
@JvmField val EP_NAME = ExtensionPointName.create<ImplementationViewSessionFactory>("com.intellij.implementationViewSessionFactory")
}
}
class PsiImplementationSessionViewFactory : ImplementationViewSessionFactory {
override fun createSession(
dataContext: DataContext,
project: Project,
isSearchDeep: Boolean,
alwaysIncludeSelf: Boolean
): ImplementationViewSession? {
return PsiImplementationViewSession.create(dataContext, project, isSearchDeep, alwaysIncludeSelf)
}
override fun createSessionForLookupElement(project: Project,
editor: Editor?,
file: VirtualFile?,
lookupItemObject: Any?,
isSearchDeep: Boolean,
alwaysIncludeSelf: Boolean): ImplementationViewSession? {
val psiFile = file?.let { PsiManager.getInstance(project).findFile(it) }
val element = lookupItemObject as? PsiElement ?: DocumentationManager.getInstance(project).getElementFromLookup(editor, psiFile)
var impls = arrayOf<PsiElement>()
var text = ""
if (element != null) {
// if (element instanceof PsiPackage) return;
val containingFile = element.containingFile
if (containingFile == null || !containingFile.viewProvider.isPhysical) return null
impls = getSelfAndImplementations(editor, element, PsiImplementationViewSession.createImplementationsSearcher(isSearchDeep))
text = SymbolPresentationUtil.getSymbolPresentableText(element)
}
return PsiImplementationViewSession(project, element, impls, text, editor, file, isSearchDeep, alwaysIncludeSelf)
}
}
| apache-2.0 | 19851b93956d5313491d1286b0e5f0df | 40.142857 | 140 | 0.740652 | 5.318182 | false | false | false | false |
google/intellij-community | plugins/kotlin/code-insight/structural-search-k1/src/org/jetbrains/kotlin/idea/structuralsearch/KotlinStructuralSearchProfile.kt | 1 | 18399 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.structuralsearch
import com.intellij.lang.Language
import com.intellij.openapi.fileTypes.LanguageFileType
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiErrorElement
import com.intellij.psi.PsiWhiteSpace
import com.intellij.psi.util.elementType
import com.intellij.structuralsearch.*
import com.intellij.structuralsearch.impl.matcher.CompiledPattern
import com.intellij.structuralsearch.impl.matcher.GlobalMatchingVisitor
import com.intellij.structuralsearch.impl.matcher.PatternTreeContext
import com.intellij.structuralsearch.impl.matcher.compiler.GlobalCompilingVisitor
import com.intellij.structuralsearch.impl.matcher.predicates.MatchPredicate
import com.intellij.structuralsearch.impl.matcher.predicates.NotPredicate
import com.intellij.structuralsearch.plugin.replace.ReplaceOptions
import com.intellij.structuralsearch.plugin.ui.Configuration
import com.intellij.structuralsearch.plugin.ui.UIUtil
import com.intellij.util.SmartList
import org.jetbrains.kotlin.idea.KotlinFileType
import org.jetbrains.kotlin.idea.KotlinLanguage
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.liveTemplates.KotlinTemplateContextType
import org.jetbrains.kotlin.idea.structuralsearch.filters.*
import org.jetbrains.kotlin.idea.structuralsearch.predicates.KotlinAlsoMatchCompanionObjectPredicate
import org.jetbrains.kotlin.idea.structuralsearch.predicates.KotlinAlsoMatchValVarPredicate
import org.jetbrains.kotlin.idea.structuralsearch.predicates.KotlinExprTypePredicate
import org.jetbrains.kotlin.idea.structuralsearch.predicates.KotlinMatchCallSemantics
import org.jetbrains.kotlin.idea.structuralsearch.visitor.KotlinCompilingVisitor
import org.jetbrains.kotlin.idea.structuralsearch.visitor.KotlinMatchingVisitor
import org.jetbrains.kotlin.idea.structuralsearch.visitor.KotlinRecursiveElementWalkingVisitor
import org.jetbrains.kotlin.kdoc.psi.impl.KDocTag
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
class KotlinStructuralSearchProfile : StructuralSearchProfile() {
override fun isMatchNode(element: PsiElement?): Boolean = element !is PsiWhiteSpace
override fun createMatchingVisitor(globalVisitor: GlobalMatchingVisitor): KotlinMatchingVisitor =
KotlinMatchingVisitor(globalVisitor)
override fun createCompiledPattern(): CompiledPattern = object : CompiledPattern() {
init {
strategy = KotlinMatchingStrategy
}
override fun getTypedVarPrefixes(): Array<String> = arrayOf(TYPED_VAR_PREFIX)
override fun isTypedVar(str: String): Boolean = when {
str.isEmpty() -> false
str[0] == '@' -> str.regionMatches(1, TYPED_VAR_PREFIX, 0, TYPED_VAR_PREFIX.length)
else -> str.startsWith(TYPED_VAR_PREFIX)
}
override fun getTypedVarString(element: PsiElement): String {
val typedVarString = super.getTypedVarString(element)
return if (typedVarString.firstOrNull() == '@') typedVarString.drop(1) else typedVarString
}
}
override fun isMyLanguage(language: Language): Boolean = language == KotlinLanguage.INSTANCE
override fun getTemplateContextTypeClass(): Class<KotlinTemplateContextType.Generic> = KotlinTemplateContextType.Generic::class.java
override fun getPredefinedTemplates(): Array<Configuration> = KotlinPredefinedConfigurations.createPredefinedTemplates()
override fun getDefaultFileType(fileType: LanguageFileType?): LanguageFileType = fileType ?: KotlinFileType.INSTANCE
override fun supportsShortenFQNames(): Boolean = true
override fun compile(elements: Array<out PsiElement>, globalVisitor: GlobalCompilingVisitor) {
KotlinCompilingVisitor(globalVisitor).compile(elements)
}
override fun getPresentableElement(element: PsiElement): PsiElement {
val elem = if (isIdentifier(element)) element.parent else return element
return if(elem is KtReferenceExpression) elem.parent else elem
}
override fun isIdentifier(element: PsiElement?): Boolean = element != null && element.node?.elementType == KtTokens.IDENTIFIER
override fun createPatternTree(
text: String,
context: PatternTreeContext,
fileType: LanguageFileType,
language: Language,
contextId: String?,
project: Project,
physical: Boolean
): Array<PsiElement> {
var elements: List<PsiElement>
val factory = KtPsiFactory(project, false)
if (PROPERTY_CONTEXT.id == contextId) {
try {
val fragment = factory.createProperty(text)
elements = listOf(getNonWhitespaceChildren(fragment).first().parent)
if (elements.first() !is KtProperty) return PsiElement.EMPTY_ARRAY
} catch (e: Exception) {
return arrayOf(factory.createComment("//").apply {
putUserData(PATTERN_ERROR, KotlinBundle.message("error.context.getter.or.setter"))
})
}
} else {
val fragment = factory.createBlockCodeFragment("Unit\n$text", null)
elements = when (fragment.lastChild) {
is PsiComment -> getNonWhitespaceChildren(fragment).drop(1)
else -> getNonWhitespaceChildren(fragment.firstChild).drop(1)
}
}
if (elements.isEmpty()) return PsiElement.EMPTY_ARRAY
// Standalone KtAnnotationEntry support
if (elements.first() is KtAnnotatedExpression && elements.first().lastChild is PsiErrorElement)
elements = getNonWhitespaceChildren(elements.first()).dropLast(1)
// Standalone KtNullableType || KtUserType w/ type parameter support
if (elements.last() is PsiErrorElement && elements.last().firstChild.elementType == KtTokens.QUEST
|| elements.first() is KtCallExpression && (elements.first() as KtCallExpression).valueArgumentList == null) {
try {
val fragment = factory.createType(text)
elements = listOf(getNonWhitespaceChildren(fragment).first().parent)
} catch (e: Exception) {}
}
// for (element in elements) print(DebugUtil.psiToString(element, false))
return elements.toTypedArray()
}
inner class KotlinValidator : KotlinRecursiveElementWalkingVisitor() {
override fun visitErrorElement(element: PsiErrorElement) {
super.visitErrorElement(element)
if (shouldShowProblem(element)) {
throw MalformedPatternException(element.errorDescription)
}
}
override fun visitComment(comment: PsiComment) {
super.visitComment(comment)
comment.getUserData(PATTERN_ERROR)?.let { error ->
throw MalformedPatternException(error)
}
}
}
override fun checkSearchPattern(pattern: CompiledPattern) {
val visitor = KotlinValidator()
val nodes = pattern.nodes
while (nodes.hasNext()) {
nodes.current().accept(visitor)
nodes.advance()
}
nodes.reset()
}
override fun shouldShowProblem(error: PsiErrorElement): Boolean {
val description = error.errorDescription
val parent = error.parent
return when {
parent is KtTryExpression && KotlinBundle.message("error.expected.catch.or.finally") == description -> false //naked try
parent is KtAnnotatedExpression && KotlinBundle.message("error.expected.an.expression") == description -> false
else -> true
}
}
override fun checkReplacementPattern(project: Project, options: ReplaceOptions) {
val matchOptions = options.matchOptions
val fileType = matchOptions.fileType!!
val dialect = matchOptions.dialect!!
val searchIsDeclaration = isProbableExpression(matchOptions.searchPattern, fileType, dialect, project)
val replacementIsDeclaration = isProbableExpression(options.replacement, fileType, dialect, project)
if (searchIsDeclaration != replacementIsDeclaration) {
throw UnsupportedPatternException(
if (searchIsDeclaration) SSRBundle.message("replacement.template.is.not.expression.error.message")
else SSRBundle.message("search.template.is.not.expression.error.message")
)
}
}
private fun ancestors(node: PsiElement?): List<PsiElement?> {
val family = mutableListOf(node)
repeat(7) { family.add(family.last()?.parent) }
return family.drop(1)
}
override fun isApplicableConstraint(
constraintName: String,
variableNode: PsiElement?,
completePattern: Boolean,
target: Boolean
): Boolean {
if (variableNode != null)
return when (constraintName) {
UIUtil.TYPE, UIUtil.TYPE_REGEX -> isApplicableType(variableNode)
UIUtil.MINIMUM_ZERO -> isApplicableMinCount(variableNode) || isApplicableMinMaxCount(variableNode)
UIUtil.MAXIMUM_UNLIMITED -> isApplicableMaxCount(variableNode) || isApplicableMinMaxCount(variableNode)
UIUtil.TEXT_HIERARCHY -> isApplicableTextHierarchy(variableNode)
UIUtil.REFERENCE -> isApplicableReference(variableNode)
AlsoMatchVarModifier.CONSTRAINT_NAME -> variableNode.parent is KtProperty && !(variableNode.parent as KtProperty).isVar
AlsoMatchValModifier.CONSTRAINT_NAME -> variableNode.parent is KtProperty && (variableNode.parent as KtProperty).isVar
AlsoMatchCompanionObjectModifier.CONSTRAINT_NAME -> variableNode.parent is KtObjectDeclaration &&
!(variableNode.parent as KtObjectDeclaration).isCompanion()
MatchCallSemanticsModifier.CONSTRAINT_NAME -> variableNode.parent.parent is KtCallElement
else -> super.isApplicableConstraint(constraintName, variableNode, completePattern, target)
}
return super.isApplicableConstraint(constraintName, null as PsiElement?, completePattern, target)
}
private fun isApplicableReference(variableNode: PsiElement): Boolean = variableNode.parent is KtNameReferenceExpression
private fun isApplicableTextHierarchy(variableNode: PsiElement): Boolean {
val family = ancestors(variableNode)
return when {
family[0] is KtClass && (family[0] as KtClass).nameIdentifier == variableNode -> true
family[0] is KtObjectDeclaration && (family[0] as KtObjectDeclaration).nameIdentifier == variableNode -> true
family[0] is KtEnumEntry && (family[0] as KtEnumEntry).nameIdentifier == variableNode -> true
family[0] is KtNamedDeclaration && family[2] is KtClassOrObject -> true
family[3] is KtSuperTypeListEntry && family[5] is KtClassOrObject -> true
family[4] is KtSuperTypeListEntry && family[6] is KtClassOrObject -> true
else -> false
}
}
private fun isApplicableType(variableNode: PsiElement): Boolean {
val family = ancestors(variableNode)
return when {
family[0] is KtNameReferenceExpression -> when (family[1]) {
is KtValueArgument,
is KtProperty,
is KtBinaryExpression, is KtBinaryExpressionWithTypeRHS,
is KtIsExpression,
is KtBlockExpression,
is KtContainerNode,
is KtArrayAccessExpression,
is KtPostfixExpression,
is KtDotQualifiedExpression,
is KtSafeQualifiedExpression,
is KtCallableReferenceExpression,
is KtSimpleNameStringTemplateEntry, is KtBlockStringTemplateEntry,
is KtPropertyAccessor,
is KtWhenEntry -> true
else -> false
}
family[0] is KtProperty -> true
family[0] is KtParameter -> true
else -> false
}
}
/**
* Returns true if the largest count filter should be [0; 1].
*/
private fun isApplicableMinCount(variableNode: PsiElement): Boolean {
val family = ancestors(variableNode)
return when {
family[0] is KtObjectDeclaration -> true
family[0] !is KtNameReferenceExpression -> false
family[1] is KtProperty -> true
family[1] is KtDotQualifiedExpression -> true
family[1] is KtCallableReferenceExpression && family[0]?.nextSibling.elementType == KtTokens.COLONCOLON -> true
family[1] is KtWhenExpression -> true
family[2] is KtTypeReference && family[3] is KtNamedFunction -> true
family[3] is KtConstructorCalleeExpression -> true
else -> false
}
}
/**
* Returns true if the largest count filter should be [1; +inf].
*/
private fun isApplicableMaxCount(variableNode: PsiElement): Boolean {
val family = ancestors(variableNode)
return when {
family[0] is KtDestructuringDeclarationEntry -> true
family[0] is KtNameReferenceExpression && family[1] is KtWhenConditionWithExpression -> true
else -> false
}
}
/**
* Returns true if the largest count filter should be [0; +inf].
*/
private fun isApplicableMinMaxCount(variableNode: PsiElement): Boolean {
val family = ancestors(variableNode)
return when {
// Containers (lists, bodies, ...)
family[0] is KtObjectDeclaration -> false
family[1] is KtClassBody -> true
family[0] is KtParameter && family[1] is KtParameterList -> true
family[0] is KtTypeParameter && family[1] is KtTypeParameterList -> true
family[2] is KtTypeParameter && family[3] is KtTypeParameterList -> true
family[1] is KtUserType && family[4] is KtParameterList && family[5] !is KtNamedFunction -> true
family[1] is KtUserType && family[3] is KtSuperTypeEntry -> true
family[1] is KtValueArgument && family[2] is KtValueArgumentList -> true
family[1] is KtBlockExpression && family[3] is KtDoWhileExpression -> true
family[0] is KtNameReferenceExpression && family[1] is KtBlockExpression -> true
family[1] is KtUserType && family[3] is KtTypeProjection && family[5] !is KtNamedFunction -> true
// Annotations
family[1] is KtUserType && family[4] is KtAnnotationEntry -> true
family[1] is KtCollectionLiteralExpression -> true
// Strings
family[1] is KtSimpleNameStringTemplateEntry -> true
// KDoc
family[0] is KDocTag -> true
// Default: count filter not applicable
else -> false
}
}
override fun getCustomPredicates(
constraint: MatchVariableConstraint,
name: String,
options: MatchOptions
): MutableList<MatchPredicate> {
val result = SmartList<MatchPredicate>()
constraint.apply {
if (!StringUtil.isEmptyOrSpaces(nameOfExprType)) {
val predicate = KotlinExprTypePredicate(
search = if (isRegexExprType) nameOfExprType else expressionTypes,
withinHierarchy = isExprTypeWithinHierarchy,
ignoreCase = !options.isCaseSensitiveMatch,
target = isPartOfSearchResults,
baseName = name,
regex = isRegexExprType
)
result.add(if (isInvertExprType) NotPredicate(predicate) else predicate)
}
if (getAdditionalConstraint(AlsoMatchValModifier.CONSTRAINT_NAME) == OneStateFilter.ENABLED ||
getAdditionalConstraint(AlsoMatchVarModifier.CONSTRAINT_NAME) == OneStateFilter.ENABLED
) result.add(KotlinAlsoMatchValVarPredicate())
if (getAdditionalConstraint(AlsoMatchCompanionObjectModifier.CONSTRAINT_NAME) == OneStateFilter.ENABLED) {
result.add(KotlinAlsoMatchCompanionObjectPredicate())
}
if (getAdditionalConstraint(MatchCallSemanticsModifier.CONSTRAINT_NAME) == OneStateFilter.ENABLED) {
result.add(KotlinMatchCallSemantics())
}
}
return result
}
private fun isProbableExpression(pattern: String, fileType: LanguageFileType, dialect: Language, project: Project): Boolean {
if(pattern.isEmpty()) return false
val searchElements = try {
createPatternTree(pattern, PatternTreeContext.Block, fileType, dialect, null, project, false)
} catch (e: Exception) { return false }
if (searchElements.isEmpty()) return false
return searchElements[0] is KtDeclaration
}
override fun getReplaceHandler(project: Project, replaceOptions: ReplaceOptions): KotlinStructuralReplaceHandler =
KotlinStructuralReplaceHandler(project)
override fun getPatternContexts(): MutableList<PatternContext> = PATTERN_CONTEXTS
companion object {
const val TYPED_VAR_PREFIX: String = "_____"
val DEFAULT_CONTEXT: PatternContext = PatternContext("default", KotlinBundle.lazyMessage("context.default"))
val PROPERTY_CONTEXT: PatternContext = PatternContext("property", KotlinBundle.lazyMessage("context.property.getter.or.setter"))
private val PATTERN_CONTEXTS: MutableList<PatternContext> = mutableListOf(DEFAULT_CONTEXT, PROPERTY_CONTEXT)
private val PATTERN_ERROR: Key<String> = Key("patternError")
fun getNonWhitespaceChildren(fragment: PsiElement): List<PsiElement> {
var element = fragment.firstChild
val result: MutableList<PsiElement> = SmartList()
while (element != null) {
if (element !is PsiWhiteSpace) result.add(element)
element = element.nextSibling
}
return result
}
}
} | apache-2.0 | 8e024e89a23a9032f63ff80b218fb115 | 47.421053 | 136 | 0.678135 | 5.397184 | false | false | false | false |
google/intellij-community | plugins/github/src/org/jetbrains/plugins/github/pullrequest/data/provider/GHPRDetailsDataProviderImpl.kt | 6 | 3977 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.pullrequest.data.provider
import com.intellij.collaboration.async.CompletableFutureUtil.completionOnEdt
import com.intellij.collaboration.async.CompletableFutureUtil.successOnEdt
import com.intellij.openapi.Disposable
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.util.EventDispatcher
import com.intellij.util.messages.MessageBus
import org.jetbrains.plugins.github.api.data.GHLabel
import org.jetbrains.plugins.github.api.data.GHUser
import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequest
import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequestRequestedReviewer
import org.jetbrains.plugins.github.pullrequest.data.GHPRIdentifier
import org.jetbrains.plugins.github.pullrequest.data.service.GHPRCommentService
import org.jetbrains.plugins.github.pullrequest.data.service.GHPRDetailsService
import com.intellij.collaboration.ui.SimpleEventListener
import org.jetbrains.plugins.github.util.CollectionDelta
import org.jetbrains.plugins.github.util.LazyCancellableBackgroundProcessValue
import java.util.concurrent.CompletableFuture
import kotlin.properties.Delegates
class GHPRDetailsDataProviderImpl(private val detailsService: GHPRDetailsService,
private val pullRequestId: GHPRIdentifier,
private val messageBus: MessageBus)
: GHPRDetailsDataProvider, Disposable {
private val detailsLoadedEventDispatcher = EventDispatcher.create(SimpleEventListener::class.java)
override var loadedDetails by Delegates.observable<GHPullRequest?>(null) { _, _, _ ->
detailsLoadedEventDispatcher.multicaster.eventOccurred()
}
private set
private val detailsRequestValue = LazyCancellableBackgroundProcessValue.create { indicator ->
detailsService.loadDetails(indicator, pullRequestId).successOnEdt {
loadedDetails = it
it
}
}
override fun loadDetails(): CompletableFuture<GHPullRequest> = detailsRequestValue.value
override fun reloadDetails() = detailsRequestValue.drop()
override fun updateDetails(indicator: ProgressIndicator, title: String?, description: String?): CompletableFuture<GHPullRequest> {
val future = detailsService.updateDetails(indicator, pullRequestId, title, description).completionOnEdt {
messageBus.syncPublisher(GHPRDataOperationsListener.TOPIC).onMetadataChanged()
}
detailsRequestValue.overrideProcess(future.successOnEdt {
loadedDetails = it
it
})
return future
}
override fun adjustReviewers(indicator: ProgressIndicator,
delta: CollectionDelta<GHPullRequestRequestedReviewer>): CompletableFuture<Unit> {
return detailsService.adjustReviewers(indicator, pullRequestId, delta).notify()
}
override fun adjustAssignees(indicator: ProgressIndicator, delta: CollectionDelta<GHUser>): CompletableFuture<Unit> {
return detailsService.adjustAssignees(indicator, pullRequestId, delta).notify()
}
override fun adjustLabels(indicator: ProgressIndicator, delta: CollectionDelta<GHLabel>): CompletableFuture<Unit> {
return detailsService.adjustLabels(indicator, pullRequestId, delta).notify()
}
override fun addDetailsReloadListener(disposable: Disposable, listener: () -> Unit) =
detailsRequestValue.addDropEventListener(disposable, listener)
override fun addDetailsLoadedListener(disposable: Disposable, listener: () -> Unit) =
SimpleEventListener.addDisposableListener(detailsLoadedEventDispatcher, disposable, listener)
private fun <T> CompletableFuture<T>.notify(): CompletableFuture<T> =
completionOnEdt {
detailsRequestValue.drop()
messageBus.syncPublisher(GHPRDataOperationsListener.TOPIC).onMetadataChanged()
}
override fun dispose() {
detailsRequestValue.drop()
}
} | apache-2.0 | 39ea65fedaf1ccbc5eb3805320394a29 | 45.8 | 140 | 0.792306 | 5.131613 | false | false | false | false |
google/intellij-community | plugins/stats-collector/src/com/intellij/stats/completion/tracker/LookupStateManager.kt | 2 | 5627 | // Copyright 2000-2022 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.stats.completion.tracker
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.codeInsight.lookup.impl.LookupImpl
import com.intellij.completion.ml.storage.LookupStorage
import com.intellij.completion.ml.util.RelevanceUtil
import com.intellij.completion.ml.util.idString
import com.intellij.stats.completion.LookupEntryInfo
import com.intellij.stats.completion.LookupState
import com.intellij.util.SlowOperations
class LookupStateManager(private val shouldLogElementFeatures: Boolean) {
private val elementToId = mutableMapOf<String, Int>()
private val idToEntryInfo = mutableMapOf<Int, LookupEntryInfo>()
private val lookupStringToHash = mutableMapOf<String, Int>()
private var currentSessionFactors: Map<String, String> = emptyMap()
fun update(lookup: LookupImpl, factorsUpdated: Boolean): LookupState {
return SlowOperations.allowSlowOperations<LookupState, Throwable> {
doUpdate(lookup, factorsUpdated)
}
}
private fun doUpdate(lookup: LookupImpl, factorsUpdated: Boolean): LookupState {
val ids = mutableListOf<Int>()
val newIds = mutableSetOf<Int>()
val items = lookup.items
val currentPosition = items.indexOf(lookup.currentItem)
val elementToId = mutableMapOf<String, Int>()
for (item in items) {
var id = getElementId(item)
if (id == null) {
id = registerElement(item)
newIds.add(id)
}
elementToId[item.idString()] = id
ids.add(id)
}
val storage = LookupStorage.get(lookup)
val commonSessionFactors = storage?.sessionFactors?.getLastUsedCommonFactors() ?: emptyMap()
val sessionFactorsToLog = computeSessionFactorsToLog(commonSessionFactors)
if (factorsUpdated) {
val infos = items.toLookupInfos(lookup, elementToId)
val newInfos = infos.filter { it.id in newIds }
val itemsDiff = infos.mapNotNull { idToEntryInfo[it.id]?.calculateDiff(it) }
infos.forEach { idToEntryInfo[it.id] = it }
return LookupState(ids, newInfos, itemsDiff, currentPosition, sessionFactorsToLog)
}
else {
val newItems = items.filter { getElementId(it) in newIds }.toLookupInfos(lookup, elementToId)
newItems.forEach { idToEntryInfo[it.id] = it }
return LookupState(ids, newItems, emptyList(), currentPosition, sessionFactorsToLog)
}
}
fun getElementId(item: LookupElement): Int? {
val itemString = item.idString()
return elementToId[itemString]
}
private fun computeSessionFactorsToLog(factors: Map<String, String>): Map<String, String> {
if (factors == currentSessionFactors) return emptyMap()
currentSessionFactors = factors
return factors
}
private fun registerElement(item: LookupElement): Int {
val itemString = item.idString()
val newId = elementToId.size
elementToId[itemString] = newId
return newId
}
private fun List<LookupElement>.toLookupInfos(lookup: LookupImpl, elementToId: Map<String, Int>): List<LookupEntryInfo> {
val item2relevance = calculateRelevance(lookup, this)
return this.map { lookupElement ->
val id = lookupElement.idString()
val lookupString = lookupElement.lookupString
val itemHash = getLookupStringHash(lookupString)
LookupEntryInfo(elementToId.getValue(id), lookupString.length, itemHash, item2relevance.getValue(id))
}
}
private fun calculateRelevance(lookup: LookupImpl, items: List<LookupElement>): Map<String, Map<String, String>> {
val lookupStorage = LookupStorage.get(lookup)
if (lookupStorage?.shouldComputeFeatures() == false) {
return items.associateBy({ it.idString() }, { emptyMap() })
}
val result = mutableMapOf<String, Map<String, String>>()
if (lookupStorage != null) {
for (item in items) {
val id = item.idString()
val factors = lookupStorage.getItemStorage(id).getLastUsedFactors()?.mapValues { it.value.toString() }
if (factors != null) {
result.setFactors(id, factors)
}
}
}
// fallback (get factors from the relevance objects)
val rest = items.filter { it.idString() !in result }
if (rest.isNotEmpty()) {
val relevanceObjects = lookup.getRelevanceObjects(rest, false)
for (item in rest) {
val relevanceMap: Map<String, String> = relevanceObjects[item]?.let { objects ->
val (relevanceMap, additionalMap) = RelevanceUtil.asRelevanceMaps(objects)
val features = mutableMapOf<String, String>()
relevanceMap.forEach { features[it.key] = it.value.toString() }
additionalMap.forEach { features[it.key] = it.value.toString() }
return@let features
} ?: emptyMap()
result.setFactors(item.idString(), relevanceMap)
}
}
return result
}
private fun MutableMap<String, Map<String, String>>.setFactors(itemId: String, factors: Map<String, String>) {
if (shouldLogElementFeatures) {
this[itemId] = factors
} else {
this[itemId] = factors.filterKeys { it in REQUIRED_FACTORS }
}
}
private fun getLookupStringHash(lookupString: String): Int {
return lookupStringToHash.computeIfAbsent(lookupString) { lookupStringToHash.size }
}
companion object {
private val REQUIRED_FACTORS: Set<String> = setOf("ml_common_item_class", "position", "result_length", "ml_rank",
"kind", "ml_python_kind", "ml_php_element_element_type", "ml_scala_kind", "ml_clangd_kind", "kotlin.kind", "ml_js_kind")
}
} | apache-2.0 | b201b92b82e7fab5be591fa17e0b1a7e | 38.083333 | 140 | 0.705349 | 4.272589 | false | false | false | false |
apache/isis | incubator/clients/kroviz/src/test/kotlin/org/apache/causeway/client/kroviz/to/HttpErrorTest.kt | 2 | 5334 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.causeway.client.kroviz.to
import org.apache.causeway.client.kroviz.handler.Http401ErrorHandler
import org.apache.causeway.client.kroviz.handler.HttpErrorHandler
import org.apache.causeway.client.kroviz.snapshots.demo2_0_0.HTTP_ERROR_401
import org.apache.causeway.client.kroviz.snapshots.demo2_0_0.HTTP_ERROR_403
import org.apache.causeway.client.kroviz.snapshots.demo2_0_0.HTTP_ERROR_405
import org.apache.causeway.client.kroviz.snapshots.demo2_0_0.HTTP_ERROR_500
import org.apache.causeway.client.kroviz.snapshots.simpleapp1_16_0.HTTP_ERROR
import org.apache.causeway.client.kroviz.snapshots.simpleapp1_16_0.HTTP_ERROR_500_UNIQUE_CONSTRAINT_VIOLATION
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
class HttpErrorTest {
@Test
fun testKnife500() {
val jsonStr = org.apache.causeway.client.kroviz.snapshots.knife.HTTP_ERROR_500.str
val error = HttpErrorHandler().parse(jsonStr) as HttpError
val code = error.getStatusCode()
assertEquals(500, code)
assertNotNull(error.getMessage())
val detail = error.detail
assertNotNull(detail)
assertNotNull(detail.className)
assertEquals(null, detail.message)
assertEquals("", error.getMessage())
assertNotNull(detail.element)
assertTrue(detail.element.size > 0)
}
@Test
fun testDemo500() {
val jsonStr = HTTP_ERROR_500.str
val error = HttpErrorHandler().parse(jsonStr) as HttpError
val code = error.getStatusCode()
assertEquals(500, code)
assertNotNull(error.getMessage())
val detail = error.detail
assertNotNull(detail)
assertNotNull(detail.className)
assertNotNull(detail.message)
assertEquals(error.getMessage(), detail.message)
assertNotNull(detail.element)
assertTrue(detail.element.size > 0)
}
@Test
fun test403() {
val jsonStr = HTTP_ERROR_403.str
val error = HttpErrorHandler().parse(jsonStr) as HttpError
val code = error.getStatusCode()
assertEquals(403, code)
assertNotNull(error.getMessage())
val detail = error.detail
assertNotNull(detail)
assertNotNull(detail.className)
assertNotNull(detail.message)
assertEquals(error.getMessage(), detail.message)
assertNotNull(detail.element)
assertTrue(detail.element.size > 0)
}
@Test
fun test405() {
val jsonStr = HTTP_ERROR_405.str
val error = HttpErrorHandler().parse(jsonStr) as HttpError
val code = error.getStatusCode()
assertEquals(405, code)
assertNotNull(error.getMessage())
val detail = error.detail
assertNotNull(detail)
assertNotNull(detail.className)
assertNotNull(detail.message)
assertEquals(error.getMessage(), detail.message)
assertNotNull(detail.element)
assertTrue(detail.element.size > 0)
}
@Test
fun test400() {
val jsonStr = HTTP_ERROR.str
val error = HttpErrorHandler().parse(jsonStr) as HttpError
val code = error.getStatusCode()
assertEquals(400, code)
assertNotNull(error.getMessage())
val detail = error.detail
assertNotNull(detail)
assertNotNull(detail.className)
assertNotNull(detail.message)
assertEquals(error.getMessage(), detail.message)
assertNotNull(detail.element)
assertTrue(detail.element.size > 0)
}
@Test
fun test401() {
val jsonStr = HTTP_ERROR_401.str
val error = Http401ErrorHandler().parse(jsonStr) as Http401Error
assertEquals(401, error.getStatusCode())
assertTrue(error.getMessage().startsWith("Unauthorized"))
assertTrue(error.getMessage().contains("/restful/"))
}
//@Test //TODO handle nested causedBy's
fun test500() {
val jsonStr = HTTP_ERROR_500_UNIQUE_CONSTRAINT_VIOLATION.str
val error = HttpErrorHandler().parse(jsonStr) as HttpError
val code = error.getStatusCode()
assertEquals(400, code)
assertNotNull(error.getMessage())
val detail = error.detail
assertNotNull(detail)
assertNotNull(detail.className)
assertNotNull(detail.message)
assertEquals(error.getMessage(), detail.message)
assertNotNull(detail.element)
assertTrue(detail.element.size > 0)
}
}
| apache-2.0 | b7329fa84257932f0ccde824c900f520 | 35.040541 | 109 | 0.687664 | 4.350734 | false | true | false | false |
JetBrains/intellij-community | platform/platform-impl/src/com/intellij/openapi/project/impl/ProjectManagerImpl.kt | 1 | 52745 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:Suppress("ReplaceGetOrSet", "ReplacePutWithAssignment")
package com.intellij.openapi.project.impl
import com.intellij.configurationStore.StoreReloadManager
import com.intellij.configurationStore.saveSettings
import com.intellij.conversion.CannotConvertException
import com.intellij.conversion.ConversionResult
import com.intellij.conversion.ConversionService
import com.intellij.diagnostic.*
import com.intellij.diagnostic.telemetry.TraceManager
import com.intellij.diagnostic.telemetry.useWithScope2
import com.intellij.featureStatistics.fusCollectors.LifecycleUsageTriggerCollector
import com.intellij.ide.*
import com.intellij.ide.impl.*
import com.intellij.ide.lightEdit.LightEdit
import com.intellij.ide.lightEdit.LightEditCompatible
import com.intellij.ide.lightEdit.LightEditService
import com.intellij.ide.lightEdit.LightEditUtil
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.ide.startup.impl.StartupManagerImpl
import com.intellij.idea.canonicalPath
import com.intellij.notification.Notification
import com.intellij.notification.NotificationType
import com.intellij.notification.NotificationsManager
import com.intellij.notification.impl.NotificationsManagerImpl
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.*
import com.intellij.openapi.application.ex.ApplicationManagerEx
import com.intellij.openapi.application.impl.LaterInvocator
import com.intellij.openapi.components.service
import com.intellij.openapi.components.serviceIfCreated
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.extensions.PluginDescriptor
import com.intellij.openapi.extensions.impl.ExtensionPointImpl
import com.intellij.openapi.extensions.impl.ExtensionsAreaImpl
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.impl.CoreProgressManager
import com.intellij.openapi.project.*
import com.intellij.openapi.project.ex.ProjectEx
import com.intellij.openapi.project.ex.ProjectManagerEx
import com.intellij.openapi.project.ex.ProjectManagerEx.Companion.IS_CHILD_PROCESS
import com.intellij.openapi.project.ex.ProjectManagerEx.Companion.PER_PROJECT_SUFFIX
import com.intellij.openapi.project.impl.ProjectImpl.Companion.preloadServicesAndCreateComponents
import com.intellij.openapi.startup.StartupManager
import com.intellij.openapi.ui.MessageDialogBuilder
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.*
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.impl.ZipHandler
import com.intellij.openapi.wm.IdeFocusManager
import com.intellij.openapi.wm.WindowManager
import com.intellij.openapi.wm.impl.WindowManagerImpl
import com.intellij.openapi.wm.impl.welcomeScreen.WelcomeFrame
import com.intellij.platform.PlatformProjectOpenProcessor
import com.intellij.platform.PlatformProjectOpenProcessor.Companion.isLoadedFromCacheButHasNoModules
import com.intellij.projectImport.ProjectAttachProcessor
import com.intellij.serviceContainer.ComponentManagerImpl
import com.intellij.ui.IdeUICustomization
import com.intellij.util.ArrayUtil
import com.intellij.util.Restarter
import com.intellij.util.ThreeState
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.io.delete
import com.intellij.util.io.exists
import io.opentelemetry.api.common.AttributeKey
import kotlinx.coroutines.*
import org.jetbrains.annotations.ApiStatus.Internal
import org.jetbrains.annotations.TestOnly
import org.jetbrains.annotations.VisibleForTesting
import java.io.File
import java.io.IOException
import java.nio.charset.StandardCharsets
import java.nio.file.*
import java.util.concurrent.CancellationException
import java.util.concurrent.ConcurrentHashMap
import kotlin.coroutines.coroutineContext
import kotlin.io.path.div
@Suppress("OVERRIDE_DEPRECATION")
@Internal
open class ProjectManagerImpl : ProjectManagerEx(), Disposable {
companion object {
@TestOnly
@JvmStatic
fun isLight(project: Project): Boolean {
return project is ProjectEx && project.isLight
}
internal suspend fun dispatchEarlyNotifications() {
val notificationManager = NotificationsManager.getNotificationsManager() as NotificationsManagerImpl
withContext(Dispatchers.EDT + ModalityState.NON_MODAL.asContextElement()) {
notificationManager.dispatchEarlyNotifications()
}
}
}
private var openProjects = arrayOf<Project>() // guarded by lock
private val openProjectByHash = ConcurrentHashMap<String, Project>()
private val lock = Any()
// we cannot use the same approach to migrate to message bus as CompilerManagerImpl because of method canCloseProject
private val listeners = ContainerUtil.createLockFreeCopyOnWriteList<ProjectManagerListener>()
private val defaultProject = DefaultProject()
private val excludeRootsCache: ExcludeRootsCache
private var getAllExcludedUrlsCallback: Runnable? = null
init {
val connection = ApplicationManager.getApplication().messageBus.simpleConnect()
connection.subscribe(TOPIC, object : ProjectManagerListener {
@Suppress("removal")
override fun projectOpened(project: Project) {
for (listener in getAllListeners(project)) {
try {
@Suppress("DEPRECATION", "removal")
listener.projectOpened(project)
}
catch (e: Exception) {
handleListenerError(e, listener)
}
}
}
override fun projectClosed(project: Project) {
for (listener in getAllListeners(project)) {
try {
listener.projectClosed(project)
}
catch (e: Exception) {
handleListenerError(e, listener)
}
}
}
override fun projectClosing(project: Project) {
for (listener in getAllListeners(project)) {
try {
listener.projectClosing(project)
}
catch (e: Exception) {
handleListenerError(e, listener)
}
}
}
override fun projectClosingBeforeSave(project: Project) {
for (listener in getAllListeners(project)) {
try {
listener.projectClosingBeforeSave(project)
}
catch (e: Exception) {
handleListenerError(e, listener)
}
}
}
})
// register unlocking perProject dirs action
if (IS_PER_PROJECT_INSTANCE_READY) {
connection.subscribe(ProjectCloseListener.TOPIC, object : ProjectCloseListener {
override fun projectClosed(project: Project) {
if (IS_CHILD_PROCESS) {
clearPerProjectDirsForProject(PathManager.getSystemDir())
}
else {
clearPerProjectDirsForProject(toPerProjectDir(PathManager.getSystemDir(), Path.of(project.basePath!!)))
}
}
})
}
excludeRootsCache = ExcludeRootsCache(connection)
}
@TestOnly
fun testOnlyGetExcludedUrlsCallback(parentDisposable: Disposable, callback: Runnable) {
check(getAllExcludedUrlsCallback == null) { "This method is not reentrant. Expected null but got $getAllExcludedUrlsCallback" }
getAllExcludedUrlsCallback = callback
Disposer.register(parentDisposable) { getAllExcludedUrlsCallback = null }
}
override val allExcludedUrls: List<String>
get() {
val callback = getAllExcludedUrlsCallback
callback?.run()
return excludeRootsCache.excludedUrls
}
override fun dispose() {
ApplicationManager.getApplication().assertWriteAccessAllowed()
// dispose manually, because TimedReference.dispose() can already be called (in Timed.disposeTimed()) and then default project resurrected
Disposer.dispose(defaultProject)
}
override fun loadProject(path: Path): Project {
check(!ApplicationManager.getApplication().isDispatchThread)
val project = ProjectImpl(filePath = path, projectName = null)
val modalityState = CoreProgressManager.getCurrentThreadProgressModality()
runBlocking(modalityState.asContextElement()) {
initProject(
file = path,
project = project,
isRefreshVfsNeeded = true,
preloadServices = true,
template = null,
isTrustCheckNeeded = false,
)
}
return project
}
override val isDefaultProjectInitialized: Boolean
get() = defaultProject.isCached
override fun getDefaultProject(): Project {
LOG.assertTrue(!ApplicationManager.getApplication().isDisposed, "Application has already been disposed!")
// call instance method to reset timeout
// re-instantiate if needed
val bus = defaultProject.messageBus
LOG.assertTrue(!bus.isDisposed)
LOG.assertTrue(defaultProject.isCached)
return defaultProject
}
@TestOnly
@Internal
fun disposeDefaultProjectAndCleanupComponentsForDynamicPluginTests() {
defaultProject.disposeDefaultProjectAndCleanupComponentsForDynamicPluginTests()
}
override fun getOpenProjects(): Array<Project> = synchronized(lock) { openProjects }
override fun isProjectOpened(project: Project): Boolean = synchronized(lock) { openProjects.contains(project) }
protected fun addToOpened(project: Project): Boolean {
assert(!project.isDisposed) { "Must not open already disposed project" }
synchronized(lock) {
if (isProjectOpened(project)) {
return false
}
openProjects += project
}
updateTheOnlyProjectField()
openProjectByHash.put(project.locationHash, project)
return true
}
fun updateTheOnlyProjectField() {
val isLightEditActive = serviceIfCreated<LightEditService>()?.project != null
if (ApplicationManager.getApplication().isUnitTestMode && !ApplicationManagerEx.isInStressTest()) {
// switch off optimization in non-stress tests to assert they don't query getProject for invalid PsiElements
ProjectCoreUtil.updateInternalTheOnlyProjectFieldTemporarily(null)
}
else {
val isDefaultInitialized = isDefaultProjectInitialized
synchronized(lock) {
val theOnlyProject = if (openProjects.size == 1 && !isDefaultInitialized && !isLightEditActive) openProjects.first() else null
ProjectCoreUtil.updateInternalTheOnlyProjectFieldTemporarily(theOnlyProject)
}
}
}
private fun removeFromOpened(project: Project) {
synchronized(lock) {
openProjects = ArrayUtil.remove(openProjects, project)
// remove by value and not by key!
openProjectByHash.values.remove(project)
}
}
override fun findOpenProjectByHash(locationHash: String?): Project? = openProjectByHash.get(locationHash)
override fun reloadProject(project: Project) {
StoreReloadManager.getInstance().reloadProject(project)
}
override fun closeProject(project: Project): Boolean {
return closeProject(project = project, saveProject = true, dispose = false, checkCanClose = true)
}
override fun forceCloseProject(project: Project, save: Boolean): Boolean {
return closeProject(project = project, saveProject = save, checkCanClose = false)
}
override suspend fun forceCloseProjectAsync(project: Project, save: Boolean): Boolean {
ApplicationManager.getApplication().assertIsNonDispatchThread()
if (save) {
// HeadlessSaveAndSyncHandler doesn't save, but if `save` is requested,
// it means that we must save in any case (for example, see GradleSourceSetsTest)
saveSettings(project, forceSavingAllSettings = true)
}
return withContext(Dispatchers.EDT) {
if (project.isDisposed) {
return@withContext false
}
closeProject(project = project, saveProject = save, checkCanClose = false)
}
}
// return true if successful
override fun closeAndDisposeAllProjects(checkCanClose: Boolean): Boolean {
var projects = openProjects
LightEditUtil.getProjectIfCreated()?.let {
projects += it
}
for (project in projects) {
if (!closeProject(project = project, checkCanClose = checkCanClose)) {
return false
}
}
return true
}
protected open fun closeProject(project: Project, saveProject: Boolean = true, dispose: Boolean = true, checkCanClose: Boolean): Boolean {
val app = ApplicationManager.getApplication()
check(!app.isWriteAccessAllowed) {
"Must not call closeProject() from under write action because fireProjectClosing() listeners must have a chance to do something useful"
}
app.assertIsWriteThread()
@Suppress("TestOnlyProblems")
if (isLight(project)) {
// if we close project at the end of the test, just mark it closed;
// if we are shutting down the entire test framework, proceed to full dispose
val projectImpl = project as ProjectImpl
if (!projectImpl.isTemporarilyDisposed) {
ApplicationManager.getApplication().runWriteAction {
projectImpl.disposeEarlyDisposable()
projectImpl.setTemporarilyDisposed(true)
removeFromOpened(project)
}
updateTheOnlyProjectField()
return true
}
projectImpl.setTemporarilyDisposed(false)
}
else if (!isProjectOpened(project) && !LightEdit.owns(project)) {
if (dispose) {
if (project is ComponentManagerImpl) {
project.stopServicePreloading()
}
ApplicationManager.getApplication().runWriteAction {
if (project is ProjectImpl) {
project.disposeEarlyDisposable()
project.startDispose()
}
Disposer.dispose(project)
}
}
return true
}
if (checkCanClose && !canClose(project)) {
return false
}
if (project is ComponentManagerImpl) {
(project as ComponentManagerImpl).stopServicePreloading()
}
closePublisher.projectClosingBeforeSave(project)
publisher.projectClosingBeforeSave(project)
if (saveProject) {
FileDocumentManager.getInstance().saveAllDocuments()
SaveAndSyncHandler.getInstance().saveSettingsUnderModalProgress(project)
}
if (checkCanClose && !ensureCouldCloseIfUnableToSave(project)) {
return false
}
// somebody can start progress here, do not wrap in write action
fireProjectClosing(project)
app.runWriteAction {
removeFromOpened(project)
if (project is ProjectImpl) {
// ignore dispose flag (dispose is passed only via deprecated API that used only by some 3d-party plugins)
project.disposeEarlyDisposable()
if (dispose) {
project.startDispose()
}
}
fireProjectClosed(project)
if (!ApplicationManagerEx.getApplicationEx().isExitInProgress) {
ZipHandler.clearFileAccessorCache()
}
LaterInvocator.purgeExpiredItems()
if (dispose) {
Disposer.dispose(project)
}
}
return true
}
override fun closeAndDispose(project: Project) = closeProject(project, checkCanClose = true)
@Suppress("removal")
override fun addProjectManagerListener(listener: ProjectManagerListener) {
listeners.add(listener)
}
override fun addProjectManagerListener(listener: VetoableProjectManagerListener) {
listeners.add(listener)
}
@Suppress("removal")
override fun removeProjectManagerListener(listener: ProjectManagerListener) {
val removed = listeners.remove(listener)
LOG.assertTrue(removed)
}
override fun removeProjectManagerListener(listener: VetoableProjectManagerListener) {
val removed = listeners.remove(listener)
LOG.assertTrue(removed)
}
override fun addProjectManagerListener(project: Project, listener: ProjectManagerListener) {
if (project.isDefault) {
// nothing happens with default project
return
}
val listeners = project.getUserData(LISTENERS_IN_PROJECT_KEY)
?: (project as UserDataHolderEx).putUserDataIfAbsent(LISTENERS_IN_PROJECT_KEY,
ContainerUtil.createLockFreeCopyOnWriteList())
listeners.add(listener)
}
override fun removeProjectManagerListener(project: Project, listener: ProjectManagerListener) {
if (project.isDefault) {
// nothing happens with default project
return
}
val listeners = project.getUserData(LISTENERS_IN_PROJECT_KEY)
LOG.assertTrue(listeners != null)
val removed = listeners!!.remove(listener)
LOG.assertTrue(removed)
}
override fun canClose(project: Project): Boolean {
if (LOG.isDebugEnabled) {
LOG.debug("enter: canClose()")
}
for (handler in CLOSE_HANDLER_EP.lazySequence()) {
try {
if (!handler.canClose(project)) {
LOG.debug("close canceled by $handler")
return false
}
}
catch (e: ProcessCanceledException) {
throw e
}
catch (e: Throwable) {
LOG.error(e)
}
}
for (listener in getAllListeners(project)) {
try {
@Suppress("DEPRECATION", "removal")
val canClose = if (listener is VetoableProjectManagerListener) listener.canClose(project) else listener.canCloseProject(project)
if (!canClose) {
LOG.debug("close canceled by $listener")
return false
}
}
catch (e: Throwable) {
handleListenerError(e, listener)
}
}
return true
}
private fun getAllListeners(project: Project): List<ProjectManagerListener> {
val projectLevelListeners = getListeners(project)
// order is critically important due to backward compatibility - project level listeners must be first
return when {
projectLevelListeners.isEmpty() -> listeners
listeners.isEmpty() -> projectLevelListeners
else -> projectLevelListeners + listeners
}
}
@Suppress("OVERRIDE_DEPRECATION")
final override fun createProject(name: String?, path: String): Project? {
ApplicationManager.getApplication().assertIsDispatchThread()
return newProject(toCanonicalName(path), OpenProjectTask {
isNewProject = true
runConfigurators = false
projectName = name
})
}
final override fun loadAndOpenProject(originalFilePath: String): Project? {
return openProject(toCanonicalName(originalFilePath), OpenProjectTask())
}
final override fun openProject(projectStoreBaseDir: Path, options: OpenProjectTask): Project? {
@Suppress("DEPRECATION")
return runUnderModalProgressIfIsEdt { openProjectAsync(projectStoreBaseDir, options) }
}
final override suspend fun openProjectAsync(projectStoreBaseDir: Path, options: OpenProjectTask): Project? {
if (LOG.isDebugEnabled && !ApplicationManager.getApplication().isUnitTestMode) {
LOG.debug("open project: $options", Exception())
}
if (options.project != null && isProjectOpened(options.project as Project)) {
LOG.info("Project is already opened -> return null")
return null
}
val activity = StartUpMeasurer.startActivity("project opening preparation")
if (!checkTrustedState(projectStoreBaseDir)) {
LOG.info("Project is not trusted -> return null")
return null
}
val shouldOpenInChildProcess = IS_PER_PROJECT_INSTANCE_ENABLED && openProjects.isNotEmpty() &&
// Do not reopen previously opened projects in new instances
!RecentProjectsManagerBase.getInstanceEx().isLastOpened(projectStoreBaseDir.toString())
if (shouldOpenInChildProcess) {
openInChildProcess(projectStoreBaseDir)
return null
}
// if we are opening project in current process (not yet PER_PROJECT), lock per-project directory
if (IS_PER_PROJECT_INSTANCE_READY) {
if (IS_CHILD_PROCESS) {
lockPerProjectDirForProject(PathManager.getSystemDir())
}
else {
lockPerProjectDirForProject(toPerProjectDir(PathManager.getSystemDir(), projectStoreBaseDir))
}
}
if (!options.forceOpenInNewFrame) {
val openProjects = openProjects
if (!openProjects.isEmpty()) {
var projectToClose = options.projectToClose
if (projectToClose == null) {
// if several projects are opened, ask to reuse not last opened project frame, but last focused (to avoid focus switching)
val lastFocusedFrame = IdeFocusManager.getGlobalInstance().lastFocusedFrame
projectToClose = lastFocusedFrame?.project
if (projectToClose == null || projectToClose is LightEditCompatible) {
projectToClose = openProjects.last()
}
}
if (checkExistingProjectOnOpen(projectToClose, options, projectStoreBaseDir)) {
LOG.info("Project check is not succeeded -> return null")
return null
}
}
}
return doOpenAsync(options, projectStoreBaseDir, activity)
}
private suspend fun doOpenAsync(options: OpenProjectTask, projectStoreBaseDir: Path, activity: Activity): Project? {
val frameAllocator = if (ApplicationManager.getApplication().isHeadlessEnvironment) {
ProjectFrameAllocator(options)
}
else {
ProjectUiFrameAllocator(options, projectStoreBaseDir)
}
val disableAutoSaveToken = SaveAndSyncHandler.getInstance().disableAutoSave()
var module: Module? = null
var result: Project? = null
var projectOpenActivity: Activity? = null
try {
frameAllocator.run { saveTemplateJob, initFrame ->
activity.end()
val initFrameEarly = !options.isNewProject && options.beforeOpen == null
val project = when {
options.project != null -> options.project!!
options.isNewProject -> prepareNewProject(options = options,
projectStoreBaseDir = projectStoreBaseDir,
saveTemplateJob = saveTemplateJob)
else -> prepareProject(options = options,
projectStoreBaseDir = projectStoreBaseDir,
initFrame = initFrame.takeIf { initFrameEarly })
}
result = project
// must be under try-catch to dispose project on beforeOpen or preparedToOpen callback failures
if (options.project == null) {
val beforeOpen = options.beforeOpen
if (beforeOpen != null && !beforeOpen(project)) {
throw CancellationException("beforeOpen callback returned false")
}
if (options.runConfigurators &&
(options.isNewProject || ModuleManager.getInstance(project).modules.isEmpty()) ||
project.isLoadedFromCacheButHasNoModules()) {
module = PlatformProjectOpenProcessor.runDirectoryProjectConfigurators(
baseDir = projectStoreBaseDir,
project = project,
newProject = options.isProjectCreatedWithWizard
)
options.preparedToOpen?.invoke(module!!)
}
}
if (!addToOpened(project)) {
throw CancellationException("project is already opened")
}
// Project is loaded and is initialized, project services and components can be accessed.
// But start-up and post start-up activities are not yet executed.
if (!initFrameEarly) {
initFrame(project)
}
projectOpenActivity = if (StartUpMeasurer.isEnabled()) StartUpMeasurer.startActivity("project opening") else null
runActivity("project startup") {
tracer.spanBuilder("open project")
.setAttribute(AttributeKey.stringKey("project"), project.name)
runInitProjectActivities(project)
}
}
}
catch (e: CancellationException) {
withContext(NonCancellable) {
result?.let { project ->
try {
try {
@Suppress("DEPRECATION")
// cancel async preloading of services as soon as possible
project.coroutineScope.coroutineContext.job.cancelAndJoin()
}
catch (secondException: Throwable) {
e.addSuppressed(secondException)
}
withContext(Dispatchers.EDT) {
closeProject(project, saveProject = false, checkCanClose = false)
}
}
catch (secondException: Throwable) {
e.addSuppressed(secondException)
}
}
failedToOpenProject(frameAllocator = frameAllocator, exception = null, options = options)
}
throw e
}
catch (e: Throwable) {
result?.let { project ->
try {
withContext(Dispatchers.EDT) {
closeProject(project, saveProject = false, checkCanClose = false)
}
}
catch (secondException: Throwable) {
e.addSuppressed(secondException)
}
}
if (ApplicationManager.getApplication().isUnitTestMode) {
throw e
}
LOG.error(e)
failedToOpenProject(frameAllocator = frameAllocator, exception = e, options = options)
return null
}
finally {
disableAutoSaveToken.finish()
projectOpenActivity?.end()
}
val project = result!!
if (!ApplicationManager.getApplication().isUnitTestMode) {
val openTimestamp = System.currentTimeMillis()
@Suppress("DEPRECATION")
project.coroutineScope?.launch {
notifyRecentManager(project, options, openTimestamp)
}
}
if (isRunStartUpActivitiesEnabled(project)) {
(StartupManager.getInstance(project) as StartupManagerImpl).runPostStartupActivities()
}
LifecycleUsageTriggerCollector.onProjectOpened(project)
options.callback?.projectOpened(project, module ?: ModuleManager.getInstance(project).modules[0])
return project
}
private suspend fun notifyRecentManager(project: Project, options: OpenProjectTask, openTimestamp: Long) {
RecentProjectsManagerBase.getInstanceEx().projectOpened(
project = project,
recentProjectMetaInfo = ((options.implOptions as? OpenProjectImplOptions))?.recentProjectMetaInfo,
openTimestamp = openTimestamp,
)
dispatchEarlyNotifications()
}
private suspend fun failedToOpenProject(frameAllocator: ProjectFrameAllocator, exception: Throwable?, options: OpenProjectTask) {
frameAllocator.projectNotLoaded(cannotConvertException = exception as? CannotConvertException)
try {
ApplicationManager.getApplication().messageBus.syncPublisher(AppLifecycleListener.TOPIC).projectOpenFailed()
}
catch (secondException: Throwable) {
LOG.error(secondException)
}
if (options.showWelcomeScreen) {
WelcomeFrame.showIfNoProjectOpened()
}
}
override fun newProject(file: Path, options: OpenProjectTask): Project? {
removeProjectConfigurationAndCaches(file)
val project = instantiateProject(file, options)
try {
val template = if (options.useDefaultProjectAsTemplate) defaultProject else null
@Suppress("DEPRECATION")
runUnderModalProgressIfIsEdt {
initProject(
file = file,
project = project,
isRefreshVfsNeeded = options.isRefreshVfsNeeded,
preloadServices = options.preloadServices,
template = template,
isTrustCheckNeeded = false,
)
}
project.setTrusted(true)
return project
}
catch (t: Throwable) {
handleErrorOnNewProject(t)
return null
}
}
override suspend fun newProjectAsync(file: Path, options: OpenProjectTask): Project {
withContext(Dispatchers.IO) {
removeProjectConfigurationAndCaches(file)
}
val project = instantiateProject(file, options)
initProject(
file = file,
project = project,
isRefreshVfsNeeded = options.isRefreshVfsNeeded,
preloadServices = options.preloadServices,
template = if (options.useDefaultProjectAsTemplate) defaultProject else null,
isTrustCheckNeeded = false,
)
project.setTrusted(true)
return project
}
protected open fun handleErrorOnNewProject(t: Throwable) {
LOG.warn(t)
try {
val errorMessage = message(t)
ApplicationManager.getApplication().invokeAndWait {
Messages.showErrorDialog(errorMessage, ProjectBundle.message("project.load.default.error"))
}
}
catch (e: NoClassDefFoundError) {
// error icon not loaded
LOG.info(e)
}
}
protected open fun instantiateProject(projectStoreBaseDir: Path, options: OpenProjectTask): ProjectImpl {
val activity = StartUpMeasurer.startActivity("project instantiation")
val project = ProjectImpl(filePath = projectStoreBaseDir, projectName = options.projectName)
activity.end()
options.beforeInit?.invoke(project)
return project
}
private suspend fun prepareNewProject(options: OpenProjectTask, projectStoreBaseDir: Path, saveTemplateJob: Job?): Project {
withContext(Dispatchers.IO) {
removeProjectConfigurationAndCaches(projectStoreBaseDir)
}
val project = instantiateProject(projectStoreBaseDir, options)
saveTemplateJob?.join()
val template = if (options.useDefaultProjectAsTemplate) defaultProject else null
initProject(file = projectStoreBaseDir,
project = project,
isRefreshVfsNeeded = options.isRefreshVfsNeeded,
preloadServices = options.preloadServices,
template = template,
isTrustCheckNeeded = false)
project.putUserData(PlatformProjectOpenProcessor.PROJECT_NEWLY_OPENED, true)
return project
}
private suspend fun prepareProject(options: OpenProjectTask,
projectStoreBaseDir: Path,
initFrame: ((project: Project) -> Unit)?): Project {
var conversionResult: ConversionResult? = null
if (options.runConversionBeforeOpen) {
val conversionService = ConversionService.getInstance()
if (conversionService != null) {
conversionResult = runActivity("project conversion") {
conversionService.convert(projectStoreBaseDir)
}
if (conversionResult.openingIsCanceled()) {
throw CancellationException("ConversionResult.openingIsCanceled() returned true")
}
}
}
val project = instantiateProject(projectStoreBaseDir, options)
// template as null here because it is not a new project
initProject(file = projectStoreBaseDir,
project = project,
isRefreshVfsNeeded = options.isRefreshVfsNeeded,
preloadServices = options.preloadServices,
template = null,
initFrame = initFrame,
isTrustCheckNeeded = true)
if (conversionResult != null && !conversionResult.conversionNotNeeded()) {
StartupManager.getInstance(project).runAfterOpened {
conversionResult.postStartupActivity(project)
}
}
return project
}
protected open fun isRunStartUpActivitiesEnabled(project: Project): Boolean = true
private suspend fun checkExistingProjectOnOpen(projectToClose: Project, options: OpenProjectTask, projectDir: Path?): Boolean {
val isValidProject = projectDir != null && ProjectUtilCore.isValidProjectPath(projectDir)
if (projectDir != null && ProjectAttachProcessor.canAttachToProject() &&
(!isValidProject || GeneralSettings.getInstance().confirmOpenNewProject == GeneralSettings.OPEN_PROJECT_ASK)) {
when (withContext(Dispatchers.EDT) { ProjectUtil.confirmOpenOrAttachProject() }) {
-1 -> {
return true
}
GeneralSettings.OPEN_PROJECT_SAME_WINDOW -> {
if (!closeAndDisposeKeepingFrame(projectToClose)) {
return true
}
}
GeneralSettings.OPEN_PROJECT_SAME_WINDOW_ATTACH -> {
if (withContext(Dispatchers.EDT) { PlatformProjectOpenProcessor.attachToProject(projectToClose, projectDir, options.callback) }) {
return true
}
}
}
}
else {
val mode = GeneralSettings.getInstance().confirmOpenNewProject
if (mode == GeneralSettings.OPEN_PROJECT_SAME_WINDOW_ATTACH && projectDir != null &&
withContext(Dispatchers.EDT) { PlatformProjectOpenProcessor.attachToProject(projectToClose, projectDir, options.callback) }) {
return true
}
val projectNameValue = options.projectName ?: projectDir?.fileName?.toString() ?: projectDir?.toString()
val exitCode = confirmOpenNewProject(options.copy(projectName = projectNameValue))
if (exitCode == GeneralSettings.OPEN_PROJECT_SAME_WINDOW) {
if (!closeAndDisposeKeepingFrame(projectToClose)) {
return true
}
}
else if (exitCode != GeneralSettings.OPEN_PROJECT_NEW_WINDOW) {
// not in a new window
return true
}
}
return false
}
private suspend fun closeAndDisposeKeepingFrame(project: Project): Boolean {
return withContext(Dispatchers.EDT) {
(WindowManager.getInstance() as WindowManagerImpl).withFrameReuseEnabled().use {
closeProject(project, checkCanClose = true)
}
}
}
}
private val tracer by lazy { TraceManager.getTracer("projectManager") }
@NlsSafe
private fun message(e: Throwable): String {
var message = e.message ?: e.localizedMessage
if (message != null) {
return message
}
message = e.toString()
return "$message (cause: ${message(e.cause ?: return message)})"
}
@Internal
@VisibleForTesting
fun CoroutineScope.runInitProjectActivities(project: Project) {
launch {
(StartupManager.getInstance(project) as StartupManagerImpl).initProject()
}
val waitEdtActivity = StartUpMeasurer.startActivity("placing calling projectOpened on event queue")
launchAndMeasure("projectOpened event executing", Dispatchers.EDT) {
waitEdtActivity.end()
tracer.spanBuilder("projectOpened event executing").useWithScope2 {
@Suppress("DEPRECATION", "removal")
ApplicationManager.getApplication().messageBus.syncPublisher(ProjectManager.TOPIC).projectOpened(project)
}
}
@Suppress("DEPRECATION")
val projectComponents = (project as ComponentManagerImpl)
.collectInitializedComponents(com.intellij.openapi.components.ProjectComponent::class.java)
if (projectComponents.isEmpty()) {
return
}
launchAndMeasure("projectOpened component executing", Dispatchers.EDT) {
for (component in projectComponents) {
try {
val componentActivity = StartUpMeasurer.startActivity(component.javaClass.name, ActivityCategory.PROJECT_OPEN_HANDLER)
component.projectOpened()
componentActivity.end()
}
catch (e: CancellationException) {
throw e
}
catch (e: ProcessCanceledException) {
throw e
}
catch (e: Throwable) {
LOG.error(e)
}
}
}
}
private val LOG = logger<ProjectManagerImpl>()
private val LISTENERS_IN_PROJECT_KEY = Key.create<MutableList<ProjectManagerListener>>("LISTENERS_IN_PROJECT_KEY")
private val CLOSE_HANDLER_EP = ExtensionPointName<ProjectCloseHandler>("com.intellij.projectCloseHandler")
private fun getListeners(project: Project): List<ProjectManagerListener> {
return project.getUserData(LISTENERS_IN_PROJECT_KEY) ?: return emptyList()
}
private val publisher: ProjectManagerListener
get() = ApplicationManager.getApplication().messageBus.syncPublisher(ProjectManager.TOPIC)
private val closePublisher: ProjectCloseListener
get() = ApplicationManager.getApplication().messageBus.syncPublisher(ProjectCloseListener.TOPIC)
private fun handleListenerError(e: Throwable, listener: ProjectManagerListener) {
if (e is ProcessCanceledException || e is CancellationException) {
throw e
}
else {
LOG.error("From the listener $listener (${listener.javaClass})", e)
}
}
private fun fireProjectClosing(project: Project) {
if (LOG.isDebugEnabled) {
LOG.debug("enter: fireProjectClosing()")
}
try {
closePublisher.projectClosing(project)
publisher.projectClosing(project)
}
catch (e: Throwable) {
LOG.warn("Failed to publish projectClosing(project) event", e)
}
}
private fun fireProjectClosed(project: Project) {
if (LOG.isDebugEnabled) {
LOG.debug("projectClosed")
}
LifecycleUsageTriggerCollector.onProjectClosed(project)
closePublisher.projectClosed(project)
publisher.projectClosed(project)
@Suppress("DEPRECATION")
val projectComponents = (project as ComponentManagerImpl)
.collectInitializedComponents(com.intellij.openapi.components.ProjectComponent::class.java)
// see "why is called after message bus" in the fireProjectOpened
for (i in projectComponents.indices.reversed()) {
val component = projectComponents.get(i)
try {
component.projectClosed()
}
catch (e: Throwable) {
LOG.error(component.toString(), e)
}
}
}
private fun ensureCouldCloseIfUnableToSave(project: Project): Boolean {
val notificationManager = ApplicationManager.getApplication().getServiceIfCreated(NotificationsManager::class.java) ?: return true
val notifications = notificationManager.getNotificationsOfType(UnableToSaveProjectNotification::class.java, project)
if (notifications.isEmpty()) {
return true
}
val message: @NlsContexts.DialogMessage StringBuilder = StringBuilder()
message.append("${ApplicationNamesInfo.getInstance().productName} was unable to save some project files," +
"\nare you sure you want to close this project anyway?")
message.append("\n\nRead-only files:\n")
var count = 0
val files = notifications.first().files
for (file in files) {
if (count == 10) {
message.append('\n').append("and ").append(files.size - count).append(" more").append('\n')
}
else {
message.append(file.path).append('\n')
count++
}
}
@Suppress("HardCodedStringLiteral")
return Messages.showYesNoDialog(project, message.toString(),
IdeUICustomization.getInstance().projectMessage("dialog.title.unsaved.project"),
Messages.getWarningIcon()) == Messages.YES
}
class UnableToSaveProjectNotification(project: Project, readOnlyFiles: List<VirtualFile>) : Notification("Project Settings",
IdeUICustomization.getInstance().projectMessage(
"notification.title.cannot.save.project"),
IdeBundle.message(
"notification.content.unable.to.save.project.files"),
NotificationType.ERROR) {
private var project: Project?
var files: List<VirtualFile>
init {
@Suppress("DEPRECATION")
setListener { notification, _ ->
val unableToSaveProjectNotification = notification as UnableToSaveProjectNotification
val p = unableToSaveProjectNotification.project
notification.expire()
if (p != null && !p.isDisposed) {
p.save()
}
}
this.project = project
files = readOnlyFiles
}
override fun expire() {
project = null
super.expire()
}
}
private fun toCanonicalName(filePath: String): Path {
val file = Path.of(filePath)
try {
if (SystemInfoRt.isWindows && FileUtil.containsWindowsShortName(filePath)) {
return file.toRealPath(LinkOption.NOFOLLOW_LINKS)
}
}
catch (ignore: InvalidPathException) {
}
catch (e: IOException) {
// OK. File does not yet exist, so its canonical path will be equal to its original path.
}
return file
}
private fun removeProjectConfigurationAndCaches(projectFile: Path) {
try {
if (Files.isRegularFile(projectFile)) {
Files.deleteIfExists(projectFile)
}
else {
Files.newDirectoryStream(projectFile.resolve(Project.DIRECTORY_STORE_FOLDER)).use { directoryStream ->
for (file in directoryStream) {
file!!.delete()
}
}
}
}
catch (ignored: IOException) {
}
try {
getProjectDataPathRoot(projectFile).delete()
}
catch (ignored: IOException) {
}
}
/**
* Checks if the project was trusted using the previous API.
* Migrates the setting to the new API, shows the Trust Project dialog if needed.
*
* @return true if we should proceed with project opening, false if the process of project opening should be canceled.
*/
private suspend fun checkOldTrustedStateAndMigrate(project: Project, projectStoreBaseDir: Path): Boolean {
val trustedPaths = TrustedPaths.getInstance()
val trustedState = trustedPaths.getProjectPathTrustedState(projectStoreBaseDir)
if (trustedState != ThreeState.UNSURE) {
return true
}
@Suppress("DEPRECATION")
val previousTrustedState = project.service<TrustedProjectSettings>().trustedState
if (previousTrustedState != ThreeState.UNSURE) {
// we were asking about this project in the previous IDE version => migrate
trustedPaths.setProjectPathTrusted(projectStoreBaseDir, previousTrustedState.toBoolean())
return true
}
return confirmOpeningAndSetProjectTrustedStateIfNeeded(projectStoreBaseDir)
}
private suspend fun initProject(file: Path,
project: ProjectImpl,
isRefreshVfsNeeded: Boolean,
preloadServices: Boolean,
template: Project?,
isTrustCheckNeeded: Boolean,
initFrame: ((project: Project) -> Unit)? = null) {
LOG.assertTrue(!project.isDefault)
try {
coroutineContext.ensureActive()
val registerComponentsActivity = createActivity(project) { "project ${StartUpMeasurer.Activities.REGISTER_COMPONENTS_SUFFIX}" }
project.registerComponents()
registerComponentsActivity?.end()
if (ApplicationManager.getApplication().isUnitTestMode) {
@Suppress("TestOnlyProblems")
for (listener in ProjectServiceContainerCustomizer.getEp().extensionList) {
listener.serviceRegistered(project)
}
}
coroutineContext.ensureActive()
project.componentStore.setPath(file, isRefreshVfsNeeded, template)
coroutineScope {
val isTrusted = async { !isTrustCheckNeeded || checkOldTrustedStateAndMigrate(project, file) }
projectInitListeners {
it.execute(project)
}
// yes, before preloadServicesAndCreateComponents
initFrame?.invoke(project)
preloadServicesAndCreateComponents(project, preloadServices)
if (!isTrusted.await()) {
throw CancellationException("not trusted")
}
}
}
catch (initThrowable: Throwable) {
try {
withContext(NonCancellable) {
project.coroutineScope.coroutineContext.job.cancelAndJoin()
writeAction {
Disposer.dispose(project)
}
}
}
catch (disposeThrowable: Throwable) {
initThrowable.addSuppressed(disposeThrowable)
}
throw initThrowable
}
}
@Suppress("DuplicatedCode")
private suspend fun confirmOpenNewProject(options: OpenProjectTask): Int {
if (ApplicationManager.getApplication().isUnitTestMode) {
return GeneralSettings.OPEN_PROJECT_NEW_WINDOW
}
var mode = GeneralSettings.getInstance().confirmOpenNewProject
if (mode == GeneralSettings.OPEN_PROJECT_ASK) {
val message = if (options.projectName == null) {
IdeBundle.message("prompt.open.project.in.new.frame")
}
else {
IdeBundle.message("prompt.open.project.with.name.in.new.frame", options.projectName)
}
val openInExistingFrame = withContext(Dispatchers.EDT) {
if (options.isNewProject)
MessageDialogBuilder.yesNoCancel(IdeUICustomization.getInstance().projectMessage("title.new.project"), message)
.yesText(IdeBundle.message("button.existing.frame"))
.noText(IdeBundle.message("button.new.frame"))
.doNotAsk(ProjectNewWindowDoNotAskOption())
.guessWindowAndAsk()
else
MessageDialogBuilder.yesNoCancel(IdeUICustomization.getInstance().projectMessage("title.open.project"), message)
.yesText(IdeBundle.message("button.existing.frame"))
.noText(IdeBundle.message("button.new.frame"))
.doNotAsk(ProjectNewWindowDoNotAskOption())
.guessWindowAndAsk()
}
mode = when (openInExistingFrame) {
Messages.YES -> GeneralSettings.OPEN_PROJECT_SAME_WINDOW
Messages.NO -> GeneralSettings.OPEN_PROJECT_NEW_WINDOW
else -> Messages.CANCEL
}
if (mode != Messages.CANCEL) {
LifecycleUsageTriggerCollector.onProjectFrameSelected(mode)
}
}
return mode
}
private inline fun createActivity(project: ProjectImpl, message: () -> String): Activity? {
return if (!StartUpMeasurer.isEnabled() || project.isDefault) null else StartUpMeasurer.startActivity(message(), ActivityCategory.DEFAULT)
}
internal suspend inline fun projectInitListeners(crossinline executor: suspend (ProjectServiceContainerInitializedListener) -> Unit) {
val extensionArea = ApplicationManager.getApplication().extensionArea as ExtensionsAreaImpl
val ep = extensionArea
.getExtensionPoint<ProjectServiceContainerInitializedListener>("com.intellij.projectServiceContainerInitializedListener")
for (adapter in ep.sortedAdapters) {
val pluginDescriptor = adapter.pluginDescriptor
if (!isCorePlugin(pluginDescriptor)) {
LOG.error(PluginException("Plugin $pluginDescriptor is not approved to add ${ep.name}", pluginDescriptor.pluginId))
continue
}
try {
executor(adapter.createInstance(ep.componentManager) ?: continue)
}
catch (e: CancellationException) {
throw e
}
catch (e: Throwable) {
LOG.error(e)
}
}
}
internal fun isCorePlugin(descriptor: PluginDescriptor): Boolean {
val id = descriptor.pluginId
return id == PluginManagerCore.CORE_ID ||
// K/N Platform Deps is a repackaged Java plugin
id.idString == "com.intellij.kotlinNative.platformDeps"
}
/**
* Usage requires IJ Platform team approval (including plugin into white-list).
*/
@Internal
interface ProjectServiceContainerInitializedListener {
/**
* Invoked after container configured.
*/
suspend fun execute(project: Project)
}
@TestOnly
interface ProjectServiceContainerCustomizer {
companion object {
@TestOnly
fun getEp(): ExtensionPointImpl<ProjectServiceContainerCustomizer> {
return (ApplicationManager.getApplication().extensionArea as ExtensionsAreaImpl)
.getExtensionPoint("com.intellij.projectServiceContainerCustomizer")
}
}
/**
* Invoked after implementation classes for project's components were determined (and loaded),
* but before components are instantiated.
*/
fun serviceRegistered(project: Project)
}
private fun readOneLine(file: Path) = Files.newBufferedReader(file).use { it.readLine().trim() }
private fun copyLineFromFileToNewSystemDir(fileName: String, systemDir: Path) {
val line = readOneLine(PathManager.getSystemDir().resolve(fileName))
val newPath = systemDir.resolve(fileName)
File(newPath.parent.toUri()).mkdirs()
Files.write(newPath, line.toByteArray(StandardCharsets.UTF_8))
}
// TODO actual FileLocks?
private fun lockPerProjectDirForProject(
systemDir: Path,
) {
// copy current token
copyLineFromFileToNewSystemDir(SpecialConfigFiles.TOKEN_FILE, systemDir)
// copy current port
copyLineFromFileToNewSystemDir(SpecialConfigFiles.PORT_FILE, systemDir)
PathManager.lockPerProjectPath(systemDir)
}
private fun deleteFileFromNewSystemDir(fileName: String, systemDir: Path) {
val filePath = systemDir.resolve(fileName)
if (filePath.exists()) Files.delete(filePath)
}
// TODO actual FileLocks?
private fun clearPerProjectDirsForProject(
systemDir: Path,
) {
PathManager.unlockPerProjectPath(systemDir)
// delete current token
deleteFileFromNewSystemDir(SpecialConfigFiles.TOKEN_FILE, systemDir)
// delete current port
deleteFileFromNewSystemDir(SpecialConfigFiles.PORT_FILE, systemDir)
}
/**
* Checks if the project path is trusted, and shows the Trust Project dialog if needed.
*
* @return true if we should proceed with project opening, false if the process of project opening should be canceled.
*/
private suspend fun checkTrustedState(projectStoreBaseDir: Path): Boolean {
val trustedState = TrustedPaths.getInstance().getProjectPathTrustedState(projectStoreBaseDir)
if (trustedState != ThreeState.UNSURE) {
// the trusted state of this project path is already known => proceed with opening
return true
}
if (isProjectImplicitlyTrusted(projectStoreBaseDir)) {
return true
}
// check if the project trusted state could be known from the previous IDE version
val metaInfo = RecentProjectsManagerBase.getInstanceEx().getProjectMetaInfo(projectStoreBaseDir)
val projectId = metaInfo?.projectWorkspaceId
val productWorkspaceFile = PathManager.getConfigDir().resolve("workspace").resolve("$projectId.xml")
if (projectId != null && Files.exists(productWorkspaceFile)) {
// this project is in recent projects => it was opened on this computer before
// => most probably we already asked about its trusted state before
// the only exception is: the project stayed in the UNKNOWN state in the previous version because it didn't utilize any dangerous features
// in this case we will ask since no UNKNOWN state is allowed, but on a later stage, when we'll be able to look into the project-wide storage
return true
}
return confirmOpeningAndSetProjectTrustedStateIfNeeded(projectStoreBaseDir)
}
private suspend fun openInChildProcess(projectStoreBaseDir: Path) {
try {
withContext(Dispatchers.IO) {
ProcessBuilder(openProjectInstanceCommand(projectStoreBaseDir))
.redirectErrorStream(true)
.redirectOutput(ProcessBuilder.Redirect.appendTo(PathManager.getLogDir().resolve("idea.log").toFile()))
.start()
.also {
LOG.info("Child process started, PID: ${it.pid()}")
}
}
}
catch (e: CancellationException) {
throw e
}
catch (e: Exception) {
LOG.error(e)
}
}
private fun toPerProjectDir(path: Path, projectStoreBaseDir: Path): Path {
val projectStoreBaseDirRelative = Paths.get("/").relativize(projectStoreBaseDir)
return path / PER_PROJECT_SUFFIX / projectStoreBaseDirRelative
}
private fun removePerProjectSuffix(path: Path, currentProjectBaseDir: Path): Path {
val projectStoreBaseDirRelative = Paths.get("/").relativize(currentProjectBaseDir)
val suffix = PER_PROJECT_SUFFIX + File.separator + projectStoreBaseDirRelative
return canonicalPath(path.toString().removeSuffix(suffix))
}
private fun openProjectInstanceCommand(projectStoreBaseDir: Path): List<String> {
return listOf(
"open",
"-n",
Restarter.getIdeStarter().toString(),
"--args",
*(mapOf(
PathManager.PROPERTY_SYSTEM_PATH to PathManager.getSystemDir(),
PathManager.PROPERTY_CONFIG_PATH to PathManager.getConfigDir(),
PathManager.PROPERTY_LOG_PATH to PathManager.getLogDir(),
PathManager.PROPERTY_PLUGINS_PATH to PathManager.getPluginsDir(),
).mapValuesTo(mutableMapOf()) { (key, value) ->
val currentProjectBaseDir = Paths.get(ProjectManagerEx.getOpenProjects().first().basePath ?: "")
val baseDir = if (IS_CHILD_PROCESS) removePerProjectSuffix(value, currentProjectBaseDir) else value
"-D$key=${toPerProjectDir(baseDir, projectStoreBaseDir)}"
}.values.toTypedArray()
),
//for (vmOption in VMOptions.readOptions("", true)) {
// command += vmOption.asPatchedAgentLibOption()
// ?: vmOption.asPatchedVMOption("splash", "false")
// ?: vmOption.asPatchedVMOption("nosplash", "true")
// ?: vmOption.asPatchedVMOption(ConfigImportHelper.SHOW_IMPORT_CONFIG_DIALOG_PROPERTY, "default-production")
// ?: customProperties.keys.firstOrNull { vmOption.isVMOption(it) }?.let { customProperties.remove(it) }
// ?: vmOption
//}
projectStoreBaseDir.toString(),
)
} | apache-2.0 | b9bb259f7a6481386fec43f284d5b37f | 35.833799 | 160 | 0.700502 | 5.175137 | false | false | false | false |
square/okhttp | okhttp/src/jvmMain/kotlin/okhttp3/internal/connection/RealConnection.kt | 3 | 14275 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp3.internal.connection
import java.io.IOException
import java.lang.ref.Reference
import java.net.Proxy
import java.net.Socket
import java.net.SocketException
import java.security.cert.X509Certificate
import java.util.concurrent.TimeUnit.MILLISECONDS
import javax.net.ssl.SSLPeerUnverifiedException
import javax.net.ssl.SSLSocket
import okhttp3.Address
import okhttp3.Connection
import okhttp3.Handshake
import okhttp3.HttpUrl
import okhttp3.OkHttpClient
import okhttp3.Protocol
import okhttp3.Route
import okhttp3.internal.assertThreadDoesntHoldLock
import okhttp3.internal.assertThreadHoldsLock
import okhttp3.internal.closeQuietly
import okhttp3.internal.concurrent.TaskRunner
import okhttp3.internal.http.ExchangeCodec
import okhttp3.internal.http.RealInterceptorChain
import okhttp3.internal.http1.Http1ExchangeCodec
import okhttp3.internal.http2.ConnectionShutdownException
import okhttp3.internal.http2.ErrorCode
import okhttp3.internal.http2.Http2Connection
import okhttp3.internal.http2.Http2ExchangeCodec
import okhttp3.internal.http2.Http2Stream
import okhttp3.internal.http2.Settings
import okhttp3.internal.http2.StreamResetException
import okhttp3.internal.isHealthy
import okhttp3.internal.tls.OkHostnameVerifier
import okhttp3.internal.ws.RealWebSocket
import okio.BufferedSink
import okio.BufferedSource
/**
* A connection to a remote web server capable of carrying 1 or more concurrent streams.
*
* Connections are shared in a connection pool. Accesses to the connection's state must be guarded
* by holding a lock on the connection.
*/
class RealConnection(
val taskRunner: TaskRunner,
val connectionPool: RealConnectionPool,
override val route: Route,
/** The low-level TCP socket. */
private var rawSocket: Socket?,
/**
* The application layer socket. Either an [SSLSocket] layered over [rawSocket], or [rawSocket]
* itself if this connection does not use SSL.
*/
private var socket: Socket?,
private var handshake: Handshake?,
private var protocol: Protocol?,
private var source: BufferedSource?,
private var sink: BufferedSink?,
private val pingIntervalMillis: Int,
) : Http2Connection.Listener(), Connection, ExchangeCodec.Carrier {
private var http2Connection: Http2Connection? = null
// These properties are guarded by this.
/**
* If true, no new exchanges can be created on this connection. It is necessary to set this to
* true when removing a connection from the pool; otherwise a racing caller might get it from the
* pool when it shouldn't. Symmetrically, this must always be checked before returning a
* connection from the pool.
*
* Once true this is always true. Guarded by this.
*/
var noNewExchanges = false
/**
* If true, this connection may not be used for coalesced requests. These are requests that could
* share the same connection without sharing the same hostname.
*/
private var noCoalescedConnections = false
/**
* The number of times there was a problem establishing a stream that could be due to route
* chosen. Guarded by this.
*/
internal var routeFailureCount = 0
private var successCount = 0
private var refusedStreamCount = 0
/**
* The maximum number of concurrent streams that can be carried by this connection. If
* `allocations.size() < allocationLimit` then new streams can be created on this connection.
*/
private var allocationLimit = 1
/** Current calls carried by this connection. */
val calls = mutableListOf<Reference<RealCall>>()
/** Timestamp when `allocations.size()` reached zero. Also assigned upon initial connection. */
var idleAtNs = Long.MAX_VALUE
/**
* Returns true if this is an HTTP/2 connection. Such connections can be used in multiple HTTP
* requests simultaneously.
*/
internal val isMultiplexed: Boolean
get() = http2Connection != null
/** Prevent further exchanges from being created on this connection. */
@Synchronized override fun noNewExchanges() {
noNewExchanges = true
}
/** Prevent this connection from being used for hosts other than the one in [route]. */
@Synchronized internal fun noCoalescedConnections() {
noCoalescedConnections = true
}
@Synchronized internal fun incrementSuccessCount() {
successCount++
}
@Throws(IOException::class)
fun start() {
idleAtNs = System.nanoTime()
if (protocol == Protocol.HTTP_2 || protocol == Protocol.H2_PRIOR_KNOWLEDGE) {
startHttp2()
}
}
@Throws(IOException::class)
private fun startHttp2() {
val socket = this.socket!!
val source = this.source!!
val sink = this.sink!!
socket.soTimeout = 0 // HTTP/2 connection timeouts are set per-stream.
val http2Connection = Http2Connection.Builder(client = true, taskRunner)
.socket(socket, route.address.url.host, source, sink)
.listener(this)
.pingIntervalMillis(pingIntervalMillis)
.build()
this.http2Connection = http2Connection
this.allocationLimit = Http2Connection.DEFAULT_SETTINGS.getMaxConcurrentStreams()
http2Connection.start()
}
/**
* Returns true if this connection can carry a stream allocation to `address`. If non-null
* `route` is the resolved route for a connection.
*/
internal fun isEligible(address: Address, routes: List<Route>?): Boolean {
assertThreadHoldsLock()
// If this connection is not accepting new exchanges, we're done.
if (calls.size >= allocationLimit || noNewExchanges) return false
// If the non-host fields of the address don't overlap, we're done.
if (!this.route.address.equalsNonHost(address)) return false
// If the host exactly matches, we're done: this connection can carry the address.
if (address.url.host == this.route().address.url.host) {
return true // This connection is a perfect match.
}
// At this point we don't have a hostname match. But we still be able to carry the request if
// our connection coalescing requirements are met. See also:
// https://hpbn.co/optimizing-application-delivery/#eliminate-domain-sharding
// https://daniel.haxx.se/blog/2016/08/18/http2-connection-coalescing/
// 1. This connection must be HTTP/2.
if (http2Connection == null) return false
// 2. The routes must share an IP address.
if (routes == null || !routeMatchesAny(routes)) return false
// 3. This connection's server certificate's must cover the new host.
if (address.hostnameVerifier !== OkHostnameVerifier) return false
if (!supportsUrl(address.url)) return false
// 4. Certificate pinning must match the host.
try {
address.certificatePinner!!.check(address.url.host, handshake()!!.peerCertificates)
} catch (_: SSLPeerUnverifiedException) {
return false
}
return true // The caller's address can be carried by this connection.
}
/**
* Returns true if this connection's route has the same address as any of [candidates]. This
* requires us to have a DNS address for both hosts, which only happens after route planning. We
* can't coalesce connections that use a proxy, since proxies don't tell us the origin server's IP
* address.
*/
private fun routeMatchesAny(candidates: List<Route>): Boolean {
return candidates.any {
it.proxy.type() == Proxy.Type.DIRECT &&
route.proxy.type() == Proxy.Type.DIRECT &&
route.socketAddress == it.socketAddress
}
}
private fun supportsUrl(url: HttpUrl): Boolean {
assertThreadHoldsLock()
val routeUrl = route.address.url
if (url.port != routeUrl.port) {
return false // Port mismatch.
}
if (url.host == routeUrl.host) {
return true // Host match. The URL is supported.
}
// We have a host mismatch. But if the certificate matches, we're still good.
return !noCoalescedConnections && handshake != null && certificateSupportHost(url, handshake!!)
}
private fun certificateSupportHost(url: HttpUrl, handshake: Handshake): Boolean {
val peerCertificates = handshake.peerCertificates
return peerCertificates.isNotEmpty() &&
OkHostnameVerifier.verify(url.host, peerCertificates[0] as X509Certificate)
}
@Throws(SocketException::class)
internal fun newCodec(client: OkHttpClient, chain: RealInterceptorChain): ExchangeCodec {
val socket = this.socket!!
val source = this.source!!
val sink = this.sink!!
val http2Connection = this.http2Connection
return if (http2Connection != null) {
Http2ExchangeCodec(client, this, chain, http2Connection)
} else {
socket.soTimeout = chain.readTimeoutMillis()
source.timeout().timeout(chain.readTimeoutMillis.toLong(), MILLISECONDS)
sink.timeout().timeout(chain.writeTimeoutMillis.toLong(), MILLISECONDS)
Http1ExchangeCodec(client, this, source, sink)
}
}
@Throws(SocketException::class)
internal fun newWebSocketStreams(exchange: Exchange): RealWebSocket.Streams {
val socket = this.socket!!
val source = this.source!!
val sink = this.sink!!
socket.soTimeout = 0
noNewExchanges()
return object : RealWebSocket.Streams(true, source, sink) {
override fun close() {
exchange.bodyComplete<IOException?>(-1L, responseDone = true, requestDone = true, e = null)
}
}
}
override fun route(): Route = route
override fun cancel() {
// Close the raw socket so we don't end up doing synchronous I/O.
rawSocket?.closeQuietly()
}
override fun socket(): Socket = socket!!
/** Returns true if this connection is ready to host new streams. */
fun isHealthy(doExtensiveChecks: Boolean): Boolean {
assertThreadDoesntHoldLock()
val nowNs = System.nanoTime()
val rawSocket = this.rawSocket!!
val socket = this.socket!!
val source = this.source!!
if (rawSocket.isClosed || socket.isClosed || socket.isInputShutdown ||
socket.isOutputShutdown) {
return false
}
val http2Connection = this.http2Connection
if (http2Connection != null) {
return http2Connection.isHealthy(nowNs)
}
val idleDurationNs = synchronized(this) { nowNs - idleAtNs }
if (idleDurationNs >= IDLE_CONNECTION_HEALTHY_NS && doExtensiveChecks) {
return socket.isHealthy(source)
}
return true
}
/** Refuse incoming streams. */
@Throws(IOException::class)
override fun onStream(stream: Http2Stream) {
stream.close(ErrorCode.REFUSED_STREAM, null)
}
/** When settings are received, adjust the allocation limit. */
@Synchronized override fun onSettings(connection: Http2Connection, settings: Settings) {
allocationLimit = settings.getMaxConcurrentStreams()
}
override fun handshake(): Handshake? = handshake
/** Track a bad route in the route database. Other routes will be attempted first. */
internal fun connectFailed(client: OkHttpClient, failedRoute: Route, failure: IOException) {
// Tell the proxy selector when we fail to connect on a fresh connection.
if (failedRoute.proxy.type() != Proxy.Type.DIRECT) {
val address = failedRoute.address
address.proxySelector.connectFailed(
address.url.toUri(), failedRoute.proxy.address(), failure
)
}
client.routeDatabase.failed(failedRoute)
}
/**
* Track a failure using this connection. This may prevent both the connection and its route from
* being used for future exchanges.
*/
@Synchronized override fun trackFailure(call: RealCall, e: IOException?) {
if (e is StreamResetException) {
when {
e.errorCode == ErrorCode.REFUSED_STREAM -> {
// Stop using this connection on the 2nd REFUSED_STREAM error.
refusedStreamCount++
if (refusedStreamCount > 1) {
noNewExchanges = true
routeFailureCount++
}
}
e.errorCode == ErrorCode.CANCEL && call.isCanceled() -> {
// Permit any number of CANCEL errors on locally-canceled calls.
}
else -> {
// Everything else wants a fresh connection.
noNewExchanges = true
routeFailureCount++
}
}
} else if (!isMultiplexed || e is ConnectionShutdownException) {
noNewExchanges = true
// If this route hasn't completed a call, avoid it for new connections.
if (successCount == 0) {
if (e != null) {
connectFailed(call.client, route, e)
}
routeFailureCount++
}
}
}
override fun protocol(): Protocol = protocol!!
override fun toString(): String {
return "Connection{${route.address.url.host}:${route.address.url.port}," +
" proxy=${route.proxy}" +
" hostAddress=${route.socketAddress}" +
" cipherSuite=${handshake?.cipherSuite ?: "none"}" +
" protocol=$protocol}"
}
companion object {
const val IDLE_CONNECTION_HEALTHY_NS = 10_000_000_000 // 10 seconds.
fun newTestConnection(
taskRunner: TaskRunner,
connectionPool: RealConnectionPool,
route: Route,
socket: Socket,
idleAtNs: Long
): RealConnection {
val result = RealConnection(
taskRunner = taskRunner,
connectionPool = connectionPool,
route = route,
rawSocket = null,
socket = socket,
handshake = null,
protocol = null,
source = null,
sink = null,
pingIntervalMillis = 0,
)
result.idleAtNs = idleAtNs
return result
}
}
}
| apache-2.0 | e753ee10f0fcfefa5cd57b15040bab25 | 33.314904 | 100 | 0.704098 | 4.341545 | false | false | false | false |
StepicOrg/stepik-android | app/src/main/java/org/stepik/android/view/course_revenue/ui/adapter/delegate/CourseBenefitsAdapterDelegate.kt | 1 | 5702 | package org.stepik.android.view.course_revenue.ui.adapter.delegate
import android.graphics.PorterDuff
import android.graphics.drawable.Drawable
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.content.res.AppCompatResources
import androidx.core.content.ContextCompat
import androidx.core.graphics.drawable.DrawableCompat
import androidx.core.view.isVisible
import kotlinx.android.extensions.LayoutContainer
import kotlinx.android.synthetic.main.item_course_benefit.*
import org.stepic.droid.R
import org.stepic.droid.util.DateTimeHelper
import org.stepik.android.domain.course_revenue.model.CourseBenefit
import org.stepik.android.domain.course_revenue.model.CourseBenefitListItem
import org.stepik.android.view.course_revenue.mapper.RevenuePriceMapper
import ru.nobird.android.ui.adapterdelegates.AdapterDelegate
import ru.nobird.android.ui.adapterdelegates.DelegateViewHolder
import java.text.DecimalFormat
import java.util.Currency
import java.util.TimeZone
class CourseBenefitsAdapterDelegate(
private val revenuePriceMapper: RevenuePriceMapper,
private val onItemClick: (CourseBenefitListItem.Data) -> Unit
) : AdapterDelegate<CourseBenefitListItem, DelegateViewHolder<CourseBenefitListItem>>() {
override fun isForViewType(position: Int, data: CourseBenefitListItem): Boolean =
data is CourseBenefitListItem.Data
override fun onCreateViewHolder(parent: ViewGroup): DelegateViewHolder<CourseBenefitListItem> =
ViewHolder(createView(parent, R.layout.item_course_benefit))
private inner class ViewHolder(
override val containerView: View
) : DelegateViewHolder<CourseBenefitListItem>(containerView), LayoutContainer {
init {
itemView.setOnClickListener { (itemData as? CourseBenefitListItem.Data)?.let { onItemClick(it) } }
}
override fun onBind(data: CourseBenefitListItem) {
data as CourseBenefitListItem.Data
val currency = Currency.getInstance(data.courseBenefit.currencyCode)
val decimalFormat = DecimalFormat().apply { setCurrency(currency) }
decimalFormat.minimumFractionDigits = 2
purchaseRefundIcon.setImageDrawable(getIconDrawable(data.courseBenefit))
purchaseRefundName.text =
if (data.courseBenefit.buyer == null && !data.courseBenefit.isInvoicePayment) {
buildString {
append(context.getString(R.string.transaction_manual_channel))
if (data.courseBenefit.description != null) {
append(": ${data.courseBenefit.description}")
}
}
} else {
data.user?.fullName ?: data.courseBenefit.buyer.toString()
}
purchaseRefundDate.text = DateTimeHelper.getPrintableDate(
data.courseBenefit.time,
DateTimeHelper.DISPLAY_DATETIME_PATTERN,
TimeZone.getDefault()
)
val transactionSum = if (data.courseBenefit.status == CourseBenefit.Status.DEBITED) {
revenuePriceMapper.mapToDisplayPrice(data.courseBenefit.currencyCode, decimalFormat.format(data.courseBenefit.paymentAmount?.toDoubleOrNull() ?: 0.0))
} else {
context.getString(R.string.course_benefits_refund)
}
val amount = revenuePriceMapper.mapToDisplayPrice(
data.courseBenefit.currencyCode,
decimalFormat.format(data.courseBenefit.amount.toDoubleOrNull() ?: 0.0),
debitPrefixRequired = data.courseBenefit.status == CourseBenefit.Status.DEBITED
)
val textColor = if (data.courseBenefit.status == CourseBenefit.Status.DEBITED) {
ContextCompat.getColor(context, R.color.material_on_background_emphasis_high_type)
} else {
ContextCompat.getColor(context, R.color.color_overlay_red)
}
purchaseRefundIncomeSum.setTextColor(textColor)
purchaseRefundTransactionSum.text = transactionSum
purchaseRefundIncomeSum.text = amount
purchaseRefundPromocode.text = data.courseBenefit.promoCode
purchaseRefundPromocode.isVisible = data.courseBenefit.promoCode != null
}
private fun getIconDrawable(data: CourseBenefit): Drawable? =
if (data.buyer == null && !data.isInvoicePayment) {
getTintedDrawable(R.color.color_on_surface_alpha_38)
} else {
if (data.status == CourseBenefit.Status.DEBITED) {
when {
data.isZLinkUsed == true ->
AppCompatResources.getDrawable(context, R.drawable.ic_purchase_z_link)
data.isInvoicePayment ->
getTintedDrawable(R.color.color_on_background)
else ->
AppCompatResources.getDrawable(context, R.drawable.ic_purchase_stepik)
}
} else {
AppCompatResources.getDrawable(context, R.drawable.ic_refund)
}
}
private fun getTintedDrawable(tint: Int): Drawable? =
AppCompatResources
.getDrawable(context, R.drawable.ic_purchase_stepik)
?.mutate()
?.let { DrawableCompat.wrap(it) }
?.also {
DrawableCompat.setTint(it, ContextCompat.getColor(context, tint))
DrawableCompat.setTintMode(it, PorterDuff.Mode.SRC_IN)
}
}
} | apache-2.0 | 3c246bf6697cbd36317075e71a4369c1 | 45.745902 | 166 | 0.652753 | 5.132313 | false | false | false | false |
customerly/Customerly-Android-SDK | customerly-android-sdk/src/main/java/io/customerly/utils/ggkext/Ext_Context.kt | 1 | 1798 | @file:Suppress("unused")
/*
* Copyright (C) 2017 Customerly
*
* 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 io.customerly.utils.ggkext
import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.ContextWrapper
import android.net.ConnectivityManager
import android.view.LayoutInflater
import io.customerly.sxdependencies.annotations.SXDrawableRes
import io.customerly.sxdependencies.annotations.SXRequiresPermission
/**
* Created by Gianni on 11/08/17.
*/
internal fun Context.inflater() : LayoutInflater = LayoutInflater.from(this)
@SXDrawableRes
internal fun Context.getDrawableId(drawableName :String) : Int =
this.resources.getIdentifier(drawableName, "drawable", this.packageName)
@SXRequiresPermission(Manifest.permission.ACCESS_NETWORK_STATE)
internal fun Context.checkConnection(): Boolean =
(this.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager).activeNetworkInfo?.isConnectedOrConnecting ?: false
internal val Context.tryBaseContextActivity :Activity?
get() {
var ctx = this
while (ctx is ContextWrapper) {
if (ctx is Activity) {
return ctx
}
ctx = ctx.baseContext
}
return null
} | apache-2.0 | 331429470236761720e37f8ce276728e | 32.943396 | 136 | 0.741935 | 4.483791 | false | false | false | false |
StepicOrg/stepik-android | model/src/main/java/org/stepik/android/model/Reply.kt | 2 | 1061 | package org.stepik.android.model
import android.os.Parcelable
import com.google.gson.annotations.SerializedName
import kotlinx.android.parcel.Parcelize
@Parcelize
data class Reply(
@SerializedName("choices")
val choices: List<Boolean>? = null,
@SerializedName("text")
val text: String? = null,
@SerializedName("attachments")
val attachments: List<Attachment>? = null,
@SerializedName("formula")
val formula: String? = null,
@SerializedName("number")
val number: String? = null,
@SerializedName("ordering")
val ordering: List<Int>? = null,
@SerializedName("language")
val language: String? = null,
@SerializedName("code")
val code: String? = null,
@SerializedName("blanks")
val blanks: List<String>? = null,
@SerializedName("solve_sql")
val solveSql: String? = null,
var tableChoices: List<TableChoiceAnswer>? = null //this is not serialize by default, because field 'choices' is already created by different type
) : Parcelable
data class ReplyWrapper(val reply: Reply?)
| apache-2.0 | c8adbe9ec6065c511e2b3432bdb96efc | 30.205882 | 151 | 0.69934 | 4.112403 | false | false | false | false |
allotria/intellij-community | plugins/completion-ml-ranking/src/com/intellij/completion/ml/personalization/session/PeriodTracker.kt | 3 | 1342 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.completion.ml.personalization.session
import kotlin.math.max
import kotlin.math.min
class PeriodTracker {
private val durations: MutableList<Long> = mutableListOf()
fun minDuration(currentPeriod: Long?): Long? {
val pastMin = durations.min()
if (pastMin == null) return currentPeriod
if (currentPeriod != null) {
return min(pastMin, currentPeriod)
}
return pastMin
}
fun maxDuration(currentPeriod: Long?): Long? {
val pastMax = durations.max()
if (pastMax == null) return currentPeriod
if (currentPeriod != null) {
return max(pastMax, currentPeriod)
}
return pastMax
}
fun average(currentPeriod: Long?): Double {
if (durations.isEmpty()) return currentPeriod?.toDouble() ?: 0.0
val pastAvg = durations.average()
if (currentPeriod == null) return pastAvg
val n = durations.size
return pastAvg * n / (n + 1) + currentPeriod / (n + 1)
}
fun count(currentPeriod: Long?): Int = durations.size + (if (currentPeriod != null) 1 else 0)
fun totalTime(currentPeriod: Long?): Long = durations.sum() + (currentPeriod ?: 0)
fun addDuration(duration: Long) {
durations.add(duration)
}
} | apache-2.0 | 9758982174affbcba47dc5d5f9f04873 | 28.844444 | 140 | 0.685544 | 4.054381 | false | false | false | false |
sdeleuze/mixit | src/main/kotlin/mixit/model/Talk.kt | 1 | 1150 | package mixit.model
import mixit.util.toSlug
import org.springframework.data.annotation.Id
import org.springframework.data.mongodb.core.mapping.Document
import java.time.LocalDateTime
@Document
data class Talk(
val format: TalkFormat,
val event: String,
val title: String,
val summary: String,
val speakerIds: List<String> = emptyList(),
val language: Language = Language.FRENCH,
val addedAt: LocalDateTime = LocalDateTime.now(),
val description: String? = null,
val topic: String? = null,
val video: String? = null,
val room: Room? = null,
val start: LocalDateTime? = null,
val end: LocalDateTime? = null,
val slug: String = title.toSlug(),
@Id val id: String? = null
)
enum class TalkFormat(val duration: Int) {
TALK(50),
LIGHTNING_TALK(5),
WORKSHOP(110),
RANDOM(25),
KEYNOTE(25)
}
@Suppress("UNUSED_PARAMETER")
enum class Room(capacity: Int) {
AMPHI1(500),
AMPHI2(200),
ROOM1(110),
ROOM2(110),
ROOM3(30),
ROOM4(30),
ROOM5(30),
ROOM6(30),
ROOM7(50),
UNKNOWN(0);
} | apache-2.0 | d94a418cd474fa7b20b53c5bed63fba8 | 22.979167 | 61 | 0.622609 | 3.616352 | false | false | false | false |
Kotlin/kotlinx.coroutines | reactive/kotlinx-coroutines-rx3/src/RxConvert.kt | 1 | 6999 | /*
* Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.coroutines.rx3
import io.reactivex.rxjava3.core.*
import io.reactivex.rxjava3.disposables.*
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.reactive.*
import org.reactivestreams.*
import java.util.concurrent.atomic.*
import kotlin.coroutines.*
/**
* Converts this job to the hot reactive completable that signals
* with [onCompleted][CompletableObserver.onComplete] when the corresponding job completes.
*
* Every subscriber gets the signal at the same time.
* Unsubscribing from the resulting completable **does not** affect the original job in any way.
*
* **Note: This is an experimental api.** Conversion of coroutines primitives to reactive entities may change
* in the future to account for the concept of structured concurrency.
*
* @param context -- the coroutine context from which the resulting completable is going to be signalled
*/
public fun Job.asCompletable(context: CoroutineContext): Completable = rxCompletable(context) {
[email protected]()
}
/**
* Converts this deferred value to the hot reactive maybe that signals
* [onComplete][MaybeEmitter.onComplete], [onSuccess][MaybeEmitter.onSuccess] or [onError][MaybeEmitter.onError].
*
* Every subscriber gets the same completion value.
* Unsubscribing from the resulting maybe **does not** affect the original deferred value in any way.
*
* **Note: This is an experimental api.** Conversion of coroutines primitives to reactive entities may change
* in the future to account for the concept of structured concurrency.
*
* @param context -- the coroutine context from which the resulting maybe is going to be signalled
*/
public fun <T> Deferred<T?>.asMaybe(context: CoroutineContext): Maybe<T> = rxMaybe(context) {
[email protected]()
}
/**
* Converts this deferred value to the hot reactive single that signals either
* [onSuccess][SingleObserver.onSuccess] or [onError][SingleObserver.onError].
*
* Every subscriber gets the same completion value.
* Unsubscribing from the resulting single **does not** affect the original deferred value in any way.
*
* **Note: This is an experimental api.** Conversion of coroutines primitives to reactive entities may change
* in the future to account for the concept of structured concurrency.
*
* @param context -- the coroutine context from which the resulting single is going to be signalled
*/
public fun <T : Any> Deferred<T>.asSingle(context: CoroutineContext): Single<T> = rxSingle(context) {
[email protected]()
}
/**
* Transforms given cold [ObservableSource] into cold [Flow].
*
* The resulting flow is _cold_, which means that [ObservableSource.subscribe] is called every time a terminal operator
* is applied to the resulting flow.
*
* A channel with the [default][Channel.BUFFERED] buffer size is used. Use the [buffer] operator on the
* resulting flow to specify a user-defined value and to control what happens when data is produced faster
* than consumed, i.e. to control the back-pressure behavior. Check [callbackFlow] for more details.
*/
public fun <T: Any> ObservableSource<T>.asFlow(): Flow<T> = callbackFlow {
val disposableRef = AtomicReference<Disposable>()
val observer = object : Observer<T> {
override fun onComplete() { close() }
override fun onSubscribe(d: Disposable) { if (!disposableRef.compareAndSet(null, d)) d.dispose() }
override fun onNext(t: T) {
/*
* Channel was closed by the downstream, so the exception (if any)
* also was handled by the same downstream
*/
try {
trySendBlocking(t)
} catch (e: InterruptedException) {
// RxJava interrupts the source
}
}
override fun onError(e: Throwable) { close(e) }
}
subscribe(observer)
awaitClose { disposableRef.getAndSet(Disposable.disposed())?.dispose() }
}
/**
* Converts the given flow to a cold observable.
* The original flow is cancelled when the observable subscriber is disposed.
*
* An optional [context] can be specified to control the execution context of calls to [Observer] methods.
* You can set a [CoroutineDispatcher] to confine them to a specific thread and/or various [ThreadContextElement] to
* inject additional context into the caller thread. By default, the [Unconfined][Dispatchers.Unconfined] dispatcher
* is used, so calls are performed from an arbitrary thread.
*/
public fun <T: Any> Flow<T>.asObservable(context: CoroutineContext = EmptyCoroutineContext) : Observable<T> = Observable.create { emitter ->
/*
* ATOMIC is used here to provide stable behaviour of subscribe+dispose pair even if
* asObservable is already invoked from unconfined
*/
val job = GlobalScope.launch(Dispatchers.Unconfined + context, start = CoroutineStart.ATOMIC) {
try {
collect { value -> emitter.onNext(value) }
emitter.onComplete()
} catch (e: Throwable) {
// 'create' provides safe emitter, so we can unconditionally call on* here if exception occurs in `onComplete`
if (e !is CancellationException) {
if (!emitter.tryOnError(e)) {
handleUndeliverableException(e, coroutineContext)
}
} else {
emitter.onComplete()
}
}
}
emitter.setCancellable(RxCancellable(job))
}
/**
* Converts the given flow to a cold flowable.
* The original flow is cancelled when the flowable subscriber is disposed.
*
* An optional [context] can be specified to control the execution context of calls to [Subscriber] methods.
* You can set a [CoroutineDispatcher] to confine them to a specific thread and/or various [ThreadContextElement] to
* inject additional context into the caller thread. By default, the [Unconfined][Dispatchers.Unconfined] dispatcher
* is used, so calls are performed from an arbitrary thread.
*/
public fun <T: Any> Flow<T>.asFlowable(context: CoroutineContext = EmptyCoroutineContext): Flowable<T> =
Flowable.fromPublisher(asPublisher(context))
/** @suppress */
@Suppress("UNUSED") // KT-42513
@JvmOverloads // binary compatibility
@JvmName("from")
@Deprecated(level = DeprecationLevel.HIDDEN, message = "") // Since 1.4, was experimental prior to that
public fun <T: Any> Flow<T>._asFlowable(context: CoroutineContext = EmptyCoroutineContext): Flowable<T> =
asFlowable(context)
/** @suppress */
@Suppress("UNUSED") // KT-42513
@JvmOverloads // binary compatibility
@JvmName("from")
@Deprecated(level = DeprecationLevel.HIDDEN, message = "") // Since 1.4, was experimental prior to that
public fun <T: Any> Flow<T>._asObservable(context: CoroutineContext = EmptyCoroutineContext) : Observable<T> = asObservable(context)
| apache-2.0 | 41311be03a9bcf6851bbab95b22002b3 | 44.154839 | 140 | 0.715817 | 4.466496 | false | false | false | false |
tsagi/JekyllForAndroid | app/src/main/java/gr/tsagi/jekyllforandroid/app/utils/JekyllRepo.kt | 2 | 1610 | package gr.tsagi.jekyllforandroid.app.utils
import android.os.AsyncTask
import org.eclipse.egit.github.core.Repository
import org.eclipse.egit.github.core.service.RepositoryService
import java.io.IOException
import java.util.concurrent.ExecutionException
/**
\* Created with IntelliJ IDEA.
\* User: jchanghong
\* Date: 1/29/14
\* Time: 15:14
\*/
class JekyllRepo {
fun getName(user: String): String? {
try {
return CheckAllRepos().execute(user).get()
} catch (e: InterruptedException) {
e.printStackTrace()
} catch (e: ExecutionException) {
e.printStackTrace()
}
return null
}
private inner class CheckAllRepos : AsyncTask<String, Void, String>() {
override fun doInBackground(vararg params: String): String {
val user = params[0]
var name: String? = null
val repositoryService = RepositoryService()
var repositories: List<Repository>? = null
try {
repositories = repositoryService.getRepositories(user)
} catch (e: IOException) {
e.printStackTrace()
}
for (repository in repositories!!) {
if (repository.name.contains(user + ".github.")) {
name = repository.name
break
}
if (repository.name.contains(user.toLowerCase() + ".github.")) {
name = repository.name
break
}
}
return name!!
}
}
}
| gpl-2.0 | 1404b63650fff4d66e6a698281aff1b0 | 24.15625 | 80 | 0.555901 | 4.791667 | false | false | false | false |
zdary/intellij-community | platform/platform-impl/src/com/intellij/ui/colorpicker/ColorIndicator.kt | 13 | 1804 | /*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ui.colorpicker
import com.intellij.ui.JBColor
import java.awt.*
import javax.swing.JComponent
private val BORDER = JBColor(Color(0, 0, 0, 26), Color(255, 255, 255, 26))
private val BORDER_STROKE = BasicStroke(2f)
class ColorIndicator(color: Color = DEFAULT_PICKER_COLOR) : JComponent() {
var color = color
set(value) {
field = value
repaint()
}
override fun paintComponent(g: Graphics) {
val originalAntialiasing = (g as Graphics2D).getRenderingHint(RenderingHints.KEY_ANTIALIASING)
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
val originalColor = g.color
val originalStroke = g.stroke
val left = insets.left
val top = insets.top
val circleWidth = width - insets.left - insets.right
val circleHeight = height - insets.top - insets.bottom
g.color = color
g.fillOval(left, top, circleWidth, circleHeight)
g.stroke = BORDER_STROKE
g.color = BORDER
g.drawOval(left, top, circleWidth, circleHeight)
g.color = originalColor
g.stroke = originalStroke
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, originalAntialiasing)
}
}
| apache-2.0 | 95b70648abdd3bd0470b3e2ebc6ef4a8 | 31.8 | 98 | 0.72561 | 4.008889 | false | false | false | false |
leafclick/intellij-community | plugins/github/src/org/jetbrains/plugins/github/pullrequest/config/GithubPullRequestsProjectUISettings.kt | 1 | 2065 | // 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.plugins.github.pullrequest.config
import com.intellij.openapi.Disposable
import com.intellij.openapi.components.*
import com.intellij.openapi.project.Project
import com.intellij.util.EventDispatcher
import java.util.*
@State(name = "GithubPullRequestsUISettings", storages = [Storage(StoragePathMacros.WORKSPACE_FILE)])
class GithubPullRequestsProjectUISettings : PersistentStateComponentWithModificationTracker<GithubPullRequestsProjectUISettings.SettingsState> {
private var state: SettingsState = SettingsState()
class SettingsState : BaseState() {
var hiddenUrls by stringSet()
var zipChanges by property(true)
}
private val changesEventDispatcher = EventDispatcher.create(ChangesEventDispatcher::class.java)
fun addChangesListener(disposable: Disposable, listener: () -> Unit) {
changesEventDispatcher.addListener(object : ChangesEventDispatcher {
override fun stateChanged() {
listener()
}
}, disposable)
}
fun getHiddenUrls(): Set<String> = state.hiddenUrls.toSet()
fun addHiddenUrl(url: String) {
if (state.hiddenUrls.add(url)) {
state.intIncrementModificationCount()
}
}
fun removeHiddenUrl(url: String) {
if (state.hiddenUrls.remove(url)) {
state.intIncrementModificationCount()
}
}
var zipChanges: Boolean
get() = state.zipChanges
set(value) {
state.zipChanges = value
changesEventDispatcher.multicaster.stateChanged()
}
override fun getStateModificationCount() = state.modificationCount
override fun getState() = state
override fun loadState(state: GithubPullRequestsProjectUISettings.SettingsState) {
this.state = state
}
companion object {
@JvmStatic
fun getInstance(project: Project) = project.service<GithubPullRequestsProjectUISettings>()
private interface ChangesEventDispatcher : EventListener {
fun stateChanged()
}
}
}
| apache-2.0 | f07e40e9d7573019ab514f9550339a6a | 31.265625 | 144 | 0.749637 | 4.904988 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/stdlib/text/RegexTest/split.kt | 2 | 306 | import kotlin.text.*
import kotlin.test.*
fun box() {
val input = """
some ${"\t"} word
split
""".trim()
assertEquals(listOf("some", "word", "split"), "\\s+".toRegex().split(input))
assertEquals(listOf("name", "value=5"), "=".toRegex().split("name=value=5", limit = 2))
}
| apache-2.0 | e3967e627ba4191df230ef5dfa121fcb | 18.125 | 91 | 0.552288 | 3.326087 | false | true | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/highlighter/AbstractDiagnosticMessageTest.kt | 2 | 8058 | // 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.util.io.FileUtil
import org.jetbrains.kotlin.analyzer.AnalysisResult
import org.jetbrains.kotlin.config.*
import org.jetbrains.kotlin.diagnostics.DiagnosticFactory
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.diagnostics.rendering.DefaultErrorMessages
import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithAllCompilerChecks
import org.jetbrains.kotlin.idea.highlighter.formatHtml.formatHtml
import org.jetbrains.kotlin.idea.project.withLanguageVersionSettings
import org.jetbrains.kotlin.idea.test.IDEA_TEST_DATA_DIR
import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase
import org.jetbrains.kotlin.idea.test.KotlinWithJdkAndRuntimeLightProjectDescriptor
import org.jetbrains.kotlin.idea.util.projectStructure.module
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.resolve.jvm.diagnostics.ErrorsJvm
import org.jetbrains.kotlin.test.Directives
import org.jetbrains.kotlin.test.InTextDirectivesUtils
import org.jetbrains.kotlin.test.KotlinTestUtils
import java.io.File
import java.lang.reflect.Field
import java.util.*
abstract class AbstractDiagnosticMessageTest : KotlinLightCodeInsightFixtureTestCase() {
private enum class MessageType(val directive: String, val extension: String) {
TEXT("TEXT", "txt"), HTML("HTML", "html");
}
override fun getProjectDescriptor() = KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE
override val testDataDirectory: File
get() = File(IDEA_TEST_DATA_DIR, "diagnosticMessage")
protected fun languageVersionSettings(fileData: String): LanguageVersionSettings {
val specificFeatures: Map<LanguageFeature, LanguageFeature.State> = parseLanguageFeatures(fileData)
val explicitLanguageVersion = InTextDirectivesUtils.findStringWithPrefixes(fileData, "// LANGUAGE_VERSION:")
val version = explicitLanguageVersion?.let { LanguageVersion.fromVersionString(it) }
val languageVersion = if (explicitLanguageVersion == null) LanguageVersionSettingsImpl.DEFAULT.languageVersion else version!!
return LanguageVersionSettingsImpl(languageVersion, LanguageVersionSettingsImpl.DEFAULT.apiVersion, emptyMap(), specificFeatures)
}
open fun analyze(file: KtFile, languageVersionSettings: LanguageVersionSettings): AnalysisResult {
val module = file.module ?: error("Module is not found for file $file")
return module.withLanguageVersionSettings(languageVersionSettings) {
file.analyzeWithAllCompilerChecks()
}
}
fun doTest(filePath: String) {
val file = File(filePath)
val fileData = KotlinTestUtils.doLoadFile(file)
val directives = KotlinTestUtils.parseDirectives(fileData)
val diagnosticNumber = getDiagnosticNumber(directives)
val diagnosticFactories = getDiagnosticFactories(directives)
val messageType = getMessageTypeDirective(directives)
val ktFile = myFixture.configureByFile(filePath) as KtFile
val languageVersionSettings = languageVersionSettings(fileData)
val analysisResult = analyze(ktFile, languageVersionSettings)
val bindingContext = analysisResult.bindingContext
val diagnostics = bindingContext.diagnostics.all().filter { diagnosticFactories.contains(it.factory) }
assertEquals("Expected diagnostics number mismatch:", diagnosticNumber, diagnostics.size)
val testName = FileUtil.getNameWithoutExtension(file.name)
for ((index, diagnostic) in diagnostics.withIndex()) {
var readableDiagnosticText: String
var extension: String
if (messageType != MessageType.TEXT && IdeErrorMessages.hasIdeSpecificMessage(diagnostic)) {
readableDiagnosticText = formatHtml(IdeErrorMessages.render(diagnostic))
extension = MessageType.HTML.extension
} else {
readableDiagnosticText = DefaultErrorMessages.render(diagnostic)
extension = MessageType.TEXT.extension
}
val errorMessageFileName = testName + (index + 1)
val outputFile = File(testDataDirectory, "$errorMessageFileName.$extension")
val actualText = "<!-- $errorMessageFileName -->\n$readableDiagnosticText"
assertSameLinesWithFile(outputFile.path, actualText)
}
}
private fun getDiagnosticFactories(directives: Directives): Set<DiagnosticFactory<*>?> {
val diagnosticsData = directives[DIAGNOSTICS_DIRECTIVE] ?: error("$DIAGNOSTICS_DIRECTIVE should be present.")
val diagnosticFactories: MutableSet<DiagnosticFactory<*>?> = HashSet()
val diagnostics = diagnosticsData.split(" ".toRegex()).toTypedArray()
for (diagnosticName in diagnostics) {
val diagnostic = getDiagnostic(diagnosticName)
assert(diagnostic is DiagnosticFactory<*>) { "Can't load diagnostic factory for $diagnosticName" }
diagnosticFactories.add(diagnostic as DiagnosticFactory<*>?)
}
return diagnosticFactories
}
private fun getDiagnostic(diagnosticName: String): Any? {
val field = getPlatformSpecificDiagnosticField(diagnosticName)
?: getFieldOrNull(Errors::class.java, diagnosticName)
?: return null
return try {
field[null]
} catch (e: IllegalAccessException) {
null
}
}
protected open fun getPlatformSpecificDiagnosticField(diagnosticName: String): Field? {
return getFieldOrNull(ErrorsJvm::class.java, diagnosticName)
}
companion object {
private const val DIAGNOSTICS_NUMBER_DIRECTIVE = "DIAGNOSTICS_NUMBER"
private const val DIAGNOSTICS_DIRECTIVE = "DIAGNOSTICS"
private const val MESSAGE_TYPE_DIRECTIVE = "MESSAGE_TYPE"
fun getFieldOrNull(kind: Class<*>, field: String): Field? {
return try {
kind.getField(field)
} catch (e: NoSuchFieldException) {
null
}
}
private fun parseLanguageFeatures(fileText: String): Map<LanguageFeature, LanguageFeature.State> {
val directives = InTextDirectivesUtils.findListWithPrefixes(fileText, "// !LANGUAGE:")
val result: MutableMap<LanguageFeature, LanguageFeature.State> = EnumMap(LanguageFeature::class.java)
for (directive in directives) {
val state = when (directive[0]) {
'+' -> LanguageFeature.State.ENABLED
'-' -> LanguageFeature.State.DISABLED
else -> continue
}
val feature = LanguageFeature.fromString(directive.substring(1)) ?: continue
result[feature] = state
}
return result
}
private fun getDiagnosticNumber(directives: Directives): Int {
val diagnosticsNumber = directives[DIAGNOSTICS_NUMBER_DIRECTIVE] ?: error("$DIAGNOSTICS_NUMBER_DIRECTIVE should be present.")
return try {
diagnosticsNumber.toInt()
} catch (e: NumberFormatException) {
throw AssertionError("$DIAGNOSTICS_NUMBER_DIRECTIVE should contain number as its value.")
}
}
private fun getMessageTypeDirective(directives: Directives): MessageType? {
val messageType = directives[MESSAGE_TYPE_DIRECTIVE] ?: return null
return try {
MessageType.valueOf(messageType)
} catch (e: IllegalArgumentException) {
throw AssertionError(
"$MESSAGE_TYPE_DIRECTIVE should be ${MessageType.TEXT.directive} " +
"or ${MessageType.HTML.directive}. But was: \"$messageType\"."
)
}
}
}
} | apache-2.0 | 340f05ad4cd1e8e273c801363d9c8299 | 46.970238 | 158 | 0.69583 | 5.504098 | false | true | false | false |
jotomo/AndroidAPS | danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_General_Get_Today_Delivery_Total.kt | 1 | 1614 | package info.nightscout.androidaps.danars.comm
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.dana.DanaPump
import info.nightscout.androidaps.danars.encryption.BleEncryption
import javax.inject.Inject
class DanaRS_Packet_General_Get_Today_Delivery_Total(
injector: HasAndroidInjector
) : DanaRS_Packet(injector) {
@Inject lateinit var danaPump: DanaPump
init {
opCode = BleEncryption.DANAR_PACKET__OPCODE_REVIEW__GET_TODAY_DELIVERY_TOTAL
aapsLogger.debug(LTag.PUMPCOMM, "New message")
}
override fun handleMessage(data: ByteArray) {
if (data.size < 8) {
failed = true
return
} else failed = false
var dataIndex = DATA_START
var dataSize = 2
danaPump.dailyTotalUnits = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0
dataIndex += dataSize
dataSize = 2
danaPump.dailyTotalBasalUnits = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0
dataIndex += dataSize
dataSize = 2
danaPump.dailyTotalBolusUnits = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0
aapsLogger.debug(LTag.PUMPCOMM, "Daily total: " + danaPump.dailyTotalUnits + " U")
aapsLogger.debug(LTag.PUMPCOMM, "Daily total bolus: " + danaPump.dailyTotalBolusUnits + " U")
aapsLogger.debug(LTag.PUMPCOMM, "Daily total basal: " + danaPump.dailyTotalBasalUnits + " U")
}
override fun getFriendlyName(): String {
return "REVIEW__GET_TODAY_DELIVERY_TOTAL"
}
} | agpl-3.0 | 3fffa0af2bee62a4b2ee7cb5ed1aaa8d | 37.452381 | 101 | 0.695787 | 4.409836 | false | false | false | false |
leafclick/intellij-community | plugins/settings-repository/src/actions/SyncAction.kt | 3 | 2049 | // 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.settingsRepository.actions
import com.intellij.notification.NotificationGroup
import com.intellij.notification.NotificationType
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.project.Project
import kotlinx.coroutines.runBlocking
import org.jetbrains.settingsRepository.*
internal val NOTIFICATION_GROUP = NotificationGroup.balloonGroup(PLUGIN_NAME)
internal abstract class SyncAction(private val syncType: SyncType) : DumbAwareAction() {
override fun update(e: AnActionEvent) {
if (ApplicationManager.getApplication().isUnitTestMode) {
return
}
val repositoryManager = icsManager.repositoryManager
e.presentation.isEnabledAndVisible = (repositoryManager.isRepositoryExists() && repositoryManager.hasUpstream()) ||
(syncType == SyncType.MERGE && icsManager.readOnlySourcesManager.repositories.isNotEmpty())
}
override fun actionPerformed(event: AnActionEvent) {
runBlocking {
syncAndNotify(syncType, event.project)
}
}
}
private suspend fun syncAndNotify(syncType: SyncType, project: Project?) {
try {
val message = if (icsManager.syncManager.sync(syncType, project)) {
icsMessage("sync.done.message")
}
else {
icsMessage("sync.up.to.date.message")
}
NOTIFICATION_GROUP.createNotification(message, NotificationType.INFORMATION).notify(project)
}
catch (e: Exception) {
LOG.warn(e)
NOTIFICATION_GROUP.createNotification(icsMessage("sync.rejected.title"), e.message ?: "Internal error", NotificationType.ERROR, null).notify(project)
}
}
internal class MergeAction : SyncAction(SyncType.MERGE)
internal class ResetToTheirsAction : SyncAction(SyncType.OVERWRITE_LOCAL)
internal class ResetToMyAction : SyncAction(SyncType.OVERWRITE_REMOTE) | apache-2.0 | 91d5e16e4475b0f328ddf4098a40bff6 | 39.196078 | 153 | 0.780381 | 4.710345 | false | false | false | false |
martinlau/fixture | src/main/kotlin/io/fixture/interceptor/NextThemeInterceptor.kt | 1 | 2160 | /*
* #%L
* fixture
* %%
* Copyright (C) 2013 Martin Lau
* %%
* 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.
* #L%
*/
package io.fixture.interceptor
import java.net.URLEncoder
import java.util.LinkedHashMap
import java.util.LinkedList
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import kotlin.dom.addClass
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter
import org.springframework.web.servlet.support.RequestContextUtils
import org.springframework.core.io.support.ResourcePatternUtils
import org.springframework.core.io.support.PathMatchingResourcePatternResolver
import java.util.Collections
class NextThemeInterceptor: HandlerInterceptorAdapter() {
val themes: List<String>
{
val resourcePatternResolver = ResourcePatternUtils.getResourcePatternResolver(PathMatchingResourcePatternResolver())
val resources = resourcePatternResolver.getResources("classpath*:/META-INF/resources/webjars/bootswatch/3.0.0/*/bootstrap.min.css")
val unsorted: MutableList<String> = resources.mapTo(LinkedList()) { it.createRelative(".").getFilename()!! }
themes = unsorted.sort()
}
override fun preHandle(request: HttpServletRequest, response: HttpServletResponse, handler: Any): Boolean {
val theme = RequestContextUtils.getThemeResolver(request)?.resolveThemeName(request)
if (theme != null) {
val nextTheme = if (theme == themes.last) themes.first
else themes.get(themes.indexOf(theme) + 1)
request.setAttribute("nextTheme", nextTheme)
}
return true;
}
}
| apache-2.0 | c9ee043e4de768e180fb3d860d3764f7 | 34.409836 | 139 | 0.743056 | 4.363636 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/facet/KotlinFacetType.kt | 1 | 1100 | // 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.facet
import com.intellij.facet.FacetType
import com.intellij.facet.FacetTypeId
import com.intellij.facet.FacetTypeRegistry
import com.intellij.openapi.module.JavaModuleType
import com.intellij.openapi.module.ModuleType
import org.jetbrains.kotlin.idea.util.isRunningInCidrIde
import org.jetbrains.kotlin.idea.KotlinIcons
import javax.swing.Icon
abstract class KotlinFacetType<C : KotlinFacetConfiguration> :
FacetType<KotlinFacet, C>(TYPE_ID, ID, NAME) {
companion object {
const val ID = "kotlin-language"
val TYPE_ID = FacetTypeId<KotlinFacet>(ID)
const val NAME = "Kotlin"
val INSTANCE
get() = FacetTypeRegistry.getInstance().findFacetType(TYPE_ID)
}
override fun isSuitableModuleType(moduleType: ModuleType<*>) = if (isRunningInCidrIde) true else moduleType is JavaModuleType
override fun getIcon(): Icon = KotlinIcons.SMALL_LOGO
}
| apache-2.0 | 89aa435a70280733dc463f0d3e096a92 | 38.285714 | 158 | 0.760909 | 4.230769 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/jvm-debugger/test/testData/evaluation/singleBreakpoint/frame/frameInlineArgumentInsideInlineFun.kt | 4 | 675 | // KT-10674: Debugger: Evaluate Expression / Watches fail for variable/parameter captured from one inline function to another
package frameInlineArgumentInsideInlineFun
class A {
inline fun inlineFun(s: (Int) -> Unit) {
val element = 1.0
s(1)
}
}
class B {
inline fun foo(s: (Int) -> Unit) {
val element = 1
A().inlineFun {
//Breakpoint!
val e = element
}
s(1)
}
}
class C {
fun bar() {
val element = 1f
B().foo {
val e = element
}
}
}
fun main(args: Array<String>) {
C().bar()
}
// PRINT_FRAME
// EXPRESSION: element
// RESULT: 1: I | apache-2.0 | 236fd49ef49e6b4aa4eca73550b5153a | 16.789474 | 125 | 0.531852 | 3.629032 | false | false | false | false |
3sidedcube/react-native-navigation | lib/android/app/src/main/java/com/reactnativenavigation/utils/View.kt | 1 | 943 | package com.reactnativenavigation.utils
import android.view.View
import android.view.ViewParent
import androidx.core.view.doOnLayout
import androidx.core.view.doOnNextLayout
import androidx.core.view.doOnPreDraw
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine
suspend fun View.awaitPost() = suspendCoroutine<Unit> { cont ->
post { cont.resume(Unit) }
}
suspend fun View.awaitLayout() = suspendCoroutine<Unit> { cont ->
doOnLayout { cont.resume(Unit) }
}
suspend fun View.awaitNextLayout() = suspendCoroutine<Unit> { cont ->
doOnNextLayout { cont.resume(Unit) }
}
suspend fun View.awaitDraw() = suspendCoroutine<Unit> { cont ->
doOnPreDraw { cont.resume(Unit) }
}
inline fun View.doOnLayoutCompat(crossinline action: (view: View) -> Unit) {
if (isLaidOut || (width > 0 && height > 0)) action(this) else doOnLayout { action(this) }
}
val View.grandparent: ViewParent
get() = parent.parent | mit | f5391a8c843711f023c16ce51d46358d | 28.5 | 93 | 0.743372 | 3.772 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/structuralsearch/search/KotlinSSBinaryExpressionTest.kt | 3 | 11746 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.structuralsearch.search
import org.jetbrains.kotlin.idea.structuralsearch.KotlinSSResourceInspectionTest
class KotlinSSBinaryExpressionTest : KotlinSSResourceInspectionTest() {
override fun getBasePath(): String = "binaryExpression"
fun testNestedBinaryExpression() { doTest("1 + 2 - 3", """
val a = <warning descr="SSR">1 + 2 - 3</warning>
""".trimIndent()) }
fun testBinaryParExpression() { doTest("3 * (2 - 3)", """
val a = <warning descr="SSR">3 * (2 - 3)</warning>
val b = 3 * 2 - 3
""".trimIndent()) }
fun testTwoBinaryExpressions() { doTest("""
a = 1
b = 2
""".trimIndent(), """
fun a() {
var a = 0
var b = 0
print(a + b)
<warning descr="SSR">a = 1</warning>
b = 2
print(a + b)
a = 1
print(a + b)
}
""".trimIndent()) }
fun testBinarySameVariable() { doTest("'_x + '_x", """
fun main() {
val foo = 1
val bar = 1
print(foo + 1)
print(<warning descr="SSR">foo + foo</warning>)
print(foo + bar)
}
""".trimIndent()) }
fun testBinaryPlus() { doTest("1 + 2", """
val a = <warning descr="SSR">1 + 2</warning>
val b = <warning descr="SSR">1.plus(2)</warning>
val c = 1 + 3
val d = 1.plus(3)
val e = 1.minus(2)
""".trimIndent()) }
fun testBinaryMinus() { doTest("1 - 2", """
val a = <warning descr="SSR">1 - 2</warning>
val b = <warning descr="SSR">1.minus(2)</warning>
val c = 1 - 3
val d = 1.minus(3)
""".trimIndent()) }
fun testBinaryTimes() { doTest("1 * 2", """
val a = <warning descr="SSR">1 * 2</warning>
val b = <warning descr="SSR">1.times(2)</warning>
val c = 1 * 3
val d = 1.times(3)
""".trimIndent()) }
fun testBinaryDiv() { doTest("1 / 2", """
val a = <warning descr="SSR">1 / 2</warning>
val b = <warning descr="SSR">1.div(2)</warning>
val c = 1 / 3
val d = 1.div(3)
""".trimIndent()) }
fun testBinaryRem() { doTest("1 % 2", """
val a = <warning descr="SSR">1 % 2</warning>
val b = <warning descr="SSR">1.rem(2)</warning>
val c = 1 % 3
val d = 1.rem(3)
""".trimIndent()) }
fun testBinaryRangeTo() { doTest("1..2", """
val a = <warning descr="SSR">1..2</warning>
val b = <warning descr="SSR">1.rangeTo(2)</warning>
val c = 1..3
val d = 1.rangeTo(3)
""".trimIndent()) }
fun testBinaryIn() { doTest("1 in 0..2", """
val a = <warning descr="SSR">1 in 0..2</warning>
val b = <warning descr="SSR">(0..2).contains(1)</warning>
val c = (0..1).contains(1)
val d = (0..2).contains(2)
val e = 2 in 0..2
val f = 1 in 1..2
val g = 1 !in 0..2
val h = !(0..2).contains(1)
""".trimIndent()) }
fun testBinaryNotIn() { doTest("1 !in 0..2", """
val a = <warning descr="SSR">1 !in 0..2</warning>
val b = <warning descr="SSR">!(0..2).contains(1)</warning>
val c = !(0..1).contains(1)
val d = !(0..2).contains(2)
val e = 2 !in 0..2
val f = 1 !in 1..2
val g = 1 in 0..2
val h = (0..2).contains(1)
val i = <warning descr="SSR">!((0..2).contains(1))</warning>
""".trimIndent()) }
fun testBinaryBigThan() { doTest("1 > 2", """
val a = <warning descr="SSR">1 > 2</warning>
val b = <warning descr="SSR">1.compareTo(2) > 0</warning>
val c = 1 > 3
val d = 1.compareTo(3) > 0
val e = 1.compareTo(2) < 0
val f = 2.compareTo(2) > 0
val g = 1.compareTo(2) > 1
""".trimIndent()) }
fun testBinaryLessThan() { doTest("1 < 2", """
val a = <warning descr="SSR">1 < 2</warning>
val b = <warning descr="SSR">1.compareTo(2) < 0</warning>
val c = 1 < 3
val d = 1.compareTo(3) < 0
val e = 1.compareTo(2) > 0
val f = 2.compareTo(2) < 0
val g = 1.compareTo(2) < 1
""".trimIndent()) }
fun testBinaryBigEqThan() { doTest("1 >= 2", """
val a = <warning descr="SSR">1 >= 2</warning>
val b = <warning descr="SSR">1.compareTo(2) >= 0</warning>
val c = 1 >= 3
val d = 1.compareTo(3) >= 0
val e = 1.compareTo(2) <= 0
val f = 2.compareTo(2) >= 0
val g = 1.compareTo(2) >= 1
""".trimIndent()) }
fun testBinaryLessEqThan() { doTest("1 <= 2", """
val a = <warning descr="SSR">1 <= 2</warning>
val b = <warning descr="SSR">1.compareTo(2) <= 0</warning>
val c = 1 <= 3
val d = 1.compareTo(3) >= 0
val e = 1.compareTo(2) >= 0
val f = 2.compareTo(2) <= 0
val g = 1.compareTo(2) <= 1
""".trimIndent()) }
fun testBinaryEquality() { doTest("a == b", """
var a: String? = "Hello world"
var b: String? = "Hello world"
var c: String? = "Hello world"
val d = <warning descr="SSR">a == b</warning>
val e = <warning descr="SSR">a?.equals(b) ?: (b === null)</warning>
val f = a == c
val g = c == b
val h = a?.equals(c) ?: (b === null)
val i = c?.equals(b) ?: (b === null)
val j = a?.equals(b) ?: (c === null)
val k = a?.equals(b)
val l = a === b
val m = a != b
""".trimIndent()) }
fun testBinaryInEquality() { doTest("a != b", """
var a: String? = "Hello world"
var b: String? = "Hello world"
var c: String? = "Hello world"
val d = <warning descr="SSR">a != b</warning>
val e = <warning descr="SSR">!(a?.equals(b) ?: (b === null))</warning>
val f = a != c
val g = c != b
val h = !(a?.equals(c) ?: (b === null))
val i = !(c?.equals(b) ?: (b === null))
val j = !(a?.equals(b) ?: (c === null))
val k = !(a?.equals(b)!!)
val l = a !== b
val m = a == b
""".trimIndent()) }
fun testElvis() { doTest("'_ ?: '_", """
fun main() {
var a: Int? = 1
val b = 2
print(<warning descr="SSR">(<warning descr="SSR">a ?: 0</warning>)</warning> + b)
}
""".trimIndent()) }
fun testBinaryPlusAssign() { doTest("'_ += '_", """
class Foo {
operator fun plusAssign(other: Foo) { print(other) }
}
fun main() {
var z = 1
<warning descr="SSR">z += 2</warning>
<warning descr="SSR">z = z + 2</warning>
print(z)
var x = Foo()
val y = Foo()
<warning descr="SSR">x.plusAssign(y)</warning>
}
""".trimIndent()) }
fun testBinaryAssignPlus() { doTest("'_x = '_x + '_", """
class Foo {
operator fun plusAssign(other: Foo) { print(other) }
}
fun main() {
var z = 1
<warning descr="SSR">z += 2</warning>
<warning descr="SSR">z = z + 2</warning>
print(z)
var x = Foo()
val y = Foo()
<warning descr="SSR">x.plusAssign(y)</warning>
}
""".trimIndent()) }
fun testBinaryMinusAssign() { doTest("'_ -= '_", """
class Foo {
operator fun minusAssign(other: Foo) { print(other) }
}
fun foo() {
var z = 1
<warning descr="SSR">z -= 2</warning>
<warning descr="SSR">z = z - 2</warning>
print(z)
var x = Foo()
val y = Foo()
<warning descr="SSR">x.minusAssign(y)</warning>
}
""".trimIndent()) }
fun testBinaryAssignMinus() { doTest("'_x = '_x - '_", """
class Foo {
operator fun minusAssign(other: Foo) { print(other) }
}
fun foo() {
var z = 1
<warning descr="SSR">z -= 2</warning>
<warning descr="SSR">z = z - 2</warning>
print(z)
var x = Foo()
val y = Foo()
<warning descr="SSR">x.minusAssign(y)</warning>
}
""".trimIndent()) }
fun testBinaryTimesAssign() { doTest("'_ *= '_", """
class Foo {
operator fun timesAssign(other: Foo) { print(other) }
}
fun foo() {
var z = 1
<warning descr="SSR">z *= 2</warning>
<warning descr="SSR">z = z * 2</warning>
print(z)
var x = Foo()
val y = Foo()
<warning descr="SSR">x.timesAssign(y)</warning>
}
""".trimIndent()) }
fun testBinaryAssignTimes() { doTest("'_x = '_x * '_", """
class Foo {
operator fun timesAssign(other: Foo) { print(other) }
}
fun foo() {
var z = 1
<warning descr="SSR">z *= 2</warning>
<warning descr="SSR">z = z * 2</warning>
print(z)
var x = Foo()
val y = Foo()
<warning descr="SSR">x.timesAssign(y)</warning>
}
""".trimIndent()) }
fun testBinaryDivAssign() { doTest("'_ /= '_", """
class Foo {
operator fun divAssign(other: Foo) { print(other) }
}
fun foo() {
var z = 1
<warning descr="SSR">z /= 2</warning>
<warning descr="SSR">z = z / 2</warning>
print(z)
var x = Foo()
val y = Foo()
<warning descr="SSR">x.divAssign(y)</warning>
}
""".trimIndent()) }
fun testBinaryAssignDiv() { doTest("'_x = '_x / '_", """
class Foo {
operator fun divAssign(other: Foo) { print(other) }
}
fun foo() {
var z = 1
<warning descr="SSR">z /= 2</warning>
<warning descr="SSR">z = z / 2</warning>
print(z)
var x = Foo()
val y = Foo()
<warning descr="SSR">x.divAssign(y)</warning>
}
""".trimIndent()) }
fun testBinaryRemAssign() { doTest("'_ %= '_", """
class Foo {
operator fun remAssign(other: Foo) { print(other) }
}
fun foo() {
var z = 1
<warning descr="SSR">z %= 2</warning>
<warning descr="SSR">z = z % 2</warning>
print(z)
var x = Foo()
val y = Foo()
<warning descr="SSR">x.remAssign(y)</warning>
}
""".trimIndent()) }
fun testBinaryAssignRem() { doTest("'_x = '_x % '_", """
class Foo {
operator fun remAssign(other: Foo) { print(other) }
}
fun foo() {
var z = 1
<warning descr="SSR">z %= 2</warning>
<warning descr="SSR">z = z % 2</warning>
print(z)
var x = Foo()
val y = Foo()
<warning descr="SSR">x.remAssign(y)</warning>
}
""".trimIndent()) }
fun testBinarySet() { doTest("a[0] = 1 + 2", """
val a = intArrayOf(0, 1)
fun b() {
<warning descr="SSR">a[0] = 1 + 2</warning>
<warning descr="SSR">a.set(0, 1 + 2)</warning>
a.set(0, 1)
a.set(1, 1 + 2)
val c = intArrayOf(1, 1)
c.set(0, 1 + 2)
a[0] = 1
a[1] = 1 + 2
}
""".trimIndent()) }
} | apache-2.0 | 0babf779b02b9b468ab7ec4e465a3094 | 31.183562 | 120 | 0.449004 | 3.652363 | false | true | false | false |
sureshg/kotlin-starter | src/main/kotlin/io/sureshg/extn/TextTerm.kt | 1 | 6065 | package io.sureshg.extn
import kotlin.coroutines.experimental.buildSequence
/**
* These extension are copied from https://github.com/xenomachina/xenocom.
*/
const val NBSP_CODEPOINT = 0xa0
internal const val SPACE_WIDTH = 1
/**
* Produces a [Sequence] of the Unicode code points in the given [String].
*/
fun String.codePointSequence(): Sequence<Int> = buildSequence {
val length = length
var offset = 0
while (offset < length) {
val codePoint = codePointAt(offset)
yield(codePoint)
offset += Character.charCount(codePoint)
}
}
fun StringBuilder.clear() {
this.setLength(0)
}
fun String.trimNewline(): String {
if (endsWith('\n')) {
return substring(0, length - 1)
} else {
return this
}
}
fun String.padLinesToWidth(width: Int): String {
val sb = StringBuilder()
var lineWidth = 0
var singleLine = true
for (codePoint in codePointSequence()) {
if (codePoint == '\n'.toInt()) {
singleLine = false
while (lineWidth < width) {
sb.append(" ")
lineWidth += SPACE_WIDTH
}
sb.append("\n")
lineWidth = 0
} else {
sb.appendCodePoint(codePoint)
lineWidth += codePointWidth(codePoint)
}
}
if (singleLine || lineWidth > 0) {
while (lineWidth < width) {
sb.append(" ")
lineWidth += SPACE_WIDTH
}
}
return sb.toString()
}
fun String.wrapText(maxWidth: Int): String {
val sb = StringBuilder()
val word = StringBuilder()
var lineWidth = 0
var wordWidth = 0
fun handleSpace() {
if (wordWidth > 0) {
if (lineWidth > 0) {
sb.append(" ")
lineWidth += SPACE_WIDTH
}
sb.append(word)
lineWidth += wordWidth
word.clear()
wordWidth = 0
}
}
for (inputCodePoint in codePointSequence()) {
if (Character.isSpaceChar(inputCodePoint) && inputCodePoint != NBSP_CODEPOINT) {
// space
handleSpace()
} else {
// non-space
val outputCodePoint = if (inputCodePoint == NBSP_CODEPOINT) ' '.toInt() else inputCodePoint
val charWidth = codePointWidth(outputCodePoint).toInt()
if (lineWidth > 0 && lineWidth + SPACE_WIDTH + wordWidth + charWidth > maxWidth) {
sb.append("\n")
lineWidth = 0
}
if (lineWidth == 0 && lineWidth + SPACE_WIDTH + wordWidth + charWidth > maxWidth) {
// Eep! Word would be longer than line. Need to break it.
sb.append(word)
word.clear()
wordWidth = 0
sb.append("\n")
lineWidth = 0
}
word.appendCodePoint(outputCodePoint)
wordWidth += charWidth
}
}
handleSpace()
return sb.toString()
}
/**
* Returns an estimated cell width of a Unicode code point when displayed on a monospace terminal.
* Possible return values are -1, 0, 1 or 2. Control characters (other than null) and Del return -1.
*
* This function is based on the public domain [wcwidth.c](https://www.cl.cam.ac.uk/~mgk25/ucs/wcwidth.c)
* written by Markus Kuhn.
*/
fun codePointWidth(ucs: Int): Int {
// 8-bit control characters
if (ucs == 0) return 0
if (ucs < 32 || (ucs >= 0x7f && ucs < 0xa0)) return -1
// Non-spacing characters. This is simulating the binary search of
// `uniset +cat=Me +cat=Mn +cat=Cf -00AD +1160-11FF +200B`.
if (ucs != 0x00AD) { // soft hyphen
val category = Character.getType(ucs).toByte()
if (category == Character.ENCLOSING_MARK || // "Me"
category == Character.NON_SPACING_MARK || // "Mn"
category == Character.FORMAT || // "Cf"
(ucs in 0x1160..0x11FF) || // Hangul Jungseong & Jongseong
ucs == 0x200B) // zero width space
return 0
}
// If we arrive here, ucs is not a combining or C0/C1 control character.
return if (ucs >= 0x1100 && (ucs <= 0x115f || // Hangul Jamo init. consonants
ucs == 0x2329 || ucs == 0x232a ||
(ucs in 0x2e80..0xa4cf && ucs != 0x303f) || // CJK ... Yi
(ucs in 0xac00..0xd7a3) || // Hangul Syllables
(ucs in 0xf900..0xfaff) || // CJK Compatibility Ideographs
(ucs in 0xfe10..0xfe19) || // Vertical forms
(ucs in 0xfe30..0xfe6f) || // CJK Compatibility Forms
(ucs in 0xff00..0xff60) || // Fullwidth Forms
(ucs in 0xffe0..0xffe6) ||
(ucs in 0x20000..0x2fffd) ||
(ucs in 0x30000..0x3fffd)))
2 else 1
}
fun String.codePointWidth(): Int = codePointSequence().sumBy { codePointWidth(it) }
fun columnize(vararg s: String, minWidths: IntArray? = null): String {
val columns = Array(s.size) { mutableListOf<String>() }
val widths = IntArray(s.size)
for (i in 0..s.size - 1) {
if (minWidths != null && i < minWidths.size) {
widths[i] = minWidths[i]
}
for (line in s[i].lineSequence()) {
val cell = line.trimNewline()
columns[i].add(cell)
widths[i] = maxOf(widths[i], cell.codePointWidth())
}
}
val height = columns.maxBy { it.size }?.size ?: 0
val sb = StringBuilder()
var firstLine = true
for (j in 0..height - 1) {
if (firstLine) {
firstLine = false
} else {
sb.append("\n")
}
var lineWidth = 0
var columnStart = 0
for (i in 0..columns.size - 1) {
columns[i].getOrNull(j)?.let { cell ->
for (k in 1..columnStart - lineWidth) sb.append(" ")
lineWidth = columnStart
sb.append(cell)
lineWidth += cell.codePointWidth()
}
columnStart += widths[i]
}
}
return sb.toString()
} | apache-2.0 | a3908f76a2a18e6ad9466d3bc66dc6a5 | 31.612903 | 105 | 0.546084 | 3.943433 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/crossLanguage/ChangeMethodParameters.kt | 1 | 10455 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix.crossLanguage
import com.intellij.codeInsight.daemon.QuickFixBundle
import com.intellij.lang.jvm.actions.AnnotationRequest
import com.intellij.lang.jvm.actions.ChangeParametersRequest
import com.intellij.lang.jvm.actions.ExpectedParameter
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.JvmPsiConversionHelper
import org.jetbrains.kotlin.asJava.elements.KtLightElement
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.descriptors.SourceElement
import org.jetbrains.kotlin.descriptors.annotations.Annotations
import org.jetbrains.kotlin.descriptors.impl.SimpleFunctionDescriptorImpl
import org.jetbrains.kotlin.descriptors.impl.ValueParameterDescriptorImpl
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.core.ShortenReferences
import org.jetbrains.kotlin.idea.quickfix.KotlinQuickFixAction
import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers
import org.jetbrains.kotlin.idea.util.resolveToKotlinType
import org.jetbrains.kotlin.load.java.NOT_NULL_ANNOTATIONS
import org.jetbrains.kotlin.load.java.NULLABLE_ANNOTATIONS
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.KotlinType
internal class ChangeMethodParameters(
target: KtNamedFunction,
val request: ChangeParametersRequest
) : KotlinQuickFixAction<KtNamedFunction>(target) {
override fun getText(): String {
val target = element ?: return KotlinBundle.message("fix.change.signature.unavailable")
val helper = JvmPsiConversionHelper.getInstance(target.project)
val parametersString = request.expectedParameters.joinToString(", ", "(", ")") { ep ->
val kotlinType =
ep.expectedTypes.firstOrNull()?.theType?.let { helper.convertType(it).resolveToKotlinType(target.getResolutionFacade()) }
val parameterName = ep.semanticNames.firstOrNull() ?: KotlinBundle.message("fix.change.signature.unnamed.parameter")
"$parameterName: ${kotlinType?.let {
IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.renderType(it)
} ?: KotlinBundle.message("fix.change.signature.error")}"
}
val shortenParameterString = StringUtil.shortenTextWithEllipsis(parametersString, 30, 5)
return QuickFixBundle.message("change.method.parameters.text", shortenParameterString)
}
override fun getFamilyName(): String = QuickFixBundle.message("change.method.parameters.family")
override fun isAvailable(project: Project, editor: Editor?, file: KtFile): Boolean = element != null && request.isValid
private sealed class ParameterModification {
data class Keep(val ktParameter: KtParameter) : ParameterModification()
data class Remove(val ktParameter: KtParameter) : ParameterModification()
data class Add(
val name: String,
val ktType: KotlinType,
val expectedAnnotations: Collection<AnnotationRequest>,
val beforeAnchor: KtParameter?
) : ParameterModification()
}
private tailrec fun getParametersModifications(
target: KtNamedFunction,
currentParameters: List<KtParameter>,
expectedParameters: List<ExpectedParameter>,
index: Int = 0,
collected: List<ParameterModification> = ArrayList(expectedParameters.size)
): List<ParameterModification> {
val expectedHead = expectedParameters.firstOrNull() ?: return collected + currentParameters.map { ParameterModification.Remove(it) }
if (expectedHead is ChangeParametersRequest.ExistingParameterWrapper) {
val expectedExistingParameter = expectedHead.existingKtParameter
if (expectedExistingParameter == null) {
LOG.error("can't find the kotlinOrigin for parameter ${expectedHead.existingParameter} at index $index")
return collected
}
val existingInTail = currentParameters.indexOf(expectedExistingParameter)
if (existingInTail == -1) {
throw IllegalArgumentException("can't find existing for parameter ${expectedHead.existingParameter} at index $index")
}
return getParametersModifications(
target,
currentParameters.subList(existingInTail + 1, currentParameters.size),
expectedParameters.subList(1, expectedParameters.size),
index,
collected
+ currentParameters.subList(0, existingInTail).map { ParameterModification.Remove(it) }
+ ParameterModification.Keep(expectedExistingParameter)
)
}
val helper = JvmPsiConversionHelper.getInstance(target.project)
val theType = expectedHead.expectedTypes.firstOrNull()?.theType ?: return emptyList()
val kotlinType = helper.convertType(theType).resolveToKotlinType(target.getResolutionFacade()) ?: return emptyList()
return getParametersModifications(
target,
currentParameters,
expectedParameters.subList(1, expectedParameters.size),
index + 1,
collected + ParameterModification.Add(
expectedHead.semanticNames.firstOrNull() ?: "param$index",
kotlinType,
expectedHead.expectedAnnotations,
currentParameters.firstOrNull { anchor ->
expectedParameters.any {
it is ChangeParametersRequest.ExistingParameterWrapper && it.existingKtParameter == anchor
}
})
)
}
private val ChangeParametersRequest.ExistingParameterWrapper.existingKtParameter
get() = (existingParameter as? KtLightElement<*, *>)?.kotlinOrigin as? KtParameter
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
if (!request.isValid) return
val target = element ?: return
val functionDescriptor = target.resolveToDescriptorIfAny(BodyResolveMode.FULL) ?: return
val parameterActions = getParametersModifications(target, target.valueParameters, request.expectedParameters)
val parametersGenerated = parameterActions.filterIsInstance<ParameterModification.Add>().let {
it zip generateParameterList(project, functionDescriptor, it).parameters
}.toMap()
for (action in parameterActions) {
when (action) {
is ParameterModification.Add -> {
val parameter = parametersGenerated.getValue(action)
for (expectedAnnotation in action.expectedAnnotations.reversed()) {
addAnnotationEntry(parameter, expectedAnnotation, null)
}
val anchor = action.beforeAnchor
if (anchor != null) {
target.valueParameterList!!.addParameterBefore(parameter, anchor)
} else {
target.valueParameterList!!.addParameter(parameter)
}
}
is ParameterModification.Keep -> {
// Do nothing
}
is ParameterModification.Remove -> {
target.valueParameterList!!.removeParameter(action.ktParameter)
}
}
}
ShortenReferences.DEFAULT.process(target.valueParameterList!!)
}
private fun generateParameterList(
project: Project,
functionDescriptor: FunctionDescriptor,
paramsToAdd: List<ParameterModification.Add>
): KtParameterList {
val newFunctionDescriptor = SimpleFunctionDescriptorImpl.create(
functionDescriptor.containingDeclaration,
functionDescriptor.annotations,
functionDescriptor.name,
functionDescriptor.kind,
SourceElement.NO_SOURCE
).apply {
initialize(
functionDescriptor.extensionReceiverParameter?.copy(this),
functionDescriptor.dispatchReceiverParameter,
functionDescriptor.contextReceiverParameters.map { it.copy(this) },
functionDescriptor.typeParameters,
paramsToAdd.mapIndexed { index, parameter ->
ValueParameterDescriptorImpl(
this, null, index, Annotations.EMPTY,
Name.identifier(parameter.name),
parameter.ktType, declaresDefaultValue = false,
isCrossinline = false, isNoinline = false, varargElementType = null, source = SourceElement.NO_SOURCE
)
},
functionDescriptor.returnType,
functionDescriptor.modality,
functionDescriptor.visibility
)
}
val renderer = IdeDescriptorRenderers.SOURCE_CODE.withOptions {
defaultParameterValueRenderer = null
}
val newFunction = KtPsiFactory(project).createFunction(renderer.render(newFunctionDescriptor)).apply {
valueParameters.forEach { param ->
param.annotationEntries.forEach { a ->
a.typeReference?.run {
val fqName = FqName(this.text)
if (fqName in (NULLABLE_ANNOTATIONS + NOT_NULL_ANNOTATIONS)) a.delete()
}
}
}
}
return newFunction.valueParameterList!!
}
companion object {
fun create(ktNamedFunction: KtNamedFunction, request: ChangeParametersRequest): ChangeMethodParameters? =
ChangeMethodParameters(ktNamedFunction, request)
private val LOG = Logger.getInstance(ChangeMethodParameters::class.java)
}
}
| apache-2.0 | 82b8c5c2b992fbb316d03acf5d28e4e7 | 44.655022 | 158 | 0.670875 | 5.876897 | false | false | false | false |
nadraliev/DsrWeatherApp | app/src/main/java/soutvoid/com/DsrWeatherApp/interactor/common/network/ServerUrls.kt | 1 | 381 | package soutvoid.com.DsrWeatherApp.interactor.common.network
object ServerUrls {
const val BASE_URL = "http://api.openweathermap.org/data/"
const val CURRENT_WEATHER_URL = "2.5/weather"
const val FORECAST_URL = "2.5/forecast"
const val UVI_URL = "2.5/uvi"
const val DAILY_FORECAST_URL = "2.5/forecast/daily"
const val TRIGGERS_URL = "3.0/triggers"
} | apache-2.0 | 1bdf1e1ede8e6eb3b77299963f7ce143 | 21.470588 | 62 | 0.690289 | 3.228814 | false | false | false | false |
androidx/androidx | wear/watchface/watchface-client/src/main/java/androidx/wear/watchface/client/InteractiveWatchFaceClient.kt | 3 | 25892 | /*
* 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.wear.watchface.client
import android.graphics.Bitmap
import android.os.Handler
import android.os.HandlerThread
import android.os.RemoteException
import android.support.wearable.watchface.SharedMemoryImage
import androidx.annotation.AnyThread
import androidx.annotation.IntDef
import androidx.annotation.Px
import androidx.annotation.RequiresApi
import androidx.wear.watchface.complications.data.ComplicationData
import androidx.wear.watchface.complications.data.toApiComplicationText
import androidx.wear.watchface.utility.TraceEvent
import androidx.wear.watchface.ComplicationSlot
import androidx.wear.watchface.ComplicationSlotsManager
import androidx.wear.watchface.ContentDescriptionLabel
import androidx.wear.watchface.Renderer
import androidx.wear.watchface.RenderParameters
import androidx.wear.watchface.TapType
import androidx.wear.watchface.WatchFaceColors
import androidx.wear.watchface.control.IInteractiveWatchFace
import androidx.wear.watchface.control.data.WatchFaceRenderParams
import androidx.wear.watchface.ComplicationSlotBoundsType
import androidx.wear.watchface.WatchFaceExperimental
import androidx.wear.watchface.control.IWatchfaceListener
import androidx.wear.watchface.control.IWatchfaceReadyListener
import androidx.wear.watchface.data.IdAndComplicationDataWireFormat
import androidx.wear.watchface.data.WatchFaceColorsWireFormat
import androidx.wear.watchface.data.WatchUiState
import androidx.wear.watchface.style.UserStyle
import androidx.wear.watchface.style.UserStyleSchema
import androidx.wear.watchface.style.UserStyleSetting.ComplicationSlotsUserStyleSetting
import androidx.wear.watchface.style.UserStyleData
import androidx.wear.watchface.toApiFormat
import java.time.Instant
import java.util.concurrent.Executor
import java.util.function.Consumer
/** @hide */
@IntDef(
value = [
DisconnectReasons.ENGINE_DIED,
DisconnectReasons.ENGINE_DETACHED
]
)
public annotation class DisconnectReason
/**
* Disconnect reasons for
* [InteractiveWatchFaceClient.ClientDisconnectListener.onClientDisconnected].
*/
public object DisconnectReasons {
/**
* The underlying engine died, probably because the watch face was killed or crashed.
* Sometimes this is due to memory pressure and it's not the watch face's fault. Usually in
* response a new [InteractiveWatchFaceClient] should be created (see
* [WatchFaceControlClient.getOrCreateInteractiveWatchFaceClient]), however if this new
* client also disconnects due to [ENGINE_DIED] within a few seconds the watchface is
* probably bad and it's recommended to switch to a safe system default watch face.
*/
public const val ENGINE_DIED: Int = 1
/**
* Wallpaper service detached from the engine, which is now defunct. The watch face itself
* has no control over this. Usually in response a new [InteractiveWatchFaceClient]
* should be created (see [WatchFaceControlClient.getOrCreateInteractiveWatchFaceClient]).
*/
public const val ENGINE_DETACHED: Int = 2
}
/**
* Controls a stateful remote interactive watch face. Typically this will be used for the current
* active watch face.
*
* Note clients should call [close] when finished.
*/
public interface InteractiveWatchFaceClient : AutoCloseable {
/**
* Sends new [ComplicationData] to the watch face. Note this doesn't have to be a full update,
* it's possible to update just one complication at a time, but doing so may result in a less
* visually clean transition.
*
* @param slotIdToComplicationData The [ComplicationData] for each
* [androidx.wear.watchface.ComplicationSlot].
*/
@Throws(RemoteException::class)
public fun updateComplicationData(slotIdToComplicationData: Map<Int, ComplicationData>)
/**
* Renders the watchface to a shared memory backed [Bitmap] with the given settings.
*
* @param renderParameters The [RenderParameters] to draw with.
* @param instant The [Instant] render with.
* @param userStyle Optional [UserStyle] to render with, if null the current style is used.
* @param idAndComplicationData Map of complication ids to [ComplicationData] to render with, or
* if null then the existing complication data if any is used.
* @return A shared memory backed [Bitmap] containing a screenshot of the watch face with the
* given settings.
*/
@RequiresApi(27)
@Throws(RemoteException::class)
public fun renderWatchFaceToBitmap(
renderParameters: RenderParameters,
instant: Instant,
userStyle: UserStyle?,
idAndComplicationData: Map<Int, ComplicationData>?
): Bitmap
/** The UTC reference preview time for this watch face in milliseconds since the epoch. */
@get:Throws(RemoteException::class)
public val previewReferenceInstant: Instant
/**
* The watchface's [OverlayStyle] which configures the system status overlay on
* Wear 3.0 and beyond. Note for older watch faces which don't support this, the default value
* will be returned.
*/
@get:Throws(RemoteException::class)
public val overlayStyle: OverlayStyle
// Default implementation, overridden below.
get() = OverlayStyle()
/**
* Renames this instance to [newInstanceId] (must be unique, usually this would be different
* from the old ID but that's not a requirement). Sets the current [UserStyle] and clears
* any complication data. Setting the new UserStyle may have a side effect of enabling or
* disabling complicationSlots, which will be visible via [ComplicationSlotState.isEnabled].
*
* NB [setWatchUiState] and [updateWatchFaceInstance] can be called in any order.
*/
@Throws(RemoteException::class)
public fun updateWatchFaceInstance(newInstanceId: String, userStyle: UserStyle)
/**
* Renames this instance to [newInstanceId] (must be unique, usually this would be different
* from the old ID but that's not a requirement). Sets the current [UserStyle] represented as a
* [UserStyleData> and clears any complication data. Setting the new UserStyle may have a
* side effect of enabling or disabling complicationSlots, which will be visible via
* [ComplicationSlotState.isEnabled].
*/
@Throws(RemoteException::class)
public fun updateWatchFaceInstance(newInstanceId: String, userStyle: UserStyleData)
/** Returns the ID of this watch face instance. */
@get:Throws(RemoteException::class)
public val instanceId: String
/** The watch face's [UserStyleSchema]. */
@get:Throws(RemoteException::class)
public val userStyleSchema: UserStyleSchema
/**
* Map of [androidx.wear.watchface.ComplicationSlot] ids to [ComplicationSlotState] for each
* [ComplicationSlot] registered with the watch face's [ComplicationSlotsManager]. The
* ComplicationSlotState is based on the initial state of each
* [androidx.wear.watchface.ComplicationSlot] plus any overrides from a
* [ComplicationSlotsUserStyleSetting]. As a consequence ComplicationSlotState may update based
* on style changes.
*/
@get:Throws(RemoteException::class)
public val complicationSlotsState: Map<Int, ComplicationSlotState>
/**
* Returns the ID of the [androidx.wear.watchface.ComplicationSlot] at the given coordinates or
* `null` if there isn't one.
*
* Note this currently doesn't support Edge complications.
*/
@SuppressWarnings("AutoBoxing")
@Throws(RemoteException::class)
public fun getComplicationIdAt(@Px x: Int, @Px y: Int): Int? =
complicationSlotsState.asSequence().firstOrNull {
it.value.isEnabled && when (it.value.boundsType) {
ComplicationSlotBoundsType.ROUND_RECT -> it.value.bounds.contains(x, y)
ComplicationSlotBoundsType.BACKGROUND -> false
ComplicationSlotBoundsType.EDGE -> false
else -> false
}
}?.key
public companion object {
/** Indicates a "down" touch event on the watch face. */
public const val TAP_TYPE_DOWN: Int = IInteractiveWatchFace.TAP_TYPE_DOWN
/**
* Indicates that a previous [TAP_TYPE_DOWN] event has been canceled. This generally happens
* when the watch face is touched but then a move or long press occurs.
*/
public const val TAP_TYPE_CANCEL: Int = IInteractiveWatchFace.TAP_TYPE_CANCEL
/**
* Indicates that an "up" event on the watch face has occurred that has not been consumed by
* another activity. A [TAP_TYPE_DOWN] always occur first. This event will not occur if a
* [TAP_TYPE_CANCEL] is sent.
*/
public const val TAP_TYPE_UP: Int = IInteractiveWatchFace.TAP_TYPE_UP
}
/**
* Sends a tap event to the watch face for processing.
*
* @param xPosition The x-coordinate of the tap in pixels
* @param yPosition The y-coordinate of the tap in pixels
* @param tapType The [TapType] of the event
*/
@Throws(RemoteException::class)
public fun sendTouchEvent(@Px xPosition: Int, @Px yPosition: Int, @TapType tapType: Int)
/**
* Returns the [ContentDescriptionLabel]s describing the watch face, for the use by screen
* readers.
*/
@get:Throws(RemoteException::class)
public val contentDescriptionLabels: List<ContentDescriptionLabel>
/**
* Updates the watch faces [WatchUiState]. NB [setWatchUiState] and [updateWatchFaceInstance]
* can be called in any order.
*/
@Throws(RemoteException::class)
public fun setWatchUiState(watchUiState: androidx.wear.watchface.client.WatchUiState)
/** Triggers watch face rendering into the surface when in ambient mode. */
@Throws(RemoteException::class)
public fun performAmbientTick()
/**
* Callback that observes when the client disconnects. Use [addClientDisconnectListener] to
* register a ClientDisconnectListener.
*/
@JvmDefaultWithCompatibility
public interface ClientDisconnectListener {
/**
* The client disconnected, typically due to the server side crashing. Note this is not
* called in response to [close] being called on [InteractiveWatchFaceClient].
*/
@Deprecated(
"Deprecated, use an overload that passes the disconnectReason",
ReplaceWith("onClientDisconnected(Int)")
)
public fun onClientDisconnected() {
}
/**
* The client disconnected, due to [disconnectReason].
*/
public fun onClientDisconnected(@DisconnectReason disconnectReason: Int) {
@Suppress("DEPRECATION")
onClientDisconnected()
}
}
/** Registers a [ClientDisconnectListener]. */
@AnyThread
public fun addClientDisconnectListener(listener: ClientDisconnectListener, executor: Executor)
/**
* Removes a [ClientDisconnectListener] previously registered by [addClientDisconnectListener].
*/
@AnyThread
public fun removeClientDisconnectListener(listener: ClientDisconnectListener)
/** Returns true if the connection to the server side is alive. */
@AnyThread
public fun isConnectionAlive(): Boolean
/**
* Interface passed to [addOnWatchFaceReadyListener] which calls
* [OnWatchFaceReadyListener.onWatchFaceReady] when the watch face is ready to render. Use
* [addOnWatchFaceReadyListener] to register a OnWatchFaceReadyListener.
*/
public fun interface OnWatchFaceReadyListener {
/**
* Called when the watchface is ready to render.
*
* Note in the event of the watch face disconnecting (e.g. due to a crash) this callback
* will never fire. Use [ClientDisconnectListener] to observe disconnects.
*/
public fun onWatchFaceReady()
}
/**
* Registers a [OnWatchFaceReadyListener] which gets called when the watch face is ready to
* render.
*
* Note in the event of the watch face disconnecting (e.g. due to a crash) the listener will
* never get called. Use [ClientDisconnectListener] to observe disconnects.
*
* @param executor The [Executor] on which to run [OnWatchFaceReadyListener].
* @param listener The [OnWatchFaceReadyListener] to run when the watchface is ready to render.
*/
public fun addOnWatchFaceReadyListener(executor: Executor, listener: OnWatchFaceReadyListener)
/**
* Stops listening for events registered by [addOnWatchFaceReadyListener].
*/
public fun removeOnWatchFaceReadyListener(listener: OnWatchFaceReadyListener)
/**
* Registers a [Consumer] which gets called initially with the current
* [Renderer.watchfaceColors] if known or `null` if not, and subsequently whenever the watch
* face's [Renderer.watchfaceColors] change.
*
* @param executor The [Executor] on which to run [listener].
* @param listener The [Consumer] to run whenever the watch face's
* [Renderer.watchfaceColors] change.
*/
@OptIn(WatchFaceExperimental::class)
@WatchFaceClientExperimental
public fun addOnWatchFaceColorsListener(
executor: Executor,
listener: Consumer<WatchFaceColors?>
) {
}
/**
* Stops listening for events registered by [addOnWatchFaceColorsListener].
*/
@OptIn(WatchFaceExperimental::class)
@WatchFaceClientExperimental
public fun removeOnWatchFaceColorsListener(listener: Consumer<WatchFaceColors?>) {}
}
/** Controls a stateful remote interactive watch face. */
@OptIn(WatchFaceExperimental::class)
internal class InteractiveWatchFaceClientImpl internal constructor(
private val iInteractiveWatchFace: IInteractiveWatchFace,
private val previewImageUpdateRequestedExecutor: Executor?,
private val previewImageUpdateRequestedListener: Consumer<String>?
) : InteractiveWatchFaceClient {
private val lock = Any()
private val disconnectListeners =
HashMap<InteractiveWatchFaceClient.ClientDisconnectListener, Executor>()
private val readyListeners =
HashMap<InteractiveWatchFaceClient.OnWatchFaceReadyListener, Executor>()
private val watchFaceColorsChangeListeners =
HashMap<Consumer<WatchFaceColors?>, Executor>()
private var watchfaceReadyListenerRegistered = false
private var lastWatchFaceColors: WatchFaceColors? = null
private var disconnectReason: Int? = null
private var closed = false
private val iWatchFaceListener = object : IWatchfaceListener.Stub() {
override fun getApiVersion() = IWatchfaceListener.API_VERSION
override fun onWatchfaceReady() {
[email protected]()
}
override fun onWatchfaceColorsChanged(watchFaceColors: WatchFaceColorsWireFormat?) {
var listenerCopy: HashMap<Consumer<WatchFaceColors?>, Executor>
synchronized(lock) {
listenerCopy = HashMap(watchFaceColorsChangeListeners)
lastWatchFaceColors = watchFaceColors?.toApiFormat()
}
for ((listener, executor) in listenerCopy) {
executor.execute {
listener.accept(lastWatchFaceColors)
}
}
}
override fun onPreviewImageUpdateRequested(watchFaceId: String) {
previewImageUpdateRequestedExecutor?.execute {
previewImageUpdateRequestedListener!!.accept(watchFaceId)
}
}
override fun onEngineDetached() {
sendDisconnectNotification(DisconnectReasons.ENGINE_DETACHED)
}
}
init {
iInteractiveWatchFace.asBinder().linkToDeath(
{
sendDisconnectNotification(DisconnectReasons.ENGINE_DIED)
},
0
)
if (iInteractiveWatchFace.apiVersion >= 6) {
iInteractiveWatchFace.addWatchFaceListener(iWatchFaceListener)
}
}
internal fun sendDisconnectNotification(reason: Int) {
val listenersCopy = synchronized(lock) {
// Don't send more than one notification.
if (disconnectReason != null) {
return
}
disconnectReason = reason
HashMap(disconnectListeners)
}
for ((listener, executor) in listenersCopy) {
executor.execute {
listener.onClientDisconnected(reason)
}
}
}
override fun updateComplicationData(
slotIdToComplicationData: Map<Int, ComplicationData>
) = TraceEvent("InteractiveWatchFaceClientImpl.updateComplicationData").use {
iInteractiveWatchFace.updateComplicationData(
slotIdToComplicationData.map {
IdAndComplicationDataWireFormat(it.key, it.value.asWireComplicationData())
}
)
}
@RequiresApi(27)
override fun renderWatchFaceToBitmap(
renderParameters: RenderParameters,
instant: Instant,
userStyle: UserStyle?,
idAndComplicationData: Map<Int, ComplicationData>?
): Bitmap = TraceEvent("InteractiveWatchFaceClientImpl.renderWatchFaceToBitmap").use {
SharedMemoryImage.ashmemReadImageBundle(
iInteractiveWatchFace.renderWatchFaceToBitmap(
WatchFaceRenderParams(
renderParameters.toWireFormat(),
instant.toEpochMilli(),
userStyle?.toWireFormat(),
idAndComplicationData?.map {
IdAndComplicationDataWireFormat(
it.key,
it.value.asWireComplicationData()
)
}
)
)
)
}
override val previewReferenceInstant: Instant
get() = Instant.ofEpochMilli(iInteractiveWatchFace.previewReferenceTimeMillis)
override val overlayStyle: OverlayStyle
get() {
if (iInteractiveWatchFace.apiVersion >= 4) {
iInteractiveWatchFace.watchFaceOverlayStyle?.let {
return OverlayStyle(it.backgroundColor, it.foregroundColor)
}
}
return OverlayStyle(null, null)
}
override fun updateWatchFaceInstance(newInstanceId: String, userStyle: UserStyle) = TraceEvent(
"InteractiveWatchFaceClientImpl.updateInstance"
).use {
iInteractiveWatchFace.updateWatchfaceInstance(newInstanceId, userStyle.toWireFormat())
}
override fun updateWatchFaceInstance(
newInstanceId: String,
userStyle: UserStyleData
) = TraceEvent(
"InteractiveWatchFaceClientImpl.updateInstance"
).use {
iInteractiveWatchFace.updateWatchfaceInstance(
newInstanceId,
userStyle.toWireFormat()
)
}
override val instanceId: String
get() = iInteractiveWatchFace.instanceId
override val userStyleSchema: UserStyleSchema
get() = UserStyleSchema(iInteractiveWatchFace.userStyleSchema)
override val complicationSlotsState: Map<Int, ComplicationSlotState>
get() = iInteractiveWatchFace.complicationDetails.associateBy(
{ it.id },
{ ComplicationSlotState(it.complicationState) }
)
override fun close() = TraceEvent("InteractiveWatchFaceClientImpl.close").use {
if (iInteractiveWatchFace.apiVersion >= 6) {
iInteractiveWatchFace.removeWatchFaceListener(iWatchFaceListener)
}
iInteractiveWatchFace.release()
synchronized(lock) {
closed = true
}
}
override fun sendTouchEvent(
xPosition: Int,
yPosition: Int,
@TapType tapType: Int
) = TraceEvent("InteractiveWatchFaceClientImpl.sendTouchEvent").use {
iInteractiveWatchFace.sendTouchEvent(xPosition, yPosition, tapType)
}
override val contentDescriptionLabels: List<ContentDescriptionLabel>
get() = iInteractiveWatchFace.contentDescriptionLabels?.map {
ContentDescriptionLabel(
it.text.toApiComplicationText(),
it.bounds,
it.tapAction
)
} ?: emptyList()
override fun setWatchUiState(
watchUiState: androidx.wear.watchface.client.WatchUiState
) = TraceEvent(
"InteractiveWatchFaceClientImpl.setSystemState"
).use {
iInteractiveWatchFace.setWatchUiState(
WatchUiState(
watchUiState.inAmbientMode,
watchUiState.interruptionFilter
)
)
}
override fun performAmbientTick() = TraceEvent(
"InteractiveWatchFaceClientImpl.performAmbientTick"
).use {
iInteractiveWatchFace.ambientTickUpdate()
}
override fun addClientDisconnectListener(
listener: InteractiveWatchFaceClient.ClientDisconnectListener,
executor: Executor
) {
val disconnectReasonCopy = synchronized(lock) {
require(!disconnectListeners.contains(listener)) {
"Don't call addClientDisconnectListener multiple times for the same listener"
}
disconnectListeners.put(listener, executor)
disconnectReason
}
disconnectReasonCopy?.let {
listener.onClientDisconnected(it)
}
}
override fun removeClientDisconnectListener(
listener: InteractiveWatchFaceClient.ClientDisconnectListener
) {
synchronized(lock) {
disconnectListeners.remove(listener)
}
}
override fun isConnectionAlive() =
iInteractiveWatchFace.asBinder().isBinderAlive && synchronized(lock) { !closed }
private fun maybeRegisterWatchfaceReadyListener() {
if (watchfaceReadyListenerRegistered) {
return
}
when {
// From version 6 we want to use IWatchFaceListener instead.
iInteractiveWatchFace.apiVersion >= 6 -> return
iInteractiveWatchFace.apiVersion >= 2 -> {
iInteractiveWatchFace.addWatchfaceReadyListener(
object : IWatchfaceReadyListener.Stub() {
override fun getApiVersion(): Int = IWatchfaceReadyListener.API_VERSION
override fun onWatchfaceReady() {
[email protected]()
}
}
)
}
else -> {
// We can emulate this on an earlier API by using a call to get userStyleSchema that
// will block until the watch face is ready. to Avoid blocking the current thread we
// spin up a temporary thread.
val thread = HandlerThread("addWatchFaceReadyListener")
thread.start()
val handler = Handler(thread.looper)
handler.post {
iInteractiveWatchFace.userStyleSchema
[email protected]()
thread.quitSafely()
}
}
}
watchfaceReadyListenerRegistered = true
}
internal fun onWatchFaceReady() {
var listenerCopy: HashMap<InteractiveWatchFaceClient.OnWatchFaceReadyListener, Executor>
synchronized(lock) {
listenerCopy = HashMap(readyListeners)
}
for ((listener, executor) in listenerCopy) {
executor.execute {
listener.onWatchFaceReady()
}
}
}
override fun addOnWatchFaceReadyListener(
executor: Executor,
listener: InteractiveWatchFaceClient.OnWatchFaceReadyListener
) {
synchronized(lock) {
require(!readyListeners.contains(listener)) {
"Don't call addWatchFaceReadyListener multiple times for the same listener"
}
maybeRegisterWatchfaceReadyListener()
readyListeners.put(listener, executor)
}
}
override fun removeOnWatchFaceReadyListener(
listener: InteractiveWatchFaceClient.OnWatchFaceReadyListener
) {
synchronized(lock) {
readyListeners.remove(listener)
}
}
@WatchFaceClientExperimental
override fun addOnWatchFaceColorsListener(
executor: Executor,
listener: Consumer<WatchFaceColors?>
) {
val colors = synchronized(lock) {
require(!watchFaceColorsChangeListeners.contains(listener)) {
"Don't call addOnWatchFaceColorsListener multiple times for the same listener"
}
maybeRegisterWatchfaceReadyListener()
watchFaceColorsChangeListeners.put(listener, executor)
lastWatchFaceColors
}
listener.accept(colors)
}
@WatchFaceClientExperimental
override fun removeOnWatchFaceColorsListener(
listener: Consumer<WatchFaceColors?>
) {
synchronized(lock) {
watchFaceColorsChangeListeners.remove(listener)
}
}
}
| apache-2.0 | 4e22bfea1d9ee08f399ce708adc1b885 | 37.472511 | 100 | 0.680519 | 5.142403 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.